tenjin-cli 0.1.0-alpha.18 → 0.1.0-alpha.19
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 +151 -40
- package/dist/{_esm-CE7KNONL.js → _esm-OVVGTKHH.js} +4 -4
- package/dist/{chunk-WUHY2AXD.js → chunk-2SQEFBAM.js} +4 -3
- package/dist/{chunk-FGR734LZ.js → chunk-3VYGDRRL.js} +5 -5
- package/dist/{chunk-PDA2BVFY.js → chunk-5DOHKQ24.js} +4 -15
- package/dist/chunk-5DOHKQ24.js.map +1 -0
- package/dist/{chunk-N35E6CM2.js → chunk-6DCELMQA.js} +6 -6
- package/dist/{chunk-WXC57XGG.js → chunk-A36LQPHV.js} +1 -1
- package/dist/chunk-A36LQPHV.js.map +1 -0
- package/dist/{chunk-BTX2QE2Y.js → chunk-A6CY6BUW.js} +3 -3
- package/dist/{chunk-TP4D47BY.js → chunk-AISBL7EY.js} +3 -3
- package/dist/{chunk-ON6C6WOX.js → chunk-AMG4SONW.js} +138 -58
- package/dist/chunk-AMG4SONW.js.map +1 -0
- package/dist/{chunk-AUKDYPPX.js → chunk-BG2EXNAA.js} +7 -6
- package/dist/chunk-BG2EXNAA.js.map +1 -0
- package/dist/{chunk-F3FUGWPZ.js → chunk-FHBGTOFA.js} +121 -40
- package/dist/chunk-FHBGTOFA.js.map +1 -0
- package/dist/{chunk-HPWO4O6S.js → chunk-FPUPBQHX.js} +2 -2
- package/dist/{chunk-3AUDA53C.js → chunk-KTAW4KGH.js} +6 -5
- package/dist/{chunk-J5INH7WB.js → chunk-LSWVVSFX.js} +106 -5
- package/dist/chunk-LSWVVSFX.js.map +1 -0
- package/dist/chunk-O2JYBOUO.js +47 -0
- package/dist/chunk-O2JYBOUO.js.map +1 -0
- package/dist/{chunk-NRQMOVKM.js → chunk-PZQRSZJV.js} +2 -2
- package/dist/{chunk-NRQMOVKM.js.map → chunk-PZQRSZJV.js.map} +1 -1
- package/dist/{chunk-N44H5TFB.js → chunk-SCAOYGKX.js} +315 -71
- package/dist/chunk-SCAOYGKX.js.map +1 -0
- package/dist/{chunk-35M3VITA.js → chunk-TDGN476R.js} +60 -7
- package/dist/chunk-TDGN476R.js.map +1 -0
- package/dist/{chunk-AR7U7BRG.js → chunk-UNV4K45L.js} +12 -18
- package/dist/{chunk-AR7U7BRG.js.map → chunk-UNV4K45L.js.map} +1 -1
- package/dist/{chunk-ZG7SFI34.js → chunk-VFVFVQM6.js} +4 -4
- package/dist/{chunk-EPCOMXLF.js → chunk-WUU3BH6G.js} +2 -2
- package/dist/{chunk-KUBEYXSO.js → chunk-XDADPAWW.js} +22 -22
- package/dist/{chunk-YPQSMIDH.js → chunk-XNP6VUAJ.js} +3 -3
- package/dist/{chunk-AWQPGIR6.js → chunk-Y66XUXVI.js} +5 -5
- package/dist/{chunk-TJMCBIZU.js → chunk-ZDKEU2GF.js} +2 -2
- package/dist/{chunk-WLMJE3GJ.js → chunk-ZTFIQC4C.js} +2 -2
- package/dist/{cli-MP3RAYHL.js → cli-456F77ZY.js} +33 -28
- package/dist/{cli-MP3RAYHL.js.map → cli-456F77ZY.js.map} +1 -1
- package/dist/{config-BJK6U5VY.js → config-BLUWOH6S.js} +9 -12
- package/dist/{doctor-KJROWE5V.js → doctor-PS45CR3T.js} +37 -29
- package/dist/{doctor-KJROWE5V.js.map → doctor-PS45CR3T.js.map} +1 -1
- package/dist/{fund-I5COXPEJ.js → fund-4SW2ZBWC.js} +17 -17
- package/dist/{hook-command-EJO2564A.js → hook-command-YTV7X333.js} +247 -24
- package/dist/hook-command-YTV7X333.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{install-NUQLLHS2.js → install-U4BIDCHH.js} +14 -13
- package/dist/{install-wallet-JPFTEC6H.js → install-wallet-EYHELQMG.js} +14 -14
- package/dist/{mcp-I5XMVE64.js → mcp-AC4PIXH5.js} +30 -26
- package/dist/{mcp-I5XMVE64.js.map → mcp-AC4PIXH5.js.map} +1 -1
- package/dist/{pay-WA3JSCNB.js → pay-VJOP6TFT.js} +19 -19
- package/dist/{send-KVUH5WDO.js → send-YH75Z6LB.js} +14 -14
- package/dist/{status-FFC6FO72.js → status-5CHCDLUE.js} +24 -17
- package/dist/status-5CHCDLUE.js.map +1 -0
- package/dist/{status-line-SAXSU6CR.js → status-line-CZAZUOAY.js} +6 -6
- package/dist/{status-line-wiring-DQZCWIUO.js → status-line-wiring-2ABDVXSJ.js} +4 -4
- package/dist/tenjin-daemon.mjs +3 -14
- package/dist/{uninstall-SWICHBTF.js → uninstall-BYVGAQMO.js} +13 -15
- package/dist/{uninstall-SWICHBTF.js.map → uninstall-BYVGAQMO.js.map} +1 -1
- package/dist/{update-W572AMXG.js → update-7QJDSHST.js} +5 -5
- package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-N2GIVMZ7.js} +2 -2
- package/dist/{wallet-L2YLAJFN.js → wallet-YZOXIXBC.js} +14 -14
- package/docs/agent-permissions.md +29 -13
- package/docs/safety-model.md +7 -1
- package/package.json +1 -1
- package/dist/chunk-35M3VITA.js.map +0 -1
- package/dist/chunk-AUKDYPPX.js.map +0 -1
- package/dist/chunk-F3FUGWPZ.js.map +0 -1
- package/dist/chunk-J5INH7WB.js.map +0 -1
- package/dist/chunk-N44H5TFB.js.map +0 -1
- package/dist/chunk-ON6C6WOX.js.map +0 -1
- package/dist/chunk-PDA2BVFY.js.map +0 -1
- package/dist/chunk-U2DZISAH.js +0 -111
- package/dist/chunk-U2DZISAH.js.map +0 -1
- package/dist/chunk-WS4JA6TC.js +0 -137
- package/dist/chunk-WS4JA6TC.js.map +0 -1
- package/dist/chunk-WXC57XGG.js.map +0 -1
- package/dist/hook-command-EJO2564A.js.map +0 -1
- package/dist/skill-placement-JMDPSKE6.js +0 -299
- package/dist/skill-placement-JMDPSKE6.js.map +0 -1
- package/dist/status-FFC6FO72.js.map +0 -1
- /package/dist/{_esm-CE7KNONL.js.map → _esm-OVVGTKHH.js.map} +0 -0
- /package/dist/{chunk-WUHY2AXD.js.map → chunk-2SQEFBAM.js.map} +0 -0
- /package/dist/{chunk-FGR734LZ.js.map → chunk-3VYGDRRL.js.map} +0 -0
- /package/dist/{chunk-N35E6CM2.js.map → chunk-6DCELMQA.js.map} +0 -0
- /package/dist/{chunk-BTX2QE2Y.js.map → chunk-A6CY6BUW.js.map} +0 -0
- /package/dist/{chunk-TP4D47BY.js.map → chunk-AISBL7EY.js.map} +0 -0
- /package/dist/{chunk-HPWO4O6S.js.map → chunk-FPUPBQHX.js.map} +0 -0
- /package/dist/{chunk-3AUDA53C.js.map → chunk-KTAW4KGH.js.map} +0 -0
- /package/dist/{chunk-ZG7SFI34.js.map → chunk-VFVFVQM6.js.map} +0 -0
- /package/dist/{chunk-EPCOMXLF.js.map → chunk-WUU3BH6G.js.map} +0 -0
- /package/dist/{chunk-KUBEYXSO.js.map → chunk-XDADPAWW.js.map} +0 -0
- /package/dist/{chunk-YPQSMIDH.js.map → chunk-XNP6VUAJ.js.map} +0 -0
- /package/dist/{chunk-AWQPGIR6.js.map → chunk-Y66XUXVI.js.map} +0 -0
- /package/dist/{chunk-TJMCBIZU.js.map → chunk-ZDKEU2GF.js.map} +0 -0
- /package/dist/{chunk-WLMJE3GJ.js.map → chunk-ZTFIQC4C.js.map} +0 -0
- /package/dist/{config-BJK6U5VY.js.map → config-BLUWOH6S.js.map} +0 -0
- /package/dist/{fund-I5COXPEJ.js.map → fund-4SW2ZBWC.js.map} +0 -0
- /package/dist/{install-NUQLLHS2.js.map → install-U4BIDCHH.js.map} +0 -0
- /package/dist/{install-wallet-JPFTEC6H.js.map → install-wallet-EYHELQMG.js.map} +0 -0
- /package/dist/{pay-WA3JSCNB.js.map → pay-VJOP6TFT.js.map} +0 -0
- /package/dist/{send-KVUH5WDO.js.map → send-YH75Z6LB.js.map} +0 -0
- /package/dist/{status-line-SAXSU6CR.js.map → status-line-CZAZUOAY.js.map} +0 -0
- /package/dist/{status-line-wiring-DQZCWIUO.js.map → status-line-wiring-2ABDVXSJ.js.map} +0 -0
- /package/dist/{update-W572AMXG.js.map → update-7QJDSHST.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → viemAdapter-By13KInL-N2GIVMZ7.js.map} +0 -0
- /package/dist/{wallet-L2YLAJFN.js.map → wallet-YZOXIXBC.js.map} +0 -0
package/docs/safety-model.md
CHANGED
|
@@ -21,7 +21,13 @@ Do not copy commands from purchased content into an allowlist, `AGENTS.md`, `CLA
|
|
|
21
21
|
|
|
22
22
|
Search, inspect, free reads, outcomes, wallet display, balance checks, doctor, and checkout-link creation are separated from purchases and transfers.
|
|
23
23
|
|
|
24
|
-
The x402 router's `request` tool and `tenjin pay` are the paying commands, and they run one gate between them: `maxAutoSpend`
|
|
24
|
+
The x402 router's `request` tool and `tenjin pay` are the paying commands, and they run one gate between them: `maxAutoSpend` and `sessionBudget` as limits on automatic router spending only, mandatory consent for manual pay, and a reservation that counts a signed authorization as spent the moment it leaves. A router lookup is ONE payment, to the provider: deciding where to route costs nothing and nobody signs for it. The boundary is split on purpose: the backend binds the call and validates its arguments against the capability's own schema, and this client checks the three things only it can: the amount signed against the spend caps, the body that comes back against the success rule the decision carries, and the destination resolving to a public address. That destination check is a check, not a pin: the request resolves the name again on its own, so a host that answers publicly at check time and privately a moment later is not closed by it. Closing it needs a resolver-aware transport that connects to the address it validated, which this release does not ship. `--max-price` is always a hard cap on `tenjin pay`. Every automatic authorization that LEAVES the process counts against the automatic session budget until the 24 hour window rolls, even where the provider never settles it: a signed EIP-3009 authorization is a bearer instrument, so a 200 that reports no match, or a 402 that rejects the payment, is the counterparty saying it did not take the money rather than proof that it cannot. Manual exposure remains recorded in the same ledger but does not consume automatic headroom. Older records without a mode or automatic counter count conservatively as automatic. The budget is deliberately the conservative side of that, and a caller can be left with less headroom than it actually spent.
|
|
25
|
+
|
|
26
|
+
The automatic daily limit is zero, a finite amount or `none`: zero blocks positive automatic payments and `none` removes that ceiling while retaining reservations and duplicate protection. Manual pay requires explicit user consent and is subject to neither automatic limit. Retired `bazaarPay` and `confirm` values are ignored after upgrade; doctor/status warn, and install/refresh remove and report them while preserving current controls and unrelated fields.
|
|
27
|
+
|
|
28
|
+
Direct third-party payments use the supported live 402 quote. Unavailable/incomplete verification and differences from an exact listing block payment unless this invocation supplies `--ignore-warnings`. Missing listings or a missing Bazaar extension require no warning or flag. Warnings remain visible and structured in JSON. This flag acknowledges registry evidence only; `--yes` confirms payment only. Manual pay requires explicit user consent regardless of configured automatic limits and must never be an autonomous workaround for router refusal. Neither flag bypasses an explicit price cap, supported challenge, destination checks or balance check. Router payments retain the offered-price ceiling and hard checks on supplied terms, with no direct-payment fallback. The current price-only protocol does not provide complete endpoint/payee quote binding.
|
|
29
|
+
|
|
30
|
+
After policy confirmation and immediately before signing, the actual signer's USDC balance must be readable and sufficient. Refusal releases the reservation and does not count spend; free and entitled delivery skips this read. The hook's bounded advisory read suppresses known unusable offers but does not authorize payment. Balances can change after a read, so settlement is not guaranteed. Once a payment authorization is transmitted, the conservative accounting described above is unchanged.
|
|
25
31
|
|
|
26
32
|
`tenjin wallet send` moves USDC out of the wallet. It exists as a human escape hatch, not as part of the agent flow.
|
|
27
33
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tenjin-cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.19",
|
|
4
4
|
"mcpName": "blog.tenjin/tenjin",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "x402 router for coding agents: one paid decision per lookup, a local wallet that pays each provider per call in USDC on Base.",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/spend-ledger.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { hasCode } from './errno';\nimport { spendLedgerPath } from './paths';\n\n/**\n * The spend ledger's READ side: its shape, the two expiries, and a read-only\n * summary. It lives outside `lib/wallet` so the router hooks can measure an\n * offer against the same session total an authorization would, without the\n * wallet entering their chunk graph (`src/router/dist-chunks.test.ts`). The\n * write side, with its lock and reservations, stays in `lib/wallet/spend.ts`.\n */\n\nexport const DEFAULT_WINDOW_MS = 86_400_000; // 24h rolling day\nexport const RESERVATION_TTL_MS = 600_000; // 10 min: a dangling reservation self-expires\n\nconst ReservationSchema = z.object({\n id: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n /** Optional so a ledger written by an older build still parses. */\n requestKey: z.string().optional(),\n});\nexport type Reservation = z.infer<typeof ReservationSchema>;\n\nconst LedgerSchema = z.object({\n schemaVersion: z.literal(2),\n windowStartMs: z.number(),\n /**\n * EXPOSURE: every authorization this window transmitted. A signed EIP-3009\n * authorization is a bearer instrument, so this is what the budget counts,\n * whatever any counterparty later says it took.\n */\n committedAtomic: z.string().regex(/^\\d+$/),\n /**\n * SETTLED: what counterparties reported actually taking, which the router's\n * waived outcomes made a different number from the line above (2026-09-23\n * lookup contract). Optional so a ledger an older build wrote still parses;\n * absent means \"everything committed was settled\", which is what that build\n * assumed. Reporting only, never a budget input: under-counting exposure\n * because a server said \"no charge\" is exactly the hole this avoids.\n */\n settledAtomic: z.string().regex(/^\\d+$/).optional(),\n reservations: z.array(ReservationSchema),\n});\nexport type Ledger = z.infer<typeof LedgerSchema>;\n\nexport function emptyLedger(nowMs: number): Ledger {\n return {\n schemaVersion: 2,\n windowStartMs: nowMs,\n committedAtomic: '0',\n settledAtomic: '0',\n reservations: [],\n };\n}\n\n/** Everything this window has spent or is holding: the budget's input. */\nexport function spentOf(ledger: {\n committedAtomic: string;\n reservations: { amountAtomic: string }[];\n}): bigint {\n return ledger.reservations.reduce(\n (sum, r) => sum + BigInt(r.amountAtomic),\n BigInt(ledger.committedAtomic),\n );\n}\n\n/**\n * ABSENT and CORRUPT both reset the window, but they are not the same fact: the\n * first is a first run, the second is spend that existed and is now gone. Only\n * the second is worth telling anyone about, so the two stay distinguishable here\n * rather than collapsing into one null.\n */\ninterface LedgerRead {\n ledger: Ledger | null;\n /** Set only when the file EXISTS and could not be turned back into a ledger. */\n corrupt?: string;\n}\n\nexport async function readLedger(path: string): Promise<LedgerRead> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n // A missing file is the ordinary first run. Any other read failure means a\n // file is there and unusable, which is the corrupt case by another name.\n if (hasCode(err, 'ENOENT')) return { ledger: null };\n return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { ledger: null, corrupt: 'not valid JSON' };\n }\n const parsed = LedgerSchema.safeParse(json);\n if (parsed.success) return { ledger: parsed.data };\n const issue = parsed.error.issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // Field-qualified: \"expected number, received undefined\" names nothing on its\n // own. zod never echoes the received VALUE, so no spend figure rides along.\n return {\n ledger: null,\n corrupt: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n}\n\nexport interface SpendSummary {\n windowStartMs: number;\n committedAtomic: string;\n reservations: { amountAtomic: string; atMs: number; requestKey?: string }[];\n}\n\n/**\n * The ledger AS AN AUTHORIZATION WOULD SEE IT, for `tenjin status`. Read-only,\n * and it applies the same two expiries the authorizer applies before it\n * evaluates a spend: a rolling window that has run out reads as a fresh one,\n * and reservations past their TTL are gone. Summing the raw file instead\n * reported spend as current, and crashed reservations as open, until the next\n * payment happened to rewrite it.\n *\n * `null` for absent or unreadable, which is the same thing to a report.\n */\nexport async function readSpendSummary(\n dir: string,\n opts: { now?: () => number; windowMs?: number } = {},\n): Promise<SpendSummary | null> {\n const { ledger } = await readLedger(spendLedgerPath(dir));\n if (ledger === null) return null;\n const nowMs = (opts.now ?? Date.now)();\n const windowMs = opts.windowMs ?? DEFAULT_WINDOW_MS;\n if (nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);\n return {\n ...ledger,\n reservations: led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O,GAAG,EAAE;AAAA,EACnF;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO,EAAE,QAAQ,MAAM,SAAS,iBAAiB;AAAA,EACnD;AACA,QAAM,SAAS,aAAa,UAAU,IAAI;AAC1C,MAAI,OAAO,QAAS,QAAO,EAAE,QAAQ,OAAO,KAAK;AACjD,QAAM,QAAQ,OAAO,MAAM,OAAO,CAAC;AACnC,QAAM,QAAQ,OAAO,KAAK,KAAK,GAAG;AAClC,QAAM,UAAU,OAAO,WAAW;AAGlC,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,SAAS,UAAU,UAAa,MAAM,SAAS,IAAI,GAAG,KAAK,KAAK,OAAO,KAAK;AAAA,EAC9E;AACF;AAkBA,eAAsB,iBACpB,KACA,OAAkD,CAAC,GACrB;AAC9B,QAAM,EAAE,OAAO,IAAI,MAAM,WAAW,gBAAgB,GAAG,CAAC;AACxD,MAAI,WAAW,KAAM,QAAO;AAC5B,QAAM,SAAS,KAAK,OAAO,KAAK,KAAK;AACrC,QAAM,WAAW,KAAK,YAAY;AAClC,MAAI,QAAQ,OAAO,iBAAiB,SAAU,QAAO,YAAY,KAAK;AACtE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,cAAc,OAAO,aAAa,OAAO,CAAC,MAAM,QAAQ,EAAE,OAAO,kBAAkB;AAAA,EACrF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/wallet/spend.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { writeFileAtomic } from '../atomic-json';\nimport { withFileLock } from '../lock';\nimport { spendLedgerPath } from '../paths';\nimport {\n DEFAULT_WINDOW_MS,\n emptyLedger,\n readLedger,\n RESERVATION_TTL_MS,\n spentOf,\n type Ledger,\n type Reservation,\n} from '../spend-ledger';\nimport {\n evaluateSpendPolicy,\n type PolicyReason,\n type SpendDecision,\n type SpendPolicy,\n} from '../policy';\nimport type { PolicyEnforcement } from './provider';\n\n/**\n * The spend-policy enforcement seam, deliberately in the WALLET PROVIDER layer,\n * BEFORE any signing/payment path, so a future hosted provider (Privy, B5)\n * inherits it: policy moves provider-side by swapping this local authorizer for\n * one the hosted signer enforces. The local authorizer is `client-only` (any\n * process that runs the CLI can edit config or the ledger), and it says so.\n *\n * sessionBudget is enforced ATOMICALLY across the per-command CLI processes an\n * agent spawns: `authorize` takes the file lock and, when a spend may proceed,\n * writes a pending RESERVATION that counts against the budget immediately. Two\n * concurrent authorizations therefore each see the other's reservation and the\n * second is denied, closing the check-then-pay TOCTOU. `commit` finalizes a\n * reservation into committed spend after settlement; `release` drops an unused\n * one (a decline or a failed payment). A reservation left dangling (a crash\n * between authorize and commit) self-expires after RESERVATION_TTL_MS.\n */\n\nexport interface SpendRequest {\n amountAtomic: bigint;\n creator: string;\n /** The caller's `--max-price` cap, if any. */\n maxPriceAtomic?: bigint;\n /**\n * THE SAME-TURN DUPLICATE GUARD. An opaque identity for the request being\n * paid for (its destination and its exact arguments), recorded on the\n * reservation. A second authorization carrying a key an unexpired reservation\n * already holds is DENIED rather than reserved, so one in-flight payment can\n * never become two because a caller retried, a harness re-fired, or a second\n * process asked for the same thing. Same lock and same file as the budget, so\n * the check is atomic across the per-command processes an agent spawns; the\n * reservation TTL is what bounds \"same turn\". Omit it and nothing changes.\n */\n requestKey?: string;\n}\n\nexport interface SpendAuthorization {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n amountAtomic: bigint;\n sessionSpentAtomic: bigint;\n sessionBudgetAtomic: bigint;\n policyEnforcement: PolicyEnforcement;\n /** The pending reservation to commit (on settlement) or release (on abort).\n * Present only when the spend may proceed and a budget is in force. */\n reservationId?: string;\n}\n\nexport interface SpendAuthorizer {\n policyEnforcement: PolicyEnforcement;\n /** Evaluate a spend against policy + the rolling session ledger, atomically\n * reserving budget when the spend may proceed. */\n authorize(req: SpendRequest): Promise<SpendAuthorization>;\n /**\n * Finalize a reservation into committed spend after settlement. Runs only\n * post-settlement, so `amountAtomic` is authoritative: if the reservation\n * TTL-expired mid-confirm (a human can out-wait RESERVATION_TTL_MS at the\n * prompt), the settled amount is still recorded rather than silently lost\n * from the rolling budget.\n */\n commit(\n reservationId: string | undefined,\n amountAtomic: bigint,\n /** What the counterparty reported actually taking, when it said so at all.\n * Omitted means \"assume it took what was authorized\", the conservative\n * reading every caller had before the router began waiving fees. */\n opts?: { settledAtomic?: bigint },\n ): Promise<void>;\n /** Drop an unused reservation (a decline, a 409, or a failed payment). */\n release(reservationId: string | undefined): Promise<void>;\n}\n\nexport interface LocalSpendAuthorizerDeps {\n dir: string;\n policy: SpendPolicy;\n /** Rolling window length (ms); default 24h. Injectable for tests. */\n windowMs?: number;\n /** Clock seam for deterministic window tests. */\n now?: () => number;\n /**\n * Called at most ONCE per authorizer when the ledger file exists but cannot be\n * read back. The reset below is fail-open by design, and a silent one hands back\n * budget the operator believes is already spent — so the caller gets to say so.\n */\n onCorrupt?: (reason: string) => void;\n}\n\nexport function createLocalSpendAuthorizer(deps: LocalSpendAuthorizerDeps): SpendAuthorizer {\n const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;\n const now = deps.now ?? Date.now;\n const path = spendLedgerPath(deps.dir);\n const lockPath = `${path}.lock`;\n // One notice per authorizer: authorize and commit each read the file, and the\n // reset is not persisted until something is written, so an unlatched warning\n // would fire twice for the same broken file within one command.\n let warnedCorrupt = false;\n\n // Roll the window and drop expired reservations; returns the live ledger.\n const freshen = (ledger: Ledger | null, nowMs: number): Ledger => {\n if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);\n return {\n ...ledger,\n reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n };\n\n const persist = async (ledger: Ledger): Promise<void> => {\n await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n };\n\n async function withLedger<T>(fn: (ledger: Ledger, nowMs: number) => Promise<T> | T): Promise<T> {\n await mkdir(deps.dir, { recursive: true, mode: 0o700 });\n return withFileLock(lockPath, async () => {\n const nowMs = now();\n const read = await readLedger(path);\n if (read.corrupt !== undefined && !warnedCorrupt) {\n warnedCorrupt = true;\n deps.onCorrupt?.(read.corrupt);\n }\n const ledger = freshen(read.ledger, nowMs);\n return fn(ledger, nowMs);\n });\n }\n\n return {\n policyEnforcement: 'client-only',\n async authorize(req: SpendRequest): Promise<SpendAuthorization> {\n return withLedger(async (ledger) => {\n const sessionSpentAtomic = spentOf(ledger);\n if (\n req.requestKey !== undefined &&\n ledger.reservations.some((r) => r.requestKey === req.requestKey)\n ) {\n return {\n decision: 'deny',\n reason: 'duplicate_in_flight',\n message:\n 'An identical request already holds a reservation in this turn. No second payment was made.',\n amountAtomic: req.amountAtomic,\n sessionSpentAtomic,\n sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,\n policyEnforcement: 'client-only',\n };\n }\n const evaluation = evaluateSpendPolicy(deps.policy, {\n amountAtomic: req.amountAtomic,\n creator: req.creator,\n ...(req.maxPriceAtomic !== undefined ? { maxPriceAtomic: req.maxPriceAtomic } : {}),\n sessionSpentAtomic,\n });\n const base: SpendAuthorization = {\n ...evaluation,\n amountAtomic: req.amountAtomic,\n sessionSpentAtomic,\n sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,\n policyEnforcement: 'client-only',\n };\n // Reserve budget atomically only when a spend may proceed AND a ceiling is\n // in force; a denied spend or a disabled budget needs no reservation.\n if (evaluation.decision === 'deny' || deps.policy.sessionBudgetAtomic === 0n) {\n return base;\n }\n const reservation: Reservation = {\n id: randomUUID(),\n amountAtomic: req.amountAtomic.toString(),\n atMs: now(),\n ...(req.requestKey !== undefined ? { requestKey: req.requestKey } : {}),\n };\n await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });\n return { ...base, reservationId: reservation.id };\n });\n },\n async commit(\n reservationId: string | undefined,\n amountAtomic: bigint,\n opts: { settledAtomic?: bigint } = {},\n ): Promise<void> {\n // No reservation id means no budget ceiling was in force at authorize\n // time; the settled spend still counts against any FUTURE budget window.\n await withLedger(async (ledger) => {\n const reservation =\n reservationId !== undefined\n ? ledger.reservations.find((r) => r.id === reservationId)\n : undefined;\n const exposure =\n reservation !== undefined ? BigInt(reservation.amountAtomic) : amountAtomic;\n // TWO NUMBERS, ON PURPOSE. The budget keeps counting what left; the\n // settled total records what was taken, and they differ whenever a\n // counterparty waives a fee against an authorization already sent.\n const settled = opts.settledAtomic ?? exposure;\n const settledSoFar = BigInt(ledger.settledAtomic ?? ledger.committedAtomic);\n await persist({\n ...ledger,\n committedAtomic: (BigInt(ledger.committedAtomic) + exposure).toString(),\n settledAtomic: (settledSoFar + settled).toString(),\n reservations:\n reservationId !== undefined\n ? ledger.reservations.filter((r) => r.id !== reservationId)\n : ledger.reservations,\n });\n });\n },\n async release(reservationId: string | undefined): Promise<void> {\n if (reservationId === undefined) return;\n await withLedger(async (ledger) => {\n if (!ledger.reservations.some((r) => r.id === reservationId)) return;\n await persist({\n ...ledger,\n reservations: ledger.reservations.filter((r) => r.id !== reservationId),\n });\n });\n },\n };\n}\n\nexport { readSpendSummary, type SpendSummary } from '../spend-ledger';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,kBAAkB;AA4GpB,SAAS,2BAA2B,MAAiD;AAC1F,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,QAAM,OAAO,gBAAgB,KAAK,GAAG;AACrC,QAAM,WAAW,GAAG,IAAI;AAIxB,MAAI,gBAAgB;AAGpB,QAAM,UAAU,CAAC,QAAuB,UAA0B;AAChE,QAAI,WAAW,QAAQ,QAAQ,OAAO,iBAAiB,SAAU,QAAO,YAAY,KAAK;AACzF,WAAO;AAAA,MACL,GAAG;AAAA,MACH,cAAc,OAAO,aAAa,OAAO,CAAC,M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,CAAC,MAAM,EAAE,OAAO,aAAa,EAAG;AAC9D,cAAM,QAAQ;AAAA,UACZ,GAAG;AAAA,UACH,cAAc,OAAO,aAAa,OAAO,CAAC,MAAM,EAAE,OAAO,aAAa;AAAA,QACxE,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/install.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { claudeAdapter } from '../adapters/claude';\nimport { persistRouterDefaults } from '../commands/config';\nimport { CliError } from '../lib/errors';\nimport { appendAllowlistRules, claudeSettingsPath } from '../lib/harness-permissions';\nimport {\n inspectHooksFile,\n ownsHookEntry,\n pruneHooks,\n writeHooks,\n type HooksResult,\n} from '../lib/harness-hooks';\nimport { toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { onPath } from '../lib/skill-wiring';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\nimport { ensureStatusLine, type StatusLineMode, type StatusLineResult } from './status-line-wiring';\n\n/**\n * `tenjin install` for the router product: five hook entries, one MCP server,\n * one permission rule, the spend defaults, and a wallet when there is none.\n *\n * WHAT IT WRITES IS WHAT IT SAYS. There is no skill to materialize, no daemon\n * to start and no background process of any kind: the hooks are plain command\n * lines, the tool lives in an MCP server the harness starts per session, and\n * every other key in the settings file is preserved byte for byte.\n */\n\nconst exec = promisify(execFile);\n\n/**\n * The harness's kill budget for each hook entry, and the number every other\n * wait inside the hook is cut from: 1 s of stdin plus 3.5 s of gate, with\n * 500 ms left for node's boot and the transcript read (`wire.test.ts` pins it).\n * Raised from 3 s because a gate abort costs the turn its hint silently.\n *\n * A machine carrying the old number is converged by the writer, not by the\n * user: the entries are ours by marker, so `install`, `install --refresh` and\n * the refresh `tenjin update` spawns all rewrite them in place.\n */\nexport const HOOK_TIMEOUT_SECONDS = 5;\nexport { MCP_SERVER_NAME };\nexport const ALLOW_RULE = REQUEST_TOOL;\n/**\n * The MCP registration follows the SAME SCOPE the hook entries do. A\n * `--project` install that wrote its hooks into the project and then registered\n * the server at user scope would reach into `~/.claude.json` on a run whose\n * whole point is to touch this project and nothing else, and `tenjin uninstall\n * --project` would leave that behind.\n *\n * Project scope writes `<project>/.mcp.json`, so the registration lives beside\n * the settings file that names the hooks and travels with the repository.\n */\nexport function mcpScope(project: boolean | undefined): 'user' | 'project' {\n return project === true ? 'project' : 'user';\n}\n\nexport function mcpAddCommand(project?: boolean): string {\n return `claude mcp add ${MCP_SERVER_NAME} -s ${mcpScope(project)} -- tenjin mcp`;\n}\n\nexport function mcpRemoveCommand(project?: boolean): string {\n return `claude mcp remove ${MCP_SERVER_NAME} -s ${mcpScope(project)}`;\n}\n\n/** The user-scope form, kept as the name the docs and the tests already use. */\nexport const MCP_ADD_COMMAND = mcpAddCommand();\n\n/**\n * Which settings file this machine's router wiring lives in, spelled once so\n * `install`, `uninstall` and `doctor` can never disagree about where to look.\n * A doctor reading the home file on a `--project` install reported a correctly\n * wired machine as unwired and exited 3.\n */\nexport function routerSettingsPath(\n opts: { project?: boolean; homeDir?: string; cwd?: string } = {},\n): string {\n if (opts.project === true) return join(opts.cwd ?? process.cwd(), '.claude', 'settings.json');\n return claudeSettingsPath(opts.homeDir ?? homedir());\n}\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n\n/**\n * The five entries, spelled once so `uninstall`, `doctor` and the tests read\n * the same list. The native tools are routed twice over one lookup: BEFORE the\n * call, as every release has, with a line pointing to a paid lookup when one\n * fits; and AFTER it, only when it came back short and nothing was said before.\n * A failed call fires PostToolUseFailure rather than PostToolUse, so the second\n * takes both.\n */\nexport function routerHookPlan(): unknown[] {\n const handler = (command: string) => [\n { type: 'command', command, timeout: HOOK_TIMEOUT_SECONDS },\n ];\n return [\n { event: 'UserPromptSubmit', hooks: handler('tenjin hook prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: handler('tenjin hook native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: handler('tenjin hook agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: handler('tenjin hook shortfall') },\n {\n event: 'PostToolUseFailure',\n matcher: NATIVE_MATCHER,\n hooks: handler('tenjin hook shortfall'),\n },\n ];\n}\n\nexport const DISCLOSURE: readonly string[] = [\n 'What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), and each task handed to a subagent, sent to Tenjin for the free routing gate.',\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\nexport interface RouterInstallArgs {\n /** Write into this project's `.claude/settings.json` instead of your home one. */\n project?: boolean;\n /**\n * Bring the entries this machine ALREADY has up to the running build, and\n * add nothing: no config write, no MCP registration, and a refusal when\n * nothing of ours is here. `tenjin update` spawns exactly this after it swaps\n * the binary, so the flag's name and meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * What to do about Claude Code's `statusLine`. Absent is the default path:\n * write ours when the key is free, and print the composition line when it is\n * not. `compose` wraps the status line already there and appends ours;\n * `skip` leaves the key alone entirely.\n */\n statusLine?: StatusLineMode;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** PATH probe for the `claude` binary. */\n which?: (bin: string) => boolean;\n /** Runs `claude mcp add`; tests inject it so no binary is spawned. The scope\n * and the working directory are passed, because project scope is decided by\n * where the command runs as much as by the flag. */\n registerMcp?: (\n command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n ) => Promise<void>;\n /** Reads the registration the scope's own file holds; tests inject it. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n}\n\nexport interface McpRegistration {\n name: string;\n registered: boolean;\n /** Which scope it went to, following the hook entries rather than the flag\n * being read twice. `project` writes `<project>/.mcp.json`. */\n scope: 'user' | 'project';\n /** The command to run by hand, when this run could not. */\n command: string;\n /**\n * WHAT THIS RUN ACTUALLY DID, which `registered` alone cannot say:\n * `already-registered` (the scope's file already launches `tenjin mcp`, and\n * nothing was spawned), `added`, `repaired` (a same-name entry launching\n * something else was removed and re-added, which only `uninstall` does now),\n * `unrepaired` (a registration this run KNOWS is wrong or unreadable and will\n * not touch) or `unavailable` (it is simply not there and this machine could\n * not add it, e.g. no `claude` on PATH). A refresh fails on `unrepaired`,\n * because reporting convergence over a registration that launches something\n * else is the thing to avoid; it still only prints the manual command for\n * `unavailable`.\n */\n reconciled: 'already-registered' | 'added' | 'repaired' | 'unrepaired' | 'unavailable';\n reason?: string;\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const cwd = deps.cwd ?? process.cwd();\n // A refresh converges EVERY install this machine has, in the scope each one\n // was made in. `tenjin update` spawns it from the HOME directory, so looking\n // ONE SCOPE, THE ONE THIS RAN IN. `--refresh` converges the install whose\n // settings file is here: home by default, this project under `--project`.\n // The fan-out across recorded projects is gone with the list it read, along\n // with a failure mode where one project's broken JSON decided what every\n // other install got. `tenjin update` is a binary swap plus this, nothing more.\n // With no flag, a refresh converges the install that is actually HERE: the\n // project file when this directory carries our entries, the home file\n // otherwise. `--project` and its absence are still explicit targets, so\n // nothing silently moves an install from one scope to the other.\n const project =\n args.project ??\n (args.refresh === true &&\n (await probeOurEntries(routerSettingsPath({ project: true, cwd }), ctx.dataDir)).state ===\n 'present');\n const settingsPath = routerSettingsPath({\n ...(project ? { project: true } : {}),\n homeDir: home,\n cwd,\n });\n\n if (args.refresh === true) {\n const probe = await probeOurEntries(settingsPath, ctx.dataDir);\n // An unreadable file is not an absence, and telling someone to install over\n // it is the wrong instruction: the writer would refuse it too.\n if (probe.state === 'unreadable') {\n throw new CliError('CONFIG_INVALID', `Could not inspect ${settingsPath}: ${probe.reason}`, {\n fix: `Fix ${settingsPath}, then re-run: tenjin update`,\n });\n }\n if (probe.state === 'absent') {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh in ${settingsPath}: no Tenjin hook entries are registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n }\n const hooks = await writeHooks({\n adapter: claudeAdapter,\n homeDir: home,\n dataDir: ctx.dataDir,\n env,\n plan: routerHookPlan(),\n settingsPath,\n });\n const permissions = await ensureAllowRule(settingsPath);\n const statusLine = await ensureStatusLine(settingsPath, {\n ...(args.statusLine !== undefined ? { mode: args.statusLine } : {}),\n ...(args.refresh === true ? { refreshOnly: true } : {}),\n });\n const mcp = await registerMcpServer(deps, env, project, cwd, home);\n if (args.refresh === true) {\n // The SAME writers, minus the one that decides anything: the entries are\n // rewritten in place by their ownership marker so an upgrade never\n // duplicates them, the rule and the registration are re-checked because a\n // new version can change either, and `config.json`, the wallet and\n // `spend.json` are not touched at all. Widening an agent's spend policy\n // during an unattended upgrade is not a convergence.\n // RECONCILED, not re-added: `claude mcp add` exits 1 on an existing entry,\n // so the registration is read first and only written when it is missing or\n // wrong (see {@link registerMcpServer}).\n // A registration this run KNOWS is wrong and could not repair is not a\n // converged install, and `tenjin update` reporting success over it is how\n // a machine keeps a stale `x402` server across upgrade after upgrade.\n if (mcp.reconciled === 'unrepaired') {\n throw new CliError(\n 'REFUSED',\n `The ${MCP_SERVER_NAME} MCP registration (${mcpScope(project)} scope) is not the router's and this run could not repair it: ${mcp.reason ?? 'unknown reason'}.`,\n { fix: `Run: ${mcp.command}`, details: { settingsPath, hooks, permissions, mcp } },\n );\n }\n return {\n data: {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n mcp,\n refresh: true,\n scope: mcpScope(project),\n },\n humanLines: refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),\n };\n }\n const spend = await persistRouterDefaults(ctx.dataDir);\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n\n const data = {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n spend: { ...spend, effective: effectiveLimits(effective.policy) },\n mcp,\n wallet,\n disclosure: DISCLOSURE,\n };\n return {\n data,\n humanLines: lines(ctx, {\n project,\n hooks,\n permissions,\n statusLine,\n mcp,\n wallet,\n policy: effective.policy,\n }),\n };\n}\n\nexport interface AllowRuleResult {\n path: string;\n rule: string;\n added: boolean;\n /** Set when the file could not be written; the rule is then not in force. */\n warning?: string;\n}\n\n/**\n * The one permission rule, through the shared allowlist writer rather than a\n * third hand-rolled one: it resolves a symlinked settings.json before the\n * rename, refuses a file it cannot parse, and compares the bytes it read before\n * committing, none of which a local copy of the merge would have.\n */\nasync function ensureAllowRule(path: string): Promise<AllowRuleResult> {\n const result = await appendAllowlistRules(path, [ALLOW_RULE]);\n return {\n path: result.path,\n rule: ALLOW_RULE,\n added: result.added.length > 0,\n ...(result.warning !== undefined\n ? { warning: result.warning }\n : result.skipped !== undefined\n ? { warning: `${result.path} was left untouched (${result.skipped}).` }\n : {}),\n };\n}\n\n/**\n * RECONCILE, do not re-add blindly. `claude mcp add` is not idempotent: Claude\n * Code 2.1.280 exits 1 on a second identical add with \"MCP server x402 already\n * exists in .mcp.json\". Running it unconditionally therefore reported a\n * perfectly healthy machine as an unregistered one and printed a repair command\n * that would fail the same way, while a same-name entry launching something\n * else never converged, because `add` refuses to overwrite it.\n *\n * So the scope's own file is read first: an entry that already launches\n * `tenjin mcp` is the goal state and nothing is spawned, and a file that cannot\n * be read is refused out loud rather than written over.\n *\n * AN `x402` ENTRY THAT LAUNCHES SOMETHING ELSE IS SOMEBODY ELSE'S. This command\n * will not delete it. It may be another tool of the user's that happens to\n * share the name, and an installer that removes a registration nobody asked it\n * to touch has destroyed configuration to make its own output look tidy. The\n * conflict is reported with the exact two commands to run, and the user decides.\n */\nasync function registerMcpServer(\n deps: RouterInstallDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<McpRegistration> {\n const scope = mcpScope(project);\n const command = mcpAddCommand(project);\n const base = { name: MCP_SERVER_NAME, scope, command };\n const existing = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n if (existing.state === 'ok') {\n return { ...base, registered: true, reconciled: 'already-registered' };\n }\n if (existing.state === 'unreadable') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n reason: `the ${scope}-scope registration file could not be read, so nothing was written over it`,\n };\n }\n // REFUSED, NOT REPLACED. Nothing of the user's is removed to make room.\n if (existing.state === 'wrong-command') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n command: `${mcpRemoveCommand(project)} && ${command}`,\n reason: `an MCP server named ${MCP_SERVER_NAME} is already registered at ${scope} scope and launches something else. This command will not remove a registration it did not write; run the two commands above if that entry is stale`,\n };\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (!which('claude')) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: 'the `claude` binary is not on PATH',\n };\n }\n try {\n await (deps.registerMcp ?? runClaudeMcpAdd)(command, { scope, cwd });\n return { ...base, registered: true, reconciled: 'added' };\n } catch (err) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The file each scope writes: the project's own `.mcp.json`, or the user's\n * `~/.claude.json`. Neither can inherit from the other. Shared by `install`,\n * which reconciles against it, and `doctor`, which reports it.\n */\nexport async function readMcpEntry(\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n): Promise<{ found: boolean; state: McpEntryState }> {\n const path = scope === 'project' ? join(cwd, '.mcp.json') : join(home, '.claude.json');\n // ONLY \"it is not there\" is an absence. A permission or filesystem error on a\n // file that DOES exist says nothing about what is registered in it, and\n // treating it as missing sent the refresh on to `claude mcp add` over a\n // registration it had never read: a failed add then looked like a machine\n // that simply lacks the tooling, and `tenjin update` exited 0 over whatever\n // was actually in there.\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'ENOTDIR') return { found: false, state: 'absent' };\n return { found: true, state: 'unreadable' };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // NOT an absence: the harness's own file is there and unreadable to this\n // build, so neither \"register it\" nor \"it is missing\" is a true statement.\n return { found: true, state: 'unreadable' };\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return { found: true, state: 'absent' };\n if (servers === null || typeof servers !== 'object' || Array.isArray(servers)) {\n return { found: true, state: 'unreadable' };\n }\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME];\n if (entry === undefined) return { found: true, state: 'absent' };\n return { found: true, state: classifyMcpEntry(entry) };\n}\n\n/** Project scope is decided by the working directory as well as the flag:\n * `claude` writes `.mcp.json` beside the project it was run in. */\nasync function runClaudeMcpAdd(\n _command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n): Promise<void> {\n await exec('claude', ['mcp', 'add', MCP_SERVER_NAME, '-s', opts.scope, '--', 'tenjin', 'mcp'], {\n timeout: 20_000,\n cwd: opts.cwd,\n });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === 0n\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/** Only the status-line state that needs the user: one this install would not\n * touch, with the command that adds the footer beside it. */\nexport function statusLineProblems(ctx: CommandContext, result: StatusLineResult): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (result.warning !== undefined) {\n return [warn(`The live status line was not registered (${result.warning})`)];\n }\n if (result.state !== 'foreign') return [];\n return [\n warn('You already have a status line, so it was left exactly as it is.'),\n ' To show the live x402 footer beside it, run:',\n ' tenjin install --status-line compose',\n ...(result.compose === undefined\n ? []\n : [' or set this command yourself:', ` ${result.compose}`]),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. The file paths, entry counts and\n * data-handling detail stay in `--json` and the docs; the terminal only grows\n * a line when something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n project: boolean;\n hooks: HooksResult;\n permissions: AllowRuleResult;\n statusLine: StatusLineResult;\n mcp: McpRegistration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === 0n ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n // The first line only says \"set up\" when it is: a settings file this run\n // would not write to means nothing was set up, and hooks without the MCP\n // server point at a `request` tool that is not there.\n const blocked = s.hooks.skipped !== undefined;\n const needsMcp = !blocked && !s.mcp.registered;\n const where = s.project ? ' in this project' : '';\n const fund = paint(ctx.io, 'bold', 'tenjin wallet fund');\n return [\n blocked\n ? paint(ctx.io, 'yellow', `! Tenjin could not finish setting up Claude Code${where}`)\n : needsMcp\n ? paint(ctx.io, 'yellow', '! Almost done: Claude Code needs one command')\n : `${ok} Tenjin is set up for Claude Code${where}`,\n ...walletLines(ctx, ok, s.wallet),\n ` Spends at most $${limits.maxAutoSpend} a lookup, ${daily}`,\n ...(s.statusLine.state === 'ours' || s.statusLine.state === 'composed'\n ? [' Live status line on: each lookup names its provider while it runs']\n : []),\n ...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),\n '',\n blocked\n ? 'Next: fix the file above, then run tenjin install again'\n : needsMcp\n ? s.wallet.status === 'created'\n ? `Next: run the command above and ${fund}, then restart Claude Code`\n : 'Next: run the command above, then restart Claude Code'\n : s.wallet.status === 'created'\n ? `Next: ${fund}, then restart Claude Code`\n : 'Next: restart Claude Code',\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(ctx: CommandContext, issues: string[]): string[] {\n if (issues.length === 0) return [`${paint(ctx.io, 'green', '✓')} Tenjin is up to date`];\n return [paint(ctx.io, 'yellow', '! Tenjin is updated, but needs one fix'), ...issues];\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** Only what needs the user, each with the command that fixes it. */\nfunction problems(\n ctx: CommandContext,\n hooks: HooksResult,\n permissions: AllowRuleResult,\n statusLine: StatusLineResult,\n mcp: McpRegistration,\n): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const out: string[] = [];\n // The hooks and the permission rule share one settings file, so a file this\n // run would not touch is reported once, not once per writer.\n if (hooks.skipped !== undefined) {\n out.push(\n warn(\n hooks.warning ??\n `${hooks.path ?? 'Your Claude Code settings file'} was left untouched (${hooks.skipped}).`,\n ),\n );\n } else {\n if (hooks.warning !== undefined) out.push(warn(hooks.warning));\n if (permissions.warning !== undefined) out.push(warn(permissions.warning));\n }\n if (!mcp.registered) {\n // The reason stays in --json: raw exec output is noise here, the fix is not.\n out.push(warn('Could not add the request tool to Claude Code. Run:'));\n out.push(` ${mcp.command}`);\n }\n out.push(...statusLineProblems(ctx, statusLine));\n return out;\n}\n\n/**\n * THREE ANSWERS, NOT TWO. A settings file that cannot be read or parsed is not\n * a file without our entries, and collapsing the two let `refreshEveryInstall`\n * read a momentarily broken project settings file as confirmed absence and\n * strike the project off `install.routerProjects` for good: repairing the file\n * afterwards did not bring it back, so every later `tenjin update` from HOME\n * silently skipped it.\n */\ntype EntriesProbe =\n { state: 'present' } | { state: 'absent' } | { state: 'unreadable'; reason: string };\n\nasync function probeOurEntries(path: string, dataDir: string): Promise<EntriesProbe> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n // `unreadable` here is the inspection's own vocabulary for \"the file exists\n // and this build could not use it\"; a file that is simply not there comes\n // back as an empty, readable inspection rather than a refusal.\n return { state: 'unreadable', reason: found.refusal.reason };\n }\n const present = Object.values(found.hooks).some((list) =>\n list.some((entry) => ownsHookEntry(entry, dataDir)),\n );\n return present ? { state: 'present' } : { state: 'absent' };\n}\n\n/** Shared with `uninstall`: the prune this module's writer already performs. */\nexport { pruneHooks };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,YAAY,YAAY;AACjC,SAAS,iBAAiB;AAgC1B,IAAM,OAAO,UAAU,QAAQ;AAYxB,IAAM,uBAAuB;AAE7B,IAAM,aAAa;AAWnB,SAAS,SAAS,SAAkD;AACzE,SAAO,YAAY,OAAO,YAAY;AACxC;AAEO,SAAS,cAAc,SAA2B;AACvD,SAAO,kBAAkB,eAAe,OAAO,SAAS,OAAO,CAAC;AAClE;AAEO,SAAS,iBAAiB,SAA2B;AAC1D,SAAO,qBAAqB,eAAe,OAAO,SAAS,OAAO,CAAC;AACrE;AAGO,IAAM,kBAAkB,cAAc;AAQtC,SAAS,mBACd,OAA8D,CAAC,GACvD;AACR,MAAI,KAAK,YAAY,KAAM,QAAO,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG,WAAW,eAAe;AAC5F,SAAO,mBAAmB,KAAK,WAAW,QAAQ,CAAC;AACrD;AAGO,IAAM,qBAAqB;AAG3B,IAAM,iBAAiB;AAUvB,SAAS,iBAA4B;AAC1C,QAAM,UAAU,CAAC,YAAoB;AAAA,IACnC,EAAE,MAAM,WAAW,SAAS,SAAS,qBAAqB;AAAA,EAC5D;AACA,SAAO;AAAA,IACL,EAAE,OAAO,oBAAoB,OAAO,QAAQ,oBAAoB,EAAE;AAAA,IAClE,EAAE,OAAO,cAA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,OAAO;AAItB,WAAO,EAAE,OAAO,cAAc,QAAQ,MAAM,QAAQ,OAAO;AAAA,EAC7D;AACA,QAAM,UAAU,OAAO,OAAO,MAAM,KAAK,EAAE;AAAA,IAAK,CAAC,SAC/C,KAAK,KAAK,CAAC,UAAU,cAAc,OAAO,OAAO,CAAC;AAAA,EACpD;AACA,SAAO,UAAU,EAAE,OAAO,UAAU,IAAI,EAAE,OAAO,SAAS;AAC5D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/progress.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { open, opendir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\n\n/**\n * The live status line's evidence: what this session is looking up right now,\n * which provider is actually being called, and what it cost.\n *\n * DISPLAY ONLY, AND STRICTLY DOWNSTREAM. Nothing here is read by the gate, the\n * decision, the spend policy or the paying leg; every write is best effort and\n * every failure is swallowed, so a full disk or a read-only data dir loses the\n * footer and changes no routing or payment outcome. That is the whole contract\n * this module has to keep.\n *\n * KEYED TO THE SESSION, NEVER GUESSED FROM IT. A record lives under the SHA-256\n * of the harness's own `session_id`, so the renderer for one session cannot see\n * another's. The hook knows that id; the tool, which runs inside the MCP server\n * process, does not, so it resolves the session in one of exactly two ways:\n *\n * - BY BINDING. An `execute` decision leaves an `id-<hash>.json` marker in the\n * session that produced it, and the model passes that id back on the tool\n * call. Resolving through the marker is proof, not inference.\n * - BY SOLE ACTIVITY. With no id, the request belongs to the only session that\n * has been active recently, and when two have been, it belongs to neither as\n * far as this module is concerned: {@link resolveProgressSession} returns\n * null and nothing is written. A missing footer is the correct failure;\n * showing one session's lookup in another session's terminal is not.\n */\n\nconst PROGRESS_DIR = 'progress';\n/** The binding marker's prefix, so it can never be read back as a call record. */\nconst BINDING_PREFIX = 'id-';\n/** A pre-call redirect's marker, keyed by the harness's `tool_use_id`. */\nconst OFFER_PREFIX = 'offer-';\n/** The session's own liveness touch, likewise outside the call-record pattern. */\nconst SESSION_FILE = 'session.json';\n/** Call records are named by a 64-hex digest and nothing else is read as one. */\nconst CALL_FILE_RE = /^[a-f0-9]{64}\\.json$/;\n\n/** An in-flight call older than this is shown as stale, never as running. */\nexport const STALE_AFTER_MS = 90_000;\n/**\n * How long a state stays on the footer once nothing has replaced it. The demo\n * holds each one for about ten seconds, which is what makes a decision that\n * takes a second readable at a one-second refresh; after that the line is\n * `x402 · ready` again.\n */\nexport const RECENT_MS = 10_000;\n/** Older than this and a record is ignored by the renderer and pruned on write. */\nexport const EXPIRY_MS = 10 * 60_000;\n/** How recently a session must have been touched to claim an id-less request. */\nexport const SESSION_ACTIVE_MS = 10 * 60_000;\n/** Above this many files a session directory is reported rather than scanned. */\nconst MAX_RECORDS = 256;\n/** A ceiling on the root scan. {@link pruneSessions} keeps it far below this:\n * a directory is one LIVE session, not one session this machine ever had. */\nconst MAX_SESSIONS = 4_096;\n/** A record larger than this is damaged or not ours; it is skipped unread. */\nconst MAX_RECORD_BYTES = 4_096;\n\nexport type ProgressPhase = 'routing' | 'calling' | 'done';\n\n/** The two markers: a session's liveness touch and a decision-id binding. */\ninterface Stamp {\n version: 1;\n at: number;\n}\n\n/** What one call looks like on disk. Every string is already masked and bounded. */\ninterface SavedProgress extends Stamp {\n phase: ProgressPhase;\n /** The tool whose activity this is, as the footer names it. */\n operation: string;\n /** What the state SAYS: the outcome on `done`, and on an in-flight record the\n * stage, when it is not the tool's own `selecting service`. */\n outcome?: string;\n /** Host plus path of the provider actually called, without a scheme. */\n endpoint?: string;\n /** The call's parameters as compact JSON. */\n parameters?: string;\n /** What the provider was paid, as USD. */\n price?: string;\n}\n\nexport interface ProgressStep {\n phase: ProgressPhase;\n operation?: string;\n outcome?: string;\n /** The executed provider's URL. It can differ from the hint's suggestion. */\n provider?: string;\n parameters?: unknown;\n price?: string;\n}\n\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\n\nfunction bounded(value: string, limit: number): string {\n const chars = Array.from(value);\n return chars.length <= limit ? value : `${chars.slice(0, limit - 1).join('')}…`;\n}\n\n/**\n * Provider text reaches a terminal here, so it is treated as hostile: control\n * characters, format characters and directional overrides are replaced before\n * anything is written, and again before anything is printed. A footer that can\n * be made to repaint the line above it is a spoofing surface, not a display.\n */\nexport function sanitize(value: string, limit: number): string {\n return bounded(\n value\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim(),\n limit,\n );\n}\n\n/**\n * The CLI's own redaction, behind a dynamic import ON PURPOSE: the rule corpus\n * and the BIP-39 wordlist are a real parse cost, the renderer runs once a\n * second, and only the write path needs them. `dist-chunks.test.ts` pins it.\n */\nasync function clean(value: string, limit: number): Promise<string> {\n const { mask } = await import('../lib/redact');\n return sanitize(mask(value), limit);\n}\n\n/** Host plus path, which is what names a provider to a person watching. */\nasync function endpointOf(value: string): Promise<string> {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return 'invalid endpoint';\n }\n if (url.username !== '' || url.password !== '') return 'invalid endpoint';\n return clean(`${url.host}${url.pathname === '/' ? '' : url.pathname}`, 110);\n}\n\nasync function parametersOf(value: unknown): Promise<string | undefined> {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json === undefined ? undefined : clean(json, 180);\n}\n\nexport function sessionDir(dataDir: string, sessionId: string): string {\n return join(dataDir, PROGRESS_DIR, digest(sessionId));\n}\n\n/** A fresh key for one call, so two overlapping lookups never share a record. */\nexport function newCallId(): string {\n return randomUUID();\n}\n\n/**\n * Mark this session live, so an id-less tool call made from it can be\n * attributed. Written on every hook event, including the ones that route\n * nothing: an open session has to be distinguishable from a closed one.\n */\nexport async function noteSession(\n dataDir: string,\n sessionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), SESSION_FILE), { version: 1, at: now });\n}\n\n/** Record that this decision id was produced in this session. */\nexport async function bindDecision(\n dataDir: string,\n sessionId: string,\n decisionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${BINDING_PREFIX}${digest(decisionId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\n/**\n * ONE ROUTING ANSWER PER LOOKUP. The pre-call hook marks the native call it\n * redirected, by the harness's own `tool_use_id`, and the after-call hook reads\n * the mark before it asks again about the same call. Expires and is pruned like every\n * other record here.\n */\nexport async function markOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\nexport async function wasOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<boolean> {\n const path = join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`);\n const stamp = await readStamp(path);\n return stamp !== null && now - stamp.at <= EXPIRY_MS;\n}\n\n/**\n * Which session directory a tool call belongs to, or null for \"cannot tell\".\n * Null is a normal answer and its only consequence is a footer that stays quiet.\n */\nexport async function resolveProgressSession(\n dataDir: string,\n opts: { id?: string; now?: number } = {},\n): Promise<string | null> {\n const now = opts.now ?? Date.now();\n const root = join(dataDir, PROGRESS_DIR);\n let names: string[];\n try {\n const directory = await opendir(root);\n names = [];\n for await (const entry of directory) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) names.push(entry.name);\n if (names.length >= MAX_SESSIONS) break;\n }\n } catch {\n return null;\n }\n if (opts.id !== undefined && opts.id.length > 0) {\n const marker = `${BINDING_PREFIX}${digest(opts.id)}.json`;\n for (const name of names) {\n const bound = await readStamp(join(root, name, marker));\n if (bound !== null && now - bound.at <= EXPIRY_MS) return join(root, name);\n }\n // A stale or unknown id says nothing about which session asked, so the\n // sole-activity rule below still applies rather than a wrong attribution.\n }\n const live: string[] = [];\n for (const name of names) {\n const touched = await readStamp(join(root, name, SESSION_FILE));\n if (touched !== null && now - touched.at <= SESSION_ACTIVE_MS) live.push(name);\n if (live.length > 1) return null;\n }\n return live.length === 1 ? join(root, live[0] as string) : null;\n}\n\n/**\n * Record one step of one call. The caller holds the directory (from\n * {@link sessionDir} or {@link resolveProgressSession}) and the call id, so a\n * step never has to re-resolve anything on the hot path.\n */\nexport async function writeProgress(\n directory: string,\n callId: string,\n step: ProgressStep,\n now = Date.now(),\n): Promise<void> {\n const endpoint = step.provider === undefined ? undefined : await endpointOf(step.provider);\n const parameters =\n step.parameters === undefined ? undefined : await parametersOf(step.parameters);\n const saved: SavedProgress = {\n version: 1,\n at: now,\n phase: step.phase,\n operation: sanitize(step.operation ?? 'request', 24) || 'request',\n ...(step.outcome !== undefined ? { outcome: sanitize(step.outcome, 40) } : {}),\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(parameters !== undefined ? { parameters } : {}),\n ...(step.price !== undefined ? { price: sanitize(step.price, 24) } : {}),\n };\n await write(join(directory, `${digest(callId)}.json`), saved);\n}\n\nexport interface LookupFooter {\n /** A decision is in flight. */\n routing(): Promise<void>;\n /** The EXECUTED provider, which can differ from what the hint suggested. */\n calling(step: { provider: string; parameters?: unknown }): Promise<void>;\n /** The outcome, and what the provider was paid for it. */\n done(\n outcome: string,\n step?: { provider?: string; parameters?: unknown; price?: string },\n ): Promise<void>;\n}\n\n/** A footer for a session this call cannot be attributed to: it writes nothing. */\nconst SILENT: LookupFooter = {\n routing: async () => undefined,\n calling: async () => undefined,\n done: async () => undefined,\n};\n\n/**\n * The `request` tool's footer: the session is resolved ONCE, at the top of the\n * call, and each later step is one small write. An unresolvable session yields\n * {@link SILENT}, and the lookup runs exactly as it would have.\n */\nexport async function openLookupFooter(\n dataDir: string,\n opts: { id?: string; operation?: string; now?: () => number } = {},\n): Promise<LookupFooter> {\n const now = opts.now ?? Date.now;\n const directory = await resolveProgressSession(dataDir, {\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n now: now(),\n }).catch(() => null);\n if (directory === null) return SILENT;\n const callId = newCallId();\n const operation = opts.operation ?? 'request';\n const step = async (patch: ProgressStep): Promise<void> => {\n await writeProgress(directory, callId, { operation, ...patch }, now());\n };\n return {\n routing: async () => {\n await step({ phase: 'routing' });\n await pruneProgress(directory, now());\n },\n calling: async (calling) => step({ phase: 'calling', ...calling }),\n done: async (outcome, detail) => step({ phase: 'done', outcome, ...detail }),\n };\n}\n\n/**\n * Remove records past {@link EXPIRY_MS}. Run from a writer, never from the\n * renderer: the footer refreshes once a second and must stay read-only.\n */\nexport async function pruneProgress(directory: string, now = Date.now()): Promise<void> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record === null || now - record.at > EXPIRY_MS) {\n await rm(join(directory, entry.name), { force: true }).catch(() => undefined);\n }\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\n/**\n * Remove the directories of sessions that are over.\n *\n * WITHOUT THIS THE ROOT ONLY GROWS, one directory per session this machine has\n * ever had, and a root big enough to hit {@link MAX_SESSIONS} would leave\n * {@link resolveProgressSession} scanning an arbitrary subset that need not\n * contain the session asking. Run from the hook, which is the one writer that\n * fires on every turn; a directory whose session is still live is never touched.\n */\nexport async function pruneSessions(dataDir: string, now = Date.now()): Promise<void> {\n const root = join(dataDir, PROGRESS_DIR);\n try {\n const directory = await opendir(root);\n let seen = 0;\n for await (const entry of directory) {\n if (++seen > MAX_SESSIONS) return;\n if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;\n const path = join(root, entry.name);\n const session = await readStamp(join(path, SESSION_FILE));\n if (session !== null && now - session.at <= SESSION_ACTIVE_MS) continue;\n // The touch is gone or old, so the only thing that can keep this\n // directory is a record still inside the renderer's window.\n if (await hasLiveRecord(path, now)) continue;\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\nasync function hasLiveRecord(directory: string, now: number): Promise<boolean> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return true;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\n/**\n * The footer for one session: one line, bounded, sanitized, and empty of\n * everything but this session's own calls. Read-only by construction.\n */\nexport async function renderProgress(\n dataDir: string,\n sessionId: string,\n options: { now?: number; columns?: number } = {},\n): Promise<string> {\n const now = options.now ?? Date.now();\n // The harness truncates to the real terminal width, and `COLUMNS` rarely\n // survives into a status-line process, so the default is a wide terminal\n // rather than a narrow one: cutting a provider's path off at 80 columns on a\n // 200-column terminal loses exactly the part worth reading.\n const columns = Math.max(45, Math.min(400, options.columns || 160));\n const directory = sessionDir(dataDir, sessionId);\n const records: SavedProgress[] = [];\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return bounded('x402 · activity exceeds display limit', columns);\n if (!entry.isFile() || !CALL_FILE_RE.test(entry.name)) continue;\n const record = await readCall(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) records.push(record);\n }\n } catch (error) {\n // A SESSION WITH NO DIRECTORY IS IDLE, not broken: it has simply not looked\n // anything up yet, and the router being on is the thing the idle line says.\n // Any OTHER read failure is this display failing, and a display that failed\n // prints nothing rather than a status it did not read.\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? READY : '';\n }\n const running = records\n .filter((row) => row.phase !== 'done' && now - row.at <= holdMs(row))\n .sort((a, b) => b.at - a.at);\n // Only a LOOKUP goes stale out loud. A hook decision has a five-second budget,\n // so one still in flight after its hold is a dead hook, and the footer says\n // ready rather than naming a stage nothing is working on.\n const stale = records.filter(\n (row) => row.phase !== 'done' && now - row.at > holdMs(row) && row.operation === 'request',\n );\n const finished = records\n .filter((row) => row.phase === 'done' && now - row.at <= RECENT_MS)\n .sort((a, b) => b.at - a.at);\n const head = running[0] ?? finished[0] ?? stale.sort((a, b) => b.at - a.at)[0];\n if (head === undefined) return READY;\n // OVERLAPPING CALLS ARE COUNTED, NOT HIDDEN. The newest running call is the\n // one worth naming; the rest are a count, because a second endpoint and its\n // parameters do not fit a line beside the first.\n const alsoRunning = running.length - (running[0] === head ? 1 : 0);\n const suffix = alsoRunning > 0 ? ` · +${alsoRunning} more` : '';\n return bounded(`${line(head, now)}${suffix}`, columns);\n}\n\n/** What the footer says when this session has nothing running or just finished.\n * It is the visible proof that the router is on, so it is never blank. */\nconst READY = 'x402 · ready';\n\n/**\n * How long this state holds the line. A lookup in flight holds it until it\n * lands, because a provider call can take a minute; everything else holds it\n * for {@link RECENT_MS}, which is how the demo reads: one state per second or\n * so, each one still there when the next arrives.\n */\nfunction holdMs(row: SavedProgress): number {\n return row.phase !== 'done' && row.operation === 'request' ? STALE_AFTER_MS : RECENT_MS;\n}\n\n/**\n * One call, as the footer says it: `x402 · <tool>: <state> <host/path> ·\n * <parameters> · <price>`. Every field is sanitized AGAIN here, because what is\n * on disk is input to this process even when this process wrote it.\n */\nfunction line(row: SavedProgress, now: number): string {\n const operation = sanitize(row.operation, 24) || 'request';\n if (row.phase !== 'done' && now - row.at > STALE_AFTER_MS) {\n return `x402 · ${operation}: stale, no outcome recorded`;\n }\n // `selecting service` is the demo's own word for a decision in flight, and a\n // stage the hook names for itself wins over it.\n const state =\n row.phase === 'routing'\n ? sanitize(row.outcome ?? 'selecting service', 40)\n : row.phase === 'calling'\n ? 'calling'\n : sanitize(row.outcome ?? 'done', 40);\n return (\n `x402 · ${operation}: ${state}` +\n (row.endpoint !== undefined ? ` ${sanitize(row.endpoint, 110)}` : '') +\n (row.parameters !== undefined ? ` · ${sanitize(row.parameters, 180)}` : '') +\n (row.price !== undefined ? ` · ${sanitize(row.price, 24)}` : '')\n );\n}\n\nasync function write(path: string, body: Stamp | SavedProgress): Promise<void> {\n try {\n await writeFileAtomic(path, JSON.stringify(body), { mode: 0o600, dirMode: 0o700 });\n } catch {\n // The footer is the only thing that can be lost here, by design.\n }\n}\n\n/** A marker's timestamp, or null for absent, damaged or not ours. */\nasync function readStamp(path: string): Promise<Stamp | null> {\n return stampOf(await readJson(path));\n}\n\nfunction stampOf(row: Record<string, unknown> | null): Stamp | null {\n if (row === null) return null;\n return row.version === 1 && typeof row.at === 'number' && Number.isFinite(row.at)\n ? { version: 1, at: row.at }\n : null;\n}\n\n/** A call record, or null. Every field is re-checked: what is on disk is input. */\nasync function readCall(path: string): Promise<SavedProgress | null> {\n const row = await readJson(path);\n const stamp = stampOf(row);\n if (row === null || stamp === null || typeof row.operation !== 'string') return null;\n if (!['routing', 'calling', 'done'].includes(row.phase as string)) return null;\n const optional = ['outcome', 'endpoint', 'parameters', 'price'] as const;\n if (!optional.every((key) => row[key] === undefined || typeof row[key] === 'string')) return null;\n return {\n ...stamp,\n phase: row.phase as ProgressPhase,\n operation: row.operation,\n ...Object.fromEntries(\n optional.filter((key) => row[key] !== undefined).map((key) => [key, row[key]]),\n ),\n };\n}\n\n/**\n * One bounded JSON object, or null. `O_NOFOLLOW` because these files live under\n * a directory the user can write: a symlink planted here must not turn a footer\n * read into a read of something else.\n */\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => undefined);\n if (file === undefined) return null;\n try {\n if ((await file.stat()).size > MAX_RECORD_BYTES) return null;\n const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_RECORD_BYTES) return null;\n const parsed: unknown = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));\n return parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)\n ? null\n : (parsed as Record<string, unknown>);\n } catch {\n return null;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