tenjin-cli 0.1.0-alpha.8 → 0.1.0-alpha.9

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.
Files changed (124) hide show
  1. package/README.md +26 -0
  2. package/dist/{buy-K2G6XQY2.js → buy-3PPC2SRQ.js} +23 -21
  3. package/dist/{candidate-DJB2NNTG.js → candidate-FCBWDN4Y.js} +10 -8
  4. package/dist/{chunk-NVHQCTIC.js → chunk-3MQSXDWS.js} +10 -11
  5. package/dist/chunk-3MQSXDWS.js.map +1 -0
  6. package/dist/{chunk-DH6D6QIO.js → chunk-6DWKU4RH.js} +11 -9
  7. package/dist/{chunk-DH6D6QIO.js.map → chunk-6DWKU4RH.js.map} +1 -1
  8. package/dist/{chunk-DQDGBWWH.js → chunk-6L34JW52.js} +3 -2
  9. package/dist/chunk-6L34JW52.js.map +1 -0
  10. package/dist/{chunk-XFHZWORF.js → chunk-6RODLWPQ.js} +101 -35
  11. package/dist/chunk-6RODLWPQ.js.map +1 -0
  12. package/dist/{chunk-VZ3AJCO5.js → chunk-75G4REUY.js} +2 -2
  13. package/dist/{chunk-C3S6725N.js → chunk-7MJCZ2OX.js} +12 -12
  14. package/dist/{chunk-PCLPVJ3J.js → chunk-7WDY4AXV.js} +15 -15
  15. package/dist/{chunk-RGTTACP3.js → chunk-ATSCQETF.js} +5 -5
  16. package/dist/{chunk-QB2NNV6C.js → chunk-AX5WQ3H5.js} +8 -6
  17. package/dist/{chunk-QB2NNV6C.js.map → chunk-AX5WQ3H5.js.map} +1 -1
  18. package/dist/{chunk-WRWCDLVK.js → chunk-BFAFOBO3.js} +23 -4
  19. package/dist/chunk-BFAFOBO3.js.map +1 -0
  20. package/dist/{chunk-DAJ56EUU.js → chunk-CTFFFQFH.js} +3 -3
  21. package/dist/{chunk-B7YB4MMU.js → chunk-E5PZEPUO.js} +9 -9
  22. package/dist/{chunk-GABYDXWL.js → chunk-FFTWWJRW.js} +21 -5
  23. package/dist/{chunk-GABYDXWL.js.map → chunk-FFTWWJRW.js.map} +1 -1
  24. package/dist/{chunk-6OE2IJMH.js → chunk-G7ECLIN6.js} +22 -22
  25. package/dist/{chunk-CYRYVZPN.js → chunk-GJKDWZ6X.js} +3 -3
  26. package/dist/{chunk-RGFBBNGP.js → chunk-I4WQXOEL.js} +16 -13
  27. package/dist/chunk-I4WQXOEL.js.map +1 -0
  28. package/dist/{chunk-OTDI5FXG.js → chunk-JURZ2T2I.js} +3 -3
  29. package/dist/{chunk-UYP7G3GZ.js → chunk-KRHUDEIQ.js} +10 -172
  30. package/dist/chunk-KRHUDEIQ.js.map +1 -0
  31. package/dist/{chunk-P3FBESBB.js → chunk-MHRREGGN.js} +5 -10
  32. package/dist/chunk-MHRREGGN.js.map +1 -0
  33. package/dist/chunk-OQXHNWM3.js +47 -0
  34. package/dist/chunk-OQXHNWM3.js.map +1 -0
  35. package/dist/chunk-P74I3WH4.js +204 -0
  36. package/dist/chunk-P74I3WH4.js.map +1 -0
  37. package/dist/{chunk-6ZBZCBR7.js → chunk-PT2NJUGG.js} +6 -6
  38. package/dist/{chunk-J6CVKC4M.js → chunk-PZRAAAY2.js} +4 -46
  39. package/dist/chunk-PZRAAAY2.js.map +1 -0
  40. package/dist/{chunk-XBJ3VLWX.js → chunk-PZSUWDF2.js} +2 -2
  41. package/dist/{chunk-BBUYCDSG.js → chunk-R2VLGNFD.js} +7 -2
  42. package/dist/chunk-R2VLGNFD.js.map +1 -0
  43. package/dist/{chunk-ZA3RFDAV.js → chunk-S4IKXAUA.js} +6 -10
  44. package/dist/chunk-S4IKXAUA.js.map +1 -0
  45. package/dist/{chunk-EDENZN2Q.js → chunk-TMZIXYPL.js} +7 -7
  46. package/dist/{chunk-YBMMV4Y4.js → chunk-TYVLXAB5.js} +26 -4
  47. package/dist/chunk-TYVLXAB5.js.map +1 -0
  48. package/dist/{chunk-URSGGRO4.js → chunk-V7BWPOKT.js} +38 -19
  49. package/dist/chunk-V7BWPOKT.js.map +1 -0
  50. package/dist/{chunk-L6AV2Q73.js → chunk-VE5BALOI.js} +5 -5
  51. package/dist/{chunk-GM4RZUVU.js → chunk-WGXUVCUF.js} +8 -6
  52. package/dist/{chunk-GM4RZUVU.js.map → chunk-WGXUVCUF.js.map} +1 -1
  53. package/dist/chunk-X3OOVSPX.js +154 -0
  54. package/dist/chunk-X3OOVSPX.js.map +1 -0
  55. package/dist/{chunk-2YX6LTCD.js → chunk-XDW6GOHO.js} +5 -5
  56. package/dist/{cli-KNCYWMAG.js → cli-ATFP3O6Y.js} +36 -27
  57. package/dist/{cli-KNCYWMAG.js.map → cli-ATFP3O6Y.js.map} +1 -1
  58. package/dist/{config-SAQEQRFB.js → config-VT5WU47R.js} +9 -6
  59. package/dist/doctor-6PEYDTB5.js +24 -0
  60. package/dist/{edit-IZZ2HIMR.js → edit-GKI37CRM.js} +21 -19
  61. package/dist/index.js +1 -1
  62. package/dist/{inspect-BFWZ5XOP.js → inspect-ITZIRZDV.js} +19 -16
  63. package/dist/{install-QXZCHIBT.js → install-BMMUPFOK.js} +217 -118
  64. package/dist/install-BMMUPFOK.js.map +1 -0
  65. package/dist/outcome-F5KN3K3Y.js +23 -0
  66. package/dist/{publish-5NTCRF2V.js → publish-F5G5WIFI.js} +22 -20
  67. package/dist/{read-T6OTMU72.js → read-II2ZO4II.js} +20 -18
  68. package/dist/{read-T6OTMU72.js.map → read-II2ZO4II.js.map} +1 -1
  69. package/dist/{run-5OGX64IY.js → run-FJWMRXZ7.js} +65 -42
  70. package/dist/run-FJWMRXZ7.js.map +1 -0
  71. package/dist/search-Z2YALF6S.js +26 -0
  72. package/dist/{send-ENE47KQE.js → send-RWOBFOBK.js} +20 -18
  73. package/dist/{send-ENE47KQE.js.map → send-RWOBFOBK.js.map} +1 -1
  74. package/dist/{session-HY4QIWHV.js → session-DJV5T3BG.js} +16 -14
  75. package/dist/{session-HY4QIWHV.js.map → session-DJV5T3BG.js.map} +1 -1
  76. package/dist/skill-heal-OK6YALW6.js +85 -0
  77. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  78. package/dist/{wallet-RBDVNZVR.js → wallet-AB4ISFMY.js} +8 -7
  79. package/dist/{wallet-OCCGEH6H.js → wallet-XVRLJZ63.js} +12 -10
  80. package/package.json +2 -1
  81. package/skills/tenjin/SKILL.md +76 -41
  82. package/skills/tenjin-search/SKILL.md +10 -6
  83. package/dist/chunk-BBUYCDSG.js.map +0 -1
  84. package/dist/chunk-DQDGBWWH.js.map +0 -1
  85. package/dist/chunk-J6CVKC4M.js.map +0 -1
  86. package/dist/chunk-NVHQCTIC.js.map +0 -1
  87. package/dist/chunk-P3FBESBB.js.map +0 -1
  88. package/dist/chunk-RGFBBNGP.js.map +0 -1
  89. package/dist/chunk-URSGGRO4.js.map +0 -1
  90. package/dist/chunk-UYP7G3GZ.js.map +0 -1
  91. package/dist/chunk-WRWCDLVK.js.map +0 -1
  92. package/dist/chunk-XFHZWORF.js.map +0 -1
  93. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  94. package/dist/chunk-ZA3RFDAV.js.map +0 -1
  95. package/dist/doctor-FBRQNOUQ.js +0 -22
  96. package/dist/install-QXZCHIBT.js.map +0 -1
  97. package/dist/outcome-VXCBEGNC.js +0 -20
  98. package/dist/run-5OGX64IY.js.map +0 -1
  99. package/dist/search-LIIWUMWV.js +0 -24
  100. /package/dist/{buy-K2G6XQY2.js.map → buy-3PPC2SRQ.js.map} +0 -0
  101. /package/dist/{candidate-DJB2NNTG.js.map → candidate-FCBWDN4Y.js.map} +0 -0
  102. /package/dist/{chunk-VZ3AJCO5.js.map → chunk-75G4REUY.js.map} +0 -0
  103. /package/dist/{chunk-C3S6725N.js.map → chunk-7MJCZ2OX.js.map} +0 -0
  104. /package/dist/{chunk-PCLPVJ3J.js.map → chunk-7WDY4AXV.js.map} +0 -0
  105. /package/dist/{chunk-RGTTACP3.js.map → chunk-ATSCQETF.js.map} +0 -0
  106. /package/dist/{chunk-DAJ56EUU.js.map → chunk-CTFFFQFH.js.map} +0 -0
  107. /package/dist/{chunk-B7YB4MMU.js.map → chunk-E5PZEPUO.js.map} +0 -0
  108. /package/dist/{chunk-6OE2IJMH.js.map → chunk-G7ECLIN6.js.map} +0 -0
  109. /package/dist/{chunk-CYRYVZPN.js.map → chunk-GJKDWZ6X.js.map} +0 -0
  110. /package/dist/{chunk-OTDI5FXG.js.map → chunk-JURZ2T2I.js.map} +0 -0
  111. /package/dist/{chunk-6ZBZCBR7.js.map → chunk-PT2NJUGG.js.map} +0 -0
  112. /package/dist/{chunk-XBJ3VLWX.js.map → chunk-PZSUWDF2.js.map} +0 -0
  113. /package/dist/{chunk-EDENZN2Q.js.map → chunk-TMZIXYPL.js.map} +0 -0
  114. /package/dist/{chunk-L6AV2Q73.js.map → chunk-VE5BALOI.js.map} +0 -0
  115. /package/dist/{chunk-2YX6LTCD.js.map → chunk-XDW6GOHO.js.map} +0 -0
  116. /package/dist/{config-SAQEQRFB.js.map → config-VT5WU47R.js.map} +0 -0
  117. /package/dist/{doctor-FBRQNOUQ.js.map → doctor-6PEYDTB5.js.map} +0 -0
  118. /package/dist/{edit-IZZ2HIMR.js.map → edit-GKI37CRM.js.map} +0 -0
  119. /package/dist/{inspect-BFWZ5XOP.js.map → inspect-ITZIRZDV.js.map} +0 -0
  120. /package/dist/{outcome-VXCBEGNC.js.map → outcome-F5KN3K3Y.js.map} +0 -0
  121. /package/dist/{publish-5NTCRF2V.js.map → publish-F5G5WIFI.js.map} +0 -0
  122. /package/dist/{search-LIIWUMWV.js.map → search-Z2YALF6S.js.map} +0 -0
  123. /package/dist/{wallet-OCCGEH6H.js.map → wallet-AB4ISFMY.js.map} +0 -0
  124. /package/dist/{wallet-RBDVNZVR.js.map → wallet-XVRLJZ63.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/install.ts","../src/lib/harness-permissions.ts","../src/lib/clack.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { z } from 'zod';\nimport { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from '../lib/errors';\nimport { hasCode } from '../lib/errno';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { ownsAnyLock, releaseOwnedLocks } from '../lib/lock';\nimport {\n deepestExisting,\n installSkill,\n resolveThroughLink,\n wrapWriteError,\n} from '../lib/skill-writer';\nimport type { SkillInstallStatus } from '../lib/skill-writer';\nimport { resolveSkillsSource, SKILL_NAMES } from '../lib/skills-source';\nimport {\n CLI_SKILL_NAMES,\n HARNESS_TARGETS,\n HOSTED_SKILL_NAME,\n harnessDetectedBy,\n harnessTargetDir,\n isModelInvocationDisabled,\n onPath,\n readSkillFile,\n} from '../lib/skill-wiring';\nimport type { HarnessTarget } from '../lib/skill-wiring';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n PublishModeSchema,\n parsePublishModeFlag,\n} from '../lib/config';\nimport type { PublishMode } from '../lib/config';\nimport { persistInstallHarness, persistPublishMode } from './config';\nimport { runWalletCreate } from './wallet';\nimport { collectDoctorChecks } from './doctor';\nimport type { DoctorDeps, DoctorChecks } from './doctor';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { recommendedPermissions } from '../lib/permissions';\nimport {\n FREE_VERB_RULES,\n inspectFreeVerbRules,\n permissionsSkipped,\n wireFreeVerbAllowlist,\n} from '../lib/harness-permissions';\nimport type { PermissionsResult } from '../lib/harness-permissions';\nimport { confirmChoice, intro as clackIntro, outro as clackOutro, selectOne } from '../lib/clack';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { Io } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n// The `--harness` vocabulary and its directory mapping are single-sourced in\n// skill-wiring beside the detection probes, because `doctor` maps a persisted choice\n// back to a directory with the same rules.\nconst HARNESSES = HARNESS_TARGETS;\ntype Harness = HarnessTarget;\n\nconst InstallInputSchema = z.object({\n harness: z.array(z.string()).optional(),\n dryRun: z.boolean().optional(),\n publishMode: z.string().optional(),\n noWallet: z.boolean().optional(),\n /** Opt-in for the ~/.claude/CLAUDE.md nudge: true (--claude-md), false\n * (--no-claude-md), or undefined (skip). Never a question: the walkthrough is\n * capped at three decisions. */\n claudeMd: z.boolean().optional(),\n /** Wire the free-verb harness allowlist without asking (`--allow-free-verbs`). */\n allowFreeVerbs: z.boolean().optional(),\n});\nexport type InstallInput = z.infer<typeof InstallInputSchema>;\n\n/**\n * The publish-mode question's seam: returns the chosen mode, or `null` when the\n * operator cancelled (which changes nothing and writes nothing). The choices\n * themselves are {@link PUBLISH_MODE_CHOICES}; the seam exists so tests answer\n * in-process and never render a prompt.\n */\nexport type PromptPublishModeFn = () => Promise<PublishMode | null>;\n\n/** A yes/no seam, same shape as buy's `confirm`. */\nexport type ConfirmFn = (label: string) => Promise<boolean>;\n\ntype PublishModeSource = 'flag' | 'existing' | 'prompt' | 'default-skipped';\ninterface PublishModeSelection {\n value: PublishMode;\n source: PublishModeSource;\n}\n\n/** How the wallet step resolved, so rendering stays separate from prompting. */\ninterface WalletOutcome {\n status: 'existing' | 'created' | 'none';\n address?: string;\n}\n\n/**\n * The one line `install` keeps in an AGENTS.md (and, opt-in, in a CLAUDE.md) so the\n * harness reads it as global guidance, not the raw ~/.agents/skills scan. It is an\n * instinct nudge: run a free `tenjin search` before regenerating public research,\n * then a pointer to where the skills live. The HTML-comment marker keeps re-runs\n * idempotent: a matching line is left untouched, a drifted line (an older install's\n * copy) is rewritten in place, and an absent line is appended, so we never duplicate.\n */\nconst SKILLS_MARKER = '<!-- tenjin-cli:skills -->';\n\n/**\n * The instinct nudge line, pointed at `skillsDir`. One line, no em dashes: the\n * marker, the search-before-regenerating nudge, then where the skills live.\n */\nfunction nudgeLine(skillsDir: string): string {\n return `${SKILLS_MARKER} Tenjin: before regenerating public research (version-specific compatibility, integration gotchas, benchmarks, dated probes), run 'tenjin search \"<question>\" --json' first; it is free and anonymous but sends the generalized question text to tenjin.blog, so strip private identifiers. Skills (tenjin-search, tenjin-publish, tenjin) are installed at ${skillsDir}; read the relevant SKILL.md before using the CLI.`;\n}\n\n/**\n * Upsert the marker line into a file's text. Finds the existing marker line by its\n * marker prefix (not exact text) so an older install's drifted copy is recognized:\n * a matching line is `none`, a drifted line is `replace`d in place, an absent marker\n * is `append`ed. `content` is the text to write (null when nothing changes).\n */\nfunction upsertMarkerLine(\n existing: string | null,\n line: string,\n): { content: string | null; change: 'append' | 'replace' | 'none' } {\n const text = existing ?? '';\n if (!text.includes(SKILLS_MARKER)) {\n const prefix = text.length === 0 || text.endsWith('\\n') ? '' : '\\n';\n return { content: `${text}${prefix}${line}\\n`, change: 'append' };\n }\n const lines = text.split('\\n');\n const idx = lines.findIndex((l) => l.includes(SKILLS_MARKER));\n if (lines[idx] === line) return { content: null, change: 'none' };\n lines[idx] = line;\n return { content: lines.join('\\n'), change: 'replace' };\n}\n\n/**\n * The Codex config.toml rule the user must add by hand. We PRINT it, never edit\n * config.toml: Codex's default workspace-write sandbox blocks network, which would\n * make every paid x402 call fail (or prompt) until this is set.\n */\nconst CODEX_NETWORK_RULE = '[sandbox_workspace_write]\\nnetwork_access = true';\n\n/** Per-skill install outcome for one harness target. */\ninterface SkillResult {\n name: string;\n status: SkillInstallStatus;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n /** Is this one of the two CLI adapter skills (as opposed to the hosted mirror)? */\n cli: boolean;\n /** Will a harness surface it to the model after this run? On a --dry-run nothing is\n * written, so it answers for the packaged copy that would land. */\n modelInvocable: boolean;\n}\n\ninterface AgentsMdResult {\n path: string;\n status: 'appended' | 'already-present' | 'updated' | 'would-append' | 'would-update';\n}\n\ninterface ClaudeMdResult {\n path: string;\n status: 'written' | 'up-to-date' | 'updated' | 'skipped' | 'would-write' | 'would-update';\n}\n\ninterface HarnessResult {\n harness: Harness;\n detected: boolean;\n detectedBy: string[];\n skillsDir: string;\n skills: SkillResult[];\n /**\n * Was the hosted zero-install `tenjin` skill already in this target before the\n * run? Reported so an upgrade over a hosted-skill machine is visible in `--json`,\n * which is exactly the state #35 was invisible in.\n */\n hostedPreexisting: boolean;\n /**\n * Narrower than {@link HarnessResult.hostedPreexisting}: the hosted skill was here\n * AND the CLI adapters were not, which is the hosted-zero-install-first funnel\n * rather than a second run finding our own mirror. This is what gates the notice.\n */\n hostedArrivedFirst: boolean;\n agentsMd?: AgentsMdResult;\n claudeMd?: ClaudeMdResult;\n codexNetworkRule?: string;\n notes: string[];\n warnings: string[];\n}\n\nexport interface InstallDeps {\n /** Home directory root for harness detection + skill destinations. Tests inject a temp dir. */\n homeDir?: string;\n /** The packaged skills source directory. Defaults to resolving it from this module's location. */\n skillsSourceDir?: string;\n /** PATH probe for `claude`/`codex` binaries. Injectable so tests never depend on the real PATH. */\n which?: (bin: string) => boolean;\n /** Environment (PATH for the default `which`). Defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Doctor check collector; defaults to the real one. Injected in tests to avoid the network. */\n collectChecks?: (ctx: CommandContext) => Promise<DoctorChecks>;\n /** Deps forwarded to the default doctor collector (e.g. a canned fetch). */\n doctorDeps?: DoctorDeps;\n /** Decision 1: the publish-mode select; defaults to the clack list. */\n promptPublishMode?: PromptPublishModeFn;\n /** Decision 2: the permissions confirm (default yes); defaults to the clack confirm. */\n confirmPermissions?: ConfirmFn;\n /** Whether decision 2 has anything left to grant; defaults to reading settings.json. */\n inspectPermissions?: (\n home: string,\n ) => Promise<{ pending: string[] | null; satisfied?: PermissionsResult }>;\n /** Decision 3: \"Create a wallet now?\"; defaults to the clack confirm (default yes). */\n confirmWallet?: ConfirmFn;\n /** Prompt-sequence chrome. Seams so tests never load the renderer. */\n intro?: (message: string) => Promise<void>;\n outro?: (message: string) => Promise<void>;\n /** Whether the human walkthrough runs (TTY, no --json, stdin is a TTY). Injected in tests. */\n isInteractive?: boolean;\n /** Does a wallet already exist? Defaults to walletFileExists(dataDir). */\n walletExists?: (dataDir: string) => Promise<boolean>;\n /** An existing wallet's address, for the \"(existing)\" line. Defaults to the local provider. */\n walletAddress?: (ctx: CommandContext) => Promise<string>;\n /** Create a wallet and return its address. Defaults to runWalletCreate. */\n createWallet?: (ctx: CommandContext) => Promise<string>;\n}\n\n/**\n * `tenjin install`: detect the installed harness(es), copy the packaged skills\n * into each one's skills directory, wire the AGENTS.md pointer, run the doctor\n * checks, then ask AT MOST THREE questions (publishing, harness permissions,\n * wallet) and print a short summary. Everything that is not one of those three\n * decisions is display: the security reference material lives in `doctor` and\n * the README, not in the middle of a setup flow.\n *\n * Like every command it is human-first (the global output contract): at a TTY\n * without `--json` it prompts and returns the walkthrough as humanLines, which\n * the dispatcher prints to stdout with no envelope. With `--json` or piped\n * stdout it returns the envelope, no prompts, no wallet step. Idempotent: a\n * re-run reports up-to-date, never duplicates the AGENTS.md line, and adds no\n * permission rule twice. `--dry-run` writes nothing.\n */\nexport async function runInstall(\n input: InstallInput,\n ctx: CommandContext,\n deps: InstallDeps = {},\n): Promise<CommandResult> {\n return withInterruptGuard((markPhase) => installBody(input, ctx, deps, markPhase));\n}\n\n/** How far the command got, for the interrupt diagnostic. */\ntype InstallPhase = 'writing-skills' | 'wired';\n\n/**\n * Run `fn` with SIGINT/SIGTERM answered for the WHOLE command, not just the\n * blocks that hold a lock. The default signal action terminates without running\n * `finally`, stranding whichever lock the command holds so every later run times\n * out on it; install takes two (the config lock behind decision 1, and the\n * wallet-create lock behind decision 3, whose scrypt work is the longest\n * interruptible window this command has). Ownership is tracked by the lock\n * itself, so the handler releases exactly what this process holds and a run still\n * QUEUED behind another cannot touch that other run's lock.\n *\n * `markPhase` carries the diagnostic past the states no lock covers: the skills\n * write holds nothing (each file lands by its own atomic rename), so without it an\n * interrupt mid-copy would report that nothing changed.\n */\nasync function withInterruptGuard(\n fn: (markPhase: (phase: InstallPhase) => void) => Promise<CommandResult>,\n): Promise<CommandResult> {\n let phase: InstallPhase | undefined;\n const onSignal = (signal: NodeJS.Signals): void => {\n const wasWriting = ownsAnyLock() || phase === 'writing-skills';\n releaseOwnedLocks();\n // An external SIGINT/SIGTERM can land while a clack prompt has the terminal\n // in raw mode with the cursor hidden; process.exit skips clack's teardown.\n // (Ctrl-C at a prompt is unaffected: raw mode delivers it as a keypress.)\n if (process.stdin.isTTY) process.stdin.setRawMode?.(false);\n if (process.stdout.isTTY) process.stdout.write('\\x1b[?25h');\n process.stderr.write(\n wasWriting\n ? `\\nInterrupted mid-write. Some files may be half-written; re-run \\`tenjin install\\` to finish.\\n`\n : phase === 'wired'\n ? `\\nInterrupted after the skills were written; later setup steps may not have finished. Re-run \\`tenjin install\\` to finish.\\n`\n : '\\nInterrupted before anything was written; nothing changed.\\n',\n );\n process.exit(signal === 'SIGINT' ? 130 : 143);\n };\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n try {\n return await fn((p) => {\n phase = p;\n });\n } finally {\n process.off('SIGINT', onSignal);\n process.off('SIGTERM', onSignal);\n }\n}\n\nasync function installBody(\n input: InstallInput,\n ctx: CommandContext,\n deps: InstallDeps,\n markPhase: (phase: InstallPhase) => void,\n): Promise<CommandResult> {\n const parsed = InstallInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new CliError('USAGE', 'Invalid install options', {\n fix: 'Run `tenjin install --help`.',\n details: parsed.error.issues,\n });\n }\n const dryRun = parsed.data.dryRun === true;\n const noWallet = parsed.data.noWallet === true;\n const claudeMdFlag = parsed.data.claudeMd;\n const allowFreeVerbs = parsed.data.allowFreeVerbs === true;\n // Validate --publish-mode UP FRONT so a bad value fails before any wiring.\n const publishModeFlag =\n parsed.data.publishMode !== undefined ? parseModeFlag(parsed.data.publishMode) : undefined;\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n // An empty or relative HOME (sudo/docker env_reset, systemd units) would make\n // every target below relative, silently installing into the current working\n // directory and reporting success while no harness reads a thing.\n if (!isAbsolute(home)) {\n throw new CliError(\n 'INTERNAL',\n 'The home directory did not resolve to an absolute path, so nothing was installed.',\n {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n },\n );\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n\n // Human-first is the global output rule (emitSuccess renders humanLines at a TTY\n // without --json and no envelope). `humanOutput` matches that gate so install\n // returns its walkthrough as humanLines; `canPrompt` additionally needs stdin, so\n // a piped-stdin run still renders a walkthrough (with defaults, no wallet prompt).\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n\n const skillsSource =\n deps.skillsSourceDir ?? resolveSkillsSource(fileURLToPath(new URL('.', import.meta.url)));\n await assertSkillsSource(skillsSource);\n\n const plans = resolvePlans(parsed.data.harness, home, which);\n // Same condition resolvePlans treats as an override, so what gets recorded below is\n // exactly what overrode detection.\n const explicitHarness = parsed.data.harness !== undefined && parsed.data.harness.length > 0;\n // The CLAUDE.md nudge is flag-only now: `--claude-md` writes it, `--no-claude-md`\n // and an absent flag skip it. It used to be a fourth interactive question, and\n // the walkthrough's whole point is that there are three.\n const claudeMdWrite = claudeMdFlag === true;\n const harnesses: HarnessResult[] = [];\n // Unlocked. What makes concurrent writers safe here is the per-file atomic\n // rename, not serialization: the rm-then-write this used to be had two runs\n // reading each other's half-built trees (7 of 15 concurrent runs failed on raw\n // ENOENT/ENOTEMPTY renames), and 24 concurrent runs pass without a lock. The\n // self-heal is the other writer, and it writes these same bytes to these same\n // paths through the same writer.\n if (!dryRun) markPhase('writing-skills');\n for (const plan of plans) {\n harnesses.push(await applyPlan(plan, skillsSource, dryRun, claudeMdWrite));\n }\n await assertSkillsLanded(plans, dryRun);\n if (!dryRun) markPhase('wired');\n // An explicit --harness is REMEMBERED, before the embedded doctor run so this run's\n // own check already honours it. Detection cannot see a harness we do not probe for,\n // so without the record a directory the user named by hand is a target for one run\n // and then invisible to every later doctor — including for the #35 shadowing defect\n // it was chosen to hold. `--dry-run` records nothing, like the publish-mode write.\n if (explicitHarness && !dryRun) {\n await underDataDir(ctx.dataDir, () =>\n persistInstallHarness(\n ctx.dataDir,\n plans.map((p) => p.harness),\n ),\n );\n }\n // The embedded doctor run inspects the same `home` install just wrote into, so\n // its skill-wiring check reports THIS run's result rather than os.homedir()'s.\n // `which` goes with it: the check gates its verdicts on harness detection, and a\n // different probe there would judge directories this run never targeted.\n const doctorDeps: DoctorDeps = { ...(deps.doctorDeps ?? {}) };\n doctorDeps.homeDir ??= home;\n doctorDeps.which ??= which;\n const collect = deps.collectChecks ?? ((c) => collectDoctorChecks(c, doctorDeps));\n const doctor = await collect(ctx);\n\n // The three decisions, in order. Each one is skipped (with its own recorded\n // reason) when a flag already settled it or when there is no one to ask.\n if (canPrompt) await (deps.intro ?? clackIntro)('tenjin install');\n const publishMode = await underDataDir(ctx.dataDir, () =>\n resolvePublishMode(publishModeFlag, ctx, deps, dryRun, canPrompt),\n );\n const permissions = await resolvePermissions({\n plans,\n home,\n deps,\n flag: allowFreeVerbs,\n dryRun,\n canPrompt,\n });\n // The wallet question belongs to the human walkthrough only: a machine run has\n // never created a key, and that stays true.\n const wallet = humanOutput\n ? await resolveWallet(ctx, deps, dryRun || !canPrompt || noWallet)\n : undefined;\n if (canPrompt) await (deps.outro ?? clackOutro)('Setup complete.');\n\n const data = {\n dryRun,\n skillsSource,\n harnesses,\n doctor: { status: doctor.failure !== undefined ? 'fail' : 'pass', checks: doctor.checks },\n publishMode,\n // Shipped with the install rather than left for the operator to discover after\n // their first auto-mode denial (#33). Static constants, no config key: see\n // lib/permissions.ts for why this is deliberately not operator-editable state.\n // `wired` is the outcome of THIS run's optional settings.json write; the three\n // recommendation tiers beside it are unchanged, so a machine consumer that\n // read `alwaysSafe` / `optIn` / `neverAllowlisted` before still does.\n permissions: { ...recommendedPermissions(), wired: permissions },\n };\n\n // Machine path (--json or piped stdout): today's envelope, no wallet step.\n if (!humanOutput) return { data };\n\n // Human path: the walkthrough as humanLines (the global emitSuccess prints them\n // to stdout at a TTY and never an envelope).\n const humanLines = buildWalkthrough(ctx.io, {\n dryRun,\n harnesses,\n publishMode,\n permissions,\n wallet: wallet ?? { status: 'none' },\n doctor,\n });\n return { data, humanLines };\n}\n\n/**\n * The two steps that write to the Tenjin data dir, with a denial there reported as\n * the directory it is rather than as a raw errno under INTERNAL. The skills are\n * already on disk by now, so the message says what failed, not that nothing\n * happened.\n */\nasync function underDataDir<T>(dataDir: string, fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n if (!hasCode(err, 'EACCES') && !hasCode(err, 'EPERM')) throw err;\n throw new CliError('INTERNAL', `Could not use the Tenjin data directory ${dataDir}.`, {\n fix: `Permission denied. Check that you can write to it (\\`ls -ld ${dataDir}\\`), then re-run \\`tenjin install\\`.`,\n cause: err,\n });\n }\n}\n\nconst EXAMPLE_QUESTION = \"what actually changed in <library> v3's public API\";\n\ninterface WalkthroughState {\n dryRun: boolean;\n harnesses: HarnessResult[];\n publishMode: PublishModeSelection;\n permissions: PermissionsResult;\n wallet: WalletOutcome;\n doctor: DoctorChecks;\n}\n\n/**\n * The human surface: anything that genuinely needs attention (a dry-run banner,\n * an overwrite warning, a consent disclosure, a failing check) followed by a\n * summary of at most five lines. On a clean install the summary IS the output.\n */\nfunction buildWalkthrough(io: Io, s: WalkthroughState): string[] {\n const lines: string[] = [];\n if (s.dryRun) lines.push(paint(io, 'yellow', 'Dry run: nothing was written.'));\n lines.push(...noticeLines(io, s));\n if (lines.length > 0) lines.push('');\n lines.push(...summaryLines(io, s));\n return lines;\n}\n\n/**\n * Everything above the summary: per-harness warnings, the Codex network rule,\n * the nudge disclosure and its undo, and any doctor check that is not ok. A\n * green doctor says nothing at all, so a clean run stays five lines.\n */\nfunction noticeLines(io: Io, s: WalkthroughState): string[] {\n const lines: string[] = [];\n for (const h of s.harnesses) {\n if (h.hostedArrivedFirst) {\n // Named by DIRECTORY: one line per harness, and the funnel puts the mirror\n // in both, so an unqualified line appears twice and reads as a stutter.\n lines.push(\n paint(\n io,\n 'dim',\n `The hosted ${HOSTED_SKILL_NAME} skill was already in ${h.skillsDir}: kept as the zero-install fallback, and the CLI skills now take precedence.`,\n ),\n );\n }\n // When a nudge line was actually written or refreshed, disclose what it does\n // (question text leaves the machine) and how to undo it. This makes a re-run\n // that silently upgrades an older pointer line visible, not just the first write.\n const nudgePaths = nudgeFilesTouched(h);\n if (nudgePaths.length > 0) {\n lines.push(\n paint(\n io,\n 'dim',\n 'The nudge tells agents to run a free anonymous `tenjin search` before regenerating research; the generalized question text is sent to tenjin.blog.',\n ),\n );\n lines.push(\n paint(\n io,\n 'dim',\n `Undo anytime: delete the ${SKILLS_MARKER} line from ${nudgePaths.join(' and ')}.`,\n ),\n );\n }\n if (h.codexNetworkRule !== undefined) {\n lines.push(paint(io, 'dim', 'Codex blocks network by default; add to ~/.codex/config.toml:'));\n for (const rl of h.codexNetworkRule.split('\\n')) lines.push(paint(io, 'dim', ` ${rl}`));\n }\n for (const w of h.warnings) lines.push(paint(io, 'yellow', `! ${w}`));\n }\n if (s.permissions.warning !== undefined) {\n // Sanitized for the same reason doctorNotices sanitizes `detail`/`fix`: this\n // string embeds a V8 JSON parse error, and V8 quotes the offending input, so\n // ~20 bytes of whatever is in settings.json (escapes included) reach the\n // terminal at the moment we tell the operator we left their file alone.\n lines.push(paint(io, 'yellow', `! ${sanitizeForTerminal(s.permissions.warning)}`));\n }\n lines.push(...doctorNotices(io, s.doctor));\n return lines;\n}\n\n/**\n * The closing summary, capped at one line per subject: skills, publishing,\n * permissions, wallet, and the command to run next.\n */\nfunction summaryLines(io: Io, s: WalkthroughState): string[] {\n return [\n ...s.harnesses.map((h) => skillsLine(io, h, s.dryRun)),\n publishingLine(io, s.publishMode.value),\n permissionsLine(io, s.permissions),\n walletLine(io, s.wallet),\n `${paint(io, 'bold', 'Next:')} tenjin search \"${EXAMPLE_QUESTION}\"`,\n ];\n}\n\nfunction harnessLabel(h: Harness): string {\n return h === 'claude' ? 'Claude Code' : h === 'codex' ? 'Codex' : 'Agent Skills';\n}\n\n/**\n * One line per harness. It names the skills rather than counting them: #35\n * shipped as \"search worked, publish was simply absent\" on a machine that\n * already had the hosted skill, and a bare \"3 skills installed\" cannot tell you\n * publish is wired.\n */\nfunction skillsLine(io: Io, h: HarnessResult, dryRun: boolean): string {\n const changed = h.skills.some((s) => s.status !== 'up-to-date');\n const verb = dryRun ? 'would install' : changed ? 'installed' : 'up to date';\n const wired: string[] = [];\n if (h.agentsMd !== undefined) wired.push('AGENTS.md nudge');\n if (h.claudeMd !== undefined && h.claudeMd.status !== 'skipped') wired.push('CLAUDE.md nudge');\n const suffix = wired.length > 0 ? ` + ${wired.join(' + ')}` : '';\n const head = `${harnessLabel(h.harness)}: ${h.skills.length} skills ${verb}${suffix}`;\n return `${paint(io, 'green', '✓')} ${paint(io, 'bold', head)} in ${h.skillsDir}. ${skillRoster(h)}.`;\n}\n\n/** One line for the settled consent mode, with the same consequence the question showed. */\nfunction publishingLine(io: Io, mode: PublishMode): string {\n return `${paint(io, 'green', '✓')} ${paint(io, 'bold', `Publishing: ${mode}`)}. ${modeBlurb(mode)}`;\n}\n\n/**\n * One line for the harness allowlist: what landed, or what to run to get it. A\n * skip is never silent, because the operator's next auto-mode session is where\n * they would otherwise find out (#33).\n *\n * \"free\", never \"read-only\": see PERMISSIONS_QUESTION for why this tier cannot\n * honestly be called the latter. The line that reports a WRITE carries the\n * `doctor` pointer too, since that is the other moment an operator learns rules\n * landed without seeing them or the flag caveat that qualifies them.\n */\nfunction permissionsLine(io: Io, p: PermissionsResult): string {\n const label = paint(io, 'bold', 'Permissions:');\n if (p.added.length > 0) {\n return `${paint(io, 'green', '✓')} ${label} ${p.added.length} free tenjin commands added to ${p.path}. Full caveats: tenjin doctor`;\n }\n if (p.skipped === undefined) {\n return `${paint(io, 'green', '✓')} ${label} the ${FREE_VERB_RULES.length} free tenjin commands were already allowed in ${p.path}`;\n }\n if (p.skipped === 'harness-not-claude') {\n return `${paint(io, 'dim', '-')} ${label} not wired (Claude Code only). Run \\`tenjin doctor\\` for the lines your harness needs.`;\n }\n if (p.skipped === 'dry-run') {\n return `${paint(io, 'dim', '-')} ${label} unchanged (dry run).`;\n }\n if (p.skipped === 'declined') {\n return `${paint(io, 'dim', '-')} ${label} unchanged. Add them anytime: tenjin install --allow-free-verbs`;\n }\n if (p.skipped === 'not-requested') {\n return `${paint(io, 'dim', '-')} ${label} unchanged. Allow the ${FREE_VERB_RULES.length} free tenjin commands with: tenjin install --allow-free-verbs`;\n }\n if (p.skipped === 'changed-since-read') {\n // Nothing is wrong with the file and the flag is not the remedy: another\n // writer touched it mid-run, so the merge has to be recomputed against what\n // is there now. The catch-all below says \"fix it\", which is wrong here.\n return `${paint(io, 'yellow', '!')} ${label} ${p.path} changed while it was being updated, so nothing was written. Re-run: tenjin install`;\n }\n return `${paint(io, 'yellow', '!')} ${label} ${p.path} was left untouched. Fix it, then: tenjin install --allow-free-verbs`;\n}\n\nfunction walletLine(io: Io, w: WalletOutcome): string {\n const label = paint(io, 'bold', 'Wallet:');\n if (w.status === 'existing') {\n return `${paint(io, 'green', '✓')} ${label} ${w.address} (existing). Check funds with: tenjin wallet balance`;\n }\n if (w.status === 'created') {\n return `${paint(io, 'green', '✓')} ${label} ${w.address}. Fund it with a few dollars of USDC on Base, then: tenjin wallet balance`;\n }\n return `${paint(io, 'dim', '-')} ${label} none. Create one later with: tenjin wallet create`;\n}\n\n/** `tenjin-search, tenjin-publish (CLI); tenjin (hosted, zero-install fallback)`. */\nfunction skillRoster(h: HarnessResult): string {\n const cli = h.skills.filter((s) => s.cli).map((s) => s.name);\n const hosted = h.skills.filter((s) => !s.cli).map((s) => s.name);\n const parts: string[] = [];\n if (cli.length > 0) parts.push(`${cli.join(', ')} (CLI)`);\n if (hosted.length > 0) parts.push(`${hosted.join(', ')} (hosted, zero-install fallback)`);\n return parts.join('; ');\n}\n\n/**\n * The nudge files whose marker line this run wrote or refreshed (append/update, and\n * their dry-run would-* previews). An untouched line (already-present / up-to-date)\n * or a skipped CLAUDE.md is not included, so the disclosure only fires on a change.\n */\nfunction nudgeFilesTouched(h: HarnessResult): string[] {\n const paths: string[] = [];\n if (\n h.agentsMd !== undefined &&\n ['appended', 'updated', 'would-append', 'would-update'].includes(h.agentsMd.status)\n ) {\n paths.push(h.agentsMd.path);\n }\n if (\n h.claudeMd !== undefined &&\n ['written', 'updated', 'would-write', 'would-update'].includes(h.claudeMd.status)\n ) {\n paths.push(h.claudeMd.path);\n }\n return paths;\n}\n\n/** The single line of consequence attached to a mode, wherever it is shown. */\nfunction modeBlurb(v: PublishMode): string {\n return v === 'auto'\n ? 'Your agent publishes clean pieces on its own; your harness still shows each command for approval.'\n : v === 'review'\n ? 'Your agent asks you in chat before every publish.'\n : 'Fully unattended; only hard blocks stop it.';\n}\n\n/**\n * Decision 3, unchanged in behavior: ask only when no wallet exists, and never\n * under `--no-wallet`, `--dry-run`, or a run we cannot prompt in.\n */\nasync function resolveWallet(\n ctx: CommandContext,\n deps: InstallDeps,\n skipCreate: boolean,\n): Promise<WalletOutcome> {\n const exists = await (deps.walletExists ?? walletFileExists)(ctx.dataDir);\n if (exists) {\n return {\n status: 'existing',\n address: await (deps.walletAddress ?? existingWalletAddress)(ctx),\n };\n }\n if (skipCreate) return { status: 'none' };\n\n const confirm = deps.confirmWallet ?? defaultConfirm;\n if (!(await confirm(WALLET_QUESTION))) return { status: 'none' };\n\n return { status: 'created', address: await (deps.createWallet ?? defaultCreateWallet)(ctx) };\n}\n\nasync function existingWalletAddress(ctx: CommandContext): Promise<string> {\n return (await describeWallet(resolveWalletProvider(ctx))).address;\n}\n\nasync function defaultCreateWallet(ctx: CommandContext): Promise<string> {\n const result = await runWalletCreate(ctx);\n return (result.data as { address: string }).address;\n}\n\n/** The shared confirm, defaulting to YES (setup ergonomics); cancel reads as no. */\nfunction defaultConfirm(label: string): Promise<boolean> {\n return confirmChoice(label, true);\n}\n\n/**\n * Doctor problems only. A fully green run prints nothing here: the summary is\n * the whole output, and \"everything checks out\" is what an absent warning means.\n */\nfunction doctorNotices(io: Io, doctor: DoctorChecks): string[] {\n const problems = doctor.checks.filter((c) => c.status !== 'ok');\n if (problems.length === 0) return [];\n const lines = [paint(io, 'yellow', 'Some checks need attention:')];\n for (const c of problems) {\n const icon = c.status === 'fail' ? paint(io, 'red', '✗') : paint(io, 'yellow', '!');\n // Same seam as renderDoctorHuman: `detail`/`fix` carry server-sourced substrings.\n lines.push(` ${icon} ${c.name}: ${sanitizeForTerminal(c.detail)}`);\n if (c.fix !== undefined) {\n lines.push(paint(io, 'dim', ` fix: ${sanitizeForTerminal(c.fix)}`));\n }\n }\n return lines;\n}\n\n// --- Publish-mode selection (D38 setup) ------------------------------------------\n\n/**\n * The STORED default: what a non-interactive run, a cancelled question, or a\n * `--dry-run` leaves `publish.mode` at, which is to say unset. It is deliberately\n * NOT the interactively recommended answer below: recommending `auto` is a thing\n * we do to a human who is looking at the consequence, never a thing that happens\n * to a machine run that was never asked.\n */\nconst DEFAULT_MODE: PublishMode = CONFIG_DEFAULTS.publish.mode;\n\n/** Decision 1's literal copy: one line of consequence per option, `auto` first. */\nexport const PUBLISH_MODE_CHOICES = [\n {\n value: 'auto',\n label: 'Auto (recommended)',\n hint: 'your agent publishes clean pieces on its own; your harness still shows each command for approval',\n },\n { value: 'review', label: 'Ask me in chat first' },\n { value: 'full-auto', label: 'Fully unattended', hint: 'only hard blocks stop it' },\n] as const satisfies readonly { value: PublishMode; label: string; hint?: string }[];\n\nexport const PUBLISH_MODE_QUESTION = 'When your agent has something worth publishing:';\n\n/**\n * Resolve (and, for an explicit choice, persist) the publish consent mode at\n * install time. Precedence: `--publish-mode` flag > an already-configured global\n * mode > the interactive select > the untouched default. Only an explicit choice\n * writes: a cancelled select, a non-interactive run, and `--dry-run` all leave\n * `publish.mode` unset so its provenance stays `default`.\n */\nasync function resolvePublishMode(\n flag: PublishMode | undefined,\n ctx: CommandContext,\n deps: InstallDeps,\n dryRun: boolean,\n interactive: boolean,\n): Promise<PublishModeSelection> {\n if (flag !== undefined) {\n if (!dryRun) await persistPublishMode(ctx.dataDir, flag); // --dry-run: would-set only\n return { value: flag, source: 'flag' };\n }\n\n // Only the GLOBAL config file counts as \"already configured\" for setup: env/flag\n // are per-run and a project `.tenjin.json` is not this machine's global choice.\n const config = await loadRawConfig(ctx.dataDir);\n if (config.publish?.mode !== undefined) {\n return { value: config.publish.mode, source: 'existing' };\n }\n\n // `interactive` is the walkthrough gate (already false under --json or off a TTY),\n // so a machine consumer never sits behind a prompt.\n if (dryRun || !interactive) return { value: DEFAULT_MODE, source: 'default-skipped' };\n\n const answer = await (deps.promptPublishMode ?? defaultPromptPublishMode)();\n if (answer === null) return { value: DEFAULT_MODE, source: 'default-skipped' }; // cancelled: no write\n // The seam is injectable, so an answer is validated rather than trusted; an\n // unparseable one is a cancel, not a write of something unknown.\n const parsed = PublishModeSchema.safeParse(answer);\n if (!parsed.success) return { value: DEFAULT_MODE, source: 'default-skipped' };\n await persistPublishMode(ctx.dataDir, parsed.data);\n return { value: parsed.data, source: 'prompt' };\n}\n\nfunction defaultPromptPublishMode(): Promise<PublishMode | null> {\n return selectOne<PublishMode>({\n message: PUBLISH_MODE_QUESTION,\n choices: PUBLISH_MODE_CHOICES.map((c) => ({ ...c })),\n initialValue: 'auto',\n });\n}\n\nfunction parseModeFlag(value: string): PublishMode {\n return parsePublishModeFlag(value, '--publish-mode');\n}\n\n// --- Harness permissions (decision 2) ---------------------------------------------\n\n/**\n * Decision 2's literal copy: one question, and a consequence that lib/permissions.ts\n * would agree with. NOT \"read-only\" and NOT \"never touches your wallet\" — that\n * module refuses both claims in as many words (`search` and `outcome` POST\n * off-machine, `read` saves to the library and can present a cached\n * wallet-derived delegation, and two of the nine rules are `wallet show` /\n * `wallet balance`). What is actually true of the whole tier is that it cannot\n * spend and cannot open the keystore, so that is what the question says.\n *\n * The pointer at `tenjin doctor` is how FLAG_CAVEAT's \"printed with the rules\n * everywhere they are printed\" contract is met at the consent moment. The\n * walkthrough no longer prints the rules or the flag caveat, so the yes/no that\n * replaced them names the one command that prints both, in full, unchanged.\n */\nexport const PERMISSIONS_QUESTION = [\n 'Let your agent search tenjin without permission popups?',\n `Adds ${FREE_VERB_RULES.length} free commands to ~/.claude/settings.json.`,\n 'None can spend USDC or open your wallet keystore;',\n 'three send or store data (search, outcome, read).',\n 'Full caveats: tenjin doctor.',\n].join(' ');\n\n/** Decision 3's literal copy. */\nexport const WALLET_QUESTION = 'Create a wallet now?';\n\n/**\n * Settle the harness allowlist. The write itself is consent-gated and free-verb\n * only (see lib/harness-permissions.ts); this decides ONLY whether to call it.\n * `--allow-free-verbs` wires it headlessly, an interactive run asks, and a\n * non-interactive run without the flag changes nothing and says so.\n */\nasync function resolvePermissions(args: {\n plans: HarnessPlan[];\n home: string;\n deps: InstallDeps;\n flag: boolean;\n dryRun: boolean;\n canPrompt: boolean;\n}): Promise<PermissionsResult> {\n const { plans, home, deps, flag, dryRun, canPrompt } = args;\n // Only Claude Code has a settings file with this shape. Codex and the shared\n // Agent Skills location gate permissions elsewhere, so there is nothing here to\n // write for them, and guessing at another harness's config would be the kind of\n // uninvited write this whole module is careful about.\n if (!plans.some((p) => p.harness === 'claude')) {\n return permissionsSkipped(plans[0]?.harness ?? 'shared', home, 'harness-not-claude');\n }\n if (dryRun) return permissionsSkipped('claude', home, 'dry-run');\n if (flag) return wireFreeVerbAllowlist(home);\n if (!canPrompt) return permissionsSkipped('claude', home, 'not-requested');\n\n // Nothing left to grant is not a question: every rule already present is the\n // ordinary state of a re-run. The SNAPSHOT's result is returned rather than\n // calling the writer again, because a second read would re-add a rule revoked in\n // between with no prompt. An unreadable file is \"unknown\", not \"already\n // allowed\", so it falls through and still asks.\n const probe = await (deps.inspectPermissions ?? inspectFreeVerbRules)(home);\n if (probe.satisfied !== undefined) return probe.satisfied;\n\n const confirm = deps.confirmPermissions ?? defaultConfirm;\n if (!(await confirm(PERMISSIONS_QUESTION))) {\n return permissionsSkipped('claude', home, 'declined');\n }\n return wireFreeVerbAllowlist(home);\n}\n\n// --- Detection + planning --------------------------------------------------------\n\ninterface HarnessPlan {\n harness: Harness;\n detected: boolean;\n detectedBy: string[];\n skillsDir: string;\n wiresAgentsMd: boolean;\n home: string;\n}\n\n/**\n * Turn detection (or an explicit --harness override) into the ordered, de-duped\n * list of targets to write. Codex and the shared fallback both land in\n * ~/.agents/skills (the harness-shared Agent Skills location), so a request for\n * both collapses to one target keyed by that directory.\n */\nfunction resolvePlans(\n override: string[] | undefined,\n home: string,\n which: (bin: string) => boolean,\n): HarnessPlan[] {\n if (override !== undefined && override.length > 0) {\n const plans = override.map((v) => planFor(validateHarness(v), ['override'], true, home));\n return dedupeBySkillsDir(plans);\n }\n\n const plans: HarnessPlan[] = [];\n // Same two probes doctor's skills check gates its per-directory verdicts on.\n const claudeBy = harnessDetectedBy(home, 'claude', which);\n const codexBy = harnessDetectedBy(home, 'codex', which);\n if (claudeBy.length > 0) plans.push(planFor('claude', claudeBy, true, home));\n if (codexBy.length > 0) plans.push(planFor('codex', codexBy, true, home));\n if (plans.length === 0) {\n // Nothing detected: the shared Agent Skills location is the fallback target, so\n // a harness installed later still finds the skills.\n plans.push(planFor('shared', ['fallback'], false, home));\n }\n return dedupeBySkillsDir(plans);\n}\n\nfunction planFor(\n harness: Harness,\n detectedBy: string[],\n detected: boolean,\n home: string,\n): HarnessPlan {\n const skillsDir = harnessTargetDir(home, harness);\n return { harness, detected, detectedBy, skillsDir, wiresAgentsMd: harness !== 'claude', home };\n}\n\nfunction dedupeBySkillsDir(plans: HarnessPlan[]): HarnessPlan[] {\n const seen = new Set<string>();\n const out: HarnessPlan[] = [];\n for (const p of plans) {\n if (seen.has(p.skillsDir)) continue;\n seen.add(p.skillsDir);\n out.push(p);\n }\n return out;\n}\n\nfunction validateHarness(value: string): Harness {\n if ((HARNESSES as readonly string[]).includes(value)) return value as Harness;\n throw new CliError('USAGE', `Unknown harness \"${value}\"`, {\n fix: `--harness must be one of: ${HARNESSES.join(', ')}.`,\n });\n}\n\n// --- Applying a plan -------------------------------------------------------------\n\n/**\n * Wire one harness target. EVERY packaged skill is written on every run,\n * unconditionally: an existing Tenjin skill in the target (typically the hosted\n * zero-install one from tenjin.blog/skills.md) is never a reason to skip, because\n * install on such a machine is the UPGRADE path (#35). The hosted mirror is kept\n * and refreshed rather than removed (roadmap G4: it is the permanent zero-install\n * curriculum); the two CLI adapter skills land beside it and supersede it while\n * the CLI is present.\n */\nasync function applyPlan(\n plan: HarnessPlan,\n skillsSource: string,\n dryRun: boolean,\n claudeMdWrite: boolean,\n): Promise<HarnessResult> {\n const skills: SkillResult[] = [];\n const warnings: string[] = [];\n for (const name of SKILL_NAMES) {\n const { status, warning, preexisting } = await installSkill(\n join(skillsSource, name),\n join(plan.skillsDir, name),\n dryRun,\n name,\n );\n skills.push({\n name,\n status,\n preexisting,\n cli: (CLI_SKILL_NAMES as readonly string[]).includes(name),\n modelInvocable: await landedInvocable(plan.skillsDir, skillsSource, name, dryRun),\n });\n if (warning !== undefined) warnings.push(warning);\n }\n\n const hostedPreexisting = skills.some((s) => s.name === HOSTED_SKILL_NAME && s.preexisting);\n // The notice is about arriving through the hosted skill, which is only news when\n // the CLI adapters were NOT already wired: after an earlier install the mirror on\n // disk is one we wrote, and announcing it is the CLI reporting its own footprint.\n const hostedArrivedFirst = hostedPreexisting && !skills.some((s) => s.cli && s.preexisting);\n const result: HarnessResult = {\n harness: plan.harness,\n detected: plan.detected,\n detectedBy: plan.detectedBy,\n skillsDir: plan.skillsDir,\n skills,\n hostedPreexisting,\n hostedArrivedFirst,\n notes: notesFor(plan, hostedArrivedFirst),\n warnings,\n };\n\n if (plan.wiresAgentsMd) {\n result.agentsMd = await wireAgentsMd(plan, dryRun);\n result.codexNetworkRule = CODEX_NETWORK_RULE;\n } else if (plan.harness === 'claude') {\n result.claudeMd = await wireClaudeMd(plan, dryRun, claudeMdWrite);\n }\n return result;\n}\n\n/**\n * Write the nudge line into ~/.claude/CLAUDE.md when opted in. Creates the file if\n * absent, rewrites a drifted marker line in place, and leaves a matching line alone.\n * `skipped` means the user opted out (or was never asked).\n */\nasync function wireClaudeMd(\n plan: HarnessPlan,\n dryRun: boolean,\n write: boolean,\n): Promise<ClaudeMdResult> {\n const path = join(plan.home, '.claude', 'CLAUDE.md');\n if (!write) return { path, status: 'skipped' };\n\n const probe = await probeMarkerText(path);\n const { content, change } = upsertMarkerLine(probe.text, nudgeLine(plan.skillsDir));\n if (change === 'none') return { path, status: 'up-to-date' };\n const writeTo = await prepareMarkerWrite(path, probe);\n if (!dryRun && content !== null) await writeMarkerFile(path, writeTo, content);\n if (change === 'append') return { path, status: dryRun ? 'would-write' : 'written' };\n return { path, status: dryRun ? 'would-update' : 'updated' };\n}\n\nfunction notesFor(plan: HarnessPlan, hostedArrivedFirst: boolean): string[] {\n const notes =\n plan.harness === 'claude'\n ? [\n 'Installed at the user level (~/.claude/skills). A Claude Code plugin will later make this automatic.',\n ]\n : [\n 'Copied into the shared Agent Skills location (~/.agents/skills). Codex and any Agent-Skills-compatible harness read it there.',\n ];\n if (hostedArrivedFirst) {\n // \"The skill stays\", never \"your copy is untouched\": the FILE is replaced by\n // this package's mirror, and a note reading as preservation beside a warning\n // saying replacement is worse than either alone.\n notes.push(\n `The hosted ${HOSTED_SKILL_NAME} skill was already here; the skill stays as the zero-install fallback (its file is replaced by this package's mirror) and the CLI skills (${CLI_SKILL_NAMES.join(', ')}) take precedence while the CLI is installed.`,\n );\n }\n return notes;\n}\n\n/**\n * Did the skill actually land model-invocable? Read back from the target so the\n * reported value is the file a harness will read, not what we intended to write.\n * A dry run wrote nothing, so it READS THE PACKAGED SOURCE — the file that would\n * land. Hardcoding `true` there was wrong for the one skill whose value can\n * legitimately be false: `assertSkillsSource` exempts the hosted mirror from the\n * invocability assertion, so a shadowed mirror ships and must report as shadowed on\n * both paths.\n */\nasync function landedInvocable(\n skillsDir: string,\n skillsSource: string,\n name: string,\n dryRun: boolean,\n): Promise<boolean> {\n // Guarded like every other read of this path. It is read back AFTER the write, so\n // an external writer can have swapped it for a pipe or a device in between, and a\n // raw read there would hang the command that just finished its work.\n const read = await readSkillFile(join(dryRun ? skillsSource : skillsDir, name, 'SKILL.md'));\n if (read.kind !== 'ok') return false;\n return !isModelInvocationDisabled(read.bytes.toString('utf8'));\n}\n\n/**\n * Every packaged skill landed in every target. Runs after ALL targets are written,\n * never mid-loop: a throw between two targets would leave target 1 rewritten and\n * target 2 untouched. (It still sits ahead of the doctor run, the publish-mode\n * question and the wallet step, so a throw here skips those either way.)\n *\n * Presence only. Whether a skill is model-invocable is a property of the PACKAGED\n * source, checked up front by `assertSkillsSource` before anything is written.\n */\nasync function assertSkillsLanded(plans: HarnessPlan[], dryRun: boolean): Promise<void> {\n if (dryRun) return;\n const missing: string[] = [];\n for (const plan of plans) {\n for (const name of SKILL_NAMES) {\n if (!existsSync(join(plan.skillsDir, name, 'SKILL.md'))) {\n missing.push(join(plan.skillsDir, name));\n }\n }\n }\n if (missing.length === 0) return;\n throw new CliError('INTERNAL', `Skills were not written: ${missing.join(', ')}`, {\n // Safe to point at permissions because nothing removes a landed file any more:\n // each shipped file arrives by its own atomic rename. When this was a\n // rm-then-write it also fired on a lost race, and sent people to chmod a\n // directory that was fine.\n fix: `Check that you can write to the skills directory (\\`ls -ld ${dirname(missing[0] ?? '')}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * Ensure the AGENTS.md pointer line is present exactly once. Append-once is GLOBAL\n * across both locations Codex/harnesses read (~/.agents/AGENTS.md and Codex's own\n * ~/.codex/AGENTS.md): if either already carries the marker we stop, so a pointer\n * already in ~/.codex/AGENTS.md is never duplicated into a later-created\n * ~/.agents/AGENTS.md. When neither has it, target selection follows what Codex\n * actually reads: prefer an existing ~/.agents/AGENTS.md, else an existing\n * ~/.codex/AGENTS.md, else create the one whose home dir exists, else fall back to\n * ~/.agents/AGENTS.md alongside the shared skills.\n */\nasync function wireAgentsMd(plan: HarnessPlan, dryRun: boolean): Promise<AgentsMdResult> {\n const shared = join(plan.home, '.agents', 'AGENTS.md');\n const codex = join(plan.home, '.codex', 'AGENTS.md');\n const line = nudgeLine(plan.skillsDir);\n\n // If either file Codex reads already carries the marker, that file owns the line:\n // refresh it in place when an older install's text drifted, else leave it. This\n // keeps append-once global while still upgrading a stale line. Probed LAZILY,\n // returning as soon as an owner is found: with the marker already in\n // ~/.agents/AGENTS.md (the steady state of a re-run), a broken ~/.codex/AGENTS.md\n // this run would never write must not fail the install. A probe can only fail the\n // run outright on an UNREADABLE candidate (see probeMarkerText for why); a\n // not-regular one fails only if it ends up the chosen path.\n const probes = new Map<string, MarkerProbe>();\n for (const path of [shared, codex]) {\n const probe = await probeMarkerText(path);\n probes.set(path, probe);\n if (probe.text?.includes(SKILLS_MARKER) === true) {\n return upsertAgentsMd(path, probe, line, dryRun);\n }\n }\n\n const chosen = chooseAgentsMdPath(plan.home);\n // Non-null: chooseAgentsMdPath only ever returns shared or codex, both probed.\n return upsertAgentsMd(chosen, probes.get(chosen)!, line, dryRun);\n}\n\nasync function upsertAgentsMd(\n path: string,\n probe: MarkerProbe,\n line: string,\n dryRun: boolean,\n): Promise<AgentsMdResult> {\n const { content, change } = upsertMarkerLine(probe.text, line);\n if (change === 'none') return { path, status: 'already-present' };\n const writeTo = await prepareMarkerWrite(path, probe);\n if (!dryRun && content !== null) await writeMarkerFile(path, writeTo, content);\n if (change === 'append') return { path, status: dryRun ? 'would-append' : 'appended' };\n return { path, status: dryRun ? 'would-update' : 'updated' };\n}\n\n/**\n * The write-side contract both nudge writers share, in ONE place so a refactor\n * cannot half-drop it: refuse a non-regular chosen path and resolve through a\n * link, BOTH unconditionally (dry runs included), so a dry run can never report\n * would-append where the real run refuses. Returns the resolved target for the\n * real write. Safe after the change-none early return: a not-regular probe has\n * null text, which can never produce `none`.\n */\nasync function prepareMarkerWrite(declared: string, probe: MarkerProbe): Promise<string> {\n assertRegularMarker(declared, probe);\n return resolveThroughLink(declared, 'the Tenjin pointer');\n}\n\n/**\n * The nudge files (AGENTS.md, CLAUDE.md) are the other two files install writes\n * into the operator's home, so the skill files' rules apply for the same reasons:\n * read through the guarded descriptor (a FIFO at the path must not hang install,\n * and an unreadable file is a typed error, not a raw errno), and write through a\n * symlink (committing with `rename` over a dotfiles-managed link would replace\n * the link with a regular file and strand its target).\n */\nasync function probeMarkerText(declared: string): Promise<MarkerProbe> {\n // `open` follows symlinks, so a dangling link reads as absent here; the\n // reachability check in the upserts fails it, on dry runs too, naming the link.\n const read = await readSkillFile(declared);\n if (read.kind === 'absent') return { text: null, notRegular: false };\n if (read.kind === 'ok') return { text: read.bytes.toString('utf8'), notRegular: false };\n // Not-regular is recorded, not thrown: a directory or FIFO cannot carry the\n // marker, so it only fails a path this run selects to write (assertRegularMarker,\n // in the upserts). Unreadable stays a hard failure even for a mere candidate: a\n // file we cannot read could own the marker (skipping it appends a duplicate into\n // the other file) or hold the operator's notes (writing over it clobbers them).\n if (read.kind === 'not-regular') return { text: null, notRegular: true };\n throw wrapWriteError(read.err, declared, 'the Tenjin pointer', declared, {\n verb: 'read',\n expected: ': the pointer lands in a regular markdown file',\n });\n}\n\ninterface MarkerProbe {\n text: string | null;\n notRegular: boolean;\n}\n\n/** The write-path half of {@link probeMarkerText}'s not-regular rule: fails the\n * path this run selects, dry runs included, so a dry run cannot promise a write\n * the real run refuses. */\nfunction assertRegularMarker(declared: string, probe: MarkerProbe): void {\n if (!probe.notRegular) return;\n throw new CliError(\n 'INTERNAL',\n `${declared} is not a regular file, so the Tenjin pointer was not written.`,\n {\n fix: `Check what is there (\\`ls -l ${declared}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/** See {@link probeMarkerText}; the write half of the same contract. `writeTo` is\n * the link-resolved target the caller obtained from `resolveThroughLink`. */\nasync function writeMarkerFile(declared: string, writeTo: string, content: string): Promise<void> {\n try {\n await writeFileAtomic(writeTo, content);\n } catch (err) {\n throw wrapWriteError(\n err,\n declared,\n 'the Tenjin pointer',\n await deepestExisting(dirname(writeTo)),\n { expected: ': the pointer lands in a regular markdown file' },\n );\n }\n}\n\nfunction chooseAgentsMdPath(home: string): string {\n const shared = join(home, '.agents', 'AGENTS.md');\n const codex = join(home, '.codex', 'AGENTS.md');\n if (existsSync(shared)) return shared;\n if (existsSync(codex)) return codex;\n if (existsSync(join(home, '.codex'))) return codex;\n return shared;\n}\n\n// --- Human rendering -------------------------------------------------------------\n\nfunction paint(io: Io, format: Parameters<typeof styleText>[0], text: string): string {\n if (io.stdout instanceof Stream) return styleText(format, text, { stream: io.stdout });\n return styleText(format, text);\n}\n\n// --- Skills source guard ---------------------------------------------------------\n\n/**\n * Guard the packaged source BEFORE any target is touched, so a bad package aborts\n * with nothing written rather than mid-copy.\n *\n * The model-invocable assertion covers only CLI_SKILL_NAMES. The hosted `tenjin`\n * mirror is written verbatim from tenjin.blog/skills.md by scripts/sync-skill.mjs\n * and its frontmatter is not authored here: if upstream ever adds\n * `disable-model-invocation: true` (a plausible way to say \"prefer the CLI\n * skills\"), asserting on it would hard-fail every install with a fix that cannot\n * work, and skill-drift.yml would stay green because the mirror still matches\n * upstream. Doctor warns about the mirror instead.\n */\nasync function assertSkillsSource(dir: string): Promise<void> {\n for (const name of SKILL_NAMES) {\n if (!existsSync(join(dir, name, 'SKILL.md'))) {\n throw new CliError('INTERNAL', `Packaged skill \"${name}\" is missing under ${dir}`, {\n fix: 'Reinstall tenjin-cli; the published package must ship every skill under skills/.',\n });\n }\n }\n for (const name of CLI_SKILL_NAMES) {\n const text = await readFile(join(dir, name, 'SKILL.md'), 'utf8');\n if (isModelInvocationDisabled(text)) {\n throw new CliError(\n 'INTERNAL',\n `Packaged skill \"${name}\" carries disable-model-invocation: true, so no harness would surface it`,\n {\n fix: 'Reinstall tenjin-cli; the published CLI skills must be model-invocable.',\n },\n );\n }\n }\n}\n","import { lstat, readFile, realpath } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * The one place the CLI WRITES a permission grant into a harness's own settings\n * file, so the invariants live here rather than at the call site:\n *\n * - CONSENT-GATED. Nothing in this module runs unless the operator said yes at\n * the install prompt or passed `--allow-free-verbs`. It is never reached by a\n * bare non-interactive run.\n * - FREE-TIER ONLY, AND NOT PARAMETERIZED. The rules are the hardcoded\n * {@link FREE_VERB_RULES} constant and the writer takes no rule argument, so\n * there is no call path — no flag, no config key, no future caller — that can\n * make it write `buy`, `publish`, `session start`, `send`, `config set`,\n * `wallet create`, `mcp`, `install`, or a broad `Bash(tenjin:*)`. A CLI that\n * could widen its own permission grant is exactly what this shape rules out.\n * - ADDITIVE ONLY. Existing entries and every other key in the file are copied\n * through verbatim, in their original order; missing rules are appended. A\n * re-run adds nothing and reports what was already present.\n * - NEVER CLOBBERS. A settings file we cannot parse, or whose `permissions` /\n * `permissions.allow` is not the shape we expect, is left untouched and\n * reported as skipped. We do not \"repair\" someone's hand-edited config.\n *\n * The rules mirror lib/permissions.ts's ALWAYS_SAFE_ALLOWLIST (the block\n * `doctor` prints and the README quotes) and are duplicated as literals on\n * purpose: that module is a DOCUMENT whose safe tier could grow, and a widened\n * tier must not silently widen what install writes. A test pins the two lists\n * equal, so drift is a red build rather than a broader grant.\n */\n\n/** Claude Code's user-level settings file, the only file this module writes. */\nexport function claudeSettingsPath(homeDir: string): string {\n return join(homeDir, '.claude', 'settings.json');\n}\n\n/**\n * The exact rules install may add. Free verbs only: none of them can spend USDC\n * or open the keystore. See lib/permissions.ts for the per-verb notes and for\n * the flag caveat that qualifies every prefix rule.\n */\nexport const FREE_VERB_RULES: readonly string[] = [\n 'Bash(tenjin search:*)',\n 'Bash(tenjin inspect:*)',\n 'Bash(tenjin read:*)',\n 'Bash(tenjin outcome:*)',\n 'Bash(tenjin doctor:*)',\n 'Bash(tenjin wallet show:*)',\n 'Bash(tenjin wallet balance:*)',\n 'Bash(tenjin config get:*)',\n 'Bash(tenjin candidate list:*)',\n];\n\n/**\n * Verb fragments that must never appear in {@link FREE_VERB_RULES}. Asserted by\n * a test rather than at runtime: the constant above is not reachable from any\n * input, so the only way one of these lands in it is an edit to this file, and a\n * test is what catches an edit.\n */\nexport const FORBIDDEN_VERB_FRAGMENTS: readonly string[] = [\n 'tenjin buy',\n 'tenjin publish',\n 'tenjin edit',\n 'tenjin session',\n 'tenjin send',\n 'tenjin config set',\n 'tenjin wallet create',\n 'tenjin mcp',\n 'tenjin install',\n 'tenjin candidate add',\n 'tenjin candidate drop',\n 'Bash(tenjin:*)',\n];\n\n/**\n * Why no rules were written. Every value is a reason to leave the file alone,\n * never a partial write: the writer either appends all missing rules or none.\n */\nexport type PermissionsSkipReason =\n | 'harness-not-claude'\n | 'not-requested'\n | 'declined'\n | 'dry-run'\n | 'unresolvable'\n | 'unreadable'\n | 'unparsable'\n | 'unexpected-shape'\n | 'changed-since-read';\n\nexport interface PermissionsResult {\n /** The harness this outcome is about; only `claude` has a settings file we write. */\n harness: string;\n /**\n * The settings file, reported even when nothing was written so a human can go\n * look. ABSENT when the harness has no such file: naming a Claude path on a\n * Codex-only install would point the envelope's reader at a file that has\n * nothing to do with their harness.\n */\n path?: string;\n added: string[];\n alreadyPresent: string[];\n skipped?: PermissionsSkipReason;\n /** Human-readable detail for a skip that is a problem rather than a choice. */\n warning?: string;\n}\n\nfunction skip(\n harness: string,\n path: string | undefined,\n reason: PermissionsSkipReason,\n warning?: string,\n): PermissionsResult {\n return {\n harness,\n ...(path !== undefined ? { path } : {}),\n added: [],\n alreadyPresent: [],\n skipped: reason,\n ...(warning !== undefined ? { warning } : {}),\n };\n}\n\n/** A decision NOT to write, shaped like a write outcome so the caller has one type. */\nexport function permissionsSkipped(\n harness: string,\n homeDir: string,\n reason: PermissionsSkipReason,\n): PermissionsResult {\n const path = harness === 'claude' ? claudeSettingsPath(homeDir) : undefined;\n return skip(harness, path, reason);\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 * Add the free-verb rules to `permissions.allow` in ~/.claude/settings.json.\n * Creates the file (and the `permissions.allow` path) when absent, appends only\n * the rules that are missing, and rewrites nothing else. Idempotent: a second\n * run returns `added: []` with every rule under `alreadyPresent` and does not\n * touch the file at all.\n */\nexport async function wireFreeVerbAllowlist(homeDir: string): Promise<PermissionsResult> {\n const found = await inspectAllowlist(homeDir);\n if ('result' in found) return found.result;\n const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;\n if (added.length === 0) return { harness: 'claude', path, added: [], alreadyPresent };\n\n // Object spreads keep the original key order and land the rebuilt `permissions`\n // in the slot it already occupied, so a diff of the file is the appended rules\n // and nothing else.\n const next = {\n ...settings,\n permissions: { ...permissions, allow: [...allow, ...added] },\n };\n // This is a whole-file read-modify-write, so a change landing between the read\n // and the rename would be erased in full, including keys that have nothing to do\n // with permissions. Claude Code writes this file too, so the other writer is not\n // hypothetical. Compare the bytes we based the edit on and refuse rather than\n // clobber; the operator re-runs and the merge is recomputed against what is\n // actually there.\n const current = await readFile(path, 'utf8').catch(() => null);\n if (current !== raw) {\n return skip(\n 'claude',\n path,\n 'changed-since-read',\n `${path} changed while it was being updated, so nothing was written. Re-run \\`tenjin install\\`.`,\n );\n }\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`);\n return { harness: 'claude', path, added, alreadyPresent };\n}\n\n/**\n * The probe the install walkthrough uses: what is still missing, plus the outcome\n * to report when nothing is. Returning the SNAPSHOT's own result matters. Calling\n * the writer again after a zero-pending probe re-reads the file, so a rule revoked\n * between the two reads was silently re-added with no prompt, which is the one\n * thing a consent gate must not do.\n *\n * `pending` is null when the file cannot be understood; that is \"unknown\", never\n * \"already allowed\", and the caller must still ask.\n */\nexport async function inspectFreeVerbRules(\n homeDir: string,\n): Promise<{ pending: string[] | null; satisfied?: PermissionsResult }> {\n const found = await inspectAllowlist(homeDir);\n if ('result' in found) return { pending: null };\n if (found.added.length > 0) return { pending: found.added };\n return {\n pending: [],\n satisfied: {\n harness: 'claude',\n path: found.path,\n added: [],\n alreadyPresent: found.alreadyPresent,\n },\n };\n}\n\ninterface AllowlistInspection {\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 permissions: Record<string, unknown>;\n allow: unknown[];\n added: string[];\n alreadyPresent: string[];\n}\n\n/**\n * Resolve and read the settings file, and work out which rules are missing.\n * Every refusal this module can reach is decided here, so the probe and the\n * write agree by construction about what is untouchable.\n */\nasync function inspectAllowlist(\n homeDir: string,\n): Promise<AllowlistInspection | { result: PermissionsResult }> {\n const declaredPath = claudeSettingsPath(homeDir);\n const refuse = (\n p: string,\n reason: PermissionsSkipReason,\n warning: string,\n ): { result: PermissionsResult } => ({ result: skip('claude', p, reason, warning) });\n\n // `lstat`, not `existsSync`: existsSync FOLLOWS a symlink, so a link pointing at\n // a file that is not there reads as \"absent\" and the create path below would\n // rename a regular file over the link. We need to know whether an ENTRY is\n // there, whatever it points at.\n const entry = await lstat(declaredPath).catch(() => null);\n\n // Resolve symlinks BEFORE writing. `writeFileAtomic` commits with a rename,\n // which replaces a symlink with a regular file: a settings.json linked into a\n // dotfiles repo would be severed, its target left stale, and future edits there\n // would stop reaching Claude Code. Renaming over the RESOLVED path edits the\n // file the operator actually maintains and leaves the link intact, which is\n // what this module's additive-only, never-clobber invariants promise. A link we\n // cannot resolve is left alone rather than overwritten; for a genuinely absent\n // file there is nothing to follow and we create it at the declared path.\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return refuse(\n declaredPath,\n 'unresolvable',\n `${declaredPath} could not be resolved (${(err as Error).message}); it was left exactly as it is.`,\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 refuse(\n path,\n 'unreadable',\n `${path} could not be read (${(err as Error).message}); no permissions were written.`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return refuse(\n path,\n 'unparsable',\n `${path} is not valid JSON (${(err as Error).message}); it was left exactly as it is.`,\n );\n }\n if (!isPlainObject(parsed)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} is not a JSON object; it was left exactly as it is.`,\n );\n }\n settings = parsed;\n }\n\n // `permissions` and `permissions.allow` may be absent (we create them), but a\n // present one of the wrong type is someone else's structure: refuse rather\n // than replace it. Unknown entry types inside `allow` are fine and ride\n // through verbatim; they simply never match a rule.\n const permissionsValue = settings.permissions;\n if (permissionsValue !== undefined && !isPlainObject(permissionsValue)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} has a \"permissions\" key that is not an object; it was left exactly as it is.`,\n );\n }\n const permissions: Record<string, unknown> = permissionsValue ?? {};\n const allowValue = permissions.allow;\n if (allowValue !== undefined && !Array.isArray(allowValue)) {\n return refuse(\n path,\n 'unexpected-shape',\n `${path} has a \"permissions.allow\" key that is not an array; it was left exactly as it is.`,\n );\n }\n const allow: unknown[] = allowValue ?? [];\n\n const present = new Set(allow.filter((e): e is string => typeof e === 'string'));\n const added = FREE_VERB_RULES.filter((rule) => !present.has(rule));\n const alreadyPresent = FREE_VERB_RULES.filter((rule) => present.has(rule));\n return { path, raw, settings, permissions, allow, added, alreadyPresent: [...alreadyPresent] };\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAAA,iBAAgB;AACzB,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY,QAAAC,aAAY;AAC1C,SAAS,eAAe;AAExB,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACPvB,SAAS,OAAO,UAAU,gBAAgB;AAC1C,SAAS,YAAY;AA+Bd,SAAS,mBAAmB,SAAyB;AAC1D,SAAO,KAAK,SAAS,WAAW,eAAe;AACjD;AAOO,IAAM,kBAAqC;AAAA,EAChD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAuDA,SAAS,KACP,SACA,MACA,QACA,SACmB;AACnB,SAAO;AAAA,IACL;AAAA,IACA,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC;AAAA,IACrC,OAAO,CAAC;AAAA,IACR,gBAAgB,CAAC;AAAA,IACjB,SAAS;AAAA,IACT,GAAI,YAAY,SAAY,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC7C;AACF;AAGO,SAAS,mBACd,SACA,SACA,QACmB;AACnB,QAAM,OAAO,YAAY,WAAW,mBAAmB,OAAO,IAAI;AAClE,SAAO,KAAK,SAAS,MAAM,MAAM;AACnC;AAEA,SAAS,cAAc,O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;AAAA,MACtC,EAAE,UAAU,iDAAiD;AAAA,IAC/D;AAAA,EACF;AACF;AAEA,SAAS,mBAAmB,MAAsB;AAChD,QAAM,SAASA,MAAK,MAAM,WAAW,WAAW;AAChD,QAAM,QAAQA,MAAK,MAAM,UAAU,WAAW;AAC9C,MAAI,WAAW,MAAM,EAAG,QAAO;AAC/B,MAAI,WAAW,KAAK,EAAG,QAAO;AAC9B,MAAI,WAAWA,MAAK,MAAM,QAAQ,CAAC,EAAG,QAAO;AAC7C,SAAO;AACT;AAIA,SAAS,MAAM,IAAQ,QAAyC,MAAsB;AACpF,MAAI,GAAG,kBAAkB,OAAQ,QAAO,UAAU,QAAQ,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC;AACrF,SAAO,UAAU,QAAQ,IAAI;AAC/B;AAgBA,eAAe,mBAAmB,KAA4B;AAC5D,aAAW,QAAQ,aAAa;AAC9B,QAAI,CAAC,WAAWA,MAAK,KAAK,MAAM,UAAU,CAAC,GAAG;AAC5C,YAAM,IAAI,SAAS,YAAY,mBAAmB,IAAI,sBAAsB,GAAG,IAAI;AAAA,QACjF,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACA,aAAW,QAAQ,iBAAiB;AAClC,UAAM,OAAO,MAAMC,UAASD,MAAK,KAAK,MAAM,UAAU,GAAG,MAAM;AAC/D,QAAI,0BAA0B,IAAI,GAAG;AACnC,YAAM,IAAI;AAAA,QACR;AAAA,QACA,mBAAmB,IAAI;AAAA,QACvB;AAAA,UACE,KAAK;AAAA,QACP;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["readFile","join","plans","join","readFile"]}
@@ -0,0 +1,23 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ runOutcome
4
+ } from "./chunk-ATSCQETF.js";
5
+ import "./chunk-JURZ2T2I.js";
6
+ import "./chunk-MHRREGGN.js";
7
+ import "./chunk-WWX32ML4.js";
8
+ import "./chunk-V7BWPOKT.js";
9
+ import "./chunk-6L34JW52.js";
10
+ import "./chunk-PZSUWDF2.js";
11
+ import "./chunk-CTFFFQFH.js";
12
+ import "./chunk-TYVLXAB5.js";
13
+ import "./chunk-UO22YNY4.js";
14
+ import "./chunk-KRHUDEIQ.js";
15
+ import "./chunk-OQXHNWM3.js";
16
+ import "./chunk-P74I3WH4.js";
17
+ import "./chunk-2I4QTOLB.js";
18
+ import "./chunk-PZRAAAY2.js";
19
+ import "./chunk-ZXTAQYNA.js";
20
+ export {
21
+ runOutcome
22
+ };
23
+ //# sourceMappingURL=outcome-F5KN3K3Y.js.map
@@ -1,31 +1,33 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  runPublish
4
- } from "./chunk-C3S6725N.js";
4
+ } from "./chunk-7MJCZ2OX.js";
5
+ import "./chunk-3MQSXDWS.js";
6
+ import "./chunk-AX5WQ3H5.js";
5
7
  import "./chunk-SGK2B724.js";
