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
|
@@ -0,0 +1 @@
|
|
|
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 type PaymentMode,\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 mode?: PaymentMode;\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 | null;\n policyEnforcement: PolicyEnforcement;\n /** The pending reservation to commit (on settlement) or release (on abort).\n * Present when the spend may proceed, including an unlimited budget. */\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; mode?: PaymentMode },\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 mode: req.mode ?? 'automatic',\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 // Unlimited budgets still reserve to prevent identical in-flight requests.\n if (evaluation.decision === 'deny') {\n return base;\n }\n const reservation: Reservation = {\n id: randomUUID(),\n mode: req.mode ?? 'automatic',\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; mode?: PaymentMode } = {},\n ): Promise<void> {\n // Record transmitted exposure even if its reservation has expired.\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 automaticCommittedAtomic: (\n BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic) +\n ((reservation ? (reservation.mode ?? 'automatic') : (opts.mode ?? 'automatic')) ===\n 'manual'\n ? 0n\n : exposure)\n ).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;AA8GpB,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,MAAM,QAAQ,EAAE,OAAO,kBAAkB;AAAA,IACrF;AAAA,EACF;AAEA,QAAM,UAAU,OAAO,WAAkC;AACvD,UAAM,gBAAgB,MAAM,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,MAClE,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,iBAAe,WAAc,IAAmE;AAC9F,UAAM,MAAM,KAAK,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AACtD,WAAO,aAAa,UAAU,YAAY;AACxC,YAAM,QAAQ,IAAI;AAClB,YAAM,OAAO,MAAM,WAAW,IAAI;AAClC,UAAI,KAAK,YAAY,UAAa,CAAC,eAAe;AAChD,wBAAgB;AAChB,aAAK,YAAY,KAAK,OAAO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+
} from "./chunk-ZTFIQC4C.js";
|
|
9
9
|
import {
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
RETIRED_SKILL_NAMES,
|
|
11
|
+
onPath,
|
|
12
|
+
persistRouterDefaults,
|
|
13
|
+
readSkillFile,
|
|
14
|
+
skillFrontmatterName,
|
|
15
|
+
skillsDirsFor
|
|
16
|
+
} from "./chunk-AMG4SONW.js";
|
|
12
17
|
import {
|
|
13
|
-
|
|
14
|
-
} from "./chunk-
|
|
18
|
+
hasCode
|
|
19
|
+
} from "./chunk-2I4QTOLB.js";
|
|
15
20
|
import {
|
|
16
21
|
resolveContextSettings
|
|
17
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-5DOHKQ24.js";
|
|
18
23
|
import {
|
|
19
24
|
toMoney
|
|
20
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-O2JYBOUO.js";
|
|
26
|
+
import {
|
|
27
|
+
loadRawConfig
|
|
28
|
+
} from "./chunk-UNV4K45L.js";
|
|
21
29
|
import {
|
|
22
30
|
ensureStatusLine
|
|
23
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-WUU3BH6G.js";
|
|
24
32
|
import {
|
|
25
33
|
appendAllowlistRules,
|
|
26
34
|
claudeAdapter,
|
|
@@ -28,19 +36,64 @@ import {
|
|
|
28
36
|
inspectHooksFile,
|
|
29
37
|
ownsHookEntry,
|
|
30
38
|
writeHooks
|
|
31
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-ZDKEU2GF.js";
|
|
32
40
|
import {
|
|
33
41
|
CliError
|
|
34
42
|
} from "./chunk-JLEF5WHM.js";
|
|
35
43
|
|
|
36
44
|
// src/router/install.ts
|
|
37
45
|
import { execFile } from "node:child_process";
|
|
38
|
-
import { readFile } from "node:fs/promises";
|
|
46
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
39
47
|
import { homedir } from "node:os";
|
|
40
|
-
import { isAbsolute, join } from "node:path";
|
|
48
|
+
import { isAbsolute, join as join2 } from "node:path";
|
|
41
49
|
import { promisify } from "node:util";
|
|
50
|
+
|
|
51
|
+
// src/lib/skill-placement.ts
|
|
52
|
+
import { lstatSync } from "node:fs";
|
|
53
|
+
import { readdir, rm, rmdir } from "node:fs/promises";
|
|
54
|
+
import { join } from "node:path";
|
|
55
|
+
function isRealDirectory(path) {
|
|
56
|
+
try {
|
|
57
|
+
return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
58
|
+
} catch (err) {
|
|
59
|
+
if (hasCode(err, "ENOENT") || hasCode(err, "ENOTDIR")) return false;
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function removeOwnedSkill(name, skillsDir) {
|
|
64
|
+
if (!isRealDirectory(skillsDir)) {
|
|
65
|
+
return { changed: false };
|
|
66
|
+
}
|
|
67
|
+
const skillDir = join(skillsDir, name);
|
|
68
|
+
if (!isRealDirectory(skillDir)) {
|
|
69
|
+
return { changed: false };
|
|
70
|
+
}
|
|
71
|
+
const path = join(skillDir, "SKILL.md");
|
|
72
|
+
const read = await readSkillFile(path);
|
|
73
|
+
if (read.kind === "absent") return { changed: false };
|
|
74
|
+
if (read.kind !== "ok" || skillFrontmatterName(read.bytes.toString("utf8")) !== name) {
|
|
75
|
+
return { changed: false };
|
|
76
|
+
}
|
|
77
|
+
await rm(path, { force: true });
|
|
78
|
+
const rest = await readdir(skillDir).catch(() => null);
|
|
79
|
+
if (rest !== null && rest.length === 0) await rmdir(skillDir).catch(() => void 0);
|
|
80
|
+
return { changed: true };
|
|
81
|
+
}
|
|
82
|
+
async function removeRetiredSkills(home, project) {
|
|
83
|
+
const removed = [];
|
|
84
|
+
const dirs = [...skillsDirsFor(home), ...project ? skillsDirsFor(project) : []];
|
|
85
|
+
for (const dir of new Set(dirs)) {
|
|
86
|
+
for (const name of RETIRED_SKILL_NAMES) {
|
|
87
|
+
if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return removed;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/router/install.ts
|
|
42
94
|
var exec = promisify(execFile);
|
|
43
95
|
var HOOK_TIMEOUT_SECONDS = 5;
|
|
96
|
+
var AFTER_CALL_TIMEOUT_SECONDS = 15;
|
|
44
97
|
var ALLOW_RULE = REQUEST_TOOL;
|
|
45
98
|
function mcpScope(project) {
|
|
46
99
|
return project === true ? "project" : "user";
|
|
@@ -53,32 +106,45 @@ function mcpRemoveCommand(project) {
|
|
|
53
106
|
}
|
|
54
107
|
var MCP_ADD_COMMAND = mcpAddCommand();
|
|
55
108
|
function routerSettingsPath(opts = {}) {
|
|
56
|
-
if (opts.project === true) return
|
|
109
|
+
if (opts.project === true) return join2(opts.cwd ?? process.cwd(), ".claude", "settings.json");
|
|
57
110
|
return claudeSettingsPath(opts.homeDir ?? homedir());
|
|
58
111
|
}
|
|
59
112
|
var DELEGATION_MATCHER = "Agent|Task";
|
|
60
113
|
var NATIVE_MATCHER = "WebSearch|WebFetch";
|
|
61
114
|
function routerHookPlan() {
|
|
62
|
-
const handler = (command) => [
|
|
63
|
-
{ type: "command", command, timeout
|
|
115
|
+
const handler = (command, timeout = HOOK_TIMEOUT_SECONDS) => [
|
|
116
|
+
{ type: "command", command, timeout }
|
|
64
117
|
];
|
|
118
|
+
const afterCall = () => handler("tenjin hook shortfall", AFTER_CALL_TIMEOUT_SECONDS);
|
|
65
119
|
return [
|
|
66
120
|
{ event: "UserPromptSubmit", hooks: handler("tenjin hook prompt") },
|
|
67
121
|
{ event: "PreToolUse", matcher: NATIVE_MATCHER, hooks: handler("tenjin hook native") },
|
|
68
122
|
{ event: "PreToolUse", matcher: DELEGATION_MATCHER, hooks: handler("tenjin hook agent") },
|
|
69
|
-
{ event: "PostToolUse", matcher: NATIVE_MATCHER, hooks:
|
|
70
|
-
{
|
|
71
|
-
event: "PostToolUseFailure",
|
|
72
|
-
matcher: NATIVE_MATCHER,
|
|
73
|
-
hooks: handler("tenjin hook shortfall")
|
|
74
|
-
}
|
|
123
|
+
{ event: "PostToolUse", matcher: NATIVE_MATCHER, hooks: afterCall() },
|
|
124
|
+
{ event: "PostToolUseFailure", matcher: NATIVE_MATCHER, hooks: afterCall() }
|
|
75
125
|
];
|
|
76
126
|
}
|
|
77
127
|
var DISCLOSURE = [
|
|
78
|
-
"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.",
|
|
128
|
+
"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. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.",
|
|
79
129
|
"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.",
|
|
80
130
|
"What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere."
|
|
81
131
|
];
|
|
132
|
+
async function inferRefreshProject(cwd, home, dataDir, readRegistration) {
|
|
133
|
+
const hooks = await probeOurEntries(routerSettingsPath({ project: true, cwd }), dataDir);
|
|
134
|
+
if (hooks.state !== "present") return false;
|
|
135
|
+
const [cwdPath, homePath] = await Promise.all([
|
|
136
|
+
realpath(cwd),
|
|
137
|
+
realpath(home).catch((err) => {
|
|
138
|
+
if (err.code === "ENOENT" || err.code === "ENOTDIR") return null;
|
|
139
|
+
throw err;
|
|
140
|
+
})
|
|
141
|
+
]);
|
|
142
|
+
if (cwdPath !== homePath) return true;
|
|
143
|
+
const user = await readRegistration("user", cwd, home);
|
|
144
|
+
if (user.state !== "absent") return false;
|
|
145
|
+
const project = await readRegistration("project", cwd, home);
|
|
146
|
+
return project.state !== "absent";
|
|
147
|
+
}
|
|
82
148
|
async function runRouterInstall(args, ctx, deps = {}) {
|
|
83
149
|
const env = deps.env ?? process.env;
|
|
84
150
|
const home = deps.homeDir ?? homedir();
|
|
@@ -87,8 +153,9 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
87
153
|
fix: "Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`."
|
|
88
154
|
});
|
|
89
155
|
}
|
|
156
|
+
await loadRawConfig(ctx.dataDir);
|
|
90
157
|
const cwd = deps.cwd ?? process.cwd();
|
|
91
|
-
const project = args.project ?? (args.refresh === true &&
|
|
158
|
+
const project = args.project ?? (args.refresh === true && await inferRefreshProject(cwd, home, ctx.dataDir, deps.readMcpEntry ?? readMcpEntry));
|
|
92
159
|
const settingsPath = routerSettingsPath({
|
|
93
160
|
...project ? { project: true } : {},
|
|
94
161
|
homeDir: home,
|
|
@@ -109,6 +176,11 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
109
176
|
);
|
|
110
177
|
}
|
|
111
178
|
}
|
|
179
|
+
const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true);
|
|
180
|
+
const removedKeysLines = spend.removed.length > 0 ? [
|
|
181
|
+
`Removed retired settings: ${spend.removed.join(", ")}. Automatic router limits remain in effect; manual pay always requires consent.`
|
|
182
|
+
] : [];
|
|
183
|
+
const removedSkills = await removeRetiredSkills(home, project ? cwd : void 0);
|
|
112
184
|
const hooks = await writeHooks({
|
|
113
185
|
adapter: claudeAdapter,
|
|
114
186
|
homeDir: home,
|
|
@@ -139,13 +211,17 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
139
211
|
statusLine,
|
|
140
212
|
mcp,
|
|
141
213
|
refresh: true,
|
|
214
|
+
spend,
|
|
215
|
+
removedSkills,
|
|
142
216
|
scope: mcpScope(project)
|
|
143
217
|
},
|
|
144
|
-
humanLines:
|
|
218
|
+
humanLines: [
|
|
219
|
+
...refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),
|
|
220
|
+
...removedKeysLines
|
|
221
|
+
]
|
|
145
222
|
};
|
|
146
223
|
}
|
|
147
|
-
const
|
|
148
|
-
const { resolveWallet } = await import("./install-wallet-JPFTEC6H.js");
|
|
224
|
+
const { resolveWallet } = await import("./install-wallet-EYHELQMG.js");
|
|
149
225
|
const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
|
|
150
226
|
const effective = await resolveContextSettings(ctx);
|
|
151
227
|
const data = {
|
|
@@ -156,19 +232,23 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
156
232
|
spend: { ...spend, effective: effectiveLimits(effective.policy) },
|
|
157
233
|
mcp,
|
|
158
234
|
wallet,
|
|
159
|
-
disclosure: DISCLOSURE
|
|
235
|
+
disclosure: DISCLOSURE,
|
|
236
|
+
removedSkills
|
|
160
237
|
};
|
|
161
238
|
return {
|
|
162
239
|
data,
|
|
163
|
-
humanLines:
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
240
|
+
humanLines: [
|
|
241
|
+
...lines(ctx, {
|
|
242
|
+
project,
|
|
243
|
+
hooks,
|
|
244
|
+
permissions,
|
|
245
|
+
statusLine,
|
|
246
|
+
mcp,
|
|
247
|
+
wallet,
|
|
248
|
+
policy: effective.policy
|
|
249
|
+
}),
|
|
250
|
+
...removedKeysLines
|
|
251
|
+
]
|
|
172
252
|
};
|
|
173
253
|
}
|
|
174
254
|
async function ensureAllowRule(path) {
|
|
@@ -235,7 +315,7 @@ function classifyMcpEntry(entry) {
|
|
|
235
315
|
return runsRouter ? "ok" : "wrong-command";
|
|
236
316
|
}
|
|
237
317
|
async function readMcpEntry(scope, cwd, home) {
|
|
238
|
-
const path = scope === "project" ?
|
|
318
|
+
const path = scope === "project" ? join2(cwd, ".mcp.json") : join2(home, ".claude.json");
|
|
239
319
|
let raw;
|
|
240
320
|
try {
|
|
241
321
|
raw = await readFile(path, "utf8");
|
|
@@ -268,7 +348,7 @@ async function runClaudeMcpAdd(_command, opts) {
|
|
|
268
348
|
function effectiveLimits(policy) {
|
|
269
349
|
return {
|
|
270
350
|
maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,
|
|
271
|
-
sessionBudget: policy.sessionBudgetAtomic ===
|
|
351
|
+
sessionBudget: policy.sessionBudgetAtomic === null ? "no daily ceiling" : toMoney(policy.sessionBudgetAtomic.toString()).usd
|
|
272
352
|
};
|
|
273
353
|
}
|
|
274
354
|
function statusLineProblems(ctx, result) {
|
|
@@ -287,7 +367,7 @@ function statusLineProblems(ctx, result) {
|
|
|
287
367
|
function lines(ctx, s) {
|
|
288
368
|
const ok = paint(ctx.io, "green", "\u2713");
|
|
289
369
|
const limits = effectiveLimits(s.policy);
|
|
290
|
-
const daily = s.policy.sessionBudgetAtomic ===
|
|
370
|
+
const daily = s.policy.sessionBudgetAtomic === null ? "no daily limit" : `$${limits.sessionBudget} a day`;
|
|
291
371
|
const blocked = s.hooks.skipped !== void 0;
|
|
292
372
|
const needsMcp = !blocked && !s.mcp.registered;
|
|
293
373
|
const where = s.project ? " in this project" : "";
|
|
@@ -295,7 +375,7 @@ function lines(ctx, s) {
|
|
|
295
375
|
return [
|
|
296
376
|
blocked ? paint(ctx.io, "yellow", `! Tenjin could not finish setting up Claude Code${where}`) : needsMcp ? paint(ctx.io, "yellow", "! Almost done: Claude Code needs one command") : `${ok} Tenjin is set up for Claude Code${where}`,
|
|
297
377
|
...walletLines(ctx, ok, s.wallet),
|
|
298
|
-
`
|
|
378
|
+
` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`,
|
|
299
379
|
...s.statusLine.state === "ours" || s.statusLine.state === "composed" ? [" Live status line on: each lookup names its provider while it runs"] : [],
|
|
300
380
|
...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),
|
|
301
381
|
"",
|
|
@@ -348,6 +428,7 @@ async function probeOurEntries(path, dataDir) {
|
|
|
348
428
|
|
|
349
429
|
export {
|
|
350
430
|
HOOK_TIMEOUT_SECONDS,
|
|
431
|
+
AFTER_CALL_TIMEOUT_SECONDS,
|
|
351
432
|
ALLOW_RULE,
|
|
352
433
|
mcpScope,
|
|
353
434
|
mcpAddCommand,
|
|
@@ -363,4 +444,4 @@ export {
|
|
|
363
444
|
readMcpEntry,
|
|
364
445
|
statusLineProblems
|
|
365
446
|
};
|
|
366
|
-
//# sourceMappingURL=chunk-
|
|
447
|
+
//# sourceMappingURL=chunk-FHBGTOFA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/install.ts","../src/lib/skill-placement.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, realpath } 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 { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig } from '../lib/config';\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 and no\n * daemon to start: the hooks are plain command lines, the tool lives in an MCP\n * server the harness starts per session, and every other key in the settings\n * file is preserved byte for byte. The one process a hook starts is the free\n * docs fetch beside a search, which exits within `PREFETCH_TIMEOUT_MS`.\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;\n/**\n * The after-call entries' kill budget, longer than the rest for the one wait\n * any hook makes: a search the pre-call arm is fetching free docs for waits up\n * to `AUGMENT_WAIT_MS` for them, and when none came back and the search was\n * short, the gate is asked after that (`wire.test.ts` pins the sum). Every\n * other after-call event returns as fast as before, so the number is a\n * ceiling, not a cost. The pre-call entry stays at\n * {@link HOOK_TIMEOUT_SECONDS}: it starts that fetch and never waits for it.\n */\nexport const AFTER_CALL_TIMEOUT_SECONDS = 15;\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 * or to add the free docs the pre-call arm fetched to a search's results. A\n * failed call fires PostToolUseFailure rather than PostToolUse, so the second\n * takes both.\n */\nexport function routerHookPlan(): unknown[] {\n const handler = (command: string, timeout = HOOK_TIMEOUT_SECONDS) => [\n { type: 'command', command, timeout },\n ];\n const afterCall = () => handler('tenjin hook shortfall', AFTER_CALL_TIMEOUT_SECONDS);\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: afterCall() },\n { event: 'PostToolUseFailure', matcher: NATIVE_MATCHER, hooks: afterCall() },\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. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\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\nasync function inferRefreshProject(\n cwd: string,\n home: string,\n dataDir: string,\n readRegistration: typeof readMcpEntry,\n): Promise<boolean> {\n const hooks = await probeOurEntries(routerSettingsPath({ project: true, cwd }), dataDir);\n if (hooks.state !== 'present') return false;\n const [cwdPath, homePath] = await Promise.all([\n realpath(cwd),\n realpath(home).catch((err: NodeJS.ErrnoException) => {\n // A missing home cannot alias this existing project. Do not require it\n // to exist (or create it) just to refresh the project's own settings.\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;\n throw err;\n }),\n ]);\n if (cwdPath !== homePath) return true;\n\n // Home shares one hooks file between scopes. Preserve a project-only install,\n // but prefer user scope when both registrations exist (including alpha.18's\n // accidental duplicate). With neither registration, the default is user.\n // Unreadable/conflicting entries stay in their scope so reconciliation refuses\n // them instead of silently creating a registration in the other scope.\n const user = await readRegistration('user', cwd, home);\n if (user.state !== 'absent') return false;\n const project = await readRegistration('project', cwd, home);\n return project.state !== 'absent';\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 await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const cwd = deps.cwd ?? process.cwd();\n // `tenjin update` runs from home, where the hooks file cannot prove scope.\n // An explicit --project still wins, including for a project rooted at home.\n const project =\n args.project ??\n (args.refresh === true &&\n (await inferRefreshProject(cwd, home, ctx.dataDir, deps.readMcpEntry ?? readMcpEntry)));\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 spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\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. Config cleanup only removes retired keys;\n // the wallet, current limits and `spend.json` are unchanged. 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 spend,\n removedSkills,\n scope: mcpScope(project),\n },\n humanLines: [\n ...refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),\n ...removedKeysLines,\n ],\n };\n }\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 removedSkills,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n project,\n hooks,\n permissions,\n statusLine,\n mcp,\n wallet,\n policy: effective.policy,\n }),\n ...removedKeysLines,\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 === null\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 === null ? '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 ` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${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","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { readSkillFile, skillFrontmatterName, skillsDirsFor } from './skill-wiring';\nimport { RETIRED_SKILL_NAMES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/** Remove only our named skill file; preserve foreign skills and adjacent user files. */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n await rm(path, { force: true });\n const rest = await readdir(skillDir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(skillDir).catch(() => undefined);\n return { changed: true };\n}\n\n/** Refresh retires obsolete skills without needing their old packaged source. */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)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 @@ var o = [{
|
|
|
28
28
|
async function s(e) {
|
|
29
29
|
let a3;
|
|
30
30
|
try {
|
|
31
|
-
a3 = await import("./_esm-
|
|
31
|
+
a3 = await import("./_esm-OVVGTKHH.js");
|
|
32
32
|
} catch {
|
|
33
33
|
throw new r(i.MISSING_PROVIDER_LIBRARY, "viem installed (npm install viem)", "viem not found");
|
|
34
34
|
}
|
|
@@ -67,4 +67,4 @@ export {
|
|
|
67
67
|
a2 as a,
|
|
68
68
|
s
|
|
69
69
|
};
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
//# sourceMappingURL=chunk-FPUPBQHX.js.map
|
|
@@ -167,13 +167,13 @@ import {
|
|
|
167
167
|
} from "./chunk-XZKD7DIF.js";
|
|
168
168
|
import {
|
|
169
169
|
sha256
|
|
170
|
-
} from "./chunk-
|
|
171
|
-
import {
|
|
172
|
-
secp256k1
|
|
173
|
-
} from "./chunk-JRGFKVAZ.js";
|
|
170
|
+
} from "./chunk-6DCELMQA.js";
|
|
174
171
|
import {
|
|
175
172
|
keccak_256
|
|
176
173
|
} from "./chunk-KG3D7FIF.js";
|
|
174
|
+
import {
|
|
175
|
+
secp256k1
|
|
176
|
+
} from "./chunk-JRGFKVAZ.js";
|
|
177
177
|
import {
|
|
178
178
|
__commonJS,
|
|
179
179
|
__export,
|
|
@@ -14897,6 +14897,7 @@ export {
|
|
|
14897
14897
|
findByNetworkAndScheme,
|
|
14898
14898
|
createPublicClient,
|
|
14899
14899
|
http,
|
|
14900
|
+
PaymentRequirementsV2Schema,
|
|
14900
14901
|
x402Version,
|
|
14901
14902
|
HTTPFacilitatorClient,
|
|
14902
14903
|
x402HTTPClient,
|
|
@@ -14906,4 +14907,4 @@ export {
|
|
|
14906
14907
|
SIWX_HEADER,
|
|
14907
14908
|
buildSiwxHeader
|
|
14908
14909
|
};
|
|
14909
|
-
//# sourceMappingURL=chunk-
|
|
14910
|
+
//# sourceMappingURL=chunk-KTAW4KGH.js.map
|
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
-
writeFileAtomic
|
|
3
|
+
writeFileAtomic,
|
|
4
|
+
writeFileAtomicExclusive
|
|
4
5
|
} from "./chunk-JLEF5WHM.js";
|
|
5
6
|
|
|
6
7
|
// src/router/progress.ts
|
|
7
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
8
9
|
import { constants } from "node:fs";
|
|
9
|
-
import { open, opendir, rm } from "node:fs/promises";
|
|
10
|
+
import { lstat, open, opendir, rm } from "node:fs/promises";
|
|
10
11
|
import { join } from "node:path";
|
|
11
12
|
var PROGRESS_DIR = "progress";
|
|
12
13
|
var BINDING_PREFIX = "id-";
|
|
13
14
|
var OFFER_PREFIX = "offer-";
|
|
14
15
|
var SESSION_FILE = "session.json";
|
|
16
|
+
var REDIRECT_PREFIX = "redirect-";
|
|
17
|
+
var AUGMENT_PREFIX = "augment-";
|
|
18
|
+
var AUGMENT_BODY_SUFFIX = ".docs";
|
|
19
|
+
var QUERY_PREFIX = "query-";
|
|
15
20
|
var CALL_FILE_RE = /^[a-f0-9]{64}\.json$/;
|
|
16
21
|
var STALE_AFTER_MS = 9e4;
|
|
17
22
|
var RECENT_MS = 1e4;
|
|
18
23
|
var EXPIRY_MS = 10 * 6e4;
|
|
19
24
|
var SESSION_ACTIVE_MS = 10 * 6e4;
|
|
25
|
+
var AUGMENT_REPEAT_MS = 5 * 6e4;
|
|
20
26
|
var MAX_RECORDS = 256;
|
|
21
27
|
var MAX_SESSIONS = 4096;
|
|
22
28
|
var MAX_RECORD_BYTES = 4096;
|
|
@@ -80,6 +86,76 @@ async function wasOffered(dataDir, sessionId, toolUseId, now = Date.now()) {
|
|
|
80
86
|
const stamp = await readStamp(path);
|
|
81
87
|
return stamp !== null && now - stamp.at <= EXPIRY_MS;
|
|
82
88
|
}
|
|
89
|
+
async function markAugment(dataDir, sessionId, toolUseId, provider, now = Date.now()) {
|
|
90
|
+
const base = join(sessionDir(dataDir, sessionId), `${AUGMENT_PREFIX}${digest(toolUseId)}`);
|
|
91
|
+
const saved = { version: 1, at: now, provider: sanitize(provider, 60) };
|
|
92
|
+
return await write(`${base}.json`, saved) ? `${base}${AUGMENT_BODY_SUFFIX}` : null;
|
|
93
|
+
}
|
|
94
|
+
async function augmentOf(dataDir, sessionId, toolUseId, now = Date.now()) {
|
|
95
|
+
const base = join(sessionDir(dataDir, sessionId), `${AUGMENT_PREFIX}${digest(toolUseId)}`);
|
|
96
|
+
const row = await readJson(`${base}.json`);
|
|
97
|
+
const stamp = stampOf(row);
|
|
98
|
+
if (row === null || stamp === null || now - stamp.at > EXPIRY_MS) return null;
|
|
99
|
+
const provider = typeof row.provider === "string" ? sanitize(row.provider, 60) : "";
|
|
100
|
+
return { at: stamp.at, provider, body: `${base}${AUGMENT_BODY_SUFFIX}` };
|
|
101
|
+
}
|
|
102
|
+
async function claimQuery(dataDir, sessionId, agentId, query, now = Date.now()) {
|
|
103
|
+
const key = digest(JSON.stringify([agentId ?? "", query]));
|
|
104
|
+
const path = join(sessionDir(dataDir, sessionId), `${QUERY_PREFIX}${key}.json`);
|
|
105
|
+
const stamp = { version: 1, at: now };
|
|
106
|
+
try {
|
|
107
|
+
await writeFileAtomicExclusive(path, JSON.stringify(stamp), { mode: 384, dirMode: 448 });
|
|
108
|
+
return true;
|
|
109
|
+
} catch {
|
|
110
|
+
}
|
|
111
|
+
const last = await readStamp(path);
|
|
112
|
+
if (last === null || now - last.at <= AUGMENT_REPEAT_MS) return false;
|
|
113
|
+
return write(path, stamp);
|
|
114
|
+
}
|
|
115
|
+
function redirectPath(dataDir, sessionId, agentId) {
|
|
116
|
+
return join(sessionDir(dataDir, sessionId), `${REDIRECT_PREFIX}${digest(agentId ?? "")}.json`);
|
|
117
|
+
}
|
|
118
|
+
async function noteRedirect(dataDir, sessionId, agentId, redirect, now = Date.now()) {
|
|
119
|
+
const saved = {
|
|
120
|
+
version: 1,
|
|
121
|
+
at: now,
|
|
122
|
+
id: digest(redirect.id),
|
|
123
|
+
category: redirect.category,
|
|
124
|
+
delivered: false
|
|
125
|
+
};
|
|
126
|
+
await write(redirectPath(dataDir, sessionId, agentId), saved);
|
|
127
|
+
}
|
|
128
|
+
async function markDelivered(dataDir, decisionId, now = Date.now()) {
|
|
129
|
+
const directory = await resolveProgressSession(dataDir, { id: decisionId, now }).catch(
|
|
130
|
+
() => null
|
|
131
|
+
);
|
|
132
|
+
if (directory === null) return;
|
|
133
|
+
const id = digest(decisionId);
|
|
134
|
+
try {
|
|
135
|
+
const dir = await opendir(directory);
|
|
136
|
+
let count = 0;
|
|
137
|
+
for await (const entry of dir) {
|
|
138
|
+
if (!entry.isFile() || !entry.name.startsWith(REDIRECT_PREFIX)) continue;
|
|
139
|
+
if (++count > MAX_RECORDS) return;
|
|
140
|
+
const path = join(directory, entry.name);
|
|
141
|
+
const last = await readRedirect(path);
|
|
142
|
+
if (last?.id !== id) continue;
|
|
143
|
+
await write(path, { ...last, delivered: true });
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async function takeUndelivered(dataDir, sessionId, agentId, category, now = Date.now()) {
|
|
150
|
+
const path = redirectPath(dataDir, sessionId, agentId);
|
|
151
|
+
const last = await readRedirect(path);
|
|
152
|
+
if (last === null || last.delivered || last.category !== category) return false;
|
|
153
|
+
if (now - last.at > EXPIRY_MS) return false;
|
|
154
|
+
return rm(path).then(
|
|
155
|
+
() => true,
|
|
156
|
+
() => false
|
|
157
|
+
);
|
|
158
|
+
}
|
|
83
159
|
async function resolveProgressSession(dataDir, opts = {}) {
|
|
84
160
|
const now = opts.now ?? Date.now();
|
|
85
161
|
const root = join(dataDir, PROGRESS_DIR);
|
|
@@ -157,14 +233,25 @@ async function pruneProgress(directory, now = Date.now()) {
|
|
|
157
233
|
for await (const entry of dir) {
|
|
158
234
|
if (++count > MAX_RECORDS) return;
|
|
159
235
|
if (!entry.isFile() || entry.name === SESSION_FILE) continue;
|
|
160
|
-
const
|
|
236
|
+
const path = join(directory, entry.name);
|
|
237
|
+
const record = agesByMtime(entry.name) ? await mtimeOf(path) : await readStamp(path);
|
|
161
238
|
if (record === null || now - record.at > EXPIRY_MS) {
|
|
162
|
-
await rm(
|
|
239
|
+
await rm(path, { force: true }).catch(() => void 0);
|
|
163
240
|
}
|
|
164
241
|
}
|
|
165
242
|
} catch {
|
|
166
243
|
}
|
|
167
244
|
}
|
|
245
|
+
function agesByMtime(name) {
|
|
246
|
+
return name.startsWith(".") || name.startsWith(AUGMENT_PREFIX) && !name.endsWith(".json");
|
|
247
|
+
}
|
|
248
|
+
async function mtimeOf(path) {
|
|
249
|
+
try {
|
|
250
|
+
return { version: 1, at: (await lstat(path)).mtimeMs };
|
|
251
|
+
} catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
168
255
|
async function pruneSessions(dataDir, now = Date.now()) {
|
|
169
256
|
const root = join(dataDir, PROGRESS_DIR);
|
|
170
257
|
try {
|
|
@@ -240,7 +327,9 @@ function line(row, now) {
|
|
|
240
327
|
async function write(path, body) {
|
|
241
328
|
try {
|
|
242
329
|
await writeFileAtomic(path, JSON.stringify(body), { mode: 384, dirMode: 448 });
|
|
330
|
+
return true;
|
|
243
331
|
} catch {
|
|
332
|
+
return false;
|
|
244
333
|
}
|
|
245
334
|
}
|
|
246
335
|
async function readStamp(path) {
|
|
@@ -250,6 +339,12 @@ function stampOf(row) {
|
|
|
250
339
|
if (row === null) return null;
|
|
251
340
|
return row.version === 1 && typeof row.at === "number" && Number.isFinite(row.at) ? { version: 1, at: row.at } : null;
|
|
252
341
|
}
|
|
342
|
+
async function readRedirect(path) {
|
|
343
|
+
const row = await readJson(path);
|
|
344
|
+
const stamp = stampOf(row);
|
|
345
|
+
if (row === null || stamp === null) return null;
|
|
346
|
+
return typeof row.id === "string" && typeof row.category === "string" && typeof row.delivered === "boolean" ? { ...stamp, id: row.id, category: row.category, delivered: row.delivered } : null;
|
|
347
|
+
}
|
|
253
348
|
async function readCall(path) {
|
|
254
349
|
const row = await readJson(path);
|
|
255
350
|
const stamp = stampOf(row);
|
|
@@ -290,10 +385,16 @@ export {
|
|
|
290
385
|
bindDecision,
|
|
291
386
|
markOffered,
|
|
292
387
|
wasOffered,
|
|
388
|
+
markAugment,
|
|
389
|
+
augmentOf,
|
|
390
|
+
claimQuery,
|
|
391
|
+
noteRedirect,
|
|
392
|
+
markDelivered,
|
|
393
|
+
takeUndelivered,
|
|
293
394
|
writeProgress,
|
|
294
395
|
openLookupFooter,
|
|
295
396
|
pruneProgress,
|
|
296
397
|
pruneSessions,
|
|
297
398
|
renderProgress
|
|
298
399
|
};
|
|
299
|
-
//# sourceMappingURL=chunk-
|
|
400
|
+
//# sourceMappingURL=chunk-LSWVVSFX.js.map
|