tenjin-cli 0.1.0-alpha.12 → 0.1.0-alpha.14
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 +36 -2
- package/dist/{buy-3DTBFZ4B.js → buy-2JBYPHAI.js} +23 -21
- package/dist/{chunk-Y7ERTA7D.js → chunk-3P3ES4XU.js} +4 -6
- package/dist/chunk-3P3ES4XU.js.map +1 -0
- package/dist/{chunk-WWIKAJFO.js → chunk-3ZW7HPY5.js} +12 -10
- package/dist/{chunk-WWIKAJFO.js.map → chunk-3ZW7HPY5.js.map} +1 -1
- package/dist/chunk-4UHNXY6B.js +786 -0
- package/dist/chunk-4UHNXY6B.js.map +1 -0
- package/dist/{chunk-6UY2UQMY.js → chunk-4Y53PDH6.js} +4 -4
- package/dist/{chunk-TUXKOIOU.js → chunk-54AJIO3E.js} +12 -13
- package/dist/chunk-54AJIO3E.js.map +1 -0
- package/dist/chunk-736DW4V3.js +65 -0
- package/dist/chunk-736DW4V3.js.map +1 -0
- package/dist/{chunk-CNUXRXI2.js → chunk-7GJQ5RGA.js} +9 -9
- package/dist/{chunk-4NTZETIL.js → chunk-7NADDA2V.js} +10 -7
- package/dist/{chunk-4NTZETIL.js.map → chunk-7NADDA2V.js.map} +1 -1
- package/dist/{chunk-UFPJBS4C.js → chunk-ACBEHJAH.js} +10 -8
- package/dist/{chunk-UFPJBS4C.js.map → chunk-ACBEHJAH.js.map} +1 -1
- package/dist/{chunk-IB63U6BM.js → chunk-B676GPS2.js} +34 -11
- package/dist/chunk-B676GPS2.js.map +1 -0
- package/dist/{chunk-MBKFZBB2.js → chunk-DAZAXFSF.js} +24 -24
- package/dist/{chunk-E6YOODH7.js → chunk-DTCXO7HS.js} +284 -406
- package/dist/chunk-DTCXO7HS.js.map +1 -0
- package/dist/{chunk-HWHYPCCH.js → chunk-ETKZWJ4B.js} +2 -2
- package/dist/{chunk-HWHYPCCH.js.map → chunk-ETKZWJ4B.js.map} +1 -1
- package/dist/{chunk-X2WZPGCF.js → chunk-FDUD3W5V.js} +5 -5
- package/dist/{chunk-6RMEX74N.js → chunk-GEHL43VE.js} +63 -26
- package/dist/chunk-GEHL43VE.js.map +1 -0
- package/dist/chunk-IU2HVT3Y.js +313 -0
- package/dist/chunk-IU2HVT3Y.js.map +1 -0
- package/dist/{chunk-4TCU3YRD.js → chunk-IUQZ4Z7M.js} +40 -8
- package/dist/chunk-IUQZ4Z7M.js.map +1 -0
- package/dist/{chunk-CBNXUQGM.js → chunk-IXZJ3JOO.js} +10 -8
- package/dist/{chunk-CBNXUQGM.js.map → chunk-IXZJ3JOO.js.map} +1 -1
- package/dist/{chunk-NUF2PKJO.js → chunk-J6FUAIRR.js} +4 -6
- package/dist/{chunk-NUF2PKJO.js.map → chunk-J6FUAIRR.js.map} +1 -1
- package/dist/{chunk-OZHJ3FLR.js → chunk-L6G35FU5.js} +5 -5
- package/dist/{chunk-ALUNME53.js → chunk-LSWP7MU2.js} +52 -68
- package/dist/chunk-LSWP7MU2.js.map +1 -0
- package/dist/chunk-MJSXP4LW.js +191 -0
- package/dist/chunk-MJSXP4LW.js.map +1 -0
- package/dist/{chunk-RSBN67PA.js → chunk-NAAMHWSI.js} +7 -6
- package/dist/chunk-NAAMHWSI.js.map +1 -0
- package/dist/{chunk-7MJVNALU.js → chunk-O75FOHXS.js} +35 -15
- package/dist/chunk-O75FOHXS.js.map +1 -0
- package/dist/{chunk-6BGYHARE.js → chunk-OWVVI4VQ.js} +15 -15
- package/dist/{chunk-PZRAAAY2.js → chunk-PAOVPSP6.js} +10 -3
- package/dist/chunk-PAOVPSP6.js.map +1 -0
- package/dist/{chunk-ROAK2DOX.js → chunk-PCX2JQ2J.js} +8 -8
- package/dist/{chunk-JTYIX6OD.js → chunk-PKW3H26Z.js} +7 -5
- package/dist/{chunk-JTYIX6OD.js.map → chunk-PKW3H26Z.js.map} +1 -1
- package/dist/{chunk-V5UHKC46.js → chunk-PQZVDCCA.js} +7 -7
- package/dist/{chunk-P74I3WH4.js → chunk-QWBUKIP2.js} +9 -5
- package/dist/chunk-QWBUKIP2.js.map +1 -0
- package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
- package/dist/chunk-UO22YNY4.js.map +1 -0
- package/dist/chunk-VEAERJVJ.js +43 -0
- package/dist/chunk-VEAERJVJ.js.map +1 -0
- package/dist/{chunk-ILDVGY7K.js → chunk-VRPLZERE.js} +25 -12
- package/dist/chunk-VRPLZERE.js.map +1 -0
- package/dist/{chunk-L3I2MVKR.js → chunk-W4VW5XYB.js} +6 -6
- package/dist/{chunk-TDDN5GXR.js → chunk-WU5CZPLD.js} +5 -5
- package/dist/chunk-WYLMJQVH.js +240 -0
- package/dist/chunk-WYLMJQVH.js.map +1 -0
- package/dist/{chunk-PZSUWDF2.js → chunk-XGZ5EVMB.js} +2 -2
- package/dist/{chunk-CLOEU7RA.js → chunk-XVPQGCH4.js} +14 -13
- package/dist/chunk-XVPQGCH4.js.map +1 -0
- package/dist/chunk-ZOBNS7CX.js +73 -0
- package/dist/chunk-ZOBNS7CX.js.map +1 -0
- package/dist/{cli-3WZGLZDP.js → cli-U2BEUA55.js} +53 -150
- package/dist/cli-U2BEUA55.js.map +1 -0
- package/dist/{config-WDGMZKHU.js → config-CNUIX23Q.js} +14 -8
- package/dist/doctor-QJJXRWTO.js +31 -0
- package/dist/edit-HJ44P44P.js +40 -0
- package/dist/{fund-JAPOFTUG.js → fund-Y5IAHZ5D.js} +19 -17
- package/dist/index.js +1 -1
- package/dist/inspect-NFQ6SQQQ.js +37 -0
- package/dist/{install-WXTOHDWC.js → install-DXX7PVUP.js} +128 -408
- package/dist/install-DXX7PVUP.js.map +1 -0
- package/dist/outcome-ANV4QIED.js +24 -0
- package/dist/publish-PCBTCXCZ.js +42 -0
- package/dist/{read-UAZGZ4UL.js → read-W7QVRBVD.js} +24 -22
- package/dist/{read-UAZGZ4UL.js.map → read-W7QVRBVD.js.map} +1 -1
- package/dist/{run-AJNCOT5R.js → run-CJWPGMIQ.js} +35 -33
- package/dist/{run-AJNCOT5R.js.map → run-CJWPGMIQ.js.map} +1 -1
- package/dist/search-JGAVKTYJ.js +25 -0
- package/dist/{send-F34ZDXDZ.js → send-C5EOKXOU.js} +13 -11
- package/dist/{send-F34ZDXDZ.js.map → send-C5EOKXOU.js.map} +1 -1
- package/dist/{session-4N4ZT3AH.js → session-OBCUUIFX.js} +16 -15
- package/dist/{session-4N4ZT3AH.js.map → session-OBCUUIFX.js.map} +1 -1
- package/dist/{skill-heal-XBEK272G.js → skill-heal-D6EPLPS6.js} +5 -6
- package/dist/skill-heal-D6EPLPS6.js.map +1 -0
- package/dist/{uninstall-BTKPHPDL.js → uninstall-OWJNJ5LI.js} +13 -8
- package/dist/uninstall-OWJNJ5LI.js.map +1 -0
- package/dist/update-24Y2CQTT.js +318 -0
- package/dist/update-24Y2CQTT.js.map +1 -0
- package/dist/{wallet-WJ6UP5OU.js → wallet-OFXDIIGP.js} +11 -10
- package/dist/{wallet-UL4P2JRO.js → wallet-SLRIYJ2U.js} +7 -7
- package/docs/agent-permissions.md +111 -16
- package/docs/command-reference.md +68 -11
- package/package.json +1 -1
- package/skills/tenjin-publish/SKILL.md +181 -192
- package/skills/tenjin-publish/references/maintain.md +39 -0
- package/skills/tenjin-search/SKILL.md +86 -279
- package/skills/tenjin-search/references/permissions.md +106 -0
- package/dist/chunk-2I4QTOLB.js +0 -11
- package/dist/chunk-2I4QTOLB.js.map +0 -1
- package/dist/chunk-4TCU3YRD.js.map +0 -1
- package/dist/chunk-6RMEX74N.js.map +0 -1
- package/dist/chunk-7MJVNALU.js.map +0 -1
- package/dist/chunk-ALUNME53.js.map +0 -1
- package/dist/chunk-CLOEU7RA.js.map +0 -1
- package/dist/chunk-E6YOODH7.js.map +0 -1
- package/dist/chunk-FKSAUOJU.js.map +0 -1
- package/dist/chunk-IB63U6BM.js.map +0 -1
- package/dist/chunk-ILDVGY7K.js.map +0 -1
- package/dist/chunk-P74I3WH4.js.map +0 -1
- package/dist/chunk-PZRAAAY2.js.map +0 -1
- package/dist/chunk-RSBN67PA.js.map +0 -1
- package/dist/chunk-SFGXAZ3M.js +0 -316
- package/dist/chunk-SFGXAZ3M.js.map +0 -1
- package/dist/chunk-TUXKOIOU.js.map +0 -1
- package/dist/chunk-Y7ERTA7D.js.map +0 -1
- package/dist/cli-3WZGLZDP.js.map +0 -1
- package/dist/doctor-EKVCP7JP.js +0 -27
- package/dist/edit-4UZQVFCK.js +0 -38
- package/dist/inspect-IEV75A42.js +0 -35
- package/dist/install-WXTOHDWC.js.map +0 -1
- package/dist/outcome-FYOFDOUK.js +0 -22
- package/dist/publish-6QNARH7E.js +0 -40
- package/dist/search-EEKTW6VK.js +0 -23
- package/dist/skill-heal-XBEK272G.js.map +0 -1
- package/dist/uninstall-BTKPHPDL.js.map +0 -1
- /package/dist/{buy-3DTBFZ4B.js.map → buy-2JBYPHAI.js.map} +0 -0
- /package/dist/{chunk-6UY2UQMY.js.map → chunk-4Y53PDH6.js.map} +0 -0
- /package/dist/{chunk-CNUXRXI2.js.map → chunk-7GJQ5RGA.js.map} +0 -0
- /package/dist/{chunk-MBKFZBB2.js.map → chunk-DAZAXFSF.js.map} +0 -0
- /package/dist/{chunk-X2WZPGCF.js.map → chunk-FDUD3W5V.js.map} +0 -0
- /package/dist/{chunk-OZHJ3FLR.js.map → chunk-L6G35FU5.js.map} +0 -0
- /package/dist/{chunk-6BGYHARE.js.map → chunk-OWVVI4VQ.js.map} +0 -0
- /package/dist/{chunk-ROAK2DOX.js.map → chunk-PCX2JQ2J.js.map} +0 -0
- /package/dist/{chunk-V5UHKC46.js.map → chunk-PQZVDCCA.js.map} +0 -0
- /package/dist/{chunk-L3I2MVKR.js.map → chunk-W4VW5XYB.js.map} +0 -0
- /package/dist/{chunk-TDDN5GXR.js.map → chunk-WU5CZPLD.js.map} +0 -0
- /package/dist/{chunk-PZSUWDF2.js.map → chunk-XGZ5EVMB.js.map} +0 -0
- /package/dist/{config-WDGMZKHU.js.map → config-CNUIX23Q.js.map} +0 -0
- /package/dist/{doctor-EKVCP7JP.js.map → doctor-QJJXRWTO.js.map} +0 -0
- /package/dist/{edit-4UZQVFCK.js.map → edit-HJ44P44P.js.map} +0 -0
- /package/dist/{fund-JAPOFTUG.js.map → fund-Y5IAHZ5D.js.map} +0 -0
- /package/dist/{inspect-IEV75A42.js.map → inspect-NFQ6SQQQ.js.map} +0 -0
- /package/dist/{outcome-FYOFDOUK.js.map → outcome-ANV4QIED.js.map} +0 -0
- /package/dist/{publish-6QNARH7E.js.map → publish-PCBTCXCZ.js.map} +0 -0
- /package/dist/{search-EEKTW6VK.js.map → search-JGAVKTYJ.js.map} +0 -0
- /package/dist/{wallet-UL4P2JRO.js.map → wallet-OFXDIIGP.js.map} +0 -0
- /package/dist/{wallet-WJ6UP5OU.js.map → wallet-SLRIYJ2U.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/skill-writer.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { hasCode } from './errno';\nimport { CliError } from './errors';\nimport { HOSTED_SKILL_NAME, readSkillFile } from './skill-wiring';\n\n/**\n * Writing one packaged skill into one harness directory, and the path guards that\n * write needs. Its own module, free of the command layer's dependencies, because\n * `install` and the post-command self-heal both write skills and the heal runs on\n * every command: reaching into commands/install would parse the wallet's viem\n * chunk on a `tenjin config`.\n */\n\nexport type SkillInstallStatus =\n 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n\nexport interface SkillInstallResult {\n status: SkillInstallStatus;\n warning?: string;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n}\n\nexport interface SkillWriteOptions {\n /**\n * Write THROUGH a symlinked destination (default), or replace it. `install`\n * follows the link, because the operator pointed it somewhere on purpose. The\n * unattended self-heal does not, and passes false: it has already refused every\n * link it could see, and this closes the gap between that look and this write,\n * where a link appearing in between would otherwise be followed. `rename` never\n * follows its final component, so the worst a race can now do is leave our\n * regular file where the new link was.\n */\n followSymlinks?: boolean;\n}\n\nexport async function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n name: string,\n opts: SkillWriteOptions = {},\n): Promise<SkillInstallResult> {\n const src = await readTree(srcDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n\n // Only the files this package SHIPS are read and written. Everything else in the\n // directory belongs to the operator: never inspected, listed, or removed. That is\n // what package managers do (npm, dpkg, Homebrew all own their files, not the\n // directory), and wholesale replacement was the single cause behind a run of\n // data-loss, symlink and enumeration bugs.\n //\n // Resolved on BOTH paths, dry run included, so a dry run cannot promise a write\n // the real run refuses.\n const writeTo = new Map<string, string>();\n await assertReachable(destDir, name);\n await assertNoCaseCollision(destDir, name);\n for (const rel of src.keys()) {\n const declared = join(destDir, rel);\n writeTo.set(\n rel,\n opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name),\n );\n }\n\n let differs = false;\n let preexisting = false;\n for (const [rel, content] of src) {\n const current = await readShippedFile(writeTo.get(rel)!, name, destDir);\n if (rel === 'SKILL.md') preexisting = current !== null;\n if (current === null || !current.equals(content)) differs = true;\n }\n const change = !preexisting ? 'create' : differs ? 'update' : 'none';\n\n if (!dryRun && change !== 'none') {\n for (const [rel, content] of src) {\n const target = writeTo.get(rel)!;\n try {\n // An existing file keeps the mode it has. A skill an operator (or their\n // dotfiles) made group-readable or read-only is theirs to have set that\n // way, and an update is no reason to hand it back at the default 0644.\n const current = await stat(target).catch(() => null);\n await writeFileAtomic(\n target,\n content,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n } catch (err) {\n // Culprit is derived from the file that FAILED, not assumed to be the\n // skills root: an existing skill directory that refuses the temp file is\n // itself the thing to chmod, and a symlinked SKILL.md fails in the link's\n // TARGET directory, which no path under destDir names.\n throw wrapWriteError(\n err,\n destDir,\n `the ${name} skill`,\n await deepestExisting(dirname(target)),\n { expected: ': a skill is a directory holding SKILL.md' },\n );\n }\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed', preexisting };\n if (change === 'none') return { status: 'up-to-date', preexisting };\n return {\n status: dryRun ? 'would-update' : 'updated',\n preexisting,\n // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a\n // differing local copy is a replacement, not the drift warning the CLI skills\n // get. Neither side carries a version or date, so the wording claims no\n // direction: the local file may well be a newer fetch than this package's copy.\n warning:\n name === HOSTED_SKILL_NAME\n ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? 'would be' : 'was'} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.`\n : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? 'would be' : 'were'} overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a shipped file, or null when it is not there.\n *\n * The node-type guard lives in `readSkillFile`, shared with the wiring check and\n * the staleness check, because all three read the same operator-controlled paths\n * and a pipe at one of them used to hang whichever command got there first.\n */\nasync function readShippedFile(\n path: string,\n name: string,\n destDir: string,\n): Promise<Buffer | null> {\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return null;\n if (read.kind === 'ok') return read.bytes;\n if (read.kind === 'not-regular') {\n throw new CliError('INTERNAL', `${path} is not a regular file, so ${name} was not written.`, {\n fix: `A skill file must be a regular file. Check what is there (\\`ls -l ${path}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n });\n }\n // Names the FILE, not its directory: this is a read failure, and pointing at a\n // perfectly writable parent is what sent operators to chmod the wrong thing.\n throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: 'read' });\n}\n\n/**\n * A destination the operator manages through a symlink is written THROUGH it, so\n * their link survives and their target is what actually changes. Same call the\n * settings.json writer makes, and the same reason: committing with `rename` over a\n * link would replace it with a regular file and strand the target.\n */\nexport async function resolveThroughLink(path: string, name: string): Promise<string> {\n const entry = await lstat(path).catch(() => null);\n if (entry === null || !entry.isSymbolicLink()) return path;\n const target = await realpath(path).catch(() => null);\n if (target !== null) return target;\n throw new CliError('INTERNAL', `${path} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a path that exists, or remove it (\\`ls -ld ${path}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * On a case-insensitive filesystem (the macOS default), a user directory named a\n * case variant of a shipped skill ALIASES the skill's path, so the write would\n * replace the user's own SKILL.md under a warning naming a path that is not on\n * disk. Detected by the alias itself: the destination resolves but the parent\n * lists only a differently-cased entry, which also means a case-SENSITIVE\n * filesystem (where both names can coexist) never trips this. Dry runs too.\n */\nasync function assertNoCaseCollision(destDir: string, name: string): Promise<void> {\n if (!existsSync(destDir)) return;\n const entries = await readdir(dirname(destDir)).catch(() => null);\n if (entries === null || entries.includes(name)) return;\n const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());\n if (variant === undefined) return;\n const actual = join(dirname(destDir), variant);\n throw new CliError(\n 'INTERNAL',\n `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,\n {\n fix: `Rename or remove ${actual}, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/**\n * Fail a destination directory that is a BROKEN SYMLINK, on dry runs too, so a dry\n * run cannot report `would-install` where the real run cannot write. It checks only\n * that: an unwritable but real directory passes here and fails at the write, with\n * the permission-denied error.\n */\nasync function assertReachable(destDir: string, name: string): Promise<void> {\n const entry = await lstat(destDir).catch(() => null);\n if (entry?.isSymbolicLink() !== true) return;\n if ((await realpath(destDir).catch(() => null)) !== null) return;\n throw new CliError('INTERNAL', `${destDir} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a directory that exists, or remove it (\\`ls -ld ${destDir}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * The directory a denied WRITE should point the operator at: the deepest existing\n * ancestor of the failed target's directory, RESOLVED. An existing skill directory\n * that refuses the temp file names itself; a directory that could not be created\n * names the ancestor that refused to create it, because `ls -ld` on a path that is\n * not there says nothing. Resolved because a destination managed through a symlink\n * denies the write in the link's TARGET, and telling the operator to chmod the\n * link's path leaves them staring at a healthy link.\n */\nexport async function deepestExisting(dir: string): Promise<string> {\n for (let cur = dir; ; cur = dirname(cur)) {\n if (existsSync(cur)) return realpath(cur).catch(() => cur);\n if (dirname(cur) === cur) return cur;\n }\n}\n\n/** A raw errno under INTERNAL reads as a CLI bug and carries no fix. */\nexport function wrapWriteError(\n err: unknown,\n /** The destination as the operator knows it (the declared path, pre-resolution). */\n dest: string,\n /** What could not be written, e.g. `the tenjin-search skill` or `the Tenjin pointer`. */\n subject: string,\n /**\n * The path to point the operator at. A READ failure names the file itself, which\n * is the thing whose mode is wrong. A WRITE failure names the deepest existing\n * directory on the failed target's resolved path.\n */\n culprit: string,\n opts: {\n /** Which side failed; a read error reported as \"could not write\" misleads. */\n verb?: 'read' | 'write';\n /** Sentence tail for the wrong-kind fix, telling the operator the expected shape. */\n expected?: string;\n } = {},\n): unknown {\n const verb = opts.verb ?? 'write';\n const denied = hasCode(err, 'EACCES') || hasCode(err, 'EPERM');\n const missing = hasCode(err, 'ENOENT');\n // A skills directory that resolves to a regular file, or a SKILL.md that resolves\n // to a directory. Pathological, but a raw ENOTDIR/EISDIR says nothing about which\n // path is the wrong kind of thing.\n const wrongKind = hasCode(err, 'ENOTDIR') || hasCode(err, 'EISDIR');\n if (!denied && !missing && !wrongKind) return err;\n const fix = denied\n ? `Permission denied on ${culprit}. Check it (\\`ls -ld ${culprit}\\`), then re-run \\`tenjin install\\`.`\n : wrongKind\n ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ''}. Check it (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`\n : `${dest} could not be created; if it is a symlink, check that its target exists (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`;\n return new CliError(\n 'INTERNAL',\n `Could not ${verb} ${subject} ${verb === 'read' ? 'at' : 'to'} ${dest}.`,\n { fix, cause: err },\n );\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,MAAM,gBAAgB;AAqCxC,eAAsB,aACpB,QACA,SACA,QACA,MACA,OAA0B,CAAC,GACE;AAC7B,QAAM,MAAM,MAAM,SAAS,MAAM;AACjC,MAAI,QAAQ,MAAM;AAEhB,UAAM,IAAI,SAAS,YAAY,yBAAyB,MAAM,WAAW;AAAA,EAC3E;AAUA,QAAM,UAAU,oBAAI,IAAoB;AACxC,QAAM,gBAAgB,SAAS,IAAI;AACnC,QAAM,sBAAsB,SAAS,IAAI;AACzC,aAAW,OAAO,IAAI,KAAK,GAAG;AAC5B,UAAM,WAAW,KAAK,SAAS,GAAG;AAClC,YAAQ;AAAA,MACN;AAAA,MACA,KAAK,mBAAmB,QAAQ,WAAW,MAAM,mBAAmB,UAAU,IAAI;AAAA,IACpF;AAAA,EACF;AAEA,MAAI,UAAU;AACd,MAAI,cAAc;AAClB,aAAW,CAAC,KAAK,OAAO,KAAK,KAAK;AAChC,UAAM,UAAU,MAAM,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AI,CAAC,MAAM,OAAO,EAAG;AACrB,UAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;AAC9C,UAAM,IAAI,SAAS,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI,CAAC;AAAA,EACrD;AACA,SAAO;AACT;","names":[]}
|
package/dist/chunk-SFGXAZ3M.js
DELETED
|
@@ -1,316 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
loadProjectConfig
|
|
4
|
-
} from "./chunk-JTYIX6OD.js";
|
|
5
|
-
import {
|
|
6
|
-
LockTimeoutError,
|
|
7
|
-
withFileLock
|
|
8
|
-
} from "./chunk-FKSAUOJU.js";
|
|
9
|
-
import {
|
|
10
|
-
CONFIG_KEYS,
|
|
11
|
-
HOOKS_CONFIG_KEYS,
|
|
12
|
-
PUBLISH_CONFIG_KEYS,
|
|
13
|
-
PublishModeSchema,
|
|
14
|
-
RawConfigSchema,
|
|
15
|
-
SEND_MAX_UNSET,
|
|
16
|
-
loadRawConfig,
|
|
17
|
-
parseSearchHookModeFlag,
|
|
18
|
-
parseStopNagFlag,
|
|
19
|
-
parseUsdToAtomic,
|
|
20
|
-
resolveSettings,
|
|
21
|
-
toMoney
|
|
22
|
-
} from "./chunk-ALUNME53.js";
|
|
23
|
-
import {
|
|
24
|
-
configPath
|
|
25
|
-
} from "./chunk-ZQIQ55KK.js";
|
|
26
|
-
import {
|
|
27
|
-
CliError,
|
|
28
|
-
writeFileAtomic
|
|
29
|
-
} from "./chunk-PZRAAAY2.js";
|
|
30
|
-
|
|
31
|
-
// src/commands/config.ts
|
|
32
|
-
import { mkdir } from "fs/promises";
|
|
33
|
-
import { styleText } from "util";
|
|
34
|
-
var CONFIRM_ABOVE = "above:";
|
|
35
|
-
var KEY_WIDTH = Math.max(
|
|
36
|
-
...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].map((key) => key.length)
|
|
37
|
-
);
|
|
38
|
-
var KEY_DESCRIPTIONS = {
|
|
39
|
-
maxAutoSpend: "auto-approve a read up to this amount",
|
|
40
|
-
sessionBudget: "cap on total auto-spend per session",
|
|
41
|
-
confirm: "when to ask before paying",
|
|
42
|
-
sendMaxAmount: "hard cap per tenjin send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes",
|
|
43
|
-
allowlistCreators: "only auto-pay these creators (empty = any)",
|
|
44
|
-
baseUrl: "Tenjin API base URL",
|
|
45
|
-
rpcUrl: "Base RPC endpoint for balance reads",
|
|
46
|
-
evalCohort: "opt in to the search evaluation cohort",
|
|
47
|
-
"publish.mode": "review=always ask, auto=ask on findings, full-auto=only hard blocks stop it",
|
|
48
|
-
"publish.defaultPrice": "price used when none is given",
|
|
49
|
-
"hooks.searchMode": "harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert",
|
|
50
|
-
"hooks.stopNag": "end-of-turn reminder about searches nothing answered yet"
|
|
51
|
-
};
|
|
52
|
-
function isPublishKey(key) {
|
|
53
|
-
return PUBLISH_CONFIG_KEYS.includes(key);
|
|
54
|
-
}
|
|
55
|
-
function isHooksKey(key) {
|
|
56
|
-
return HOOKS_CONFIG_KEYS.includes(key);
|
|
57
|
-
}
|
|
58
|
-
async function runConfigList(ctx) {
|
|
59
|
-
const settings = await resolveFromContext(ctx);
|
|
60
|
-
const data = {};
|
|
61
|
-
const humanLines = [];
|
|
62
|
-
for (const key of CONFIG_KEYS) {
|
|
63
|
-
const entry = renderSetting(key, settings[key].value, settings[key].source);
|
|
64
|
-
data[key] = entry;
|
|
65
|
-
humanLines.push(describedLine(key, entry));
|
|
66
|
-
}
|
|
67
|
-
for (const key of PUBLISH_CONFIG_KEYS) {
|
|
68
|
-
const entry = renderPublishSetting(key, settings);
|
|
69
|
-
data[key] = entry;
|
|
70
|
-
humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));
|
|
71
|
-
}
|
|
72
|
-
for (const key of HOOKS_CONFIG_KEYS) {
|
|
73
|
-
const entry = renderHooksSetting(key, settings);
|
|
74
|
-
data[key] = entry;
|
|
75
|
-
humanLines.push(describedLine(key, entry));
|
|
76
|
-
}
|
|
77
|
-
return { data, humanLines };
|
|
78
|
-
}
|
|
79
|
-
async function runConfigGet({ key }, ctx) {
|
|
80
|
-
if (isPublishKey(key)) {
|
|
81
|
-
const settings2 = await resolveFromContext(ctx);
|
|
82
|
-
const entry2 = renderPublishSetting(key, settings2);
|
|
83
|
-
return {
|
|
84
|
-
data: { key, ...entry2 },
|
|
85
|
-
humanLines: [withNote(formatLine(key, entry2), downgradeNote(key, settings2))]
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
if (isHooksKey(key)) {
|
|
89
|
-
const entry2 = renderHooksSetting(key, await resolveFromContext(ctx));
|
|
90
|
-
return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
|
|
91
|
-
}
|
|
92
|
-
const configKey = assertKey(key);
|
|
93
|
-
const settings = await resolveFromContext(ctx);
|
|
94
|
-
const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);
|
|
95
|
-
return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };
|
|
96
|
-
}
|
|
97
|
-
async function runConfigSet({ key, value }, ctx) {
|
|
98
|
-
if (isPublishKey(key)) return setPublishKey(key, value, ctx);
|
|
99
|
-
if (isHooksKey(key)) return setHooksKey(key, value, ctx);
|
|
100
|
-
const configKey = assertKey(key);
|
|
101
|
-
const stored = parseValue(configKey, value);
|
|
102
|
-
await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));
|
|
103
|
-
const entry = renderSetting(configKey, stored, "file");
|
|
104
|
-
return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };
|
|
105
|
-
}
|
|
106
|
-
async function setPublishKey(key, value, ctx) {
|
|
107
|
-
const entry = key === "publish.mode" ? { value: parsePublishMode(value), source: "file" } : { value: toMoney(parseUsdToAtomic(value)), source: "file" };
|
|
108
|
-
const subkey = key === "publish.mode" ? "mode" : "defaultPrice";
|
|
109
|
-
const stored = key === "publish.mode" ? entry.value : entry.value.atomic;
|
|
110
|
-
await persist(ctx.dataDir, (existing) => ({
|
|
111
|
-
...existing,
|
|
112
|
-
publish: { ...existing.publish, [subkey]: stored }
|
|
113
|
-
}));
|
|
114
|
-
return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
|
|
115
|
-
}
|
|
116
|
-
async function setHooksKey(key, value, ctx) {
|
|
117
|
-
const subkey = key === "hooks.searchMode" ? "searchMode" : "stopNag";
|
|
118
|
-
const parsed = key === "hooks.searchMode" ? parseSearchHookModeFlag(value, key) : parseStopNagFlag(value, key);
|
|
119
|
-
await persist(ctx.dataDir, (existing) => ({
|
|
120
|
-
...existing,
|
|
121
|
-
hooks: { ...existing.hooks, [subkey]: parsed }
|
|
122
|
-
}));
|
|
123
|
-
const entry = { value: parsed, source: "file" };
|
|
124
|
-
return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
|
|
125
|
-
}
|
|
126
|
-
function parsePublishMode(value) {
|
|
127
|
-
const parsed = PublishModeSchema.safeParse(value);
|
|
128
|
-
if (parsed.success) return parsed.data;
|
|
129
|
-
throw new CliError("USAGE", `Invalid publish mode: ${JSON.stringify(value)}`, {
|
|
130
|
-
fix: 'Use "review", "auto", or "full-auto".'
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
async function persistPublishMode(dir, mode) {
|
|
134
|
-
await persist(dir, (existing) => ({
|
|
135
|
-
...existing,
|
|
136
|
-
publish: { ...existing.publish, mode }
|
|
137
|
-
}));
|
|
138
|
-
}
|
|
139
|
-
async function persistSearchHookMode(dir, mode) {
|
|
140
|
-
await persist(dir, (existing) => ({
|
|
141
|
-
...existing,
|
|
142
|
-
hooks: { ...existing.hooks, searchMode: mode }
|
|
143
|
-
}));
|
|
144
|
-
}
|
|
145
|
-
async function persistInstallHarness(dir, harness) {
|
|
146
|
-
await persist(dir, (existing) => ({
|
|
147
|
-
...existing,
|
|
148
|
-
install: { ...existing.install, harness: [...harness] }
|
|
149
|
-
}));
|
|
150
|
-
}
|
|
151
|
-
async function resolveFromContext(ctx) {
|
|
152
|
-
const config = await loadRawConfig(ctx.dataDir);
|
|
153
|
-
const project = await loadProjectConfig(process.cwd());
|
|
154
|
-
return resolveSettings({
|
|
155
|
-
config,
|
|
156
|
-
flags: { baseUrl: ctx.flags.baseUrl },
|
|
157
|
-
env: process.env,
|
|
158
|
-
project: project?.layer
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
function assertKey(key) {
|
|
162
|
-
if (CONFIG_KEYS.includes(key)) return key;
|
|
163
|
-
throw new CliError("USAGE", `Unknown config key: ${JSON.stringify(key)}`, {
|
|
164
|
-
fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].join(", ")}.`
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
function renderSetting(key, stored, source) {
|
|
168
|
-
return { ...renderValue(key, stored), source };
|
|
169
|
-
}
|
|
170
|
-
function renderPublishSetting(key, settings) {
|
|
171
|
-
if (key === "publish.mode") {
|
|
172
|
-
return { value: settings.publishMode.value, source: settings.publishMode.source };
|
|
173
|
-
}
|
|
174
|
-
return {
|
|
175
|
-
value: toMoney(settings.publishDefaultPrice.value),
|
|
176
|
-
source: settings.publishDefaultPrice.source
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
function renderHooksSetting(key, settings) {
|
|
180
|
-
const resolved = key === "hooks.searchMode" ? settings.hooksSearchMode : settings.hooksStopNag;
|
|
181
|
-
return { value: resolved.value, source: resolved.source };
|
|
182
|
-
}
|
|
183
|
-
function renderValue(key, stored) {
|
|
184
|
-
if (Array.isArray(stored) || typeof stored === "boolean") return { value: stored };
|
|
185
|
-
if (key === "maxAutoSpend" || key === "sessionBudget") return { value: toMoney(stored) };
|
|
186
|
-
if (key === "sendMaxAmount") {
|
|
187
|
-
return { value: stored === "none" || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };
|
|
188
|
-
}
|
|
189
|
-
if (key === "confirm" && stored.startsWith(CONFIRM_ABOVE)) {
|
|
190
|
-
return { value: stored, threshold: toMoney(stored.slice(CONFIRM_ABOVE.length)) };
|
|
191
|
-
}
|
|
192
|
-
return { value: stored };
|
|
193
|
-
}
|
|
194
|
-
function parseValue(key, value) {
|
|
195
|
-
switch (key) {
|
|
196
|
-
case "maxAutoSpend":
|
|
197
|
-
case "sessionBudget":
|
|
198
|
-
return parseUsdToAtomic(value);
|
|
199
|
-
// throws USAGE on a bad amount
|
|
200
|
-
case "sendMaxAmount":
|
|
201
|
-
return value === "none" ? "none" : parseUsdToAtomic(value);
|
|
202
|
-
case "confirm":
|
|
203
|
-
return parseConfirm(value);
|
|
204
|
-
case "allowlistCreators":
|
|
205
|
-
return parseAllowlist(value);
|
|
206
|
-
case "baseUrl":
|
|
207
|
-
case "rpcUrl":
|
|
208
|
-
return parseHttpUrl(value);
|
|
209
|
-
case "evalCohort":
|
|
210
|
-
return parseBoolean(value);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
function parseBoolean(value) {
|
|
214
|
-
if (value === "true") return true;
|
|
215
|
-
if (value === "false") return false;
|
|
216
|
-
throw new CliError("USAGE", `Invalid boolean value: ${JSON.stringify(value)}`, {
|
|
217
|
-
fix: 'Use "true" or "false".'
|
|
218
|
-
});
|
|
219
|
-
}
|
|
220
|
-
function parseConfirm(value) {
|
|
221
|
-
if (value === "always") return "always";
|
|
222
|
-
if (value.startsWith(CONFIRM_ABOVE)) {
|
|
223
|
-
return `${CONFIRM_ABOVE}${parseUsdToAtomic(value.slice(CONFIRM_ABOVE.length))}`;
|
|
224
|
-
}
|
|
225
|
-
throw new CliError("USAGE", `Invalid confirm value: ${JSON.stringify(value)}`, {
|
|
226
|
-
fix: 'Use "always" or "above:<usd>", e.g. above:0.25.'
|
|
227
|
-
});
|
|
228
|
-
}
|
|
229
|
-
function parseAllowlist(value) {
|
|
230
|
-
const entries = value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
|
|
231
|
-
for (const entry of entries) {
|
|
232
|
-
if (/\s/.test(entry)) {
|
|
233
|
-
throw new CliError("USAGE", `Invalid creator entry: ${JSON.stringify(entry)}`, {
|
|
234
|
-
fix: "Creator entries cannot contain spaces; separate multiple with commas."
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
return entries;
|
|
239
|
-
}
|
|
240
|
-
function parseHttpUrl(value) {
|
|
241
|
-
let url;
|
|
242
|
-
try {
|
|
243
|
-
url = new URL(value);
|
|
244
|
-
} catch {
|
|
245
|
-
throw new CliError("USAGE", `Invalid URL: ${JSON.stringify(value)}`, {
|
|
246
|
-
fix: "Pass an absolute http(s) URL like https://tenjin.blog."
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
250
|
-
throw new CliError("USAGE", `URL must be http or https: ${JSON.stringify(value)}`, {
|
|
251
|
-
fix: "Pass an absolute http(s) URL like https://tenjin.blog."
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
return value;
|
|
255
|
-
}
|
|
256
|
-
async function persist(dir, merge) {
|
|
257
|
-
await mkdir(dir, { recursive: true, mode: 448 });
|
|
258
|
-
const lockPath = `${configPath(dir)}.lock`;
|
|
259
|
-
try {
|
|
260
|
-
await withFileLock(lockPath, async () => {
|
|
261
|
-
const existing = await loadRawConfig(dir);
|
|
262
|
-
const merged = merge(existing);
|
|
263
|
-
const validated = RawConfigSchema.parse(merged);
|
|
264
|
-
await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}
|
|
265
|
-
`, {
|
|
266
|
-
mode: 420,
|
|
267
|
-
dirMode: 448
|
|
268
|
-
});
|
|
269
|
-
});
|
|
270
|
-
} catch (err) {
|
|
271
|
-
if (err instanceof LockTimeoutError) {
|
|
272
|
-
throw new CliError("INTERNAL", err.message, {
|
|
273
|
-
fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
|
|
274
|
-
cause: err
|
|
275
|
-
});
|
|
276
|
-
}
|
|
277
|
-
throw err;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
function formatLine(key, entry) {
|
|
281
|
-
const label = key.padEnd(KEY_WIDTH);
|
|
282
|
-
return ` ${label} ${displayValue(entry)} ${styleText("dim", `(${entry.source})`)}`;
|
|
283
|
-
}
|
|
284
|
-
function describedLine(key, entry, note) {
|
|
285
|
-
const description = KEY_DESCRIPTIONS[key];
|
|
286
|
-
let line = formatLine(key, entry);
|
|
287
|
-
if (description !== void 0) line += ` ${styleText("dim", `- ${description}`)}`;
|
|
288
|
-
return withNote(line, note);
|
|
289
|
-
}
|
|
290
|
-
function withNote(line, note) {
|
|
291
|
-
return note !== void 0 ? `${line} ${styleText("dim", `(${note})`)}` : line;
|
|
292
|
-
}
|
|
293
|
-
function downgradeNote(key, settings) {
|
|
294
|
-
if (key !== "publish.mode" || settings.publishMode.downgradedWarning === void 0) {
|
|
295
|
-
return void 0;
|
|
296
|
-
}
|
|
297
|
-
return "downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)";
|
|
298
|
-
}
|
|
299
|
-
function displayValue(entry) {
|
|
300
|
-
const { value } = entry;
|
|
301
|
-
if (Array.isArray(value)) return value.length > 0 ? value.join(", ") : "(empty)";
|
|
302
|
-
if (typeof value === "boolean") return value ? "true" : "false";
|
|
303
|
-
if (typeof value === "object") return `${value.usd} USD`;
|
|
304
|
-
if (entry.threshold !== void 0) return `above ${entry.threshold.usd} USD`;
|
|
305
|
-
return value;
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
export {
|
|
309
|
-
runConfigList,
|
|
310
|
-
runConfigGet,
|
|
311
|
-
runConfigSet,
|
|
312
|
-
persistPublishMode,
|
|
313
|
-
persistSearchHookMode,
|
|
314
|
-
persistInstallHarness
|
|
315
|
-
};
|
|
316
|
-
//# sourceMappingURL=chunk-SFGXAZ3M.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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 HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n parseSearchHookModeFlag,\n parseStopNagFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n SearchHookMode,\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(\n ...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS].map((key) => key.length),\n);\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 'hooks.searchMode':\n 'harness WebSearch hook: auto=ask Tenjin first, remind=static reminder, off=inert',\n 'hooks.stopNag': 'end-of-turn reminder about searches nothing answered yet',\n};\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_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 for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\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 if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\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 if (isHooksKey(key)) return setHooksKey(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\n/**\n * `config set hooks.searchMode`. Merged into the nested hooks block through the\n * same locked read-modify-write every other set uses, so a subkey a newer CLI\n * wrote survives. The installed hook script reads this file on every run, so the\n * new mode takes effect immediately with no re-install.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const subkey = key === 'hooks.searchMode' ? 'searchMode' : 'stopNag';\n const parsed =\n key === 'hooks.searchMode' ? parseSearchHookModeFlag(value, key) : parseStopNagFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [subkey]: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\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 * Persist `hooks.searchMode` through the same locked merge-write, for `install`'s\n * hook decision. The mode is already a validated SearchHookMode.\n */\nexport async function persistSearchHookMode(dir: string, mode: SearchHookMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, searchMode: 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, ...HOOKS_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\n/** The list/get shape for a hooks key: a plain enum string either way. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const resolved = key === 'hooks.searchMode' ? settings.hooksSearchMode : settings.hooksStopNag;\n return { value: resolved.value, source: resolved.source };\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;AA+C1B,IAAM,gBAAgB;AACtB,IAAM,YAAY,KAAK;AAAA,EACrB,GAAG,CAAC,GAAG,aAAa,GAAG,qBAAqB,GAAG,iBAAiB,EAAE,IAAI,CAAC,QAAQ,IAAI,MAAM;AAC3F;AAMA,IAAM,mBAA2C;AAAA,EAC/C,cAAc;AAAA,EACd,eAAe;AAAA,EACf,SAAS;AAAA,EACT,eACE;AAAA,EACF,mBAAmB;AAAA,EACnB,SAA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@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/client-meta.ts","../src/lib/http.ts"],"sourcesContent":["import pkg from '../../package.json';\n\n/**\n * The CLI's identity on every HTTP request, sent as the standard `User-Agent`\n * header from the shared transport (`http.ts`). The server's\n * `parseUserAgentProduct()` (tenjin PR #544) reads the leading RFC 9110 product\n * token (`tenjin-cli/<version>`) for canonical attribution; `X-Tenjin-Client` is\n * retired and this CLI sends it nowhere.\n */\nexport const TENJIN_USER_AGENT = `tenjin-cli/${pkg.version} (+https://tenjin.blog)`;\n","import { CliError } from './errors';\nimport { TENJIN_USER_AGENT } from './client-meta';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n}\n\n/**\n * The one place the identity is written; both transports funnel their Headers\n * through it, so a third entry point cannot ship without it. `.set` on a Headers\n * object is what makes it total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated.\n */\nfunction applyUserAgent(headers: Headers): Headers {\n headers.set('user-agent', TENJIN_USER_AGENT);\n return headers;\n}\n\n/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(callerHeaders?: Record<string, string>): Record<string, string> {\n return Object.fromEntries(applyUserAgent(new Headers(callerHeaders ?? {})).entries());\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect';\n status?: number;\n requestId?: string;\n message: string;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n headers: withUserAgent(opts.headers),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n }\n const wantsAccept = opts.method === 'POST' || opts.method === 'PUT' || body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"],"mappings":";;;;;;;;;AASO,IAAM,oBAAoB,cAAc,gBAAI,OAAO;;;ACe1D,SAAS,eAAe,SAA2B;AACjD,UAAQ,IAA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1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/wallet/store.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\n\n/** A 0x-prefixed 32-byte hex private key (case-insensitive). */\nexport const PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/** The wallet-record schema this build writes and reads. Anything higher on disk\n * was written by a newer CLI; see `readWalletRecord`. */\nexport const WALLET_SCHEMA_VERSION = 2;\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance` keep working\n * without a passphrase; signing decrypts, and so does `doctor` when it can reach\n * a passphrase without prompting. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(WALLET_SCHEMA_VERSION),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n },\n );\n }\n // A NEWER CLI's record is a downgrade, not a corruption, and must be caught\n // BEFORE the generic parse failure below: that failure says to move the file\n // aside and run `wallet create`, which on a downgrade abandons a funded wallet.\n // CONTRACT_MISMATCH is the API layer's code for a schema version skew.\n const newer = newerSchemaVersion(json);\n if (newer !== null) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,\n {\n fix: 'Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds.',\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** The schema version of a record from a future CLI, or null when this build reads it. */\nfunction newerSchemaVersion(json: unknown): number | null {\n if (typeof json !== 'object' || json === null) return null;\n const v = (json as Record<string, unknown>).schemaVersion;\n // Integral only: `2.5` is not a schema we will ship, and calling it \"from the\n // future\" would send the operator into an upgrade loop. Integrality rather than\n // SAFE integrality, because an absurd-but-whole version is still a version, and\n // the alternative branch tells them to move the wallet aside and recreate it.\n return typeof v === 'number' && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n\nfunction isNotFound(err: unknown): boolean {\n return hasCode(err, 'ENOENT');\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AASxB,IAAM,iBAAiB;AAC9B,IAAM,aAAa;AAUnB,IAAM,mBAAmB,iBAAE,OAAO;AAAA,EAChC,QAAQ,iBAAE,OAAO;AAAA,IACf,QAAQ,iBAAE,QAAQ,aAAa;AAAA,IAC/B,YAAY,iBAAE,OAAO;AAAA,IACrB,cAAc,iBAAE,OAAO,EAAE,IAAI,iBAAE,OAAO,EAAE,CAAC;AAAA,IACzC,KAAK,iBAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;AAAA,IAChC,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC;AAAA,IAC3C,KAAK,iBAAE,OAAO;AAAA,EAChB,CAAC;AAAA,EACD,IAAI,iBAAE,OAAO;AAAA,EACb,SAAS,iBAAE,QAAQ,CAAC;AACtB,CAAC;AAIM,IAAM,wBAAwB;AAa9B,IAAM,qBAAqB,iBAAE,OAAO;AAAA,EACzC,eAAe,iBAAE,QAAQ,qBAAqB;AAAA,EAC9C,UAAU,iBAAE,QAAQ,OAAO;AAAA,EAC3B,SAAS,iBAAE,OAAO,EAAE,MAAM,YAAY,wCAAwC;AAAA,E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