6
- import "./chunk-NVHQCTIC.js";
7
- import "./chunk-QB2NNV6C.js";
8
- import "./chunk-PCLPVJ3J.js";
8
+ import "./chunk-7WDY4AXV.js";
9
+ import "./chunk-KZAAWQNP.js";
9
10
  import "./chunk-S5RYMCV6.js";
10
11
  import "./chunk-POJRB2AE.js";
11
12
  import "./chunk-YLYINX2H.js";
12
- import "./chunk-GABYDXWL.js";
13
- import "./chunk-RGFBBNGP.js";
14
- import "./chunk-WRWCDLVK.js";
15
- import "./chunk-VZ3AJCO5.js";
16
- import "./chunk-P3FBESBB.js";
13
+ import "./chunk-FFTWWJRW.js";
14
+ import "./chunk-I4WQXOEL.js";
15
+ import "./chunk-BFAFOBO3.js";
16
+ import "./chunk-75G4REUY.js";
17
+ import "./chunk-MHRREGGN.js";
17
18
  import "./chunk-WWX32ML4.js";
18
- import "./chunk-URSGGRO4.js";
19
- import "./chunk-DQDGBWWH.js";
20
- import "./chunk-XBJ3VLWX.js";
21
- import "./chunk-2I4QTOLB.js";
22
- import "./chunk-BBUYCDSG.js";
23
- import "./chunk-KZAAWQNP.js";
24
- import "./chunk-DAJ56EUU.js";
25
- import "./chunk-YBMMV4Y4.js";
19
+ import "./chunk-V7BWPOKT.js";
20
+ import "./chunk-6L34JW52.js";
21
+ import "./chunk-PZSUWDF2.js";
22
+ import "./chunk-R2VLGNFD.js";
23
+ import "./chunk-CTFFFQFH.js";
24
+ import "./chunk-TYVLXAB5.js";
26
25
  import "./chunk-UO22YNY4.js";
