tenjin-cli 0.1.0-alpha.14 → 0.1.0-alpha.16
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/NOTICE.md +54 -7
- package/README.md +41 -295
- package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
- package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-25TJPVBF.js +353 -0
- package/dist/chunk-25TJPVBF.js.map +1 -0
- package/dist/chunk-2BKS2FVE.js +93 -0
- package/dist/chunk-2BKS2FVE.js.map +1 -0
- package/dist/chunk-2QYORQBF.js +55 -0
- package/dist/chunk-2QYORQBF.js.map +1 -0
- package/dist/{chunk-ACBEHJAH.js → chunk-2U5ZVEV3.js} +14 -16
- package/dist/chunk-2U5ZVEV3.js.map +1 -0
- package/dist/{chunk-MJSXP4LW.js → chunk-3AJS6LLN.js} +11 -8
- package/dist/chunk-3AJS6LLN.js.map +1 -0
- package/dist/{chunk-OWVVI4VQ.js → chunk-3AUDA53C.js} +7650 -7361
- package/dist/chunk-3AUDA53C.js.map +1 -0
- package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
- package/dist/chunk-56MOAIP5.js.map +1 -0
- package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-5X4SZ5BF.js +227 -0
- package/dist/chunk-5X4SZ5BF.js.map +1 -0
- package/dist/chunk-7WEQQJLG.js +68 -0
- package/dist/chunk-7WEQQJLG.js.map +1 -0
- package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
- package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-PAOVPSP6.js → chunk-BBVUVBUO.js} +517 -138
- package/dist/chunk-BBVUVBUO.js.map +1 -0
- package/dist/{chunk-ETKZWJ4B.js → chunk-BFFM2WFK.js} +8 -8
- package/dist/chunk-BFFM2WFK.js.map +1 -0
- package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
- package/dist/chunk-DMZZLPZN.js +205 -0
- package/dist/chunk-DMZZLPZN.js.map +1 -0
- package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
- package/dist/chunk-EGELTSPU.js.map +1 -0
- package/dist/chunk-GULLJQXA.js +698 -0
- package/dist/chunk-GULLJQXA.js.map +1 -0
- package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-HVRC33OL.js +174 -0
- package/dist/chunk-HVRC33OL.js.map +1 -0
- package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-L3PVMIYQ.js +10328 -0
- package/dist/chunk-L3PVMIYQ.js.map +1 -0
- package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
- package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-OCBHUHWB.js +69 -0
- package/dist/chunk-OCBHUHWB.js.map +1 -0
- package/dist/chunk-OIM4HLN6.js +1405 -0
- package/dist/chunk-OIM4HLN6.js.map +1 -0
- package/dist/{chunk-PKW3H26Z.js → chunk-OJLYNM4Z.js} +56 -33
- package/dist/chunk-OJLYNM4Z.js.map +1 -0
- package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-PZEN5PHN.js +285 -0
- package/dist/chunk-PZEN5PHN.js.map +1 -0
- package/dist/chunk-SKAHDQH7.js +1785 -0
- package/dist/chunk-SKAHDQH7.js.map +1 -0
- package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/{chunk-QWBUKIP2.js → chunk-U5DXNFJC.js} +23 -94
- package/dist/chunk-U5DXNFJC.js.map +1 -0
- package/dist/chunk-USS336NF.js +165 -0
- package/dist/chunk-USS336NF.js.map +1 -0
- package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
- package/dist/chunk-WH7OWT6G.js.map +1 -0
- package/dist/chunk-WXC57XGG.js +29 -0
- package/dist/chunk-WXC57XGG.js.map +1 -0
- package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/{chunk-7GJQ5RGA.js → chunk-YEETV6IW.js} +1077 -1039
- package/dist/chunk-YEETV6IW.js.map +1 -0
- package/dist/{chunk-B676GPS2.js → chunk-YJHHCWM3.js} +39 -16
- package/dist/chunk-YJHHCWM3.js.map +1 -0
- package/dist/{cli-U2BEUA55.js → cli-M3XCSOU6.js} +295 -349
- package/dist/cli-M3XCSOU6.js.map +1 -0
- package/dist/config-MXOX7XDR.js +41 -0
- package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
- package/dist/doctor-LU4YIZWM.js +349 -0
- package/dist/doctor-LU4YIZWM.js.map +1 -0
- package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/{chunk-3ZW7HPY5.js → fund-A54P2QFK.js} +81 -22
- package/dist/fund-A54P2QFK.js.map +1 -0
- package/dist/hook-command-U6KWPEDQ.js +377 -0
- package/dist/hook-command-U6KWPEDQ.js.map +1 -0
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/dist/install-XUM2XSHW.js +53 -0
- package/dist/install-wallet-QIOFORTX.js +105 -0
- package/dist/install-wallet-QIOFORTX.js.map +1 -0
- package/dist/{run-CJWPGMIQ.js → mcp-HJC2PLRV.js} +3725 -10661
- package/dist/mcp-HJC2PLRV.js.map +1 -0
- package/dist/paths-P2N4JTDZ.js +49 -0
- package/dist/pay-SBXZEPEP.js +37 -0
- package/dist/redact-46ZHF2NH.js +17 -0
- package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/{send-C5EOKXOU.js → send-ASD2ZXJD.js} +28 -30
- package/dist/send-ASD2ZXJD.js.map +1 -0
- package/dist/{chunk-NAAMHWSI.js → skill-placement-NFVHY6A3.js} +159 -12
- package/dist/skill-placement-NFVHY6A3.js.map +1 -0
- package/dist/status-T2SDB57A.js +63 -0
- package/dist/status-T2SDB57A.js.map +1 -0
- package/dist/status-line-CGPUSDMC.js +71 -0
- package/dist/status-line-CGPUSDMC.js.map +1 -0
- package/dist/status-line-wiring-BYPHTYZE.js +30 -0
- package/dist/tenjin-daemon.mjs +20060 -0
- package/dist/tenjin-shim.mjs +251 -0
- package/dist/tenjin-vitest-reporter.mjs +49 -0
- package/dist/uninstall-FKYZHAM3.js +144 -0
- package/dist/uninstall-FKYZHAM3.js.map +1 -0
- package/dist/{update-24Y2CQTT.js → update-ANJ2AOTN.js} +133 -17
- package/dist/update-ANJ2AOTN.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/wallet-PWAHVKWW.js +31 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +68 -342
- package/docs/safety-model.md +25 -6
- package/package.json +8 -7
- package/LICENSE +0 -21
- package/dist/buy-2JBYPHAI.js +0 -46
- package/dist/chunk-3P3ES4XU.js +0 -144
- package/dist/chunk-3P3ES4XU.js.map +0 -1
- package/dist/chunk-3ZW7HPY5.js.map +0 -1
- package/dist/chunk-47PP7TAG.js.map +0 -1
- package/dist/chunk-4UHNXY6B.js +0 -786
- package/dist/chunk-4UHNXY6B.js.map +0 -1
- package/dist/chunk-4Y53PDH6.js +0 -213
- package/dist/chunk-4Y53PDH6.js.map +0 -1
- package/dist/chunk-54AJIO3E.js +0 -198
- package/dist/chunk-54AJIO3E.js.map +0 -1
- package/dist/chunk-736DW4V3.js +0 -65
- package/dist/chunk-736DW4V3.js.map +0 -1
- package/dist/chunk-7GJQ5RGA.js.map +0 -1
- package/dist/chunk-7NADDA2V.js +0 -161
- package/dist/chunk-7NADDA2V.js.map +0 -1
- package/dist/chunk-ACBEHJAH.js.map +0 -1
- package/dist/chunk-B676GPS2.js.map +0 -1
- package/dist/chunk-DAZAXFSF.js +0 -1357
- package/dist/chunk-DAZAXFSF.js.map +0 -1
- package/dist/chunk-DTCXO7HS.js +0 -791
- package/dist/chunk-DTCXO7HS.js.map +0 -1
- package/dist/chunk-ETKZWJ4B.js.map +0 -1
- package/dist/chunk-FDUD3W5V.js +0 -317
- package/dist/chunk-FDUD3W5V.js.map +0 -1
- package/dist/chunk-GEHL43VE.js +0 -711
- package/dist/chunk-GEHL43VE.js.map +0 -1
- package/dist/chunk-IU2HVT3Y.js +0 -313
- package/dist/chunk-IU2HVT3Y.js.map +0 -1
- package/dist/chunk-IUQZ4Z7M.js +0 -162
- package/dist/chunk-IUQZ4Z7M.js.map +0 -1
- package/dist/chunk-IXZJ3JOO.js +0 -614
- package/dist/chunk-IXZJ3JOO.js.map +0 -1
- package/dist/chunk-J6FUAIRR.js +0 -205
- package/dist/chunk-J6FUAIRR.js.map +0 -1
- package/dist/chunk-L6G35FU5.js +0 -105
- package/dist/chunk-L6G35FU5.js.map +0 -1
- package/dist/chunk-LSWP7MU2.js +0 -290
- package/dist/chunk-LSWP7MU2.js.map +0 -1
- package/dist/chunk-M2O56UK7.js.map +0 -1
- package/dist/chunk-MJSXP4LW.js.map +0 -1
- package/dist/chunk-MJZZTKCC.js.map +0 -1
- package/dist/chunk-NAAMHWSI.js.map +0 -1
- package/dist/chunk-O75FOHXS.js +0 -372
- package/dist/chunk-O75FOHXS.js.map +0 -1
- package/dist/chunk-OWVVI4VQ.js.map +0 -1
- package/dist/chunk-PAOVPSP6.js.map +0 -1
- package/dist/chunk-PCX2JQ2J.js +0 -233
- package/dist/chunk-PCX2JQ2J.js.map +0 -1
- package/dist/chunk-PKW3H26Z.js.map +0 -1
- package/dist/chunk-PQZVDCCA.js +0 -125
- package/dist/chunk-PQZVDCCA.js.map +0 -1
- package/dist/chunk-QWBUKIP2.js.map +0 -1
- package/dist/chunk-SGK2B724.js +0 -67
- package/dist/chunk-SGK2B724.js.map +0 -1
- package/dist/chunk-UHTVXQ2O.js +0 -140
- package/dist/chunk-UHTVXQ2O.js.map +0 -1
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-VEAERJVJ.js +0 -43
- package/dist/chunk-VEAERJVJ.js.map +0 -1
- package/dist/chunk-VRPLZERE.js +0 -1421
- package/dist/chunk-VRPLZERE.js.map +0 -1
- package/dist/chunk-W4VW5XYB.js +0 -149
- package/dist/chunk-W4VW5XYB.js.map +0 -1
- package/dist/chunk-WU5CZPLD.js +0 -145
- package/dist/chunk-WU5CZPLD.js.map +0 -1
- package/dist/chunk-WYLMJQVH.js +0 -240
- package/dist/chunk-WYLMJQVH.js.map +0 -1
- package/dist/chunk-XGZ5EVMB.js +0 -35
- package/dist/chunk-XGZ5EVMB.js.map +0 -1
- package/dist/chunk-XVPQGCH4.js +0 -176
- package/dist/chunk-XVPQGCH4.js.map +0 -1
- package/dist/chunk-ZOBNS7CX.js.map +0 -1
- package/dist/chunk-ZQIQ55KK.js +0 -51
- package/dist/chunk-ZQIQ55KK.js.map +0 -1
- package/dist/cli-U2BEUA55.js.map +0 -1
- package/dist/config-CNUIX23Q.js +0 -32
- package/dist/doctor-QJJXRWTO.js +0 -31
- package/dist/edit-HJ44P44P.js +0 -40
- package/dist/fund-Y5IAHZ5D.js +0 -40
- package/dist/inspect-NFQ6SQQQ.js +0 -37
- package/dist/install-DXX7PVUP.js +0 -854
- package/dist/install-DXX7PVUP.js.map +0 -1
- package/dist/outcome-ANV4QIED.js +0 -24
- package/dist/publish-PCBTCXCZ.js +0 -42
- package/dist/read-W7QVRBVD.js +0 -160
- package/dist/read-W7QVRBVD.js.map +0 -1
- package/dist/run-CJWPGMIQ.js.map +0 -1
- package/dist/search-JGAVKTYJ.js +0 -25
- package/dist/secp256k1-XRPVBC6V.js.map +0 -1
- package/dist/send-C5EOKXOU.js.map +0 -1
- package/dist/session-OBCUUIFX.js +0 -89
- package/dist/session-OBCUUIFX.js.map +0 -1
- package/dist/skill-heal-D6EPLPS6.js +0 -84
- package/dist/skill-heal-D6EPLPS6.js.map +0 -1
- package/dist/uninstall-OWJNJ5LI.js +0 -73
- package/dist/uninstall-OWJNJ5LI.js.map +0 -1
- package/dist/update-24Y2CQTT.js.map +0 -1
- package/dist/usdc-4VCDHFWX.js +0 -38
- package/dist/usdc-4VCDHFWX.js.map +0 -1
- package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
- package/dist/wallet-OFXDIIGP.js +0 -33
- package/dist/wallet-OFXDIIGP.js.map +0 -1
- package/dist/wallet-SLRIYJ2U.js +0 -42
- package/dist/wallet-SLRIYJ2U.js.map +0 -1
- package/docs/command-reference.md +0 -261
- package/skills/tenjin/SKILL.md +0 -364
- package/skills/tenjin-publish/SKILL.md +0 -224
- package/skills/tenjin-publish/references/maintain.md +0 -39
- package/skills/tenjin-search/SKILL.md +0 -149
- package/skills/tenjin-search/references/permissions.md +0 -106
- /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{buy-2JBYPHAI.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
- /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
- /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
- /package/dist/{config-CNUIX23Q.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{doctor-QJJXRWTO.js.map → install-XUM2XSHW.js.map} +0 -0
- /package/dist/{edit-HJ44P44P.js.map → paths-P2N4JTDZ.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
- /package/dist/{fund-Y5IAHZ5D.js.map → redact-46ZHF2NH.js.map} +0 -0
- /package/dist/{inspect-NFQ6SQQQ.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
- /package/dist/{outcome-ANV4QIED.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
- /package/dist/{publish-PCBTCXCZ.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
- /package/dist/{search-JGAVKTYJ.js.map → wallet-PWAHVKWW.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/config.ts","../src/lib/clack.ts","../src/lib/harness-hooks.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { stopHookIsCurrent } from '../lib/harness-hooks';\nimport {\n CONFIG_KEYS,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n loadRawConfig,\n parseSearchHookModeFlag,\n parseStopNagFlag,\n parseUpdateModeFlag,\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 UpdateConfigKey,\n} from '../lib/config';\nimport {\n detectHarnesses,\n harnessInPlay,\n harnessTargetDir,\n onPath,\n type HarnessTarget,\n} 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\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Whether this machine's harness is Claude Code (the only settings file we write).\n * Absent, it is DETECTED the way install and doctor detect it. */\n harnessIsClaude?: boolean;\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** Whether the installed Stop hook matches this build; defaults to reading it. */\n stopHookIsCurrent?: (dataDir: string) => Promise<boolean>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\nconst CONFIRM_ABOVE = 'above:';\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...UPDATE_CONFIG_KEYS].map(\n (key) => key.length,\n ),\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':\n 'end-of-turn reminder about searches nothing answered yet: on=both arms, deliberate-only=drop the batched web-search arm, off=neither',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\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\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_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 for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\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 if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\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 deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx, deps);\n if (isUpdateKey(key)) return setUpdateKey(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 deps: ConfigSetDeps,\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 const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') return { data: { key, ...entry }, humanLines };\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n added: string[];\n removed: string[];\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(mode: PublishMode, pending: readonly string[]): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} free-verb rule(s) \\`tenjin install\\` writes.` : '';\n return (\n `publish.mode ${mode} is unattended only if your harness allowlist carries ` +\n `${MODE_GATED_RULES.join(' and ')}. Add them to ~/.claude/settings.json now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { added: [], removed: [] };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n added: [],\n removed: [],\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { added: result.added, removed: result.removed };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n const isClaude = deps.harnessIsClaude ?? (await claudeInPlay(home, ctx, deps));\n if (!isClaude) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode);\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = await (deps.retractModeGated ?? retractModeGatedRules)(home);\n if (retracted.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return { added: [], removed: retracted.removed };\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [])))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return write();\n}\n\n/** Claude Code's business? The union install and doctor target with: detected on\n * PATH or by its home directory, or named by a past `--harness`, which outranks\n * the probes. */\nasync function claudeInPlay(\n home: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<boolean> {\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((c) => c.install?.harness ?? [])\n .catch(() => [] as HarnessTarget[]);\n return harnessInPlay(\n home,\n harnessTargetDir(home, 'claude'),\n detectHarnesses(home, which),\n requested,\n );\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n if (sync.added.length > 0) {\n lines.push(`Added ${sync.added.length} harness rule(s) to your allowlist.`);\n }\n if (sync.removed.length > 0) {\n lines.push(`Removed ${sync.removed.join(', ')} from your allowlist.`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\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 script reads this file on every run, so a value\n * that script UNDERSTANDS takes effect immediately with no re-install — which is\n * every value it shipped knowing about, and not `deliberate-only` on a script\n * written before that existed. That one case is reported, once, below.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\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 // ONE honest line, not a nag loop: the value is stored either way, and the\n // operator is told the running script predates it rather than left believing a\n // setting took that did not.\n const current = await (deps.stopHookIsCurrent ?? stopHookIsCurrent)(ctx.dataDir);\n const stale =\n parsed === 'deliberate-only' && !current\n ? `The installed Stop hook predates ${JSON.stringify(parsed)} and will keep treating it as \"on\". Run \\`tenjin install\\` to update it.`\n : undefined;\n return {\n data: { key, ...entry, ...(stale !== undefined ? { hookScriptStale: true } : {}) },\n humanLines: [formatLine(key, entry), ...(stale !== undefined ? [stale] : [])],\n };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: 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","import type { Readable, Writable } from 'node:stream';\n\n/**\n * The pretty-prompt renderer behind the install walkthrough's seams.\n *\n * @clack/prompts is a devDependency BUNDLED by tsup (published `dependencies`\n * stays `{}`), and every entry point here is behind a dynamic `import()` so it\n * lands in its own split chunk: a `search` or `doctor` run never parses it.\n *\n * Nothing in this module is reachable from a machine run. Commands call it only\n * on the real interactive path (a TTY on both stdout and stdin, no `--json`),\n * and always through an injectable seam, so unit tests supply answers directly\n * and never touch clack or a terminal.\n *\n * Prompts render on STDERR, like every other prompt in this CLI: stdout carries\n * the human walkthrough (or a single JSON envelope) and must not be interleaved\n * with prompt chrome.\n */\n\n/** Cancel (ctrl-C, escape) is not an answer. Callers map `null` to their own default. */\nexport type Cancelled = null;\n\nexport interface SelectChoice<T extends string> {\n value: T;\n label: string;\n /** The one line of consequence shown beside the label. */\n hint?: string;\n}\n\n/** Streams a prompt reads and draws on. Injected by tests; defaults to the real ones. */\ninterface PromptStreams {\n input?: Readable;\n output?: Writable;\n}\n\n/** DECTCUM show-cursor. Written on the EOF path in case the prompt did not get to. */\nconst SHOW_CURSOR = '\\x1b[?25h';\n\n/**\n * Settle a prompt when its input goes away instead of hanging forever.\n *\n * Ctrl-D at a clack prompt leaves its promise unsettled: no resolve, no reject,\n * no cancel symbol. The process then dies on an unsettled top-level await with\n * exit 13, nothing printed, and the cursor still hidden. The readline seam this\n * replaced handled it on purpose (\"ctrl-D mid-prompt reads as the default\"), and\n * that behavior has to survive the renderer swap.\n *\n * \"Input goes away\" is two different events, and only covering one of them was\n * the original bug:\n *\n * - The STREAM ends. A pipe closes, a harness detaches, stdin was already at\n * EOF. Caught via `end` / `close`.\n * - The ctrl-D BYTE (0x04) arrives with the stream still open. This is what a\n * real terminal sends, and it is the common case. A prompt puts stdin in raw\n * mode, where 0x04 is ordinary data rather than EOF, so no stream event ever\n * fires; clack has no binding for it and simply keeps waiting. Caught via the\n * `keypress` decoder readline installs, which is a read-only view of the same\n * bytes: listening there takes nothing away from the prompt, where a `data`\n * listener would risk flipping the stream to flowing before clack reads it.\n *\n * Two mechanisms settle it, because one of them is advisory. The AbortSignal is\n * clack's own teardown: it flips the prompt to `cancel`, which restores the\n * cursor and raw mode and resolves with the cancel symbol. The race is the\n * guarantee, for a prompt that is not yet listening or never settles anyway; on\n * that path we restore the cursor ourselves, since no prompt did.\n */\nfunction withInputEnd<T>(\n streams: Required<PromptStreams>,\n onEnd: T,\n run: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController();\n let settleEnd: (() => void) | undefined;\n const ended = new Promise<T>((resolve) => {\n settleEnd = () => {\n streams.output.write(SHOW_CURSOR);\n resolve(onEnd);\n };\n });\n\n const end = (): void => {\n controller.abort();\n settleEnd?.();\n };\n const onKeypress = (_text: string | undefined, key?: { name?: string; ctrl?: boolean }): void => {\n if (key?.ctrl === true && key.name === 'd') end();\n };\n\n streams.input.on('keypress', onKeypress);\n // A stream that finished before we got here never emits `end` again, so ask.\n if (streams.input.readableEnded) {\n queueMicrotask(end);\n } else {\n streams.input.once('end', end);\n streams.input.once('close', end);\n }\n\n return Promise.race([run(controller.signal), ended]).finally(() => {\n streams.input.off('keypress', onKeypress);\n streams.input.off('end', end);\n streams.input.off('close', end);\n });\n}\n\nfunction resolveStreams(streams: PromptStreams): Required<PromptStreams> {\n return { input: streams.input ?? process.stdin, output: streams.output ?? process.stderr };\n}\n\n/**\n * A single-choice list. Returns the chosen value, or `null` when the operator\n * cancelled or the input ended, both of which callers treat as \"leave everything\n * as it was\".\n */\nexport async function selectOne<T extends string>(opts: {\n message: string;\n choices: readonly SelectChoice<T>[];\n initialValue: T;\n streams?: PromptStreams;\n}): Promise<T | Cancelled> {\n const { select, isCancel } = await import('@clack/prompts');\n const streams = resolveStreams(opts.streams ?? {});\n return withInputEnd<T | Cancelled>(streams, null, async (signal) => {\n // Instantiated at `string`, not at `T`: clack's `Option<Value>` is a conditional\n // type that a generic `T extends string` cannot resolve. The values come from\n // this call's own choices, so narrowing the answer back is sound.\n const answer = await select<string>({\n message: opts.message,\n options: opts.choices.map((c) => ({\n value: c.value as string,\n label: c.label,\n ...(c.hint !== undefined ? { hint: c.hint } : {}),\n })),\n initialValue: opts.initialValue,\n input: streams.input,\n output: streams.output,\n signal,\n });\n return isCancel(answer) ? null : (answer as T);\n });\n}\n\n/** A yes/no confirm. Cancelling, or an input that ends, reads as no. */\nexport async function confirmChoice(\n message: string,\n initialValue = true,\n streams: PromptStreams = {},\n): Promise<boolean> {\n const { confirm, isCancel } = await import('@clack/prompts');\n const resolved = resolveStreams(streams);\n return withInputEnd<boolean>(resolved, false, async (signal) => {\n const answer = await confirm({\n message,\n initialValue,\n input: resolved.input,\n output: resolved.output,\n signal,\n });\n return isCancel(answer) ? false : answer;\n });\n}\n\n/** Open the walkthrough's prompt sequence with a title bar. */\nexport async function intro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.intro(message, { output: process.stderr });\n}\n\n/** Close it, so the last prompt is not left dangling above plain stdout lines. */\nexport async function outro(message: string): Promise<void> {\n const clack = await import('@clack/prompts');\n clack.outro(message, { output: process.stderr });\n}\n","import { lstat, readFile, realpath } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { claudeSettingsPath } from './harness-permissions';\nimport { hooksDir } from './paths';\nimport {\n STOP_HOOK_FILE,\n WEBSEARCH_HOOK_FILE,\n stopHookScript,\n websearchHookScript,\n} from './hook-scripts';\nimport type { SearchHookMode } from './config';\n\n/**\n * The second place the CLI writes into a harness's own settings file, and it\n * carries the same invariants as lib/harness-permissions.ts for the same reasons:\n * additive only, never clobbers a file it cannot understand, and refuses rather\n * than overwriting a change that landed mid-run. Read that module's header first;\n * what follows is only what is different here.\n *\n * WHAT A HOOK ENTRY IS. Unlike a permission rule, a hook entry names an\n * executable. Two properties keep that honest:\n *\n * - The command can only ever be `node <path under the Tenjin data dir>`. There\n * is no argument, no config key, and no call path that lets a caller point a\n * hook at some other program, and the scripts themselves are generated from\n * constants in lib/hook-scripts.ts rather than from anything on the wire.\n * - Neither hook can block, deny, or modify a tool call. The WebSearch hook emits\n * `additionalContext` and never `permissionDecision`, so a WebSearch always\n * proceeds; the Stop hook only ever adds a line at the end of a turn.\n *\n * OWNERSHIP IS BY PATH. An entry is ours when its command mentions one of our two\n * script filenames. That is what makes a re-install idempotent, lets a drifted\n * command (an older install's path, a moved data dir) be rewritten in place\n * instead of duplicated, and keeps every entry someone else wrote untouched.\n */\n\n/** The hook events this module writes, in the order they are reported. */\nexport const HOOK_EVENTS = ['PreToolUse', 'Stop'] as const;\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** The tool the WebSearch hook fires on. Never `WebFetch`, never a wildcard. */\nexport const WEBSEARCH_MATCHER = 'WebSearch';\n\n/**\n * Seconds the harness allows each hook before killing it, and the HARD bound on\n * how long either can delay anything. The scripts' own watchdogs (2s and 1.5s)\n * are the design budget and cover the ordinary case, but they are event-loop\n * timers: a synchronous read that blocks outlasts them. This kill does not, so it\n * is the number to quote when the question is \"what is the worst case\".\n */\nconst HOOK_TIMEOUT_SECONDS = 5;\n\nexport type HooksSkipReason =\n | 'harness-not-claude'\n | 'mode-off'\n | 'declined'\n | 'dry-run'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read';\n\nexport interface HooksResult {\n /** The harness this outcome is about; only `claude` has a settings file we write. */\n harness: string;\n /** The settings file, absent when the harness has no such file. */\n path?: string;\n /** Where the hook scripts live (or would). */\n scriptsDir: string;\n /** The behavior the installed scripts will follow (config `hooks.searchMode`). */\n mode: SearchHookMode;\n /** Events whose entry this run appended. */\n added: HookEvent[];\n /** Events whose entry was already there, byte-identical. */\n alreadyPresent: HookEvent[];\n /** Events whose existing entry pointed somewhere else and was rewritten in place. */\n updated: HookEvent[];\n /** Script files this run wrote or refreshed. */\n scripts: string[];\n skipped?: HooksSkipReason;\n /** Human-readable detail for a skip that is a problem rather than a choice. */\n warning?: string;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n}\n\n/** The undo, stated the same way everywhere it is shown. */\nexport function hooksUndo(settingsPath: string, scriptsDir: string): string {\n return `Undo anytime: \\`tenjin config set hooks.searchMode off\\` disarms them, or delete the tenjin hook entries from ${settingsPath} and the scripts in ${scriptsDir}.`;\n}\n\nfunction skip(\n reason: HooksSkipReason,\n args: {\n harness: string;\n path?: string;\n scriptsDir: string;\n mode: SearchHookMode;\n warning?: string;\n fix?: string;\n },\n): HooksResult {\n return {\n harness: args.harness,\n ...(args.path !== undefined ? { path: args.path } : {}),\n scriptsDir: args.scriptsDir,\n mode: args.mode,\n added: [],\n alreadyPresent: [],\n updated: [],\n scripts: [],\n skipped: reason,\n ...(args.warning !== undefined ? { warning: args.warning } : {}),\n ...(args.fix !== undefined ? { fix: args.fix } : {}),\n };\n}\n\n/** A decision NOT to wire, shaped like a write outcome so the caller has one type. */\nexport function hooksSkipped(\n harness: string,\n homeDir: string,\n dataDir: string,\n mode: SearchHookMode,\n reason: HooksSkipReason,\n): HooksResult {\n return skip(reason, {\n harness,\n ...(harness === 'claude' ? { path: claudeSettingsPath(homeDir) } : {}),\n scriptsDir: hooksDir(dataDir),\n mode,\n fix: fixFor(reason),\n });\n}\n\n/**\n * The command that turns a skip into a write. Every skipped state names one, so a\n * machine consumer reading the envelope never has to work out the remedy from\n * prose, which is the same contract a CliError's `fix` carries.\n */\nfunction fixFor(reason: HooksSkipReason): string {\n switch (reason) {\n case 'harness-not-claude':\n return 'Hooks are wired for Claude Code only. Re-run `tenjin install --harness claude` on a machine with Claude Code.';\n case 'mode-off':\n return 'Enable them with `tenjin config set hooks.searchMode auto`, then re-run `tenjin install`.';\n case 'declined':\n case 'dry-run':\n return 'Wire them with `tenjin install --search-hooks auto`.';\n case 'changed-since-read':\n return 'Another process changed the file mid-run; re-run `tenjin install`.';\n default:\n return 'Fix the reported file, then re-run `tenjin install --search-hooks auto`.';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Quote a path for the shell the harness runs a `command` hook through. POSIX\n * shells take single quotes (with the standard `'\\''` escape for an embedded\n * one); cmd.exe does not understand them at all and takes double quotes. Getting\n * this wrong on a home directory with a space silently installs a hook that can\n * never run, so it is a real branch rather than an assumption about paths.\n */\nexport function quoteForShell(path: string, platform: string = process.platform): string {\n if (platform === 'win32') return `\"${path}\"`;\n return `'${path.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction commandFor(scriptPath: string, platform?: string): string {\n return `node ${quoteForShell(scriptPath, platform)}`;\n}\n\n/** One hook handler, exactly as it is written into settings.json. */\nfunction handlerFor(scriptPath: string, platform?: string): Record<string, unknown> {\n return {\n type: 'command',\n command: commandFor(scriptPath, platform),\n timeout: HOOK_TIMEOUT_SECONDS,\n };\n}\n\n/** Is this settings.json entry one of ours? Keyed on the script FILENAME, so a\n * data dir that moved is recognized as our entry and rewritten, not duplicated. */\nfunction ownsEntry(entry: unknown, scriptFile: string): boolean {\n if (!isPlainObject(entry)) return false;\n const handlers = entry.hooks;\n if (!Array.isArray(handlers)) return false;\n return handlers.some(\n (h) => isPlainObject(h) && typeof h.command === 'string' && h.command.includes(scriptFile),\n );\n}\n\ninterface HookSpec {\n event: HookEvent;\n scriptFile: string;\n script: string;\n /** Absent for Stop, which the harness fires on every occurrence with no matcher. */\n matcher?: string;\n}\n\nfunction specs(dataDir: string): HookSpec[] {\n return [\n {\n event: 'PreToolUse',\n scriptFile: WEBSEARCH_HOOK_FILE,\n script: websearchHookScript(dataDir),\n matcher: WEBSEARCH_MATCHER,\n },\n { event: 'Stop', scriptFile: STOP_HOOK_FILE, script: stopHookScript(dataDir) },\n ];\n}\n\n/**\n * Does the Stop hook ON DISK match what this build would write?\n *\n * `hooks.stopNag` is read by the installed script at run time, so a `config set`\n * takes effect immediately — but only for values that script UNDERSTANDS. A\n * script written before `deliberate-only` existed maps every non-`off` value to\n * `on`, so the set succeeds, `config get` reports it effective from `file`, and\n * the batch keeps firing. Never throws: a machine with no hook installed is not\n * drifted, it is unhooked, and neither is this function's caller's problem to\n * fail on.\n */\nexport async function stopHookIsCurrent(dataDir: string): Promise<boolean> {\n const spec = specs(dataDir).find((h) => h.scriptFile === STOP_HOOK_FILE);\n if (spec === undefined) return true;\n const path = join(hooksDir(dataDir), STOP_HOOK_FILE);\n const onDisk = await readFile(path, 'utf8').catch(() => null);\n // Absent means nothing is running that could be stale.\n return onDisk === null || onDisk === spec.script;\n}\n\nexport interface WireHooksOptions {\n homeDir: string;\n dataDir: string;\n mode: SearchHookMode;\n /** Shell-quoting target; injected so both branches are testable on one machine. */\n platform?: string;\n}\n\n/**\n * Write the hook scripts and merge their entries into ~/.claude/settings.json.\n *\n * The SCRIPTS are written whatever the mode, including `off`: the mode is read by\n * the script at run time, so an operator who later flips `hooks.searchMode` back\n * to `auto` gets working hooks without re-installing. Only `mode: 'off'` is\n * refused at the caller (see `hooksSkipped`), which leaves settings.json alone\n * entirely.\n *\n * Idempotent: a second run rewrites no script whose bytes match, appends no entry\n * that is already there, and does not touch settings.json at all when nothing\n * changed.\n */\nexport async function wireSearchHooks(opts: WireHooksOptions): Promise<HooksResult> {\n const { homeDir, dataDir, mode, platform } = opts;\n const scriptsDir = hooksDir(dataDir);\n const plan = specs(dataDir);\n\n const found = await inspectSettings(homeDir, scriptsDir, mode);\n if ('result' in found) return found.result;\n const { path, raw, settings, hooks } = found;\n\n const added: HookEvent[] = [];\n const alreadyPresent: HookEvent[] = [];\n const updated: HookEvent[] = [];\n const nextHooks: Record<string, unknown> = { ...hooks };\n\n for (const spec of plan) {\n const existing = hooks[spec.event];\n if (existing !== undefined && !Array.isArray(existing)) {\n return refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} has a \"hooks.${spec.event}\" key that is not an array; it was left exactly as it is.`,\n );\n }\n const list: unknown[] = existing ?? [];\n const desired = {\n ...(spec.matcher !== undefined ? { matcher: spec.matcher } : {}),\n hooks: [handlerFor(join(scriptsDir, spec.scriptFile), platform)],\n };\n const idx = list.findIndex((e) => ownsEntry(e, spec.scriptFile));\n if (idx === -1) {\n nextHooks[spec.event] = [...list, desired];\n added.push(spec.event);\n continue;\n }\n if (JSON.stringify(list[idx]) === JSON.stringify(desired)) {\n alreadyPresent.push(spec.event);\n continue;\n }\n // Ours, but stale: an older install's path, or a data dir that moved. Rewritten\n // IN PLACE so the entry keeps its position among whatever else is registered.\n nextHooks[spec.event] = list.map((e, i) => (i === idx ? desired : e));\n updated.push(spec.event);\n }\n\n // Nothing to register: no guard is involved, so the scripts are simply brought\n // up to date. This is the path a re-run takes after an upgrade changed a body.\n if (added.length === 0 && updated.length === 0) {\n const scripts = await writeScripts(plan, scriptsDir);\n return { harness: 'claude', path, scriptsDir, mode, added, alreadyPresent, updated, scripts };\n }\n\n const next = { ...settings, hooks: nextHooks };\n // TWO compares, and both are load-bearing.\n //\n // The FIRST is cheap and early: it refuses before a single byte is written, so\n // the ordinary contended case costs nothing and leaves nothing half-done.\n const changed = async (): Promise<boolean> =>\n (await readFile(path, 'utf8').catch(() => null)) !== raw;\n if (await changed()) return refuseChanged(path, scriptsDir, mode, []);\n\n // Past the first guard, and still before the entry that points at them, so a\n // harness never reads an entry naming a file that is not on disk yet.\n const scripts = await writeScripts(plan, scriptsDir);\n\n // The SECOND compare sits ADJACENT to the commit, because the writes above are\n // two read/write/rename sequences wide and this is a whole-file replacement\n // built from a snapshot taken before them. Claude Code writing settings.json\n // during that window passed the first compare and would be erased here. The\n // refusal reports the scripts that WERE refreshed, so the result describes what\n // actually happened rather than claiming nothing was touched: the bodies are\n // versioned and idempotent, so a refreshed script with no new entry is inert\n // and the re-run the fix names simply registers it.\n if (await changed()) return refuseChanged(path, scriptsDir, mode, scripts);\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`);\n return { harness: 'claude', path, scriptsDir, mode, added, alreadyPresent, updated, scripts };\n}\n\n/**\n * The `changed-since-read` refusal, carrying whatever scripts the run had already\n * refreshed. Nothing about settings.json is written on this path.\n */\nfunction refuseChanged(\n path: string,\n scriptsDir: string,\n mode: SearchHookMode,\n scripts: string[],\n): HooksResult {\n return {\n ...refuse(\n path,\n scriptsDir,\n mode,\n 'changed-since-read',\n `${path} changed while it was being updated, so no hooks were registered. Re-run \\`tenjin install\\`.`,\n ),\n scripts,\n };\n}\n\n/** Bring each script up to date, returning the ones this run actually wrote. A\n * body that already matches is left alone, so a re-run rewrites nothing. */\nasync function writeScripts(plan: HookSpec[], scriptsDir: string): Promise<string[]> {\n const written: string[] = [];\n for (const spec of plan) {\n const target = join(scriptsDir, spec.scriptFile);\n const onDisk = await readFile(target, 'utf8').catch(() => null);\n if (onDisk === spec.script) continue;\n await writeFileAtomic(target, spec.script, { mode: 0o755, dirMode: 0o700 });\n written.push(target);\n }\n return written;\n}\n\nfunction refuse(\n path: string,\n scriptsDir: string,\n mode: SearchHookMode,\n reason: HooksSkipReason,\n warning: string,\n): HooksResult {\n return skip(reason, { harness: 'claude', path, scriptsDir, mode, warning, fix: fixFor(reason) });\n}\n\ninterface SettingsInspection {\n path: string;\n /** The exact bytes read, so the commit can prove nothing changed underneath it. */\n raw: string | null;\n settings: Record<string, unknown>;\n hooks: Record<string, unknown>;\n}\n\n/**\n * Resolve and read the settings file. Every refusal lives here, so the shape\n * checks and the write agree by construction. Symlinks are resolved before the\n * write for the same reason lib/harness-permissions.ts resolves them: committing\n * with a rename over a dotfiles-managed link would sever it.\n */\nasync function inspectSettings(\n homeDir: string,\n scriptsDir: string,\n mode: SearchHookMode,\n): Promise<SettingsInspection | { result: HooksResult }> {\n const declaredPath = claudeSettingsPath(homeDir);\n const entry = await lstat(declaredPath).catch(() => null);\n\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return {\n result: refuse(\n declaredPath,\n scriptsDir,\n mode,\n 'unresolvable',\n `${declaredPath} could not be resolved (${(err as Error).message}); it was left exactly as it is.`,\n ),\n };\n }\n }\n\n let settings: Record<string, unknown> = {};\n let raw: string | null = null;\n if (entry !== null) {\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unreadable',\n `${path} could not be read (${(err as Error).message}); no hooks were registered.`,\n ),\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unparsable',\n `${path} is not valid JSON (${(err as Error).message}); it was left exactly as it is.`,\n ),\n };\n }\n if (!isPlainObject(parsed)) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} is not a JSON object; it was left exactly as it is.`,\n ),\n };\n }\n settings = parsed;\n }\n\n const hooksValue = settings.hooks;\n if (hooksValue !== undefined && !isPlainObject(hooksValue)) {\n return {\n result: refuse(\n path,\n scriptsDir,\n mode,\n 'unexpected-shape',\n `${path} has a \"hooks\" key that is not an object; it was left exactly as it is.`,\n ),\n };\n }\n return { path, raw, settings, hooks: hooksValue ?? {} };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,iBAAiB;;;ACkC1B,IAAM,cAAc;AA8BpB,SAAS,aACP,SACA,OACA,KACY;AACZ,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI;AACJ,QAAM,QAAQ,IAAI,QAAW,CAAC,YAAY;AACxC,gBAAY,MAAM;AAChB,cAAQ,OAAO,MAAM,WAAW;AAChC,cAAQ,KAAK;AAAA,IACf;AAAA,EACF,CAAC;AAED,QAAM,MAAM,MAAY;AACtB,eAAW,MAAM;AACjB,gBAAY;AAAA,EACd;AACA,QAAM,aAAa,CAAC,OAA2B,QAAkD;AAC/F,QAAI,KAAK,SAAS,QAAQ,IAAI,SAAS,IAAK,KAAI;AAAA,EAClD;AAEA,UAAQ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AS,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":["scripts","settings","entry"]}
|
package/dist/chunk-4Y53PDH6.js
DELETED
|
@@ -1,213 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
findStoredCandidate
|
|
4
|
-
} from "./chunk-7NADDA2V.js";
|
|
5
|
-
import {
|
|
6
|
-
SLUG_RE,
|
|
7
|
-
UUID_RE
|
|
8
|
-
} from "./chunk-736DW4V3.js";
|
|
9
|
-
import {
|
|
10
|
-
CliError,
|
|
11
|
-
external_exports,
|
|
12
|
-
writeFileAtomic
|
|
13
|
-
} from "./chunk-PAOVPSP6.js";
|
|
14
|
-
|
|
15
|
-
// src/lib/library.ts
|
|
16
|
-
import { createHash } from "crypto";
|
|
17
|
-
import { readFile, readdir } from "fs/promises";
|
|
18
|
-
import { isAbsolute, join, relative, resolve } from "path";
|
|
19
|
-
var ReceiptSchema = external_exports.object({
|
|
20
|
-
schemaVersion: external_exports.literal(1),
|
|
21
|
-
resourceId: external_exports.string(),
|
|
22
|
-
slug: external_exports.string(),
|
|
23
|
-
title: external_exports.string(),
|
|
24
|
-
handle: external_exports.string(),
|
|
25
|
-
url: external_exports.string(),
|
|
26
|
-
priceAtomic: external_exports.string(),
|
|
27
|
-
entitlement: external_exports.enum(["free", "entitled", "purchased"]),
|
|
28
|
-
contentHash: external_exports.string(),
|
|
29
|
-
settlementTxHash: external_exports.string().optional(),
|
|
30
|
-
savedAt: external_exports.string()
|
|
31
|
-
});
|
|
32
|
-
function libraryDir(dataDir) {
|
|
33
|
-
return join(dataDir, "library");
|
|
34
|
-
}
|
|
35
|
-
function resourceDir(dataDir, resourceId) {
|
|
36
|
-
return join(libraryDir(dataDir), resourceId);
|
|
37
|
-
}
|
|
38
|
-
function isSafeIdentity(resourceId, slug) {
|
|
39
|
-
return UUID_RE.test(resourceId) && slug.length <= 80 && SLUG_RE.test(slug);
|
|
40
|
-
}
|
|
41
|
-
function assertContained(dataDir, resourceId, slug) {
|
|
42
|
-
if (!isSafeIdentity(resourceId, slug)) {
|
|
43
|
-
throw new CliError("CONTRACT_MISMATCH", "The server returned an unsafe resource identity.", {
|
|
44
|
-
fix: "Update tenjin-cli or report the resource; the id/slug is not a valid identity.",
|
|
45
|
-
details: { resourceId, slug }
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
const root = resolve(libraryDir(dataDir));
|
|
49
|
-
const target = resolve(bodyPath(dataDir, resourceId, slug));
|
|
50
|
-
const rel = relative(root, target);
|
|
51
|
-
if (rel.startsWith("..") || isAbsolute(rel) || rel.split(/[\\/]/).includes("..")) {
|
|
52
|
-
throw new CliError("CONTRACT_MISMATCH", "The delivery path escapes the library directory.", {
|
|
53
|
-
fix: "Update tenjin-cli; the resource identity is unsafe."
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
function bodyPath(dataDir, resourceId, slug) {
|
|
58
|
-
return join(resourceDir(dataDir, resourceId), `${slug}.md`);
|
|
59
|
-
}
|
|
60
|
-
function receiptPath(dataDir, resourceId) {
|
|
61
|
-
return join(resourceDir(dataDir, resourceId), "receipt.json");
|
|
62
|
-
}
|
|
63
|
-
function contentHash(bodyMd) {
|
|
64
|
-
return `sha256:${createHash("sha256").update(bodyMd, "utf8").digest("hex")}`;
|
|
65
|
-
}
|
|
66
|
-
async function findDelivered(dataDir, resourceId) {
|
|
67
|
-
if (!UUID_RE.test(resourceId)) return null;
|
|
68
|
-
let receiptRaw;
|
|
69
|
-
try {
|
|
70
|
-
receiptRaw = await readFile(receiptPath(dataDir, resourceId), "utf8");
|
|
71
|
-
} catch {
|
|
72
|
-
return null;
|
|
73
|
-
}
|
|
74
|
-
const parsed = ReceiptSchema.safeParse(safeJson(receiptRaw));
|
|
75
|
-
if (!parsed.success) return null;
|
|
76
|
-
const path = bodyPath(dataDir, resourceId, parsed.data.slug);
|
|
77
|
-
let bodyMd;
|
|
78
|
-
try {
|
|
79
|
-
bodyMd = await readFile(path, "utf8");
|
|
80
|
-
} catch {
|
|
81
|
-
return null;
|
|
82
|
-
}
|
|
83
|
-
return { receipt: parsed.data, bodyMd, bodyPath: path };
|
|
84
|
-
}
|
|
85
|
-
var READ_PATH_RE = /\/api\/read\/([^/]+)\/([^/]+)\/?$/;
|
|
86
|
-
function parseReadPath(url) {
|
|
87
|
-
let pathname;
|
|
88
|
-
try {
|
|
89
|
-
pathname = new URL(url).pathname;
|
|
90
|
-
} catch {
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
const m = READ_PATH_RE.exec(pathname);
|
|
94
|
-
if (m === null || m[1] === void 0 || m[2] === void 0) return null;
|
|
95
|
-
return { handle: decodeURIComponent(m[1]), slug: decodeURIComponent(m[2]) };
|
|
96
|
-
}
|
|
97
|
-
function canonicalReadUrl(url) {
|
|
98
|
-
if (parseReadPath(url) === null) return url;
|
|
99
|
-
const mark = url.search(/[?#]/);
|
|
100
|
-
const path = mark === -1 ? url : url.slice(0, mark);
|
|
101
|
-
if (!path.endsWith("/")) return url;
|
|
102
|
-
return path.slice(0, -1) + (mark === -1 ? "" : url.slice(mark));
|
|
103
|
-
}
|
|
104
|
-
async function findDeliveredByUrl(dataDir, url) {
|
|
105
|
-
const target = parseReadPath(url);
|
|
106
|
-
if (target === null) return null;
|
|
107
|
-
let entries;
|
|
108
|
-
try {
|
|
109
|
-
entries = await readdir(libraryDir(dataDir));
|
|
110
|
-
} catch {
|
|
111
|
-
return null;
|
|
112
|
-
}
|
|
113
|
-
for (const resourceId of entries) {
|
|
114
|
-
if (!UUID_RE.test(resourceId)) continue;
|
|
115
|
-
const delivered = await findDelivered(dataDir, resourceId);
|
|
116
|
-
if (delivered === null) continue;
|
|
117
|
-
const saved = parseReadPath(delivered.receipt.url);
|
|
118
|
-
if (saved !== null && saved.handle === target.handle && saved.slug === target.slug) {
|
|
119
|
-
return delivered;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
return null;
|
|
123
|
-
}
|
|
124
|
-
async function saveDelivery(dataDir, input) {
|
|
125
|
-
assertContained(dataDir, input.resourceId, input.slug);
|
|
126
|
-
const path = bodyPath(dataDir, input.resourceId, input.slug);
|
|
127
|
-
const receipt = {
|
|
128
|
-
schemaVersion: 1,
|
|
129
|
-
resourceId: input.resourceId,
|
|
130
|
-
slug: input.slug,
|
|
131
|
-
title: input.title,
|
|
132
|
-
handle: input.handle,
|
|
133
|
-
url: input.url,
|
|
134
|
-
priceAtomic: input.priceAtomic,
|
|
135
|
-
entitlement: input.entitlement,
|
|
136
|
-
contentHash: contentHash(input.bodyMd),
|
|
137
|
-
...input.settlementTxHash !== void 0 ? { settlementTxHash: input.settlementTxHash } : {},
|
|
138
|
-
savedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
139
|
-
};
|
|
140
|
-
await writeFileAtomic(path, input.bodyMd, { mode: 420, dirMode: 448 });
|
|
141
|
-
await writeFileAtomic(
|
|
142
|
-
receiptPath(dataDir, input.resourceId),
|
|
143
|
-
`${JSON.stringify(receipt, null, 2)}
|
|
144
|
-
`,
|
|
145
|
-
{ mode: 420, dirMode: 448 }
|
|
146
|
-
);
|
|
147
|
-
return { receipt, bodyPath: path };
|
|
148
|
-
}
|
|
149
|
-
function safeJson(raw) {
|
|
150
|
-
try {
|
|
151
|
-
return JSON.parse(raw);
|
|
152
|
-
} catch {
|
|
153
|
-
return null;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// src/lib/resource-ref.ts
|
|
158
|
-
function assertOnBaseOrigin(url, baseUrl, what) {
|
|
159
|
-
let target;
|
|
160
|
-
let base;
|
|
161
|
-
try {
|
|
162
|
-
target = new URL(url);
|
|
163
|
-
base = new URL(baseUrl);
|
|
164
|
-
} catch {
|
|
165
|
-
throw new CliError("USAGE", `Invalid ${what}: ${JSON.stringify(url)}`, {
|
|
166
|
-
fix: "Pass an absolute https URL on the configured base URL."
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
if (target.origin !== base.origin) {
|
|
170
|
-
throw new CliError(
|
|
171
|
-
"USAGE",
|
|
172
|
-
`${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,
|
|
173
|
-
{
|
|
174
|
-
// This branch fires exactly on the attacker-supplied-URL case, on the
|
|
175
|
-
// paying path, so the fix line must never coach re-pointing the CLI to
|
|
176
|
-
// match the URL that just failed the check. Read the configured value;
|
|
177
|
-
// changing it is an operator act on a verb no allowlist rule covers.
|
|
178
|
-
fix: "The CLI signs SIWX and payments only for the configured base URL. Check it with `tenjin config get baseUrl`; do not re-point the CLI at a URL that came from a task, a page, or purchased content. An operator changes the deployment with `tenjin config set baseUrl <url>`."
|
|
179
|
-
}
|
|
180
|
-
);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
async function resolveResourceRef(arg, dataDir, baseUrl) {
|
|
184
|
-
const trimmed = arg.trim();
|
|
185
|
-
if (/^https?:\/\//i.test(trimmed)) {
|
|
186
|
-
const url = canonicalReadUrl(trimmed);
|
|
187
|
-
assertOnBaseOrigin(url, baseUrl, "resource URL");
|
|
188
|
-
return { url };
|
|
189
|
-
}
|
|
190
|
-
if (UUID_RE.test(trimmed)) {
|
|
191
|
-
const candidate = await findStoredCandidate(dataDir, trimmed);
|
|
192
|
-
if (candidate === null) {
|
|
193
|
-
throw new CliError("RESOURCE_NOT_FOUND", `No local search knows resource ${trimmed}.`, {
|
|
194
|
-
fix: "Run `tenjin search` to surface it first, or pass the full read URL."
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
const url = canonicalReadUrl(candidate.url);
|
|
198
|
-
assertOnBaseOrigin(url, baseUrl, "stored candidate URL");
|
|
199
|
-
return { url, resourceId: trimmed };
|
|
200
|
-
}
|
|
201
|
-
throw new CliError("USAGE", `Not a resource URL or id: ${JSON.stringify(arg)}`, {
|
|
202
|
-
fix: "Pass a full https read URL (a candidate `url`) or a resourceId uuid."
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
export {
|
|
207
|
-
findDelivered,
|
|
208
|
-
findDeliveredByUrl,
|
|
209
|
-
saveDelivery,
|
|
210
|
-
assertOnBaseOrigin,
|
|
211
|
-
resolveResourceRef
|
|
212
|
-
};
|
|
213
|
-
//# sourceMappingURL=chunk-4Y53PDH6.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/library.ts","../src/lib/resource-ref.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * Filesystem identity is server-controlled (the read body's id + slug), so it is\n * hostile input to a path. resourceId must be a uuid and slug must match the\n * server's slug charset (lib/posts.ts slugify: lowercase a-z0-9 groups joined by\n * single hyphens, no leading/trailing hyphen, <=80 chars). This is the primary\n * guard; assertContained is the defense-in-depth backstop.\n */\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/**\n * Local library delivery (spec 10): purchased or freely-read bodies are saved\n * under `<dataDir>/library/<resourceId>/<slug>.md` with a sidecar `receipt.json`\n * carrying the entitlement + payment identity. A `buy` on already-delivered\n * content re-delivers FROM DISK, the receipt is the local entitlement record, so\n * a repeat buy never re-pays and never re-fetches. `contentHash` is the sha256 the\n * outcome endpoint expects, computed over the exact saved bytes.\n */\n\nexport type Entitlement = 'free' | 'entitled' | 'purchased';\n\nexport const ReceiptSchema = z.object({\n schemaVersion: z.literal(1),\n resourceId: z.string(),\n slug: z.string(),\n title: z.string(),\n handle: z.string(),\n url: z.string(),\n priceAtomic: z.string(),\n entitlement: z.enum(['free', 'entitled', 'purchased']),\n contentHash: z.string(),\n settlementTxHash: z.string().optional(),\n savedAt: z.string(),\n});\nexport type Receipt = z.infer<typeof ReceiptSchema>;\n\nexport function libraryDir(dataDir: string): string {\n return join(dataDir, 'library');\n}\n\nexport function resourceDir(dataDir: string, resourceId: string): string {\n return join(libraryDir(dataDir), resourceId);\n}\n\n/** True when `resourceId` is a uuid and `slug` matches the server's slug charset,\n * so neither can carry a path separator or `..`. */\nexport function isSafeIdentity(resourceId: string, slug: string): boolean {\n return RESOURCE_ID_RE.test(resourceId) && slug.length <= 80 && SLUG_RE.test(slug);\n}\n\n/**\n * Defense-in-depth: refuse a delivery whose identity is malformed OR whose\n * resolved write path escapes the library root. A malicious server returning\n * id='../../etc' or slug='../../evil' is rejected as a contract violation before\n * any bytes (or directories) are written.\n */\nfunction assertContained(dataDir: string, resourceId: string, slug: string): void {\n if (!isSafeIdentity(resourceId, slug)) {\n throw new CliError('CONTRACT_MISMATCH', 'The server returned an unsafe resource identity.', {\n fix: 'Update tenjin-cli or report the resource; the id/slug is not a valid identity.',\n details: { resourceId, slug },\n });\n }\n const root = resolve(libraryDir(dataDir));\n const target = resolve(bodyPath(dataDir, resourceId, slug));\n const rel = relative(root, target);\n if (rel.startsWith('..') || isAbsolute(rel) || rel.split(/[\\\\/]/).includes('..')) {\n throw new CliError('CONTRACT_MISMATCH', 'The delivery path escapes the library directory.', {\n fix: 'Update tenjin-cli; the resource identity is unsafe.',\n });\n }\n}\n\nexport function bodyPath(dataDir: string, resourceId: string, slug: string): string {\n return join(resourceDir(dataDir, resourceId), `${slug}.md`);\n}\n\nexport function receiptPath(dataDir: string, resourceId: string): string {\n return join(resourceDir(dataDir, resourceId), 'receipt.json');\n}\n\n/** sha256 over the UTF-8 bytes of `bodyMd`, \"sha256:<64 hex>\" (server contract). */\nexport function contentHash(bodyMd: string): string {\n return `sha256:${createHash('sha256').update(bodyMd, 'utf8').digest('hex')}`;\n}\n\nexport interface DeliveredResource {\n receipt: Receipt;\n bodyMd: string;\n bodyPath: string;\n}\n\n/** Return the on-disk delivery for a resource, or null when nothing is saved yet\n * (or the sidecar is unreadable/corrupt, treated as absent, never a hard error). */\nexport async function findDelivered(\n dataDir: string,\n resourceId: string,\n): Promise<DeliveredResource | null> {\n // A non-uuid resourceId can never have been a saved directory; treat it as\n // absent rather than probing an attacker-shaped path.\n if (!RESOURCE_ID_RE.test(resourceId)) return null;\n let receiptRaw: string;\n try {\n receiptRaw = await readFile(receiptPath(dataDir, resourceId), 'utf8');\n } catch {\n return null;\n }\n const parsed = ReceiptSchema.safeParse(safeJson(receiptRaw));\n if (!parsed.success) return null;\n const path = bodyPath(dataDir, resourceId, parsed.data.slug);\n let bodyMd: string;\n try {\n bodyMd = await readFile(path, 'utf8');\n } catch {\n return null;\n }\n return { receipt: parsed.data, bodyMd, bodyPath: path };\n}\n\n/**\n * The read route's path shape. The trailing slash is OPTIONAL here, which is a\n * deliberate tolerance: a URL a human pasted with one addresses the same piece.\n * `parseReadPath` and `canonicalReadUrl` share this regex so the shape they\n * tolerate and the shape one of them removes can never drift apart.\n */\nconst READ_PATH_RE = /\\/api\\/read\\/([^/]+)\\/([^/]+)\\/?$/;\n\n/** The (handle, slug) a read URL points at, path-only so base-url/trailing-slash\n * differences never matter. Null when the URL is not a read-route URL. */\nexport function parseReadPath(url: string): { handle: string; slug: string } | null {\n let pathname: string;\n try {\n pathname = new URL(url).pathname;\n } catch {\n return null;\n }\n const m = READ_PATH_RE.exec(pathname);\n if (m === null || m[1] === undefined || m[2] === undefined) return null;\n return { handle: decodeURIComponent(m[1]), slug: decodeURIComponent(m[2]) };\n}\n\n/**\n * A read URL in the spelling the transport should ask for: the same URL with\n * `parseReadPath`'s optional trailing slash removed.\n *\n * This exists because the tolerance above and the transport disagree without it.\n * `fetchRead` pins `blockRedirects`, so a 3xx anywhere on the read path is a hard\n * failure rather than a hop — and the read route legitimately canonicalizes\n * `/api/read/<handle>/<slug>/` to the no-slash form. Left un-normalized, a URL a\n * user pasted with a trailing slash therefore dies at the FIRST probe of both\n * `read` and `buy`, on a redirect the pin is not there to catch: it is\n * same-origin, so no other host's bytes are in play.\n *\n * Removing the slash instead of relaxing the pin keeps the two concerns apart.\n * Canonicalizing a URL is this function's job; refusing to follow a redirect\n * stays the transport's, unconditionally.\n *\n * Path-only and conservative: a non-read URL is returned untouched, the query and\n * fragment are preserved byte-for-byte, and only the ONE slash the regex tolerates\n * is removed (so `/api/read/h/s//`, which `parseReadPath` already rejects, is left\n * exactly as it came in). It cannot change the origin, which is why callers may\n * origin-check the result rather than the input.\n */\nexport function canonicalReadUrl(url: string): string {\n if (parseReadPath(url) === null) return url;\n const mark = url.search(/[?#]/);\n const path = mark === -1 ? url : url.slice(0, mark);\n if (!path.endsWith('/')) return url;\n return path.slice(0, -1) + (mark === -1 ? '' : url.slice(mark));\n}\n\n/**\n * Find a delivered resource by its READ URL (handle/slug), for the double-pay\n * guard on a `buy <url>` where the resourceId isn't known up front. Scans the\n * library's receipts and matches on the URL's handle+slug path, so a repeat buy\n * of an owned resource re-delivers from disk before any network or payment.\n */\nexport async function findDeliveredByUrl(\n dataDir: string,\n url: string,\n): Promise<DeliveredResource | null> {\n const target = parseReadPath(url);\n if (target === null) return null;\n let entries: string[];\n try {\n entries = await readdir(libraryDir(dataDir));\n } catch {\n return null;\n }\n for (const resourceId of entries) {\n if (!RESOURCE_ID_RE.test(resourceId)) continue;\n const delivered = await findDelivered(dataDir, resourceId);\n if (delivered === null) continue;\n const saved = parseReadPath(delivered.receipt.url);\n if (saved !== null && saved.handle === target.handle && saved.slug === target.slug) {\n return delivered;\n }\n }\n return null;\n}\n\nexport interface SaveDeliveryInput {\n resourceId: string;\n slug: string;\n title: string;\n handle: string;\n url: string;\n priceAtomic: string;\n entitlement: Entitlement;\n bodyMd: string;\n settlementTxHash?: string;\n}\n\nexport interface SavedDelivery {\n receipt: Receipt;\n bodyPath: string;\n}\n\n/** Persist the body + receipt atomically. Idempotent by path: re-saving the same\n * resource overwrites the sidecar (e.g. a free read later becomes a purchase). */\nexport async function saveDelivery(\n dataDir: string,\n input: SaveDeliveryInput,\n): Promise<SavedDelivery> {\n assertContained(dataDir, input.resourceId, input.slug);\n const path = bodyPath(dataDir, input.resourceId, input.slug);\n const receipt: Receipt = {\n schemaVersion: 1,\n resourceId: input.resourceId,\n slug: input.slug,\n title: input.title,\n handle: input.handle,\n url: input.url,\n priceAtomic: input.priceAtomic,\n entitlement: input.entitlement,\n contentHash: contentHash(input.bodyMd),\n ...(input.settlementTxHash !== undefined ? { settlementTxHash: input.settlementTxHash } : {}),\n savedAt: new Date().toISOString(),\n };\n await writeFileAtomic(path, input.bodyMd, { mode: 0o644, dirMode: 0o700 });\n await writeFileAtomic(\n receiptPath(dataDir, input.resourceId),\n `${JSON.stringify(receipt, null, 2)}\\n`,\n { mode: 0o644, dirMode: 0o700 },\n );\n return { receipt, bodyPath: path };\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { CliError } from './errors';\nimport { findStoredCandidate } from './search-store';\nimport { canonicalReadUrl } from './library';\nimport { UUID_RE } from './ids';\n\n/**\n * Resolve a `<resource-url-or-id>` CLI argument to the payable read URL. A full\n * http(s) URL must live on the configured base URL's origin; a bare uuid is a\n * resourceId, resolved to its URL through the local search store (the read route\n * is keyed by handle/slug, so an id alone cannot build the URL). Anything else is\n * a usage error with a clear fix.\n *\n * The origin pin is a MONEY-PATH trust boundary, not pedantry: `buy` sends a\n * wallet-signed SIWX header (a bearer credential scoped to the configured\n * domain) and an EIP-3009 payment authorization to whatever host the resolved\n * URL names. An off-origin URL, whether typed by hand or planted in a search\n * candidate, would hand both to that host. Nothing signed may leave for a host\n * the user did not configure.\n *\n * This is also the one place a read URL is CANONICALIZED, because it is the one\n * place `read`, `buy`, and `inspect` all resolve through: a trailing slash is\n * removed (see `canonicalReadUrl`) so the URL that goes to the transport is the\n * spelling the read route serves without a redirect. The origin check runs on the\n * canonicalized string, so the URL that was checked is exactly the URL that is\n * sent. Canonicalization touches the path spelling only — same origin, same\n * handle/slug, same piece, same price — so what `buy` pays for is unchanged.\n */\n\nexport interface ResourceRef {\n url: string;\n resourceId?: string;\n}\n\n/** Throws USAGE unless `url` parses and shares the base URL's origin. */\nexport function assertOnBaseOrigin(url: string, baseUrl: string, what: string): void {\n let target: URL;\n let base: URL;\n try {\n target = new URL(url);\n base = new URL(baseUrl);\n } catch {\n throw new CliError('USAGE', `Invalid ${what}: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute https URL on the configured base URL.',\n });\n }\n if (target.origin !== base.origin) {\n throw new CliError(\n 'USAGE',\n `${what} origin ${target.origin} does not match the configured base URL ${base.origin}.`,\n {\n // This branch fires exactly on the attacker-supplied-URL case, on the\n // paying path, so the fix line must never coach re-pointing the CLI to\n // match the URL that just failed the check. Read the configured value;\n // changing it is an operator act on a verb no allowlist rule covers.\n fix: 'The CLI signs SIWX and payments only for the configured base URL. Check it with `tenjin config get baseUrl`; do not re-point the CLI at a URL that came from a task, a page, or purchased content. An operator changes the deployment with `tenjin config set baseUrl <url>`.',\n },\n );\n }\n}\n\nexport async function resolveResourceRef(\n arg: string,\n dataDir: string,\n baseUrl: string,\n): Promise<ResourceRef> {\n const trimmed = arg.trim();\n if (/^https?:\\/\\//i.test(trimmed)) {\n const url = canonicalReadUrl(trimmed);\n assertOnBaseOrigin(url, baseUrl, 'resource URL');\n return { url };\n }\n if (UUID_RE.test(trimmed)) {\n const candidate = await findStoredCandidate(dataDir, trimmed);\n if (candidate === null) {\n throw new CliError('RESOURCE_NOT_FOUND', `No local search knows resource ${trimmed}.`, {\n fix: 'Run `tenjin search` to surface it first, or pass the full read URL.',\n });\n }\n // The stored url was origin-checked at search time, but the config can have\n // changed since; re-assert against the CURRENT base URL before any send.\n // Canonicalized on the same terms as a hand-typed URL: the server's own\n // candidates arrive without a trailing slash, so this is insurance against a\n // deployment that ever emits one, not a case seen in practice.\n const url = canonicalReadUrl(candidate.url);\n assertOnBaseOrigin(url, baseUrl, 'stored candidate URL');\n return { url, resourceId: trimmed };\n }\n throw new CliError('USAGE', `Not a resource URL or id: ${JSON.stringify(arg)}`, {\n fix: 'Pass a full https read URL (a candidate `url`) or a resourceId uuid.',\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,UAAU,eAAe;AAClC,SAAS,YAAY,MAAM,UAAU,eAAe;AAyB7C,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EACpC,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,YAAY,iBAAE,OAAO;AAAA,EACrB,MAAM,iBAAE,OAAO;AAAA,EACf,OAAO,iBAAE,OAAO;AAAA,EAChB,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OAAO;AAAA,EACd,aAAa,iBAAE,OAAO;AAAA,EACtB,aAAa,iBAAE,KAAK,CAAC,QAAQ,YAAY,WAAW,CAAC;AAAA,EACrD,aAAa,iBAAE,OAAO;AAAA,EACtB,kBAAkB,iBAAE,OAAO,EAAE,SAAS;AAAA,EACtC,SAAS,iBAAE,OAAO;AACpB,CAAC;AAGM,SAAS,WAAW,SAAyB;AAClD,SAAO,KAAK,SAAS,SAAS;AAChC;AAEO,SAAS,YAAY,SAAiB,YAA4B;AACvE,SAAO,KAAK,WAAW,OAAO,GAAG,UAAU;AAC7C;AAIO,SAAS,eAAe,YAAoB,MAAuB;AACxE,SAAO,QAAe,KAAK,UAAU,KAAK,KAAK,UAAU,MAAM,QAAQ,KAAK,IAAI;AAClF;AAQA,SAAS,gBAAgB,SAAiB,YAAoB,MAAoB;AAChF,MAAI,CAAC,eAAe,YAAY,IAAI,GAAG;AACrC,UAAM,IAAI,SAAS,qBAAqB,oDAAoD;AAAA,MAC1F,KAAK;AAAA,MACL,SAAS,EAAE,YAAY,KAAK;AAAA,IAC9B,CAAC;AAAA,EACH;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AAsB,mBACpB,KACA,SACA,SACsB;AACtB,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,gBAAgB,KAAK,OAAO,GAAG;AACjC,UAAM,MAAM,iBAAiB,OAAO;AACpC,uBAAmB,KAAK,SAAS,cAAc;AAC/C,WAAO,EAAE,IAAI;AAAA,EACf;AACA,MAAI,QAAQ,KAAK,OAAO,GAAG;AACzB,UAAM,YAAY,MAAM,oBAAoB,SAAS,OAAO;AAC5D,QAAI,cAAc,MAAM;AACtB,YAAM,IAAI,SAAS,sBAAsB,kCAAkC,OAAO,KAAK;AAAA,QACrF,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAMA,UAAM,MAAM,iBAAiB,UAAU,GAAG;AAC1C,uBAAmB,KAAK,SAAS,sBAAsB;AACvD,WAAO,EAAE,KAAK,YAAY,QAAQ;AAAA,EACpC;AACA,QAAM,IAAI,SAAS,SAAS,6BAA6B,KAAK,UAAU,GAAG,CAAC,IAAI;AAAA,IAC9E,KAAK;AAAA,EACP,CAAC;AACH;","names":[]}
|
package/dist/chunk-54AJIO3E.js
DELETED
|
@@ -1,198 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
composeUserAgent
|
|
4
|
-
} from "./chunk-VEAERJVJ.js";
|
|
5
|
-
import {
|
|
6
|
-
CliError
|
|
7
|
-
} from "./chunk-PAOVPSP6.js";
|
|
8
|
-
|
|
9
|
-
// src/lib/http.ts
|
|
10
|
-
function applyUserAgent(headers, callerUserAgent) {
|
|
11
|
-
headers.set("user-agent", composeUserAgent({ caller: callerUserAgent }));
|
|
12
|
-
return headers;
|
|
13
|
-
}
|
|
14
|
-
function withUserAgent(callerHeaders, callerUserAgent) {
|
|
15
|
-
return Object.fromEntries(
|
|
16
|
-
applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries()
|
|
17
|
-
);
|
|
18
|
-
}
|
|
19
|
-
var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
|
|
20
|
-
"sign-in-with-x",
|
|
21
|
-
"payment-signature",
|
|
22
|
-
"x-payment",
|
|
23
|
-
"tenjin-session-delegation"
|
|
24
|
-
]);
|
|
25
|
-
function carriesSignedMaterial(headers) {
|
|
26
|
-
return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
|
|
27
|
-
}
|
|
28
|
-
async function fetchJson(url, opts) {
|
|
29
|
-
const doFetch = opts.fetchImpl ?? fetch;
|
|
30
|
-
const controller = new AbortController();
|
|
31
|
-
let timedOut = false;
|
|
32
|
-
const timer = setTimeout(() => {
|
|
33
|
-
timedOut = true;
|
|
34
|
-
controller.abort();
|
|
35
|
-
}, opts.timeoutMs);
|
|
36
|
-
try {
|
|
37
|
-
let res;
|
|
38
|
-
try {
|
|
39
|
-
res = await doFetch(url, {
|
|
40
|
-
signal: controller.signal,
|
|
41
|
-
headers: withUserAgent(opts.headers, opts.callerUserAgent)
|
|
42
|
-
});
|
|
43
|
-
} catch (err) {
|
|
44
|
-
return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
|
|
45
|
-
}
|
|
46
|
-
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
47
|
-
if (!res.ok) {
|
|
48
|
-
return {
|
|
49
|
-
ok: false,
|
|
50
|
-
kind: "http",
|
|
51
|
-
status: res.status,
|
|
52
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
53
|
-
message: `Request to ${url} failed with status ${res.status}`
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
let json;
|
|
57
|
-
try {
|
|
58
|
-
json = await res.json();
|
|
59
|
-
} catch (err) {
|
|
60
|
-
if (timedOut) return timeoutFailure(url, opts.timeoutMs);
|
|
61
|
-
if (err instanceof SyntaxError) {
|
|
62
|
-
return {
|
|
63
|
-
ok: false,
|
|
64
|
-
kind: "invalid-json",
|
|
65
|
-
status: res.status,
|
|
66
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
67
|
-
message: `Response from ${url} was not valid JSON`
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
return {
|
|
71
|
-
ok: false,
|
|
72
|
-
kind: "network",
|
|
73
|
-
status: res.status,
|
|
74
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
75
|
-
message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
return {
|
|
79
|
-
ok: true,
|
|
80
|
-
status: res.status,
|
|
81
|
-
json,
|
|
82
|
-
...requestId !== void 0 ? { requestId } : {}
|
|
83
|
-
};
|
|
84
|
-
} finally {
|
|
85
|
-
clearTimeout(timer);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
function timeoutFailure(url, timeoutMs) {
|
|
89
|
-
return {
|
|
90
|
-
ok: false,
|
|
91
|
-
kind: "timeout",
|
|
92
|
-
message: `Request to ${url} timed out after ${timeoutMs}ms`
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
function prepareRequest(url, opts) {
|
|
96
|
-
try {
|
|
97
|
-
let body;
|
|
98
|
-
const merged = new Headers(opts.headers ?? {});
|
|
99
|
-
if (opts.jsonBody !== void 0) {
|
|
100
|
-
body = JSON.stringify(opts.jsonBody);
|
|
101
|
-
merged.set("content-type", "application/json");
|
|
102
|
-
}
|
|
103
|
-
const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
|
|
104
|
-
if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
|
|
105
|
-
const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
|
|
106
|
-
const signed = carriesSignedMaterial(headers);
|
|
107
|
-
return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };
|
|
108
|
-
} catch (err) {
|
|
109
|
-
return {
|
|
110
|
-
ok: false,
|
|
111
|
-
kind: "network",
|
|
112
|
-
message: `Request to ${url} failed: ${errorMessage(err)}`
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
async function httpRequest(url, opts) {
|
|
117
|
-
const doFetch = opts.fetchImpl ?? fetch;
|
|
118
|
-
const controller = new AbortController();
|
|
119
|
-
let timedOut = false;
|
|
120
|
-
const timer = setTimeout(() => {
|
|
121
|
-
timedOut = true;
|
|
122
|
-
controller.abort();
|
|
123
|
-
}, opts.timeoutMs);
|
|
124
|
-
try {
|
|
125
|
-
const prepared = prepareRequest(url, opts);
|
|
126
|
-
if (!prepared.ok) return prepared;
|
|
127
|
-
const { headers, body, signed, pinned } = prepared;
|
|
128
|
-
let res;
|
|
129
|
-
try {
|
|
130
|
-
res = await doFetch(url, {
|
|
131
|
-
method: opts.method ?? "GET",
|
|
132
|
-
headers,
|
|
133
|
-
body,
|
|
134
|
-
signal: controller.signal,
|
|
135
|
-
...pinned ? { redirect: "manual" } : {}
|
|
136
|
-
});
|
|
137
|
-
} catch (err) {
|
|
138
|
-
return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
|
|
139
|
-
}
|
|
140
|
-
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
141
|
-
if (pinned && res.status >= 300 && res.status < 400) {
|
|
142
|
-
return {
|
|
143
|
-
ok: false,
|
|
144
|
-
kind: "blocked-redirect",
|
|
145
|
-
status: res.status,
|
|
146
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
147
|
-
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.`
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
let text;
|
|
151
|
-
try {
|
|
152
|
-
text = await res.text();
|
|
153
|
-
} catch (err) {
|
|
154
|
-
if (timedOut) return timeoutFailure(url, opts.timeoutMs);
|
|
155
|
-
return {
|
|
156
|
-
ok: false,
|
|
157
|
-
kind: "network",
|
|
158
|
-
status: res.status,
|
|
159
|
-
...requestId !== void 0 ? { requestId } : {},
|
|
160
|
-
message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
let json;
|
|
164
|
-
if (text.length > 0) {
|
|
165
|
-
try {
|
|
166
|
-
json = JSON.parse(text);
|
|
167
|
-
} catch {
|
|
168
|
-
json = void 0;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
return {
|
|
172
|
-
ok: true,
|
|
173
|
-
status: res.status,
|
|
174
|
-
header: (name) => res.headers.get(name) ?? void 0,
|
|
175
|
-
json,
|
|
176
|
-
...requestId !== void 0 ? { requestId } : {}
|
|
177
|
-
};
|
|
178
|
-
} finally {
|
|
179
|
-
clearTimeout(timer);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
function fetchFailureToCliError(failure, opts = {}) {
|
|
183
|
-
const code = failure.kind === "network" || failure.kind === "timeout" ? "NETWORK_ERROR" : failure.kind === "invalid-json" ? "CONTRACT_MISMATCH" : "API_UNREACHABLE";
|
|
184
|
-
return new CliError(code, failure.message, {
|
|
185
|
-
...opts.fix !== void 0 ? { fix: opts.fix } : {},
|
|
186
|
-
...opts.details !== void 0 ? { details: opts.details } : {}
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
function errorMessage(err) {
|
|
190
|
-
return err instanceof Error ? err.message : String(err);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
export {
|
|
194
|
-
fetchJson,
|
|
195
|
-
httpRequest,
|
|
196
|
-
fetchFailureToCliError
|
|
197
|
-
};
|
|
198
|
-
//# sourceMappingURL=chunk-54AJIO3E.js.map
|