tenjin-cli 0.1.0-alpha.5 → 0.1.0-alpha.7
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 +107 -33
- package/dist/{buy-YMXXVNFH.js → buy-XVOMNWKN.js} +18 -16
- package/dist/{candidate-H7FR4AU5.js → candidate-DJB2NNTG.js} +7 -8
- package/dist/{chunk-TXPPMK4L.js → chunk-2KIDDWQO.js} +5 -5
- package/dist/{chunk-3IRDP7TN.js → chunk-2L73UI6T.js} +6 -4
- package/dist/{chunk-3IRDP7TN.js.map → chunk-2L73UI6T.js.map} +1 -1
- package/dist/{chunk-ZW3B5LWX.js → chunk-2YX6LTCD.js} +5 -5
- package/dist/{chunk-HTDALK7M.js → chunk-5X4EBGGU.js} +15 -12
- package/dist/{chunk-HTDALK7M.js.map → chunk-5X4EBGGU.js.map} +1 -1
- package/dist/{chunk-RTJLLPFA.js → chunk-6S44OLND.js} +123 -23
- package/dist/chunk-6S44OLND.js.map +1 -0
- package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
- package/dist/chunk-7WDY4AXV.js.map +1 -0
- package/dist/{chunk-NFSOVL3C.js → chunk-BBUYCDSG.js} +12 -3
- package/dist/chunk-BBUYCDSG.js.map +1 -0
- package/dist/chunk-CYRYVZPN.js +213 -0
- package/dist/chunk-CYRYVZPN.js.map +1 -0
- package/dist/{chunk-MDDGEGSW.js → chunk-DAJ56EUU.js} +3 -3
- package/dist/{chunk-IOPWPMT2.js → chunk-DH6D6QIO.js} +5 -5
- package/dist/chunk-E6BNARCS.js +614 -0
- package/dist/chunk-E6BNARCS.js.map +1 -0
- package/dist/chunk-GABYDXWL.js +190 -0
- package/dist/chunk-GABYDXWL.js.map +1 -0
- package/dist/{chunk-LAM66WFJ.js → chunk-GM4RZUVU.js} +6 -8
- package/dist/{chunk-LAM66WFJ.js.map → chunk-GM4RZUVU.js.map} +1 -1
- package/dist/{chunk-ZDY2KY5X.js → chunk-GXYNLMUQ.js} +28 -11
- package/dist/chunk-GXYNLMUQ.js.map +1 -0
- package/dist/{chunk-PAUXMRSF.js → chunk-J6CVKC4M.js} +73 -2
- package/dist/chunk-J6CVKC4M.js.map +1 -0
- package/dist/{chunk-BIKAUVC2.js → chunk-KT2DGKFT.js} +40 -6
- package/dist/chunk-KT2DGKFT.js.map +1 -0
- package/dist/chunk-L6AV2Q73.js +105 -0
- package/dist/chunk-L6AV2Q73.js.map +1 -0
- package/dist/{chunk-CVX6JNGD.js → chunk-OTDI5FXG.js} +3 -5
- package/dist/{chunk-CVX6JNGD.js.map → chunk-OTDI5FXG.js.map} +1 -1
- package/dist/chunk-PIIWLEEG.js +337 -0
- package/dist/chunk-PIIWLEEG.js.map +1 -0
- package/dist/{chunk-PYNSGYBE.js → chunk-PLU3E63S.js} +249 -552
- package/dist/chunk-PLU3E63S.js.map +1 -0
- package/dist/{chunk-C444K6MI.js → chunk-RGFBBNGP.js} +42 -17
- package/dist/{chunk-C444K6MI.js.map → chunk-RGFBBNGP.js.map} +1 -1
- package/dist/chunk-SGK2B724.js +67 -0
- package/dist/chunk-SGK2B724.js.map +1 -0
- package/dist/{chunk-5SCU253N.js → chunk-UYP7G3GZ.js} +2 -2
- package/dist/{chunk-ZIYVN4CD.js → chunk-VZ3AJCO5.js} +3 -5
- package/dist/{chunk-ZIYVN4CD.js.map → chunk-VZ3AJCO5.js.map} +1 -1
- package/dist/{chunk-NJF2WENW.js → chunk-WDJTGVKN.js} +2 -2
- package/dist/{chunk-NJF2WENW.js.map → chunk-WDJTGVKN.js.map} +1 -1
- package/dist/{chunk-4WVKXKDK.js → chunk-WI5EOAQQ.js} +29 -238
- package/dist/chunk-WI5EOAQQ.js.map +1 -0
- package/dist/{chunk-QONTBYQW.js → chunk-WRWCDLVK.js} +4 -6
- package/dist/{chunk-QONTBYQW.js.map → chunk-WRWCDLVK.js.map} +1 -1
- package/dist/chunk-XBJ3VLWX.js +35 -0
- package/dist/chunk-XBJ3VLWX.js.map +1 -0
- package/dist/{chunk-ADJYSM45.js → chunk-ZEWY3RJ3.js} +27 -13
- package/dist/chunk-ZEWY3RJ3.js.map +1 -0
- package/dist/chunk-ZFE7STX7.js +143 -0
- package/dist/chunk-ZFE7STX7.js.map +1 -0
- package/dist/{cli-IW76QTN3.js → cli-7B2QNJG3.js} +231 -23
- package/dist/cli-7B2QNJG3.js.map +1 -0
- package/dist/{config-VCOS7P5K.js → config-SAQEQRFB.js} +5 -6
- package/dist/{doctor-WS65JG3V.js → doctor-ENJ22XWN.js} +10 -9
- package/dist/{publish-DSFWQRUN.js → edit-2QO5GQDU.js} +18 -16
- package/dist/index.js +1 -1
- package/dist/{inspect-SFJWUQHO.js → inspect-IPKKQB2S.js} +15 -14
- package/dist/{install-RVPQPCKH.js → install-7ZIYISQ7.js} +17 -17
- package/dist/outcome-NSDE2KAJ.js +20 -0
- package/dist/publish-7WIFFNFG.js +40 -0
- package/dist/read-5TQR7LCF.js +158 -0
- package/dist/read-5TQR7LCF.js.map +1 -0
- package/dist/{run-OMPKA43G.js → run-NPKIP26Y.js} +102 -28
- package/dist/{run-OMPKA43G.js.map → run-NPKIP26Y.js.map} +1 -1
- package/dist/search-63ELMRZH.js +24 -0
- package/dist/{send-3G4C64HJ.js → send-ENE47KQE.js} +7 -7
- package/dist/session-FZU4VFFE.js +87 -0
- package/dist/session-FZU4VFFE.js.map +1 -0
- package/dist/{wallet-PP22LAX7.js → wallet-OCCGEH6H.js} +7 -7
- package/dist/{wallet-B7KJS2R5.js → wallet-RBDVNZVR.js} +5 -5
- package/dist/wallet-RBDVNZVR.js.map +1 -0
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +2 -2
- package/skills/tenjin-publish/SKILL.md +12 -4
- package/skills/tenjin-search/SKILL.md +68 -12
- package/dist/chunk-2JQ5JSG6.js +0 -68
- package/dist/chunk-2JQ5JSG6.js.map +0 -1
- package/dist/chunk-4WVKXKDK.js.map +0 -1
- package/dist/chunk-ADJYSM45.js.map +0 -1
- package/dist/chunk-BIKAUVC2.js.map +0 -1
- package/dist/chunk-FU6MCSLG.js.map +0 -1
- package/dist/chunk-L4IHCN6B.js +0 -63
- package/dist/chunk-L4IHCN6B.js.map +0 -1
- package/dist/chunk-NFSOVL3C.js.map +0 -1
- package/dist/chunk-PAUXMRSF.js.map +0 -1
- package/dist/chunk-PYNSGYBE.js.map +0 -1
- package/dist/chunk-RTJLLPFA.js.map +0 -1
- package/dist/chunk-ZDY2KY5X.js.map +0 -1
- package/dist/cli-IW76QTN3.js.map +0 -1
- package/dist/outcome-GNYCSZ7J.js +0 -20
- package/dist/search-KOI6Y7P6.js +0 -24
- /package/dist/{buy-YMXXVNFH.js.map → buy-XVOMNWKN.js.map} +0 -0
- /package/dist/{candidate-H7FR4AU5.js.map → candidate-DJB2NNTG.js.map} +0 -0
- /package/dist/{chunk-TXPPMK4L.js.map → chunk-2KIDDWQO.js.map} +0 -0
- /package/dist/{chunk-ZW3B5LWX.js.map → chunk-2YX6LTCD.js.map} +0 -0
- /package/dist/{chunk-MDDGEGSW.js.map → chunk-DAJ56EUU.js.map} +0 -0
- /package/dist/{chunk-IOPWPMT2.js.map → chunk-DH6D6QIO.js.map} +0 -0
- /package/dist/{chunk-5SCU253N.js.map → chunk-UYP7G3GZ.js.map} +0 -0
- /package/dist/{config-VCOS7P5K.js.map → config-SAQEQRFB.js.map} +0 -0
- /package/dist/{doctor-WS65JG3V.js.map → doctor-ENJ22XWN.js.map} +0 -0
- /package/dist/{inspect-SFJWUQHO.js.map → edit-2QO5GQDU.js.map} +0 -0
- /package/dist/{outcome-GNYCSZ7J.js.map → inspect-IPKKQB2S.js.map} +0 -0
- /package/dist/{install-RVPQPCKH.js.map → install-7ZIYISQ7.js.map} +0 -0
- /package/dist/{publish-DSFWQRUN.js.map → outcome-NSDE2KAJ.js.map} +0 -0
- /package/dist/{search-KOI6Y7P6.js.map → publish-7WIFFNFG.js.map} +0 -0
- /package/dist/{wallet-B7KJS2R5.js.map → search-63ELMRZH.js.map} +0 -0
- /package/dist/{send-3G4C64HJ.js.map → send-ENE47KQE.js.map} +0 -0
- /package/dist/{wallet-PP22LAX7.js.map → wallet-OCCGEH6H.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/edit.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag, type PublishMode } from '../lib/config';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { sanitizeForTerminal } from '../lib/output';\nimport {\n deriveCard,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n buildPostUpdateBody,\n getOwnPost,\n updatePost,\n type OwnPost,\n type OwnPostCard,\n type PostUpdateInput,\n type ResourceCardUpdate,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin edit <postId>`: the agent-side twin of the web answer-card panel. With\n * no change flags it READS the owner-scoped post and prints it; with change flags\n * it merge-updates via `PUT /api/posts/<id>` — omitted key = keep, `--clear` sends\n * the explicit null (or the empty container) the server's merge clears on, and an\n * array flag REPLACES the stored array wholesale (`--add-question` is the append\n * convenience that reads first and sends the merged array).\n *\n * The gates are publish's, deliberately: the same deterministic scan over the new\n * body + card text (a live secret hard-blocks in every mode) and the same\n * publish.mode consent cascade, because an edit ships content to the same public\n * page a publish does.\n *\n * Unlike publish, the wallet is touched BEFORE consent, and that is a real\n * tradeoff, not a technicality: the before→after summary the user approves can\n * only be built from the stored post, and reading it is owner-scoped. The read\n * changes nothing on the server and burns no nonce, but on first use it\n * establishes a session key, so one wallet signature and a delegation persisted to\n * `~/.tenjin/session.json` precede any approval. What that delegation can DO is\n * scoped to the run: a no-flag show mints `read`, and only an invocation that\n * intends to write asks for `read+write`. We accept the remaining cost, because\n * the alternative is asking a human to approve a diff we cannot show them.\n *\n * Exit codes: 0 success (and the read-only show), 2 usage, 3 needs_confirmation /\n * non-bypassable publish_blocked, 4 a write failure after approval.\n */\n\nexport interface EditArgs {\n /** The post uuid to edit. */\n postId: string;\n /** Card array flags: REPLACE the stored array wholesale. */\n question?: string[];\n task?: string[];\n /** Append convenience: read the stored array, add, dedupe, send the merged array. */\n addQuestion?: string[];\n addTask?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n /** Post fields. */\n title?: string;\n /** Post price, decimal USD at the edge (O1). */\n price?: string;\n /** A Markdown file whose body (frontmatter stripped) replaces the stored body. */\n body?: string;\n excerpt?: string;\n /** Card fields to clear (repeatable); see CLEAR_FIELDS. */\n clear?: string[];\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n}\n\nexport interface EditDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runEdit(\n args: EditArgs,\n ctx: CommandContext,\n deps: EditDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n\n if (!UUID_RE.test(args.postId)) {\n throw new CliError('USAGE', `Invalid post id: ${JSON.stringify(args.postId)}`, {\n fix: 'Pass the post uuid from `tenjin publish`’s receipt or your desk.',\n });\n }\n // A mistyped --mode must never silently land on a looser mode and apply an edit\n // unconfirmed; validate it at the edge, exactly as publish does.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n // Every edge check that can fail on the FLAGS alone runs before the wallet: a\n // typo must cost nothing, not a signature and a round trip.\n rejectEmptyValues(args);\n assertAppendExclusivity(args);\n const clears = parseClears(args);\n const cardFlags = cardFlagsFrom(args);\n const priceAtomic = args.price !== undefined ? parseUsdToAtomic(args.price) : undefined;\n const bodyFile = args.body !== undefined ? await readBodyFile(args.body) : undefined;\n const wantsChange = hasChangeFlags(args);\n\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n // Least privilege, decided before the wallet is asked for anything: a show is a\n // READ, so it mints a read-scoped delegation rather than leaving a write-capable\n // one on disk for a command that never writes. A cached read+write session still\n // serves it, so this costs no extra signature.\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n scope: wantsChange ? 'read+write' : 'read',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n const client = {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n const stored = await getOwnPost(args.postId, auth, client);\n if (!wantsChange) return showReceipt(stored);\n\n // The append path merges onto the STORED array (exact-string dedupe) and sends\n // the result: the server replaces arrays wholesale, so there is no append there.\n if (args.addQuestion !== undefined && args.addQuestion.length > 0) {\n cardFlags.question = appendUnique(storedList(stored, 'questionsAnswered'), args.addQuestion);\n }\n if (args.addTask !== undefined && args.addTask.length > 0) {\n cardFlags.task = appendUnique(storedList(stored, 'tasksSupported'), args.addTask);\n }\n\n // deriveCard validates the set fields against the server's bounds and reports\n // them under the same dotted `resource.<field>` keys the server would.\n const intent: PostUpdateInput = {\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(bodyFile !== undefined ? { bodyMd: bodyFile.body } : {}),\n ...(args.excerpt !== undefined ? { excerpt: args.excerpt } : {}),\n ...(priceAtomic !== undefined ? { priceAtomic } : {}),\n ...withClears(deriveCard({}, cardFlags), clears, stored.resource),\n };\n\n // Diff before deciding anything: a no-op edit is not an edit. With nothing left\n // after pruning there is nothing to confirm, nothing new to scan, and no reason\n // to burn a nonce on a write that changes nothing. Exit 0 with the current post.\n const { input, lines: changes } = diffUpdate(stored, intent);\n if (changes.length === 0) return noChangeReceipt(stored);\n // Bounds-check the pruned body here so a miss is USAGE before the consent\n // prompt; updatePost rebuilds the same body for the wire (pure, so identical).\n buildPostUpdateBody(input);\n\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each edit asks you once. Set auto to apply clean edits automatically',\n );\n\n // Gate parity with publish (#38): the source project's own git remote slugs are\n // private-by-default, so text quoting them warns. Markers derive from the\n // CONTENT's project — the body file's own directory when there is one, else the\n // working directory — never from wherever the shell happens to be.\n const markerRoot = args.body !== undefined ? dirname(resolve(cwd, args.body)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n // The scan covers exactly what this edit SHIPS: the typed text behind the keys\n // that survived pruning, plus the body file only when the body itself survived.\n // Scanning the raw flags instead would block on a value that prunes away — a\n // secret already public in the stored scope, restated verbatim, would refuse an\n // unrelated title change while the same flags alone exit 0. A secret in a\n // surviving value still blocks in every mode, never cleared by --yes.\n const findings = dedupeFindings([\n ...(input.bodyMd !== undefined ? scan(bodyFile?.raw ?? '', scanContext) : []),\n ...scan(shippedTypedText(args, input), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the new content (it is never masked away by --yes), then re-run.',\n details: { mode: settings.mode, findings: blocking.map(publicFinding) },\n });\n }\n\n const notes = editNotes(args, stored, bodyFile, clears);\n for (const line of [...notes, ...changes]) ctx.io.stderr.write(`${line}\\n`);\n\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, changes.length), {\n fix: 'Review the changes, then re-run with --yes.',\n details: {\n mode: settings.mode,\n postId: stored.id,\n title: sanitizeForTerminal(stored.title),\n changes,\n ...(notes.length > 0 ? { notes } : {}),\n findings: warns.map(publicFinding),\n },\n });\n }\n\n const updated = await updatePost(args.postId, input, auth, client);\n return updateReceipt(updated, changes, notes, settings.mode);\n}\n\n// ---------------------------------------------------------------------------\n// Receipts.\n// ---------------------------------------------------------------------------\n\n/** The read half of the loop: the stored post + card, owner view. */\nfunction showReceipt(post: OwnPost): CommandResult {\n const price = toMoney(post.price);\n const card = post.resource;\n const lines = [\n `${sanitizeForTerminal(post.title)} (${sanitizeForTerminal(post.status)}), ${price.usd} USD (${price.atomic} atomic)`,\n `url: ${sanitizeForTerminal(post.url)}`,\n ...(hasText(post.excerpt) ? [`excerpt: ${preview(post.excerpt)}`] : []),\n ...cardLines(card),\n eligibilityLine(card),\n ];\n return { data: post, humanLines: lines };\n}\n\n/**\n * The applied-update receipt. `changes` (and `notes`) are mirrored INTO the data\n * as well as printed, the way publish mirrors its stderr warnings into the\n * receipt: an MCP client gets a discard sink for stderr, so a summary that lives\n * only there is a summary it can never show the user. `changes: []` is the\n * unambiguous machine signal that nothing was written.\n */\nfunction updateReceipt(\n post: OwnPost,\n changes: string[],\n notes: string[],\n mode: PublishMode,\n): CommandResult {\n const card = post.resource;\n const lines = [\n `Updated ${sanitizeForTerminal(post.title)} → ${sanitizeForTerminal(post.url)}`,\n eligibilityLine(card),\n ...(post.warnings ?? []).map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n // `mode` is echoed because a per-call --mode (or the MCP `mode` argument) is\n // otherwise invisible in a transcript: the receipt would look identical\n // whether the caller loosened the gate for this run or not.\n data: { ...post, mode, changes, ...(notes.length > 0 ? { notes } : {}) },\n humanLines: lines,\n };\n}\n\n/** Nothing to write: the post as it stands, and an empty change list to prove it. */\nfunction noChangeReceipt(post: OwnPost): CommandResult {\n return {\n data: { ...post, changes: [] },\n humanLines: [\n `No changes: every value given already matches ${sanitizeForTerminal(post.title)}. Nothing was written.`,\n ],\n };\n}\n\n/** The card fields that are set, one per line; nothing for a post with no card. */\nfunction cardLines(card: OwnPostCard | undefined): string[] {\n if (card === undefined) return [];\n const lines: string[] = [];\n const list = (label: string, values: string[] | null | undefined): void => {\n if (values !== undefined && values !== null && values.length > 0) {\n lines.push(\n `${label} (${values.length}): ${values.map((v) => sanitizeForTerminal(v)).join(' | ')}`,\n );\n }\n };\n list('questionsAnswered', card.questionsAnswered);\n list('tasksSupported', card.tasksSupported);\n for (const [label, value] of [\n ['scope', card.scope],\n ['exclusions', card.exclusions],\n ['artifactType', card.artifactType],\n ['temporalMode', card.temporalMode],\n ['asOf', card.asOf],\n ['validUntil', card.validUntil],\n ['provenance', card.provenanceSummary],\n ['methodology', card.methodologySummary],\n ['supersedesPostId', card.supersedesPostId],\n ] as const) {\n if (hasText(value)) lines.push(`${label}: ${preview(value)}`);\n }\n if (card.appliesTo !== undefined && card.appliesTo !== null) {\n for (const [key, values] of Object.entries(card.appliesTo)) {\n lines.push(\n `appliesTo ${sanitizeForTerminal(key)}: ${values.map((v) => sanitizeForTerminal(v)).join(', ')}`,\n );\n }\n }\n return lines;\n}\n\nfunction eligibilityLine(card: OwnPostCard | undefined): string {\n if (card === undefined) return 'No answer card (browse-only document).';\n const missing = missingSentences(card.cacheEligibleMissing).map(sanitizeForTerminal);\n if (card.cacheEligible) return 'Answer card is search-eligible.';\n return missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Answer card is not search-eligible.';\n}\n\n// ---------------------------------------------------------------------------\n// The before→after summary.\n// ---------------------------------------------------------------------------\n\n/**\n * Diff what the flags ASK for against what is stored, and return both the terse\n * summary and an input pruned to the fields that actually move.\n *\n * Pruning is not cosmetic. A card key that rides along unchanged still counts as a\n * card write server-side, which re-runs the embedding for a card nobody edited;\n * and on a post with NO card, a lone `scope: null` mints an all-default card row,\n * turning a browse-only document into a card-bearing one. Comparing first and\n * sending only the difference is what keeps `edit` idempotent.\n */\nfunction diffUpdate(\n stored: OwnPost,\n intent: PostUpdateInput,\n): { input: PostUpdateInput; lines: string[] } {\n const lines: string[] = [];\n const input: PostUpdateInput = {};\n\n // Both sides trimmed, because the server trims these before storing them: an\n // untrimmed compare would call \" x\" a change from \"x\" forever.\n const title = intent.title?.trim();\n if (title !== undefined && title !== stored.title) {\n input.title = title;\n lines.push(`title: ${preview(stored.title)} → ${preview(title)}`);\n }\n if (intent.priceAtomic !== undefined && intent.priceAtomic !== stored.price) {\n const before = toMoney(stored.price);\n const after = toMoney(intent.priceAtomic);\n input.priceAtomic = intent.priceAtomic;\n lines.push(\n `price: ${before.usd} USD (${before.atomic} atomic) → ${after.usd} USD (${after.atomic} atomic)`,\n );\n }\n if (intent.bodyMd !== undefined && intent.bodyMd !== stored.bodyMd) {\n input.bodyMd = intent.bodyMd;\n lines.push(`body: ${(stored.bodyMd ?? '').length} → ${intent.bodyMd.length} characters`);\n }\n const excerpt = intent.excerpt?.trim();\n if (excerpt !== undefined && excerpt !== (stored.excerpt ?? '')) {\n input.excerpt = excerpt;\n lines.push(`excerpt: ${preview(stored.excerpt)} → ${preview(excerpt)}`);\n }\n\n const card = diffCard(stored.resource, intent.resource);\n lines.push(...card.lines);\n if (card.card !== undefined) input.resource = card.card;\n\n // Empty means EMPTY: the caller reads no lines as \"this edit is a no-op\" and\n // skips the write, so a sentinel line here would report a change that isn't one.\n return { input, lines };\n}\n\n/**\n * How each card key is diffed. The Record over `keyof ResourceCardUpdate` is the\n * point: adding a field to the card type without saying how it diffs is a compile\n * error here, not a field that silently never reaches the wire. `none` marks a\n * field no flag and no clear can set today, so it can never appear in `next`;\n * giving one a flag means moving it to a real pass.\n */\ntype CardPass = 'list' | 'iso' | 'scalar' | 'map' | 'none';\nconst CARD_PASS = {\n questionsAnswered: 'list',\n tasksSupported: 'list',\n asOf: 'iso',\n validUntil: 'iso',\n scope: 'scalar',\n exclusions: 'scalar',\n artifactType: 'scalar',\n temporalMode: 'scalar',\n provenanceSummary: 'scalar',\n methodologySummary: 'scalar',\n supersedesPostId: 'scalar',\n appliesTo: 'map',\n mediaType: 'none',\n maintenanceCadence: 'none',\n reproductionMinutes: 'none',\n estimatedPaidInputCost: 'none',\n} as const satisfies Record<keyof ResourceCardUpdate, CardPass>;\n\n/** The card keys assigned to one pass, as a union of literal keys. */\ntype KeysIn<P extends CardPass> = {\n [K in keyof typeof CARD_PASS]: (typeof CARD_PASS)[K] extends P ? K : never;\n}[keyof typeof CARD_PASS];\n\nfunction keysIn<P extends CardPass>(pass: P): KeysIn<P>[] {\n return Object.entries(CARD_PASS)\n .filter(([, value]) => value === pass)\n .map(([key]) => key) as KeysIn<P>[];\n}\n\n/** The two card keys whose flag name differs from the field name. */\nconst CARD_LABEL: Partial<Record<keyof ResourceCardUpdate, string>> = {\n provenanceSummary: 'provenance',\n methodologySummary: 'methodology',\n};\nfunction cardLabel(key: keyof ResourceCardUpdate): string {\n return CARD_LABEL[key] ?? key;\n}\n\n/**\n * The card half of the diff. Every comparison treats an ABSENT stored value as\n * already-cleared, which is what makes clearing a field on a cardless post the\n * no-op it should be rather than a card-creating write.\n */\nfunction diffCard(\n stored: OwnPostCard | undefined,\n next: ResourceCardUpdate | undefined,\n): { card?: ResourceCardUpdate; lines: string[] } {\n const lines: string[] = [];\n const card: Record<string, unknown> = {};\n const keep = (key: keyof ResourceCardUpdate, value: unknown, line: string): void => {\n card[key] = value;\n lines.push(line);\n };\n if (next === undefined) return { lines };\n\n // Lists replace wholesale, so order counts; an absent stored list reads as empty.\n for (const key of keysIn('list')) {\n const after = next[key];\n if (after === undefined) continue;\n const old = stored?.[key] ?? [];\n if (sameList(old, after)) continue;\n const added = after.filter((v) => !old.includes(v));\n const detail =\n after.length === 0 ? ' (cleared)' : added.length > 0 ? ` (new: ${previewList(added)})` : '';\n keep(key, after, `${key}: ${old.length} → ${after.length}${detail}`);\n }\n\n // The timestamps compare as INSTANTS and are sent canonicalized. The server\n // echoes a timestamptz through toISOString(), while a flag carries whatever the\n // user typed, so \"2026-07-01T00:00:00Z\" and \"2026-07-01T00:00:00.000Z\" are the\n // same moment spelled two ways — comparing the spellings would re-write the\n // field on every single run.\n for (const key of keysIn('iso')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = isoInstant(stored?.[key]);\n const to = isoInstant(after);\n if (from === to) continue;\n keep(key, to, `${key}: ${preview(from)} → ${to === null ? '(cleared)' : preview(to)}`);\n }\n\n for (const key of keysIn('scalar')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = stored?.[key] ?? null;\n if (from === after) continue;\n keep(\n key,\n after,\n `${cardLabel(key)}: ${preview(from)} → ${after === null ? '(cleared)' : preview(after)}`,\n );\n }\n\n // appliesTo is one value, not a key count: a same-size swap (products=Base →\n // products=Vercel) has identical counts on both sides, so a count compare would\n // call a real change a no-op and a count RENDER would print it as one.\n for (const key of keysIn('map')) {\n const after = next[key];\n if (after === undefined) continue;\n const before = stored?.[key] ?? {};\n if (sameAppliesTo(before, after)) continue;\n keep(key, after, `${key}: ${appliesToPreview(before)} → ${appliesToPreview(after)}`);\n }\n\n return { ...(Object.keys(card).length > 0 ? { card: card as ResourceCardUpdate } : {}), lines };\n}\n\n/**\n * A timestamp as its canonical instant, so two spellings of one moment compare\n * equal. An unparseable value (never from a flag — validateIso ran — but possible\n * from a future server format) passes through rather than being silently dropped.\n */\nfunction isoInstant(value: string | null | undefined): string | null {\n if (value === undefined || value === null) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? new Date(ms).toISOString() : value;\n}\n\n/** Map equality: keys order-insensitive, each key's values order-sensitive. */\nfunction sameAppliesTo(a: Record<string, string[]>, b: Record<string, string[]>): boolean {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (!sameList(aKeys, bKeys)) return false;\n return aKeys.every((key) => sameList(a[key] ?? [], b[key] ?? []));\n}\n\n/** The advisory notes a --body edit needs, in the order a human reads them. */\nfunction editNotes(\n args: EditArgs,\n stored: OwnPost,\n bodyFile: BodyFile | undefined,\n clears: ClearField[],\n): string[] {\n if (bodyFile === undefined) return [];\n const notes: string[] = [];\n if (bodyFile.hadFrontmatter) {\n notes.push(\n 'note: frontmatter in the body file was ignored; metadata changes only through flags.',\n );\n }\n if (args.excerpt === undefined) {\n notes.push(\n `note: the excerpt stays as-is (${preview(stored.excerpt)}) and remains lexically indexed; the server does not re-derive it. Pass --excerpt to change it.`,\n );\n }\n // Only when asOf really is staying put: a run that clears it is already saying\n // so in the summary, and both lines together would contradict each other.\n const asOfMoves = args.asOf !== undefined || clears.includes('asOf');\n if (stored.resource?.temporalMode === 'snapshot' && !asOfMoves) {\n notes.push(\n `note: asOf is unchanged (${preview(stored.resource.asOf)}) on this snapshot card, and search freshness gating uses it. Pass --as-of to move it.`,\n );\n }\n return notes;\n}\n\n// ---------------------------------------------------------------------------\n// Flag parsing + validation.\n// ---------------------------------------------------------------------------\n\n/** The card fields `--clear` accepts, named as the flag that sets each one. */\nconst CLEAR_FIELDS = [\n 'scope',\n 'exclusions',\n 'asOf',\n 'validUntil',\n 'provenance',\n 'methodology',\n 'supersedesPostId',\n 'questionsAnswered',\n 'tasksSupported',\n 'appliesTo',\n] as const;\ntype ClearField = (typeof CLEAR_FIELDS)[number];\n\n/** clear name → the card key it targets. */\nconst CLEAR_KEY = {\n scope: 'scope',\n exclusions: 'exclusions',\n asOf: 'asOf',\n validUntil: 'validUntil',\n provenance: 'provenanceSummary',\n methodology: 'methodologySummary',\n supersedesPostId: 'supersedesPostId',\n questionsAnswered: 'questionsAnswered',\n tasksSupported: 'tasksSupported',\n appliesTo: 'appliesTo',\n} as const satisfies Record<ClearField, keyof ResourceCardUpdate>;\n\n/**\n * clear name → the value that clears its key server-side. Each value is typed as\n * the card field it lands on, so sending the wrong shape (a null where the merge\n * clears with `[]`, or an `[]` where it wants null) is a compile error, not a\n * validation_failed discovered in production.\n */\nconst CLEAR_VALUE: { [F in ClearField]: ResourceCardUpdate[(typeof CLEAR_KEY)[F]] } = {\n scope: null,\n exclusions: null,\n asOf: null,\n validUntil: null,\n provenance: null,\n methodology: null,\n supersedesPostId: null,\n questionsAnswered: [],\n tasksSupported: [],\n appliesTo: {},\n};\n\n/** clear name → the set-flags that would contradict it in the same invocation. */\nconst CLEAR_CONFLICTS: Record<ClearField, Array<keyof EditArgs>> = {\n scope: ['scope'],\n exclusions: ['exclusions'],\n asOf: ['asOf'],\n validUntil: ['validUntil'],\n provenance: ['provenance'],\n methodology: ['methodology'],\n supersedesPostId: [],\n questionsAnswered: ['question', 'addQuestion'],\n tasksSupported: ['task', 'addTask'],\n appliesTo: ['appliesTo'],\n};\n\n/** The CLI spelling of each arg key, for error messages. */\nconst FLAG_NAME: Record<string, string> = {\n question: '--question',\n task: '--task',\n addQuestion: '--add-question',\n addTask: '--add-task',\n scope: '--scope',\n exclusions: '--exclusions',\n appliesTo: '--applies-to',\n asOf: '--as-of',\n validUntil: '--valid-until',\n artifactType: '--artifact-type',\n temporalMode: '--temporal-mode',\n provenance: '--provenance',\n methodology: '--methodology',\n title: '--title',\n price: '--price',\n body: '--body',\n excerpt: '--excerpt',\n};\n\nconst CHANGE_KEYS: Array<keyof EditArgs> = [\n 'question',\n 'task',\n 'addQuestion',\n 'addTask',\n 'scope',\n 'exclusions',\n 'appliesTo',\n 'asOf',\n 'validUntil',\n 'artifactType',\n 'temporalMode',\n 'provenance',\n 'methodology',\n 'title',\n 'price',\n 'body',\n 'excerpt',\n 'clear',\n];\n\nfunction hasChangeFlags(args: EditArgs): boolean {\n return CHANGE_KEYS.some((key) => {\n const value = args[key];\n return Array.isArray(value) ? value.length > 0 : value !== undefined;\n });\n}\n\n/**\n * An explicit empty value is refused for every set-flag: `--scope \"\"` reads as\n * \"clear the scope\", but only `--clear scope` sends the null that clears it, and a\n * silently-sent empty string would set a blank field instead. One spelling per\n * intent, no ambiguity.\n */\nfunction rejectEmptyValues(args: EditArgs): void {\n for (const [key, flag] of Object.entries(FLAG_NAME)) {\n const value = args[key as keyof EditArgs];\n const empties =\n typeof value === 'string'\n ? [value]\n : Array.isArray(value)\n ? value.filter((v) => typeof v === 'string')\n : [];\n for (const v of empties) {\n if (v.trim().length === 0) {\n const clearable = (CLEAR_FIELDS as readonly string[]).includes(clearNameFor(key));\n throw new CliError('USAGE', `${flag} cannot be empty.`, {\n fix: clearable\n ? `Pass a value, or clear the field with \\`--clear ${clearNameFor(key)}\\`.`\n : 'Pass a value, or omit the flag to keep the stored one.',\n });\n }\n }\n }\n}\n\n/** The `--clear` name a set-flag arg key corresponds to (identity where they match). */\nfunction clearNameFor(key: string): string {\n if (key === 'question' || key === 'addQuestion') return 'questionsAnswered';\n if (key === 'task' || key === 'addTask') return 'tasksSupported';\n return key;\n}\n\nfunction assertAppendExclusivity(args: EditArgs): void {\n const both = (a: string[] | undefined, b: string[] | undefined): boolean =>\n a !== undefined && a.length > 0 && b !== undefined && b.length > 0;\n if (both(args.question, args.addQuestion)) {\n throw new CliError('USAGE', 'Pass either --question or --add-question, not both.', {\n fix: '--question replaces the stored questions; --add-question appends to them.',\n });\n }\n if (both(args.task, args.addTask)) {\n throw new CliError('USAGE', 'Pass either --task or --add-task, not both.', {\n fix: '--task replaces the stored tasks; --add-task appends to them.',\n });\n }\n}\n\nfunction parseClears(args: EditArgs): ClearField[] {\n const raw = args.clear ?? [];\n const out: ClearField[] = [];\n for (const name of raw) {\n if (!(CLEAR_FIELDS as readonly string[]).includes(name)) {\n throw new CliError('USAGE', `Cannot clear ${JSON.stringify(name)}.`, {\n fix: `Clearable fields: ${CLEAR_FIELDS.join(', ')}.`,\n });\n }\n const field = name as ClearField;\n for (const key of CLEAR_CONFLICTS[field]) {\n const value = args[key];\n const given = Array.isArray(value) ? value.length > 0 : value !== undefined;\n if (given) {\n throw new CliError(\n 'USAGE',\n `--clear ${field} contradicts ${FLAG_NAME[key as string] ?? String(key)}.`,\n { fix: 'Set the field or clear it, not both in the same run.' },\n );\n }\n }\n if (!out.includes(field)) out.push(field);\n }\n return out;\n}\n\nfunction cardFlagsFrom(args: EditArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The card this edit ASKS for: the validated set fields plus the clears. Built\n * from an allowlist (deriveCard's output keys and CLEAR_KEY) and never from a\n * spread of the GET, so a server-owned key (cacheEligible, cacheEligibleMissing,\n * schemaVersion) cannot reach a strictObject body that would reject it.\n *\n * What actually protects the server's D14 invariant (no card row on a browse-only\n * post) is diffCard: it defaults an absent stored value to already-cleared, so a\n * clear on a post with no card compares equal and prunes away. Dropping the clears\n * here as well is a deliberate redundant backstop, one step earlier and local to\n * the one condition that matters, because the cost of that invariant breaking is a\n * plain document silently becoming card-bearing.\n */\nfunction withClears(\n set: ResourceCardInput | undefined,\n clears: ClearField[],\n stored: OwnPostCard | undefined,\n): { resource?: ResourceCardUpdate } {\n const applicable = stored !== undefined ? clears : [];\n if (set === undefined && applicable.length === 0) return {};\n const card: Record<string, unknown> = { ...(set ?? {}) };\n for (const name of applicable) {\n card[CLEAR_KEY[name]] = CLEAR_VALUE[name];\n }\n return Object.keys(card).length > 0 ? { resource: card as ResourceCardUpdate } : {};\n}\n\ninterface BodyFile {\n /** The whole file, frontmatter included; what the scan reads. */\n raw: string;\n /** The Markdown below the frontmatter; what becomes bodyMd. */\n body: string;\n hadFrontmatter: boolean;\n}\n\nasync function readBodyFile(file: string): Promise<BodyFile> {\n let raw: string;\n try {\n raw = await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin edit <id> --body post.md`.',\n cause: err,\n });\n }\n const { frontmatter, body } = parseFrontmatter(raw);\n return { raw, body, hadFrontmatter: Object.keys(frontmatter).length > 0 };\n}\n\nfunction storedList(post: OwnPost, key: 'questionsAnswered' | 'tasksSupported'): string[] {\n return post.resource?.[key] ?? [];\n}\n\n/** Append, preserving order, skipping exact-string duplicates already stored. */\nfunction appendUnique(stored: string[], additions: string[]): string[] {\n const out = [...stored];\n for (const item of additions) {\n if (!out.includes(item)) out.push(item);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Scan input + message shaping (publish's, over the edit's new content).\n// ---------------------------------------------------------------------------\n\n/**\n * The text this invocation actually SHIPS, and only that. Two filters, each\n * closing a way the gate could fire on text the edit does not publish:\n *\n * - the key must have survived pruning. A flag whose value already matches the\n * stored one changes nothing, so its text is not \"new content\" at all; blocking\n * on it refuses an edit over a secret that is already public and that no flag\n * here can remove.\n * - the value must be one the user TYPED. The append path contributes its added\n * strings, never the merged array it sends, for the same reason.\n *\n * Everything that does ship is scanned, so a secret in a surviving value blocks in\n * every mode, never cleared by --yes.\n */\nfunction shippedTypedText(args: EditArgs, input: PostUpdateInput): string {\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n if (input.title !== undefined) add(args.title);\n if (input.excerpt !== undefined) add(args.excerpt);\n\n const card = input.resource;\n if (card === undefined) return parts.join('\\n');\n if (card.scope !== undefined) add(args.scope);\n if (card.exclusions !== undefined) add(args.exclusions);\n if (card.provenanceSummary !== undefined) add(args.provenance);\n if (card.methodologySummary !== undefined) add(args.methodology);\n if (card.asOf !== undefined) add(args.asOf);\n if (card.validUntil !== undefined) add(args.validUntil);\n if (card.questionsAnswered !== undefined) {\n for (const item of args.question ?? args.addQuestion ?? []) add(item);\n }\n if (card.tasksSupported !== undefined) {\n for (const item of args.task ?? args.addTask ?? []) add(item);\n }\n if (card.appliesTo !== undefined && args.appliesTo !== undefined) {\n // The parsed values, matching what actually ships on the card.\n for (const values of Object.values(parseAppliesToFlags(args.appliesTo))) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Edit blocked: the new content contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, changeCount: number): string {\n return warnCount > 0\n ? `Edit needs confirmation: ${changeCount} change(s), ${warnCount} finding(s).`\n : `Edit needs confirmation: ${changeCount} change(s).`;\n}\n\n// ---------------------------------------------------------------------------\n// Small formatting helpers.\n// ---------------------------------------------------------------------------\n\nconst PREVIEW_MAX = 60;\n/** A whole rendered line's budget: a max-size card is 8 keys × 20 × 120 chars. */\nconst LINE_MAX = 200;\n\n/** Terminal-safe, whitespace-collapsed, and capped: the one place values are cut. */\nfunction clip(value: string, max = PREVIEW_MAX): string {\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n return clean.length > max ? `${clean.slice(0, max)}…` : clean;\n}\n\n/** A short, terminal-safe rendering of a stored or new value for the summary. */\nfunction preview(value: string | null | undefined): string {\n if (value === undefined || value === null || value.length === 0) return '(unset)';\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n if (clean.length === 0) return '(unset)';\n return clean.length > PREVIEW_MAX\n ? `${JSON.stringify(clean.slice(0, PREVIEW_MAX))}…`\n : JSON.stringify(clean);\n}\n\nfunction previewList(values: string[]): string {\n return values.map((v) => preview(v)).join(', ');\n}\n\n/**\n * `products=Base|Vercel, runtimes=node` — the VALUES, so a swap reads as a swap.\n * Every value takes the same 60-char cap the rest of the summary uses, and the\n * whole rendering is capped too: a full-size card would otherwise put ~19KB on one\n * stderr line.\n */\nfunction appliesToPreview(appliesTo: Record<string, string[]>): string {\n const entries = Object.entries(appliesTo);\n if (entries.length === 0) return '(unset)';\n const rendered = entries\n .map(([key, values]) => `${clip(key)}=${values.map((v) => clip(v)).join('|')}`)\n .join(', ');\n return clip(rendered, LINE_MAX);\n}\n\nfunction sameList(a: string[], b: string[]): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction hasText(value: string | null | undefined): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AA2GjC,eAAsB,QACpB,MACA,KACA,OAAiB,CAAC,GACM;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAEpC,MAAI,CAAC,QAAQ,KAAK,KAAK,MAAM,GAAG;AAC9B,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI;AAAA,MAC7E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AAGA,MAAI,KAAK,SAAS,OAAW,sBAAqB,KAAK,MAAM,QAAQ;AAGrE,oBAAkB,IAAI;AACtB,0BAAwB,IAAI;AAC5B,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AO,OAAO,IAAI,CAAC,MAAM,QAAQ,CAAC,CAAC,EAAE,KAAK,IAAI;AAChD;AAQA,SAAS,iBAAiB,WAA6C;AACrE,QAAM,UAAU,OAAO,QAAQ,SAAS;AACxC,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,WAAW,QACd,IAAI,CAAC,CAAC,KAAK,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAC7E,KAAK,IAAI;AACZ,SAAO,KAAK,UAAU,QAAQ;AAChC;AAEA,SAAS,SAAS,GAAa,GAAsB;AACnD,SAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC,GAAG,MAAM,MAAM,EAAE,CAAC,CAAC;AAC9D;AAEA,SAAS,QAAQ,OAA2C;AAC1D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS;AAC5D;","names":[]}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
hasCode
|
|
4
|
+
} from "./chunk-2I4QTOLB.js";
|
|
5
|
+
import {
|
|
6
|
+
CliError,
|
|
7
|
+
external_exports,
|
|
8
|
+
sessionPath
|
|
9
|
+
} from "./chunk-J6CVKC4M.js";
|
|
10
|
+
|
|
11
|
+
// src/lib/session-present.ts
|
|
12
|
+
import { createHash, randomBytes, webcrypto } from "crypto";
|
|
13
|
+
import { readFile, stat } from "fs/promises";
|
|
14
|
+
function scopeSatisfies(cached, required) {
|
|
15
|
+
if (cached === required) return true;
|
|
16
|
+
return required === "read" && cached === "read+write";
|
|
17
|
+
}
|
|
18
|
+
var EXP_SKEW_MS = 6e4;
|
|
19
|
+
var P256JwkSchema = external_exports.object({
|
|
20
|
+
kty: external_exports.literal("EC"),
|
|
21
|
+
crv: external_exports.literal("P-256"),
|
|
22
|
+
d: external_exports.string().min(1),
|
|
23
|
+
x: external_exports.string().min(1),
|
|
24
|
+
y: external_exports.string().min(1)
|
|
25
|
+
}).passthrough();
|
|
26
|
+
var SessionFileSchema = external_exports.object({
|
|
27
|
+
/** Lowercased wallet address this delegation is bound to. */
|
|
28
|
+
address: external_exports.string(),
|
|
29
|
+
/**
|
|
30
|
+
* The `scheme://host[:port]` this delegation was minted against.
|
|
31
|
+
*
|
|
32
|
+
* Load-bearing, not bookkeeping. The delegation is a wallet-derived credential
|
|
33
|
+
* and `--base-url` rides every leaf command, including the always-safe `read`.
|
|
34
|
+
* Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`
|
|
35
|
+
* hands the credential to a host the agent chose, with the origin guard
|
|
36
|
+
* satisfied because the same flag set both sides of it. Binding the file to its
|
|
37
|
+
* origin closes that however the base URL arrived — flag, environment, or a
|
|
38
|
+
* rewritten config. It also makes a stale file after a prod/localhost/preview
|
|
39
|
+
* switch fail closed rather than present a delegation that cannot verify.
|
|
40
|
+
*/
|
|
41
|
+
origin: external_exports.string(),
|
|
42
|
+
/** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */
|
|
43
|
+
delegation: external_exports.string(),
|
|
44
|
+
/** Delegation expiry (ISO 8601); a request is never signed at/after this. */
|
|
45
|
+
exp: external_exports.string(),
|
|
46
|
+
scope: external_exports.string(),
|
|
47
|
+
/** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */
|
|
48
|
+
publicKeyRaw: external_exports.string(),
|
|
49
|
+
privateKeyJwk: P256JwkSchema
|
|
50
|
+
});
|
|
51
|
+
var subtle = webcrypto.subtle;
|
|
52
|
+
function toBase64(bytes) {
|
|
53
|
+
return Buffer.from(bytes).toString("base64");
|
|
54
|
+
}
|
|
55
|
+
function contentDigest(body) {
|
|
56
|
+
const hash = createHash("sha256").update(body, "utf8").digest();
|
|
57
|
+
return `sha-256=:${hash.toString("base64")}:`;
|
|
58
|
+
}
|
|
59
|
+
function targetUri(url) {
|
|
60
|
+
const u = new URL(url);
|
|
61
|
+
return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
|
|
62
|
+
}
|
|
63
|
+
function signatureParams(input) {
|
|
64
|
+
const covered = input.contentDigest !== void 0 ? '"@method" "@target-uri" "content-digest"' : '"@method" "@target-uri"';
|
|
65
|
+
return `(${covered});created=${input.created};nonce="${input.nonce}";keyid="${input.keyid}";alg="ecdsa-p256-sha256"`;
|
|
66
|
+
}
|
|
67
|
+
function signatureBase(input) {
|
|
68
|
+
const params = signatureParams(input);
|
|
69
|
+
const lines = [
|
|
70
|
+
`"@method": ${input.method.toUpperCase()}`,
|
|
71
|
+
`"@target-uri": ${targetUri(input.url)}`,
|
|
72
|
+
...input.contentDigest !== void 0 ? [`"content-digest": ${input.contentDigest}`] : [],
|
|
73
|
+
`"@signature-params": ${params}`
|
|
74
|
+
];
|
|
75
|
+
return lines.join("\n");
|
|
76
|
+
}
|
|
77
|
+
async function importSigningKey(jwk) {
|
|
78
|
+
try {
|
|
79
|
+
return await subtle.importKey(
|
|
80
|
+
"jwk",
|
|
81
|
+
jwk,
|
|
82
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
83
|
+
false,
|
|
84
|
+
["sign"]
|
|
85
|
+
);
|
|
86
|
+
} catch (err) {
|
|
87
|
+
throw new CliError("INTERNAL", "The cached session key is not a usable P-256 key.", {
|
|
88
|
+
fix: "Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.",
|
|
89
|
+
cause: err
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function signBase(jwk, base) {
|
|
94
|
+
const key = await importSigningKey(jwk);
|
|
95
|
+
const sig = await subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, Buffer.from(base, "utf8"));
|
|
96
|
+
return toBase64(new Uint8Array(sig));
|
|
97
|
+
}
|
|
98
|
+
function keyidFor(publicKeyRaw) {
|
|
99
|
+
return `p256:${publicKeyRaw}`;
|
|
100
|
+
}
|
|
101
|
+
async function signWithSession(file, req, deps = {}) {
|
|
102
|
+
const now = deps.now ?? Date.now;
|
|
103
|
+
const nonce = deps.nonce ?? (() => randomBytes(16).toString("hex"));
|
|
104
|
+
const digest = req.method === "GET" ? void 0 : contentDigest(req.body);
|
|
105
|
+
const params = {
|
|
106
|
+
method: req.method,
|
|
107
|
+
url: req.url,
|
|
108
|
+
...digest !== void 0 ? { contentDigest: digest } : {},
|
|
109
|
+
created: Math.floor(now() / 1e3),
|
|
110
|
+
nonce: nonce(),
|
|
111
|
+
keyid: keyidFor(file.publicKeyRaw)
|
|
112
|
+
};
|
|
113
|
+
const signature = await signBase(file.privateKeyJwk, signatureBase(params));
|
|
114
|
+
return {
|
|
115
|
+
"Tenjin-Session-Delegation": file.delegation,
|
|
116
|
+
"Signature-Input": `tenjin=${signatureParams(params)}`,
|
|
117
|
+
Signature: `tenjin=:${signature}:`,
|
|
118
|
+
...digest !== void 0 ? { "Content-Digest": digest } : {}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
async function readSessionFile(dir) {
|
|
122
|
+
const path = sessionPath(dir);
|
|
123
|
+
if (process.platform !== "win32") {
|
|
124
|
+
try {
|
|
125
|
+
const mode = (await stat(path)).mode & 511;
|
|
126
|
+
if ((mode & 63) !== 0) return { kind: "loosened", mode };
|
|
127
|
+
} catch (err) {
|
|
128
|
+
if (hasCode(err, "ENOENT")) return { kind: "absent" };
|
|
129
|
+
return { kind: "unreadable", message: messageOf(err), cause: err };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
let raw;
|
|
133
|
+
try {
|
|
134
|
+
raw = await readFile(path, "utf8");
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (hasCode(err, "ENOENT")) return { kind: "absent" };
|
|
137
|
+
return { kind: "unreadable", message: messageOf(err), cause: err };
|
|
138
|
+
}
|
|
139
|
+
let json;
|
|
140
|
+
try {
|
|
141
|
+
json = JSON.parse(raw);
|
|
142
|
+
} catch {
|
|
143
|
+
return { kind: "corrupt", reason: "not valid JSON" };
|
|
144
|
+
}
|
|
145
|
+
const parsed = SessionFileSchema.safeParse(json);
|
|
146
|
+
if (!parsed.success) {
|
|
147
|
+
const issue = parsed.error.issues[0];
|
|
148
|
+
const field = issue?.path.join(".");
|
|
149
|
+
const message = issue?.message ?? "schema mismatch";
|
|
150
|
+
return {
|
|
151
|
+
kind: "corrupt",
|
|
152
|
+
reason: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
return { kind: "ok", file: parsed.data };
|
|
156
|
+
}
|
|
157
|
+
async function loadSessionFile(dir) {
|
|
158
|
+
const state = await readSessionFile(dir);
|
|
159
|
+
if (state.kind === "ok") return state.file;
|
|
160
|
+
if (state.kind === "unreadable") {
|
|
161
|
+
throw new CliError("INTERNAL", `Could not read the session cache at ${sessionPath(dir)}`, {
|
|
162
|
+
fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,
|
|
163
|
+
cause: state.cause
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
function messageOf(err) {
|
|
169
|
+
return err instanceof Error ? err.message : String(err);
|
|
170
|
+
}
|
|
171
|
+
function isSessionPresentable(file, now, required, origin) {
|
|
172
|
+
if (file.origin !== origin) return false;
|
|
173
|
+
if (!scopeSatisfies(file.scope, required)) return false;
|
|
174
|
+
const expMs = Date.parse(file.exp);
|
|
175
|
+
if (!Number.isFinite(expMs)) return false;
|
|
176
|
+
return now < expMs - EXP_SKEW_MS;
|
|
177
|
+
}
|
|
178
|
+
function isSessionUsable(file, address, now, required, origin) {
|
|
179
|
+
if (file.address !== address.toLowerCase()) return false;
|
|
180
|
+
return isSessionPresentable(file, now, required, origin);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export {
|
|
184
|
+
signWithSession,
|
|
185
|
+
readSessionFile,
|
|
186
|
+
loadSessionFile,
|
|
187
|
+
isSessionPresentable,
|
|
188
|
+
isSessionUsable
|
|
189
|
+
};
|
|
190
|
+
//# sourceMappingURL=chunk-GABYDXWL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issue = parsed.error.issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // Field-qualified, because \"expected string, received undefined\" names no\n // field and the migration case (a pre-origin file) is exactly that message.\n // zod never echoes the received VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IA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UAAM,QAAQ,OAAO,KAAK,KAAK,GAAG;AAClC,UAAM,UAAU,OAAO,WAAW;AAIlC,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ,UAAU,UAAa,MAAM,SAAS,IAAI,GAAG,KAAK,KAAK,OAAO,KAAK;AAAA,IAC7E;AAAA,EACF;AACA,SAAO,EAAE,MAAM,MAAM,MAAM,OAAO,KAAK;AACzC;AAGA,eAAsB,gBAAgB,KAA0C;AAC9E,QAAM,QAAQ,MAAM,gBAAgB,GAAG;AACvC,MAAI,MAAM,SAAS,KAAM,QAAO,MAAM;AAItC,MAAI,MAAM,SAAS,cAAc;AAC/B,UAAM,IAAI,SAAS,YAAY,uCAAuC,YAAY,GAAG,CAAC,IAAI;AAAA,MACxF,KAAK,6BAA6B,YAAY,GAAG,CAAC;AAAA,MAClD,OAAO,MAAM;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,SAAS,UAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AASO,SAAS,qBACd,MACA,KACA,UACA,QACS;AACT,MAAI,KAAK,WAAW,OAAQ,QAAO;AACnC,MAAI,CAAC,eAAe,KAAK,OAAO,QAAQ,EAAG,QAAO;AAClD,QAAM,QAAQ,KAAK,MAAM,KAAK,GAAG;AACjC,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,SAAO,MAAM,QAAQ;AACvB;AAGO,SAAS,gBACd,MACA,SACA,KACA,UACA,QACS;AACT,MAAI,KAAK,YAAY,QAAQ,YAAY,EAAG,QAAO;AACnD,SAAO,qBAAqB,MAAM,KAAK,UAAU,MAAM;AACzD;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
loadProjectConfig
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-DAJ56EUU.js";
|
|
5
5
|
import {
|
|
6
6
|
LockTimeoutError,
|
|
7
7
|
withFileLock
|
|
@@ -16,14 +16,12 @@ import {
|
|
|
16
16
|
parseUsdToAtomic,
|
|
17
17
|
resolveSettings,
|
|
18
18
|
toMoney
|
|
19
|
-
} from "./chunk-
|
|
20
|
-
import {
|
|
21
|
-
writeFileAtomic
|
|
22
|
-
} from "./chunk-2JQ5JSG6.js";
|
|
19
|
+
} from "./chunk-UYP7G3GZ.js";
|
|
23
20
|
import {
|
|
24
21
|
CliError,
|
|
25
|
-
configPath
|
|
26
|
-
|
|
22
|
+
configPath,
|
|
23
|
+
writeFileAtomic
|
|
24
|
+
} from "./chunk-J6CVKC4M.js";
|
|
27
25
|
|
|
28
26
|
// src/commands/config.ts
|
|
29
27
|
import { mkdir } from "fs/promises";
|
|
@@ -272,4 +270,4 @@ export {
|
|
|
272
270
|
persistPublishMode,
|
|
273
271
|
persistInstallHarness
|
|
274
272
|
};
|
|
275
|
-
//# sourceMappingURL=chunk-
|
|
273
|
+
//# sourceMappingURL=chunk-GM4RZUVU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/config.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport {\n CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n} from '../lib/config';\nimport type { HarnessTarget } from '../lib/skill-wiring';\nimport { loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * How one config key is presented in `data`. `value` is the machine form: dual\n * Money for the spend keys, the stored string for `confirm`/URLs, the string[]\n * for the allowlist. `threshold` rides along only for `confirm: above:<atomic>`\n * so an agent reads the dollar amount without re-parsing the string.\n */\ninterface RenderedValue {\n value: Money | string | string[] | boolean;\n threshold?: Money;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n}\n\nconst CONFIRM_ABOVE = 'above:';\nconst KEY_WIDTH = Math.max(...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS].map((key) => key.length));\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'auto-approve a read up to this amount',\n sessionBudget: 'cap on total auto-spend per session',\n confirm: 'when to ask before paying',\n sendMaxAmount:\n 'hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL',\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n};\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n { key, value }: { key: string; value: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) return setPublishKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice`. mode validates to the enum;\n * defaultPrice parses decimal USD at the edge into atomic (matching the spend\n * keys). The subkey is merged into the nested publish block, so a sibling subkey\n * (or an unknown one a newer CLI wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey = key === 'publish.mode' ? 'mode' : 'defaultPrice';\n const stored = key === 'publish.mode' ? (entry.value as string) : (entry.value as Money).atomic;\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Record the explicit `--harness` set `install` was given, through the same locked\n * merge-write. It REPLACES the previous record rather than unioning with it: the last\n * explicit request is the current intent, and re-running install with the right flag\n * is then the way out of a mistaken one. Detected harnesses are never recorded — they\n * are re-probed on every `doctor` — so this file holds only what detection cannot see.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly HarnessTarget[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n if (key === 'confirm' && stored.startsWith(CONFIRM_ABOVE)) {\n return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'maxAutoSpend':\n case 'sessionBudget':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'confirm':\n return parseConfirm(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'evalCohort':\n return parseBoolean(value);\n }\n}\n\nfunction parseBoolean(value: string): boolean {\n if (value === 'true') return true;\n if (value === 'false') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"true\" or \"false\".',\n });\n}\n\nfunction parseConfirm(value: string): string {\n if (value === 'always') return 'always';\n if (value.startsWith(CONFIRM_ABOVE)) {\n return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;\n }\n throw new CliError('USAGE', `Invalid confirm value: ${JSON.stringify(value)}`, {\n fix: 'Use \"always\" or \"above:<usd>\", e.g. above:0.25.',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n if (entry.threshold !== undefined) return `above ${entry.threshold.usd} USD`; // confirm\n return value; // 'always', baseUrl, rpcUrl\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,iBAAiB;AA0C1B,IAAM,gBAAgB;AACtB,IAAM,YAAY,KAAK,IAAI,GAAG,CAAC,GAAG,aAAa,GAAG,mBAAmB,EAAE,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC;AAM/F,IAAM,mBAA2C;AAAA,EAC/C,cAAc;AAAA,EACd,eAAe;AAAA,EACf,SAAS;AAAA,EACT,eACE;AAAA,EACF,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,wBAAwB;AAC1B;AAEA,SAAS,aAAa,KAAsC;AAC1D,SAAQ,oBAA0C,SAAS,GAAG;AAChE;AAQA,eAAsB,cAAc,KAA6C;AAC/E,QAAM,WAAW,MAAM,mBAAmB,GAAG;AAC7C,QAAM,OAAwC,CAAC;AAC/C,QAAM,aAAuB,CAAC;AAC9B,aAAW,OAAO,aAAa;AAC7B,UAAM,QAAQ,cAAc,KAAK,SAAS,GAAG,EAAE,OAAO,SAAS,GAAG,EAAE,MAAM;AAC1E,SAAK,GAAG,IAAI;AACZ,eAAW,KAAK,cAAc,KAAK,KAAK,CAAC;AAAA,EAC3C;AACA,aAAW,OAAO,qBAAqB;AACrC,UAAM,QAAQ,qBAAqB,KAAK,QAAQ;AAChD,SAAK,GAAG,IAAI;AACZ,eAAW,KAAK,cAAc,KAAK,OAAO,cAAc,KAAK,QAAQ,CAAC,CAAC;AAAA,EACzE;AACA,SAAO,EAAE,MAAM,WAAW;AAC5B;AAGA,eAAsB,aACpB,EAAE,IAAI,GACN,KACwB;AACxB,MAAI,aAAa,GAAG,GAAG;AACrB,UAAMA,YAAW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,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,MAAI,MAAM,cAAc,OAAW,QAAO,SAAS,MAAM,UAAU,GAAG;AACtE,SAAO;AACT;","names":["settings","entry"]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/config.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport {\n CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n} from '../lib/config';\nimport type { HarnessTarget } from '../lib/skill-wiring';\nimport { loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * How one config key is presented in `data`. `value` is the machine form: dual\n * Money for the spend keys, the stored string for `confirm`/URLs, the string[]\n * for the allowlist. `threshold` rides along only for `confirm: above:<atomic>`\n * so an agent reads the dollar amount without re-parsing the string.\n */\ninterface RenderedValue {\n value: Money | string | string[] | boolean;\n threshold?: Money;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n}\n\nconst CONFIRM_ABOVE = 'above:';\nconst KEY_WIDTH = Math.max(...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS].map((key) => key.length));\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'auto-approve a read up to this amount',\n sessionBudget: 'cap on total auto-spend per session',\n confirm: 'when to ask before paying',\n sendMaxAmount:\n 'hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL',\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n};\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n { key, value }: { key: string; value: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) return setPublishKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice`. mode validates to the enum;\n * defaultPrice parses decimal USD at the edge into atomic (matching the spend\n * keys). The subkey is merged into the nested publish block, so a sibling subkey\n * (or an unknown one a newer CLI wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey = key === 'publish.mode' ? 'mode' : 'defaultPrice';\n const stored = key === 'publish.mode' ? (entry.value as string) : (entry.value as Money).atomic;\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Record the explicit `--harness` set `install` was given, through the same locked\n * merge-write. It REPLACES the previous record rather than unioning with it: the last\n * explicit request is the current intent, and re-running install with the right flag\n * is then the way out of a mistaken one. Detected harnesses are never recorded — they\n * are re-probed on every `doctor` — so this file holds only what detection cannot see.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly HarnessTarget[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n if (key === 'confirm' && stored.startsWith(CONFIRM_ABOVE)) {\n return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'maxAutoSpend':\n case 'sessionBudget':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'confirm':\n return parseConfirm(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'evalCohort':\n return parseBoolean(value);\n }\n}\n\nfunction parseBoolean(value: string): boolean {\n if (value === 'true') return true;\n if (value === 'false') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"true\" or \"false\".',\n });\n}\n\nfunction parseConfirm(value: string): string {\n if (value === 'always') return 'always';\n if (value.startsWith(CONFIRM_ABOVE)) {\n return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;\n }\n throw new CliError('USAGE', `Invalid confirm value: ${JSON.stringify(value)}`, {\n fix: 'Use \"always\" or \"above:<usd>\", e.g. above:0.25.',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: 'Pass an absolute http(s) URL like https://tenjin.blog.',\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n if (entry.threshold !== undefined) return `above ${entry.threshold.usd} USD`; // confirm\n return value; // 'always', baseUrl, rpcUrl\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,iBAAiB;AA0C1B,IAAM,gBAAgB;AACtB,IAAM,YAAY,KAAK,IAAI,GAAG,CAAC,GAAG,aAAa,GAAG,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M,GAAG;AAClD,MAAI,MAAM,cAAc,OAAW,QAAO,SAAS,MAAM,UAAU,GAAG;AACtE,SAAO;AACT;","names":["settings","entry"]}
|
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
package_default
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-WDJTGVKN.js";
|
|
5
5
|
|
|
6
6
|
// src/lib/http.ts
|
|
7
|
+
var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
|
|
8
|
+
"sign-in-with-x",
|
|
9
|
+
"payment-signature",
|
|
10
|
+
"x-payment",
|
|
11
|
+
"tenjin-session-delegation"
|
|
12
|
+
]);
|
|
13
|
+
function carriesSignedMaterial(headers) {
|
|
14
|
+
return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
|
|
15
|
+
}
|
|
7
16
|
async function fetchJson(url, opts) {
|
|
8
17
|
const doFetch = opts.fetchImpl ?? fetch;
|
|
9
18
|
const controller = new AbortController();
|
|
@@ -86,19 +95,33 @@ async function httpRequest(url, opts) {
|
|
|
86
95
|
body = JSON.stringify(opts.jsonBody);
|
|
87
96
|
headers["content-type"] = "application/json";
|
|
88
97
|
}
|
|
89
|
-
if (opts.method === "POST" || body !== void 0)
|
|
98
|
+
if (opts.method === "POST" || opts.method === "PUT" || body !== void 0) {
|
|
99
|
+
headers["accept"] ??= "application/json";
|
|
100
|
+
}
|
|
101
|
+
const signed = carriesSignedMaterial(headers);
|
|
102
|
+
const pinned = signed || opts.blockRedirects === true;
|
|
90
103
|
let res;
|
|
91
104
|
try {
|
|
92
105
|
res = await doFetch(url, {
|
|
93
106
|
method: opts.method ?? "GET",
|
|
94
107
|
headers,
|
|
95
108
|
body,
|
|
96
|
-
signal: controller.signal
|
|
109
|
+
signal: controller.signal,
|
|
110
|
+
...pinned ? { redirect: "manual" } : {}
|
|
97
111
|
});
|
|
98
112
|
} catch (err) {
|
|
99
113
|
return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
|
|
100
114
|
}
|
|
101
115
|
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
116
|
+
if (pinned && res.status >= 300 && res.status < 400) {
|
|
117
|
+
return {
|
|
118
|
+
ok: false,
|
|
119
|
+
kind: "blocked-redirect",
|
|
120
|
+
status: res.status,
|
|
121
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
122
|
+
message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
|
|
123
|
+
};
|
|
124
|
+
}
|
|
102
125
|
let text;
|
|
103
126
|
try {
|
|
104
127
|
text = await res.text();
|
|
@@ -138,15 +161,9 @@ function errorMessage(err) {
|
|
|
138
161
|
// src/lib/client-meta.ts
|
|
139
162
|
var CLIENT_HEADER = `tenjin-cli/${package_default.version}`;
|
|
140
163
|
|
|
141
|
-
// src/lib/url.ts
|
|
142
|
-
function trimSlash(url) {
|
|
143
|
-
return url.replace(/\/+$/, "");
|
|
144
|
-
}
|
|
145
|
-
|
|
146
164
|
export {
|
|
147
165
|
fetchJson,
|
|
148
166
|
httpRequest,
|
|
149
|
-
CLIENT_HEADER
|
|
150
|
-
trimSlash
|
|
167
|
+
CLIENT_HEADER
|
|
151
168
|
};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
169
|
+
//# sourceMappingURL=chunk-GXYNLMUQ.js.map
|