27
- import "./chunk-UYP7G3GZ.js";
28
- import "./chunk-J6CVKC4M.js";
26
+ import "./chunk-KRHUDEIQ.js";
27
+ import "./chunk-OQXHNWM3.js";
28
+ import "./chunk-P74I3WH4.js";
29
+ import "./chunk-2I4QTOLB.js";
30
+ import "./chunk-PZRAAAY2.js";
29
31
  import "./chunk-M2O56UK7.js";
30
32
  import "./chunk-UHTVXQ2O.js";
31
33
  import "./chunk-W6R3HAAG.js";
@@ -37,4 +39,4 @@ import "./chunk-ZXTAQYNA.js";
37
39
  export {
38
40
  runPublish
39
41
  };
40
- //# sourceMappingURL=publish-5NTCRF2V.js.map
42
+ //# sourceMappingURL=publish-F5G5WIFI.js.map
@@ -3,12 +3,13 @@ import {
3
3
  deliverExisting,
4
4
  deliverFresh,
5
5
  parseSectionsBudget
6
- } from "./chunk-L6AV2Q73.js";
6
+ } from "./chunk-VE5BALOI.js";
7
7
  import {
8
8
  fetchRead
9
- } from "./chunk-ZA3RFDAV.js";
9
+ } from "./chunk-S4IKXAUA.js";
10
10
  import "./chunk-SGK2B724.js";
