tenjin-cli 0.1.0-alpha.13 → 0.1.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -2
- package/dist/{buy-X4VPHFUA.js → buy-2JBYPHAI.js} +16 -14
- package/dist/{chunk-6JKD46OJ.js → chunk-3ZW7HPY5.js} +4 -4
- package/dist/chunk-4UHNXY6B.js +786 -0
- package/dist/chunk-4UHNXY6B.js.map +1 -0
- package/dist/{chunk-IFPKA32J.js → chunk-4Y53PDH6.js} +2 -2
- package/dist/{chunk-SPUORKD7.js → chunk-54AJIO3E.js} +11 -12
- package/dist/chunk-54AJIO3E.js.map +1 -0
- package/dist/{chunk-JVBMPU5G.js → chunk-7GJQ5RGA.js} +5 -3
- package/dist/{chunk-JVBMPU5G.js.map → chunk-7GJQ5RGA.js.map} +1 -1
- package/dist/{chunk-BRAVLUGI.js → chunk-7NADDA2V.js} +9 -6
- package/dist/{chunk-BRAVLUGI.js.map → chunk-7NADDA2V.js.map} +1 -1
- package/dist/{chunk-T4UWMVKV.js → chunk-ACBEHJAH.js} +4 -4
- package/dist/{chunk-XXY77EZJ.js → chunk-DAZAXFSF.js} +7 -7
- package/dist/{chunk-OE36HRWG.js → chunk-DTCXO7HS.js} +257 -405
- package/dist/chunk-DTCXO7HS.js.map +1 -0
- package/dist/{chunk-CA3JV7FX.js → chunk-ETKZWJ4B.js} +2 -2
- package/dist/{chunk-CA3JV7FX.js.map → chunk-ETKZWJ4B.js.map} +1 -1
- package/dist/{chunk-NKN4YC5C.js → chunk-FDUD3W5V.js} +2 -2
- package/dist/{chunk-L4XNT3UW.js → chunk-GEHL43VE.js} +49 -17
- package/dist/chunk-GEHL43VE.js.map +1 -0
- package/dist/chunk-IU2HVT3Y.js +313 -0
- package/dist/chunk-IU2HVT3Y.js.map +1 -0
- package/dist/{chunk-OXUJ3FXU.js → chunk-IUQZ4Z7M.js} +36 -8
- package/dist/chunk-IUQZ4Z7M.js.map +1 -0
- package/dist/{chunk-YMUJZWHB.js → chunk-IXZJ3JOO.js} +5 -5
- package/dist/{chunk-47YKYDOF.js → chunk-L6G35FU5.js} +2 -2
- package/dist/{chunk-ELVDOTU7.js → chunk-LSWP7MU2.js} +4 -4
- package/dist/chunk-LSWP7MU2.js.map +1 -0
- package/dist/{chunk-OUJDDY5L.js → chunk-MJSXP4LW.js} +30 -28
- package/dist/chunk-MJSXP4LW.js.map +1 -0
- package/dist/{chunk-WVHPGQH5.js → chunk-NAAMHWSI.js} +5 -2
- package/dist/chunk-NAAMHWSI.js.map +1 -0
- package/dist/{chunk-IKAJSA7E.js → chunk-O75FOHXS.js} +29 -11
- package/dist/chunk-O75FOHXS.js.map +1 -0
- package/dist/{chunk-WMFRCSNC.js → chunk-PCX2JQ2J.js} +3 -3
- package/dist/{chunk-IGHSLJUF.js → chunk-PKW3H26Z.js} +5 -5
- package/dist/{chunk-3NZCU6SD.js → chunk-PQZVDCCA.js} +4 -4
- package/dist/{chunk-OC3EIDCP.js → chunk-QWBUKIP2.js} +7 -1
- package/dist/chunk-QWBUKIP2.js.map +1 -0
- package/dist/{chunk-FKSAUOJU.js → chunk-UO22YNY4.js} +1 -69
- package/dist/chunk-UO22YNY4.js.map +1 -0
- package/dist/chunk-VEAERJVJ.js +43 -0
- package/dist/chunk-VEAERJVJ.js.map +1 -0
- package/dist/{chunk-GCGMXA2O.js → chunk-VRPLZERE.js} +16 -5
- package/dist/chunk-VRPLZERE.js.map +1 -0
- package/dist/{chunk-IAR25V2E.js → chunk-W4VW5XYB.js} +4 -4
- package/dist/chunk-WYLMJQVH.js +240 -0
- package/dist/chunk-WYLMJQVH.js.map +1 -0
- package/dist/{chunk-TXVC46SA.js → chunk-XVPQGCH4.js} +11 -10
- package/dist/chunk-XVPQGCH4.js.map +1 -0
- package/dist/chunk-ZOBNS7CX.js +73 -0
- package/dist/chunk-ZOBNS7CX.js.map +1 -0
- package/dist/{cli-XK5JZWU6.js → cli-U2BEUA55.js} +34 -36
- package/dist/{cli-XK5JZWU6.js.map → cli-U2BEUA55.js.map} +1 -1
- package/dist/{config-CNK7MYUR.js → config-CNUIX23Q.js} +12 -6
- package/dist/{doctor-R7N7FUX5.js → doctor-QJJXRWTO.js} +11 -7
- package/dist/{edit-QSUEG7CL.js → edit-HJ44P44P.js} +13 -11
- package/dist/{fund-JF6A76YS.js → fund-Y5IAHZ5D.js} +10 -8
- package/dist/index.js +1 -1
- package/dist/{inspect-NFNAA4LA.js → inspect-NFQ6SQQQ.js} +14 -12
- package/dist/{install-YQVM3SUW.js → install-DXX7PVUP.js} +122 -401
- package/dist/install-DXX7PVUP.js.map +1 -0
- package/dist/outcome-ANV4QIED.js +24 -0
- package/dist/{publish-O2I6IAEL.js → publish-PCBTCXCZ.js} +14 -12
- package/dist/{read-UF7QVQOU.js → read-W7QVRBVD.js} +14 -12
- package/dist/{read-UF7QVQOU.js.map → read-W7QVRBVD.js.map} +1 -1
- package/dist/{run-GDZWHNWZ.js → run-CJWPGMIQ.js} +26 -24
- package/dist/{run-GDZWHNWZ.js.map → run-CJWPGMIQ.js.map} +1 -1
- package/dist/search-JGAVKTYJ.js +25 -0
- package/dist/{send-SI254H3R.js → send-C5EOKXOU.js} +7 -6
- package/dist/{send-SI254H3R.js.map → send-C5EOKXOU.js.map} +1 -1
- package/dist/{session-GJZJEXLJ.js → session-OBCUUIFX.js} +7 -6
- package/dist/{session-GJZJEXLJ.js.map → session-OBCUUIFX.js.map} +1 -1
- package/dist/{skill-heal-BPFT22XS.js → skill-heal-D6EPLPS6.js} +3 -3
- package/dist/skill-heal-D6EPLPS6.js.map +1 -0
- package/dist/{uninstall-7ZZG6WQ5.js → uninstall-OWJNJ5LI.js} +11 -5
- package/dist/uninstall-OWJNJ5LI.js.map +1 -0
- package/dist/{update-FPSBITLB.js → update-24Y2CQTT.js} +16 -13
- package/dist/update-24Y2CQTT.js.map +1 -0
- package/dist/{wallet-TZVD2M4I.js → wallet-OFXDIIGP.js} +7 -6
- package/dist/{wallet-NS7TYWNN.js → wallet-SLRIYJ2U.js} +4 -3
- package/docs/agent-permissions.md +100 -16
- package/docs/command-reference.md +21 -11
- package/package.json +1 -1
- package/skills/tenjin-publish/SKILL.md +181 -205
- package/skills/tenjin-publish/references/maintain.md +39 -0
- package/skills/tenjin-search/SKILL.md +86 -279
- package/skills/tenjin-search/references/permissions.md +106 -0
- package/dist/chunk-ELVDOTU7.js.map +0 -1
- package/dist/chunk-FKSAUOJU.js.map +0 -1
- package/dist/chunk-GCGMXA2O.js.map +0 -1
- package/dist/chunk-IKAJSA7E.js.map +0 -1
- package/dist/chunk-L4XNT3UW.js.map +0 -1
- package/dist/chunk-OC3EIDCP.js.map +0 -1
- package/dist/chunk-OE36HRWG.js.map +0 -1
- package/dist/chunk-OUJDDY5L.js.map +0 -1
- package/dist/chunk-OXUJ3FXU.js.map +0 -1
- package/dist/chunk-SPUORKD7.js.map +0 -1
- package/dist/chunk-TXVC46SA.js.map +0 -1
- package/dist/chunk-UUARTUY2.js +0 -349
- package/dist/chunk-UUARTUY2.js.map +0 -1
- package/dist/chunk-WVHPGQH5.js.map +0 -1
- package/dist/install-YQVM3SUW.js.map +0 -1
- package/dist/outcome-IUSYFJTN.js +0 -22
- package/dist/search-JVOHEF3E.js +0 -23
- package/dist/skill-heal-BPFT22XS.js.map +0 -1
- package/dist/uninstall-7ZZG6WQ5.js.map +0 -1
- package/dist/update-FPSBITLB.js.map +0 -1
- /package/dist/{buy-X4VPHFUA.js.map → buy-2JBYPHAI.js.map} +0 -0
- /package/dist/{chunk-6JKD46OJ.js.map → chunk-3ZW7HPY5.js.map} +0 -0
- /package/dist/{chunk-IFPKA32J.js.map → chunk-4Y53PDH6.js.map} +0 -0
- /package/dist/{chunk-T4UWMVKV.js.map → chunk-ACBEHJAH.js.map} +0 -0
- /package/dist/{chunk-XXY77EZJ.js.map → chunk-DAZAXFSF.js.map} +0 -0
- /package/dist/{chunk-NKN4YC5C.js.map → chunk-FDUD3W5V.js.map} +0 -0
- /package/dist/{chunk-YMUJZWHB.js.map → chunk-IXZJ3JOO.js.map} +0 -0
- /package/dist/{chunk-47YKYDOF.js.map → chunk-L6G35FU5.js.map} +0 -0
- /package/dist/{chunk-WMFRCSNC.js.map → chunk-PCX2JQ2J.js.map} +0 -0
- /package/dist/{chunk-IGHSLJUF.js.map → chunk-PKW3H26Z.js.map} +0 -0
- /package/dist/{chunk-3NZCU6SD.js.map → chunk-PQZVDCCA.js.map} +0 -0
- /package/dist/{chunk-IAR25V2E.js.map → chunk-W4VW5XYB.js.map} +0 -0
- /package/dist/{config-CNK7MYUR.js.map → config-CNUIX23Q.js.map} +0 -0
- /package/dist/{doctor-R7N7FUX5.js.map → doctor-QJJXRWTO.js.map} +0 -0
- /package/dist/{edit-QSUEG7CL.js.map → edit-HJ44P44P.js.map} +0 -0
- /package/dist/{fund-JF6A76YS.js.map → fund-Y5IAHZ5D.js.map} +0 -0
- /package/dist/{inspect-NFNAA4LA.js.map → inspect-NFQ6SQQQ.js.map} +0 -0
- /package/dist/{outcome-IUSYFJTN.js.map → outcome-ANV4QIED.js.map} +0 -0
- /package/dist/{publish-O2I6IAEL.js.map → publish-PCBTCXCZ.js.map} +0 -0
- /package/dist/{search-JVOHEF3E.js.map → search-JGAVKTYJ.js.map} +0 -0
- /package/dist/{wallet-NS7TYWNN.js.map → wallet-OFXDIIGP.js.map} +0 -0
- /package/dist/{wallet-TZVD2M4I.js.map → wallet-SLRIYJ2U.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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,MAAM,GAAG,YAAY,UAAU;AAEvC,MAAI,QAAQ,MAAM,eAAe;AA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W,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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
findStoredCandidate
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-7NADDA2V.js";
|
|
5
5
|
import {
|
|
6
6
|
SLUG_RE,
|
|
7
7
|
UUID_RE
|
|
@@ -210,4 +210,4 @@ export {
|
|
|
210
210
|
assertOnBaseOrigin,
|
|
211
211
|
resolveResourceRef
|
|
212
212
|
};
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
213
|
+
//# sourceMappingURL=chunk-4Y53PDH6.js.map
|
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
} from "./chunk-
|
|
3
|
+
composeUserAgent
|
|
4
|
+
} from "./chunk-VEAERJVJ.js";
|
|
5
5
|
import {
|
|
6
6
|
CliError
|
|
7
7
|
} from "./chunk-PAOVPSP6.js";
|
|
8
8
|
|
|
9
|
-
// src/lib/client-meta.ts
|
|
10
|
-
var TENJIN_USER_AGENT = `tenjin-cli/${package_default.version} (+https://tenjin.blog)`;
|
|
11
|
-
|
|
12
9
|
// src/lib/http.ts
|
|
13
|
-
function applyUserAgent(headers) {
|
|
14
|
-
headers.set("user-agent",
|
|
10
|
+
function applyUserAgent(headers, callerUserAgent) {
|
|
11
|
+
headers.set("user-agent", composeUserAgent({ caller: callerUserAgent }));
|
|
15
12
|
return headers;
|
|
16
13
|
}
|
|
17
|
-
function withUserAgent(callerHeaders) {
|
|
18
|
-
return Object.fromEntries(
|
|
14
|
+
function withUserAgent(callerHeaders, callerUserAgent) {
|
|
15
|
+
return Object.fromEntries(
|
|
16
|
+
applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries()
|
|
17
|
+
);
|
|
19
18
|
}
|
|
20
19
|
var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
|
|
21
20
|
"sign-in-with-x",
|
|
@@ -39,7 +38,7 @@ async function fetchJson(url, opts) {
|
|
|
39
38
|
try {
|
|
40
39
|
res = await doFetch(url, {
|
|
41
40
|
signal: controller.signal,
|
|
42
|
-
headers: withUserAgent(opts.headers)
|
|
41
|
+
headers: withUserAgent(opts.headers, opts.callerUserAgent)
|
|
43
42
|
});
|
|
44
43
|
} catch (err) {
|
|
45
44
|
return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
|
|
@@ -103,7 +102,7 @@ function prepareRequest(url, opts) {
|
|
|
103
102
|
}
|
|
104
103
|
const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
|
|
105
104
|
if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
|
|
106
|
-
const headers = Object.fromEntries(applyUserAgent(merged).entries());
|
|
105
|
+
const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
|
|
107
106
|
const signed = carriesSignedMaterial(headers);
|
|
108
107
|
return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };
|
|
109
108
|
} catch (err) {
|
|
@@ -196,4 +195,4 @@ export {
|
|
|
196
195
|
httpRequest,
|
|
197
196
|
fetchFailureToCliError
|
|
198
197
|
};
|
|
199
|
-
//# sourceMappingURL=chunk-
|
|
198
|
+
//# sourceMappingURL=chunk-54AJIO3E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/http.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { composeUserAgent } from './client-meta';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n /**\n * INTERNAL. A caller's own product sequence, composed BEHIND the CLI's\n * identity (see `composeUserAgent`). The package ships a `bin` and no\n * `exports` map, so this is not a supported seam for code outside this repo:\n * the documented handoff is the `TENJIN_CALLER_USER_AGENT` environment\n * variable, which is what a subprocess launcher sets and what this falls back\n * to. Kept as an option so an in-repo caller can pass a value the environment\n * does not carry.\n */\n callerUserAgent?: string;\n}\n\n/**\n * The one place the identity is written for anything that can import it; both\n * transports funnel their Headers through it, so a third entry point on this\n * side cannot ship without it. The generated hook scripts are the one request\n * path that cannot reach here, and they carry their own mirrored composer\n * (`lib/hook-scripts.ts`) rather than an exemption. `.set` on a Headers\n * object is what makes this total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated, so a\n * call-specific header cannot erase the composed field or add a second one.\n */\nfunction applyUserAgent(headers: Headers, callerUserAgent?: string): Headers {\n headers.set('user-agent', composeUserAgent({ caller: callerUserAgent }));\n return headers;\n}\n\n/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(\n callerHeaders?: Record<string, string>,\n callerUserAgent?: string,\n): Record<string, string> {\n return Object.fromEntries(\n applyUserAgent(new Headers(callerHeaders ?? {}), callerUserAgent).entries(),\n );\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect';\n status?: number;\n requestId?: string;\n message: string;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n headers: withUserAgent(opts.headers, opts.callerUserAgent),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** INTERNAL; see `FetchJsonOptions.callerUserAgent`. */\n callerUserAgent?: string;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n }\n const wantsAccept = opts.method === 'POST' || opts.method === 'PUT' || body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"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AS,KAAK,QAAQ,IAAI,CAAC;AAAA,EAChE,CAAC;AACH;AAEA,SAAS,aAAa,KAAsB;AAC1C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;","names":[]}
|
|
@@ -10,9 +10,11 @@ import {
|
|
|
10
10
|
emitNotice
|
|
11
11
|
} from "./chunk-B676GPS2.js";
|
|
12
12
|
import {
|
|
13
|
-
evaluateSpendPolicy,
|
|
14
13
|
withFileLock
|
|
15
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-ZOBNS7CX.js";
|
|
15
|
+
import {
|
|
16
|
+
evaluateSpendPolicy
|
|
17
|
+
} from "./chunk-UO22YNY4.js";
|
|
16
18
|
import {
|
|
17
19
|
archivedWalletPath,
|
|
18
20
|
passphraseBlobPath,
|
|
@@ -1640,4 +1642,4 @@ export {
|
|
|
1640
1642
|
@noble/ciphers/esm/utils.js:
|
|
1641
1643
|
(*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
|
|
1642
1644
|
*/
|
|
1643
|
-
//# sourceMappingURL=chunk-
|
|
1645
|
+
//# sourceMappingURL=chunk-7GJQ5RGA.js.map
|