11
- import "./chunk-PCLPVJ3J.js";
11
+ import "./chunk-7WDY4AXV.js";
12
+ import "./chunk-KZAAWQNP.js";
12
13
  import "./chunk-S5RYMCV6.js";
13
14
  import "./chunk-POJRB2AE.js";
14
15
  import "./chunk-YLYINX2H.js";
@@ -16,37 +17,38 @@ import {
16
17
  isSessionPresentable,
17
18
  loadSessionFile,
18
19
  signWithSession
19
- } from "./chunk-GABYDXWL.js";
20
+ } from "./chunk-FFTWWJRW.js";
20
21
  import {
21
22
  findDelivered,
22
23
  findDeliveredByUrl,
23
24
  resolveResourceRef
24
- } from "./chunk-CYRYVZPN.js";
25
- import "./chunk-OTDI5FXG.js";
26
- import "./chunk-P3FBESBB.js";
25
+ } from "./chunk-GJKDWZ6X.js";
26
+ import "./chunk-JURZ2T2I.js";
27
+ import "./chunk-MHRREGGN.js";
27
28
  import "./chunk-WWX32ML4.js";
28
- import "./chunk-URSGGRO4.js";
29
- import "./chunk-DQDGBWWH.js";
29
+ import "./chunk-V7BWPOKT.js";
30
+ import "./chunk-6L34JW52.js";
30
31
  import {
31
32
  originOf
32
- } from "./chunk-XBJ3VLWX.js";
33
- import "./chunk-2I4QTOLB.js";
33
+ } from "./chunk-PZSUWDF2.js";
34
34
  import {
35
35
  sanitizeForTerminal
36
- } from "./chunk-BBUYCDSG.js";
37
- import "./chunk-KZAAWQNP.js";
36
+ } from "./chunk-R2VLGNFD.js";
38
37
  import {
39
38
  resolveContextSettings
40
- } from "./chunk-DAJ56EUU.js";
41
- import "./chunk-YBMMV4Y4.js";
39
+ } from "./chunk-CTFFFQFH.js";
40
+ import "./chunk-TYVLXAB5.js";
42
41
  import "./chunk-UO22YNY4.js";
43
42
  import {
44
43
  formatUsdDisplay,
45
44
  toMoney
46
- } from "./chunk-UYP7G3GZ.js";
45
+ } from "./chunk-KRHUDEIQ.js";
46
+ import "./chunk-OQXHNWM3.js";
47
+ import "./chunk-P74I3WH4.js";
48
+ import "./chunk-2I4QTOLB.js";
47
49
  import {
48
50
  CliError
49
- } from "./chunk-J6CVKC4M.js";
51
+ } from "./chunk-PZRAAAY2.js";
50
52
  import "./chunk-UHTVXQ2O.js";
51
53
  import "./chunk-W6R3HAAG.js";
52
54
  import "./chunk-XJN5WUKL.js";
@@ -155,4 +157,4 @@ function refusal(ref, requirement, check) {
155
157
  export {
156
158
  runRead
157
159
  };
158
- //# sourceMappingURL=read-T6OTMU72.js.map
160
+ //# sourceMappingURL=read-II2ZO4II.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/read.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, toMoney } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { resolveResourceRef } from '../lib/resource-ref';\nimport { fetchRead } from '../lib/read-client';\nimport type { ReadBody, SessionReadResult } from '../lib/read-client';\nimport { findDelivered, findDeliveredByUrl } from '../lib/library';\nimport {\n deliverExisting,\n deliverFresh,\n parseSectionsBudget,\n type PresentOpts,\n} from '../lib/delivery';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { isSessionPresentable, loadSessionFile, signWithSession } from '../lib/session-present';\nimport type { SessionFile } from '../lib/session-present';\nimport { originOf } from '../lib/url';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin read <resource-url-or-id>`, the FREE-ONLY delivery verb (#42).\n *\n * `buy` was the only verb that delivered a body, so a zero-cost re-read of\n * something you already own was indistinguishable — to a prefix-matching harness\n * permission classifier, and to a human reading a transcript — from a purchase.\n * `read` is the half of `buy` that never spends:\n * 1. local library (already delivered → re-deliver from disk, no network)\n * 2. first GET, unauthenticated → a FREE resource delivers immediately\n * 3. a PAID resource, with a read-scoped session key on disk for THIS origin →\n * present it on ONE bodyless signed GET; a 200 means this wallet owns the\n * piece and it delivers, free\n * 4. anything else → REFUSED (exit 3), naming the price, and pointing at\n * `tenjin buy` only when the server actually answered \"you do not own this\".\n * Nothing is charged, and the refusal lands before any payment could be\n * constructed, because none can be.\n *\n * The hard invariant, test-pinned rather than merely intended (read.test.ts): this\n * module and its whole transitive import graph never reach `lib/x402-pay`,\n * `lib/wallet`, or `lib/session-key`. Step 3 uses the present-only half, so read\n * can load a delegation and sign with it but cannot mint one and cannot pay.\n * Those two are the whole of what the pin guarantees; what a minted delegation is\n * worth to a holder is answered in `lib/permissions.ts`.\n *\n * Step 3 therefore presents ONLY to the origin the session was minted against.\n * `--base-url` rides this verb like every other and `read` is always-safe, so\n * without that check one auto-allowed command line would hand a wallet-derived\n * credential to a host an agent picked.\n */\n\nexport interface ReadArgs {\n ref: string;\n /** Include the full body in the machine output (default: outline only). */\n printBody?: boolean;\n /** Include leading sections within this token budget (deterministic split). */\n sections?: string;\n}\n\nexport interface ReadDeps {\n /** No `provider`/`authorizer` seam, unlike BuyDeps: there is no wallet to inject. */\n fetchImpl?: typeof fetch;\n /** Clock seam (ms since epoch) for the session-expiry decision. */\n now?: () => number;\n}\n\nexport async function runRead(\n args: ReadArgs,\n ctx: CommandContext,\n deps: ReadDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const sectionsBudget = parseSectionsBudget(args.sections);\n const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);\n const presentOpts: PresentOpts = { printBody: args.printBody === true, sectionsBudget };\n\n // 1. Library idempotence, BEFORE any network: an owned resource re-delivers\n // from disk. This is the case #42 exists for — the re-read that used to need\n // a `buy` approval. Matched by id or by url, exactly as buy matches it.\n const existing =\n ref.resourceId !== undefined\n ? await findDelivered(ctx.dataDir, ref.resourceId)\n : await findDeliveredByUrl(ctx.dataDir, ref.url);\n if (existing !== null) {\n return deliverExisting(existing, presentOpts);\n }\n\n const fetchOpts = {\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n // 2. First GET, unauthenticated — the same probe buy opens with, and like buy's\n // probe it is unattributed (no search id rides a non-purchase).\n const first = await fetchRead(ref.url, fetchOpts);\n\n if (first.kind === 'entitled') {\n // Free resource (no payment challenge was issued): deliver and save. No wallet\n // was resolved to get here.\n return await deliverFresh(ctx.dataDir, ref.url, first.body, 'free', undefined, presentOpts);\n }\n\n if (first.kind === 'already_purchased') {\n // A plain GET carries no payment header, so the read route cannot answer the\n // owned-re-pay 409 here; the contract makes this unreachable. Same loud failure\n // buy raises rather than guessing a recovery chain.\n throw new CliError('API_UNREACHABLE', 'Unexpected 409 on an unauthenticated read.', {\n fix: 'Retry; if it persists, update tenjin-cli.',\n });\n }\n\n // A paid resource. Capture the advertised price: it is what the refusal reports.\n const firstRequirement = first.paymentRequired.accepts[0];\n if (firstRequirement === undefined) {\n throw new CliError('PAYMENT_FAILED', 'The 402 advertised no payment requirements.', {\n fix: 'Try another candidate; this resource looks misconfigured.',\n });\n }\n\n // 3. Paid and not on disk. A live session key minted for THIS origin means the\n // wallet may already own the piece. Exactly one attempt: re-establishing\n // would need the wallet this module cannot reach.\n const cached = await loadSessionFile(ctx.dataDir);\n const now = deps.now ?? Date.now;\n // Against the origin of the URL actually being signed, not the configured base\n // URL. They are equal only because `resolveResourceRef` asserted it in another\n // module; checking the request target makes this guard locally sound instead of\n // dependent on a pin someone could move.\n const origin = originOf(ref.url);\n const outcome = await presentIfUsable(cached, origin, now, ref.url, fetchOpts);\n if (outcome.kind === 'entitled') {\n return await deliverFresh(\n ctx.dataDir,\n ref.url,\n outcome.body,\n 'entitled',\n undefined,\n presentOpts,\n );\n }\n\n // 4. Not entitled, not asked, or not answered: refuse (exit 3) on the advertised\n // price. No payment is constructed; none can be.\n throw refusal(ref, firstRequirement, outcome.check);\n}\n\n/** What the entitlement question got, which is not the same as what was asked. */\ntype EntitlementCheck =\n | 'not_performed'\n | 'session'\n | 'session_rejected'\n | 'session_inconclusive'\n | 'session_origin_mismatch';\n\ntype PresentOutcome =\n { kind: 'entitled'; body: ReadBody } | { kind: 'refuse'; check: EntitlementCheck };\n\n/** Failures that must NOT be folded into a price refusal; see `present`. */\nconst LOUD_CODES = new Set(['CONTRACT_MISMATCH', 'RATE_LIMITED']);\n\n/**\n * Decide whether the cached session may be presented, and present it if so.\n *\n * The origin mismatch is its own outcome rather than \"no session\": the two are\n * indistinguishable to an agent, and the remedy for one is the remedy the other\n * must NOT get. `not_performed` tells the agent to run `session start`, which is\n * the single verb that opens the keystore — and an agent that reached a mismatch\n * by carrying `--base-url` would carry it straight into that suggestion, minting\n * a wallet-signed delegation against the wrong host and clobbering the good one.\n */\nasync function presentIfUsable(\n cached: SessionFile | null,\n origin: string,\n now: () => number,\n url: string,\n fetchOpts: { timeoutMs: number; fetchImpl?: typeof fetch },\n): Promise<PresentOutcome> {\n if (cached === null) return { kind: 'refuse', check: 'not_performed' };\n if (cached.origin !== origin) {\n return { kind: 'refuse', check: 'session_origin_mismatch' };\n }\n if (!isSessionPresentable(cached, now(), 'read', origin)) {\n return { kind: 'refuse', check: 'not_performed' };\n }\n return await present(cached, url, fetchOpts, now);\n}\n\n/**\n * The one signed GET. Never throws for a transport failure: the first 402 already\n * told us the price, and losing it turns a recoverable refusal into a bare\n * network error that says nothing about the piece. Two exceptions stay loud: a\n * blocked redirect (a signal about where a credential was nearly sent) and a\n * rate limit (a recoverable pause the CLI models explicitly everywhere else —\n * swallowing it costs a looping agent its backoff and points it at a\n * keystore-opening command instead).\n */\nasync function present(\n session: SessionFile,\n url: string,\n fetchOpts: { timeoutMs: number; fetchImpl?: typeof fetch },\n now: () => number,\n): Promise<PresentOutcome> {\n let second: SessionReadResult;\n try {\n const sessionHeaders = await signWithSession(session, { method: 'GET', url }, { now });\n second = await fetchRead(url, { ...fetchOpts, sessionHeaders });\n } catch (err) {\n if (err instanceof CliError && LOUD_CODES.has(err.code)) throw err;\n return { kind: 'refuse', check: 'session_inconclusive' };\n }\n switch (second.kind) {\n case 'entitled':\n return { kind: 'entitled', body: second.body };\n case 'payment_required':\n // The only state where the server actually answered the ownership question.\n return { kind: 'refuse', check: 'session' };\n case 'session_rejected':\n // The delegation was declined (expired, revoked, origin drift, rotated\n // wallet). The entitlement question was never asked, so \"you must buy\" is\n // not the answer — re-minting is.\n return { kind: 'refuse', check: 'session_rejected' };\n case 'already_purchased':\n // A 409 on a request carrying no payment is contract-anomalous: the server\n // said \"already purchased\" and delivered nothing. Handled by name rather\n // than swept into a default, because the one thing this must never become\n // is a price refusal telling the agent to buy what it was just told it owns.\n return { kind: 'refuse', check: 'session_inconclusive' };\n }\n}\n\n/**\n * The exit-3 refusal: the price, in human money, plus the move that actually gets\n * past it. `entitlementCheck` reports what the server said, and the fix follows\n * from it rather than from a single default:\n *\n * - `session` — the server answered \"you do not own this\". Buying is the answer.\n * - `session_origin_mismatch` — a session exists, for a DIFFERENT origin. The\n * remedy is to stop redirecting the CLI, never to mint. `sessionCommand` is\n * deliberately absent: recommending it here would send an agent that still\n * carries `--base-url` to wallet-sign a delegation against the wrong host and\n * overwrite the good one.\n * - everything else — the question is still open, so re-minting may deliver it\n * free and `sessionCommand` rides.\n */\nfunction refusal(\n ref: { url: string; resourceId?: string },\n requirement: { amount: string; network: string },\n check: EntitlementCheck,\n): CliError {\n const price = toMoney(requirement.amount);\n // formatUsdDisplay (not the machine `usd`) because this string is human copy:\n // a price a person reads renders as 0.10, never 0.1.\n const priceText = `${formatUsdDisplay(price.atomic)} USD (${price.atomic} atomic)`;\n const url = sanitizeForTerminal(ref.url);\n const buyFix = `Run \\`tenjin buy ${url}\\` to pay and read it, or \\`tenjin inspect\\` for the card first.`;\n const mismatch = check === 'session_origin_mismatch';\n const mintable = check !== 'session' && !mismatch;\n const fix = mismatch\n ? `Your session key was minted for a different Tenjin deployment, so it was not presented. Read from the origin it belongs to, rather than minting a new session against this one. Check the configured origin with \\`tenjin config get baseUrl\\` and drop any host override. ${buyFix}`\n : mintable\n ? `${buyFix} If you already bought it, \\`tenjin session start --scope read\\` lets this read recover it free.`\n : buyFix;\n return new CliError('REFUSED', `This piece costs ${priceText}; \\`tenjin read\\` never pays.`, {\n fix,\n details: {\n reason: 'payment_required',\n entitlementCheck: check,\n url: ref.url,\n ...(ref.resourceId !== undefined ? { resourceId: ref.resourceId } : {}),\n price,\n network: requirement.network,\n buyCommand: `tenjin buy ${ref.url}`,\n ...(mintable ? { sessionCommand: 'tenjin session start --scope read' } : {}),\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA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,UAAU,OAAO,uBAAuB;AAAA,EAC3D;AACF;AAgBA,SAAS,QACP,KACA,aACA,OACU;AACV,QAAM,QAAQ,QAAQ,YAAY,MAAM;AAGxC,QAAM,YAAY,GAAG,iBAAiB,MAAM,MAAM,CAAC,SAAS,MAAM,MAAM;AACxE,QAAM,MAAM,oBAAoB,IAAI,GAAG;AACvC,QAAM,SAAS,oBAAoB,GAAG;AACtC,QAAM,WAAW,UAAU;AAC3B,QAAM,WAAW,UAAU,aAAa,CAAC;AACzC,QAAM,MAAM,WACR,8QAA8Q,MAAM,KACpR,WACE,GAAG,MAAM,qGACT;AACN,SAAO,IAAI,SAAS,WAAW,oBAAoB,SAAS,iCAAiC;AAAA,IAC3F;AAAA,IACA,SAAS;AAAA,MACP,QAAQ;AAAA,MACR,kBAAkB;AAAA,MAClB,KAAK,IAAI;AAAA,MACT,GAAI,IAAI,eAAe,SAAY,EAAE,YAAY,IAAI,WAAW,IAAI,CAAC;AAAA,MACrE;AAAA,MACA,SAAS,YAAY;AAAA,MACrB,YAAY,cAAc,IAAI,GAAG;AAAA,MACjC,GAAI,WAAW,EAAE,gBAAgB,oCAAoC,IAAI,CAAC;AAAA,IAC5E;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/commands/read.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, toMoney } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { resolveResourceRef } from '../lib/resource-ref';\nimport { fetchRead } from '../lib/read-client';\nimport type { ReadBody, SessionReadResult } from '../lib/read-client';\nimport { findDelivered, findDeliveredByUrl } from '../lib/library';\nimport {\n deliverExisting,\n deliverFresh,\n parseSectionsBudget,\n type PresentOpts,\n} from '../lib/delivery';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { isSessionPresentable, loadSessionFile, signWithSession } from '../lib/session-present';\nimport type { SessionFile } from '../lib/session-present';\nimport { originOf } from '../lib/url';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin read <resource-url-or-id>`, the FREE-ONLY delivery verb (#42).\n *\n * `buy` was the only verb that delivered a body, so a zero-cost re-read of\n * something you already own was indistinguishable — to a prefix-matching harness\n * permission classifier, and to a human reading a transcript — from a purchase.\n * `read` is the half of `buy` that never spends:\n * 1. local library (already delivered → re-deliver from disk, no network)\n * 2. first GET, unauthenticated → a FREE resource delivers immediately\n * 3. a PAID resource, with a read-scoped session key on disk for THIS origin →\n * present it on ONE bodyless signed GET; a 200 means this wallet owns the\n * piece and it delivers, free\n * 4. anything else → REFUSED (exit 3), naming the price, and pointing at\n * `tenjin buy` only when the server actually answered \"you do not own this\".\n * Nothing is charged, and the refusal lands before any payment could be\n * constructed, because none can be.\n *\n * The hard invariant, test-pinned rather than merely intended (read.test.ts): this\n * module and its whole transitive import graph never reach `lib/x402-pay`,\n * `lib/wallet`, or `lib/session-key`. Step 3 uses the present-only half, so read\n * can load a delegation and sign with it but cannot mint one and cannot pay.\n * Those two are the whole of what the pin guarantees; what a minted delegation is\n * worth to a holder is answered in `lib/permissions.ts`.\n *\n * Step 3 therefore presents ONLY to the origin the session was minted against.\n * `--base-url` rides this verb like every other and `read` is always-safe, so\n * without that check one auto-allowed command line would hand a wallet-derived\n * credential to a host an agent picked.\n */\n\nexport interface ReadArgs {\n ref: string;\n /** Include the full body in the machine output (default: outline only). */\n printBody?: boolean;\n /** Include leading sections within this token budget (deterministic split). */\n sections?: string;\n}\n\nexport interface ReadDeps {\n /** No `provider`/`authorizer` seam, unlike BuyDeps: there is no wallet to inject. */\n fetchImpl?: typeof fetch;\n /** Clock seam (ms since epoch) for the session-expiry decision. */\n now?: () => number;\n}\n\nexport async function runRead(\n args: ReadArgs,\n ctx: CommandContext,\n deps: ReadDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const sectionsBudget = parseSectionsBudget(args.sections);\n const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);\n const presentOpts: PresentOpts = { printBody: args.printBody === true, sectionsBudget };\n\n // 1. Library idempotence, BEFORE any network: an owned resource re-delivers\n // from disk. This is the case #42 exists for — the re-read that used to need\n // a `buy` approval. Matched by id or by url, exactly as buy matches it.\n const existing =\n ref.resourceId !== undefined\n ? await findDelivered(ctx.dataDir, ref.resourceId)\n : await findDeliveredByUrl(ctx.dataDir, ref.url);\n if (existing !== null) {\n return deliverExisting(existing, presentOpts);\n }\n\n const fetchOpts = {\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n // 2. First GET, unauthenticated — the same probe buy opens with, and like buy's\n // probe it is unattributed (no search id rides a non-purchase).\n const first = await fetchRead(ref.url, fetchOpts);\n\n if (first.kind === 'entitled') {\n // Free resource (no payment challenge was issued): deliver and save. No wallet\n // was resolved to get here.\n return await deliverFresh(ctx.dataDir, ref.url, first.body, 'free', undefined, presentOpts);\n }\n\n if (first.kind === 'already_purchased') {\n // A plain GET carries no payment header, so the read route cannot answer the\n // owned-re-pay 409 here; the contract makes this unreachable. Same loud failure\n // buy raises rather than guessing a recovery chain.\n throw new CliError('API_UNREACHABLE', 'Unexpected 409 on an unauthenticated read.', {\n fix: 'Retry; if it persists, update tenjin-cli.',\n });\n }\n\n // A paid resource. Capture the advertised price: it is what the refusal reports.\n const firstRequirement = first.paymentRequired.accepts[0];\n if (firstRequirement === undefined) {\n throw new CliError('PAYMENT_FAILED', 'The 402 advertised no payment requirements.', {\n fix: 'Try another candidate; this resource looks misconfigured.',\n });\n }\n\n // 3. Paid and not on disk. A live session key minted for THIS origin means the\n // wallet may already own the piece. Exactly one attempt: re-establishing\n // would need the wallet this module cannot reach.\n const cached = await loadSessionFile(ctx.dataDir);\n const now = deps.now ?? Date.now;\n // Against the origin of the URL actually being signed, not the configured base\n // URL. They are equal only because `resolveResourceRef` asserted it in another\n // module; checking the request target makes this guard locally sound instead of\n // dependent on a pin someone could move.\n const origin = originOf(ref.url);\n const outcome = await presentIfUsable(cached, origin, now, ref.url, fetchOpts);\n if (outcome.kind === 'entitled') {\n return await deliverFresh(\n ctx.dataDir,\n ref.url,\n outcome.body,\n 'entitled',\n undefined,\n presentOpts,\n );\n }\n\n // 4. Not entitled, not asked, or not answered: refuse (exit 3) on the advertised\n // price. No payment is constructed; none can be.\n throw refusal(ref, firstRequirement, outcome.check);\n}\n\n/** What the entitlement question got, which is not the same as what was asked. */\ntype EntitlementCheck =\n | 'not_performed'\n | 'session'\n | 'session_rejected'\n | 'session_inconclusive'\n | 'session_origin_mismatch';\n\ntype PresentOutcome =\n { kind: 'entitled'; body: ReadBody } | { kind: 'refuse'; check: EntitlementCheck };\n\n/** Failures that must NOT be folded into a price refusal; see `present`. */\nconst LOUD_CODES = new Set(['CONTRACT_MISMATCH', 'RATE_LIMITED']);\n\n/**\n * Decide whether the cached session may be presented, and present it if so.\n *\n * The origin mismatch is its own outcome rather than \"no session\": the two are\n * indistinguishable to an agent, and the remedy for one is the remedy the other\n * must NOT get. `not_performed` tells the agent to run `session start`, which is\n * the single verb that opens the keystore — and an agent that reached a mismatch\n * by carrying `--base-url` would carry it straight into that suggestion, minting\n * a wallet-signed delegation against the wrong host and clobbering the good one.\n */\nasync function presentIfUsable(\n cached: SessionFile | null,\n origin: string,\n now: () => number,\n url: string,\n fetchOpts: { timeoutMs: number; fetchImpl?: typeof fetch },\n): Promise<PresentOutcome> {\n if (cached === null) return { kind: 'refuse', check: 'not_performed' };\n if (cached.origin !== origin) {\n return { kind: 'refuse', check: 'session_origin_mismatch' };\n }\n if (!isSessionPresentable(cached, now(), 'read', origin)) {\n return { kind: 'refuse', check: 'not_performed' };\n }\n return await present(cached, url, fetchOpts, now);\n}\n\n/**\n * The one signed GET. Never throws for a transport failure: the first 402 already\n * told us the price, and losing it turns a recoverable refusal into a bare\n * network error that says nothing about the piece. Two exceptions stay loud: a\n * blocked redirect (a signal about where a credential was nearly sent) and a\n * rate limit (a recoverable pause the CLI models explicitly everywhere else —\n * swallowing it costs a looping agent its backoff and points it at a\n * keystore-opening command instead).\n */\nasync function present(\n session: SessionFile,\n url: string,\n fetchOpts: { timeoutMs: number; fetchImpl?: typeof fetch },\n now: () => number,\n): Promise<PresentOutcome> {\n let second: SessionReadResult;\n try {\n const sessionHeaders = await signWithSession(session, { method: 'GET', url }, { now });\n second = await fetchRead(url, { ...fetchOpts, sessionHeaders });\n } catch (err) {\n if (err instanceof CliError && LOUD_CODES.has(err.code)) throw err;\n return { kind: 'refuse', check: 'session_inconclusive' };\n }\n switch (second.kind) {\n case 'entitled':\n return { kind: 'entitled', body: second.body };\n case 'payment_required':\n // The only state where the server actually answered the ownership question.\n return { kind: 'refuse', check: 'session' };\n case 'session_rejected':\n // The delegation was declined (expired, revoked, origin drift, rotated\n // wallet). The entitlement question was never asked, so \"you must buy\" is\n // not the answer — re-minting is.\n return { kind: 'refuse', check: 'session_rejected' };\n case 'already_purchased':\n // A 409 on a request carrying no payment is contract-anomalous: the server\n // said \"already purchased\" and delivered nothing. Handled by name rather\n // than swept into a default, because the one thing this must never become\n // is a price refusal telling the agent to buy what it was just told it owns.\n return { kind: 'refuse', check: 'session_inconclusive' };\n }\n}\n\n/**\n * The exit-3 refusal: the price, in human money, plus the move that actually gets\n * past it. `entitlementCheck` reports what the server said, and the fix follows\n * from it rather than from a single default:\n *\n * - `session` — the server answered \"you do not own this\". Buying is the answer.\n * - `session_origin_mismatch` — a session exists, for a DIFFERENT origin. The\n * remedy is to stop redirecting the CLI, never to mint. `sessionCommand` is\n * deliberately absent: recommending it here would send an agent that still\n * carries `--base-url` to wallet-sign a delegation against the wrong host and\n * overwrite the good one.\n * - everything else — the question is still open, so re-minting may deliver it\n * free and `sessionCommand` rides.\n */\nfunction refusal(\n ref: { url: string; resourceId?: string },\n requirement: { amount: string; network: string },\n check: EntitlementCheck,\n): CliError {\n const price = toMoney(requirement.amount);\n // formatUsdDisplay (not the machine `usd`) because this string is human copy:\n // a price a person reads renders as 0.10, never 0.1.\n const priceText = `${formatUsdDisplay(price.atomic)} USD (${price.atomic} atomic)`;\n const url = sanitizeForTerminal(ref.url);\n const buyFix = `Run \\`tenjin buy ${url}\\` to pay and read it, or \\`tenjin inspect\\` for the card first.`;\n const mismatch = check === 'session_origin_mismatch';\n const mintable = check !== 'session' && !mismatch;\n const fix = mismatch\n ? `Your session key was minted for a different Tenjin deployment, so it was not presented. Read from the origin it belongs to, rather than minting a new session against this one. Check the configured origin with \\`tenjin config get baseUrl\\` and drop any host override. ${buyFix}`\n : mintable\n ? `${buyFix} If you already bought it, \\`tenjin session start --scope read\\` lets this read recover it free.`\n : buyFix;\n return new CliError('REFUSED', `This piece costs ${priceText}; \\`tenjin read\\` never pays.`, {\n fix,\n details: {\n reason: 'payment_required',\n entitlementCheck: check,\n url: ref.url,\n ...(ref.resourceId !== undefined ? { resourceId: ref.resourceId } : {}),\n price,\n network: requirement.network,\n buyCommand: `tenjin buy ${ref.url}`,\n ...(mintable ? { sessionCommand: 'tenjin session start --scope read' } : {}),\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,eAAsB,QACpB,MACA,KACA,OAAiB,CAAC,GACM;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,iBAAiB,oBAAoB,KAAK,QAAQ;AACxD,QAAM,MAAM,MAAM,mBAAmB,KAAK,KAAK,IAAI,SAAS,SAAS,OAAO;AAC5E,QAAM,cAA2B,EAAE,WAAW,KAAK,cAAc,MAAM,eAAe;AAKtF,QAAM,WACJ,IAAI,eAAe,SACf,MAAM,cAAc,IAAI,SAAS,IAAI,UAAU,IAC/C,MAAM,mBAAmB,IAAI,SAAS,IAAI,GAAG;AACnD,MAAI,aAAa,MAAM;AACrB,WAAO,gBAAgB,UAAU,WAAW;AAAA,EAC9C;AAEA,QAAM,YAAY;AAAA,IAChB,WAAW,IAAI,MAAM;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY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