tenjin-cli 0.1.0-alpha.12 → 0.1.0-alpha.13

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 (126) hide show
  1. package/README.md +1 -0
  2. package/dist/{buy-3DTBFZ4B.js → buy-X4VPHFUA.js} +20 -20
  3. package/dist/{chunk-V5UHKC46.js → chunk-3NZCU6SD.js} +7 -7
  4. package/dist/{chunk-Y7ERTA7D.js → chunk-3P3ES4XU.js} +4 -6
  5. package/dist/chunk-3P3ES4XU.js.map +1 -0
  6. package/dist/{chunk-OZHJ3FLR.js → chunk-47YKYDOF.js} +5 -5
  7. package/dist/{chunk-WWIKAJFO.js → chunk-6JKD46OJ.js} +12 -10
  8. package/dist/{chunk-WWIKAJFO.js.map → chunk-6JKD46OJ.js.map} +1 -1
  9. package/dist/chunk-736DW4V3.js +65 -0
  10. package/dist/chunk-736DW4V3.js.map +1 -0
  11. package/dist/{chunk-IB63U6BM.js → chunk-B676GPS2.js} +34 -11
  12. package/dist/chunk-B676GPS2.js.map +1 -0
  13. package/dist/{chunk-4NTZETIL.js → chunk-BRAVLUGI.js} +2 -2
  14. package/dist/{chunk-HWHYPCCH.js → chunk-CA3JV7FX.js} +2 -2
  15. package/dist/{chunk-HWHYPCCH.js.map → chunk-CA3JV7FX.js.map} +1 -1
  16. package/dist/{chunk-ALUNME53.js → chunk-ELVDOTU7.js} +50 -66
  17. package/dist/chunk-ELVDOTU7.js.map +1 -0
  18. package/dist/{chunk-ILDVGY7K.js → chunk-GCGMXA2O.js} +13 -11
  19. package/dist/{chunk-ILDVGY7K.js.map → chunk-GCGMXA2O.js.map} +1 -1
  20. package/dist/{chunk-L3I2MVKR.js → chunk-IAR25V2E.js} +6 -6
  21. package/dist/{chunk-6UY2UQMY.js → chunk-IFPKA32J.js} +4 -4
  22. package/dist/{chunk-JTYIX6OD.js → chunk-IGHSLJUF.js} +6 -4
  23. package/dist/{chunk-JTYIX6OD.js.map → chunk-IGHSLJUF.js.map} +1 -1
  24. package/dist/{chunk-7MJVNALU.js → chunk-IKAJSA7E.js} +12 -10
  25. package/dist/{chunk-7MJVNALU.js.map → chunk-IKAJSA7E.js.map} +1 -1
  26. package/dist/{chunk-NUF2PKJO.js → chunk-J6FUAIRR.js} +4 -6
  27. package/dist/{chunk-NUF2PKJO.js.map → chunk-J6FUAIRR.js.map} +1 -1
  28. package/dist/{chunk-CNUXRXI2.js → chunk-JVBMPU5G.js} +5 -7
  29. package/dist/{chunk-CNUXRXI2.js.map → chunk-JVBMPU5G.js.map} +1 -1
  30. package/dist/{chunk-6RMEX74N.js → chunk-L4XNT3UW.js} +21 -16
  31. package/dist/chunk-L4XNT3UW.js.map +1 -0
  32. package/dist/{chunk-X2WZPGCF.js → chunk-NKN4YC5C.js} +5 -5
  33. package/dist/{chunk-P74I3WH4.js → chunk-OC3EIDCP.js} +3 -5
  34. package/dist/{chunk-P74I3WH4.js.map → chunk-OC3EIDCP.js.map} +1 -1
  35. package/dist/{chunk-E6YOODH7.js → chunk-OE36HRWG.js} +31 -5
  36. package/dist/{chunk-E6YOODH7.js.map → chunk-OE36HRWG.js.map} +1 -1
  37. package/dist/chunk-OUJDDY5L.js +189 -0
  38. package/dist/chunk-OUJDDY5L.js.map +1 -0
  39. package/dist/{chunk-6BGYHARE.js → chunk-OWVVI4VQ.js} +15 -15
  40. package/dist/{chunk-4TCU3YRD.js → chunk-OXUJ3FXU.js} +5 -1
  41. package/dist/{chunk-4TCU3YRD.js.map → chunk-OXUJ3FXU.js.map} +1 -1
  42. package/dist/{chunk-PZRAAAY2.js → chunk-PAOVPSP6.js} +10 -3
  43. package/dist/chunk-PAOVPSP6.js.map +1 -0
  44. package/dist/{chunk-TUXKOIOU.js → chunk-SPUORKD7.js} +3 -3
  45. package/dist/{chunk-UFPJBS4C.js → chunk-T4UWMVKV.js} +9 -7
  46. package/dist/{chunk-UFPJBS4C.js.map → chunk-T4UWMVKV.js.map} +1 -1
  47. package/dist/{chunk-CLOEU7RA.js → chunk-TXVC46SA.js} +8 -8
  48. package/dist/{chunk-SFGXAZ3M.js → chunk-UUARTUY2.js} +42 -9
  49. package/dist/chunk-UUARTUY2.js.map +1 -0
  50. package/dist/{chunk-ROAK2DOX.js → chunk-WMFRCSNC.js} +8 -8
  51. package/dist/{chunk-TDDN5GXR.js → chunk-WU5CZPLD.js} +5 -5
  52. package/dist/{chunk-RSBN67PA.js → chunk-WVHPGQH5.js} +4 -6
  53. package/dist/{chunk-RSBN67PA.js.map → chunk-WVHPGQH5.js.map} +1 -1
  54. package/dist/{chunk-PZSUWDF2.js → chunk-XGZ5EVMB.js} +2 -2
  55. package/dist/{chunk-MBKFZBB2.js → chunk-XXY77EZJ.js} +24 -24
  56. package/dist/{chunk-CBNXUQGM.js → chunk-YMUJZWHB.js} +10 -8
  57. package/dist/{chunk-CBNXUQGM.js.map → chunk-YMUJZWHB.js.map} +1 -1
  58. package/dist/{cli-3WZGLZDP.js → cli-XK5JZWU6.js} +51 -146
  59. package/dist/cli-XK5JZWU6.js.map +1 -0
  60. package/dist/{config-WDGMZKHU.js → config-CNK7MYUR.js} +7 -7
  61. package/dist/doctor-R7N7FUX5.js +27 -0
  62. package/dist/{edit-4UZQVFCK.js → edit-QSUEG7CL.js} +19 -19
  63. package/dist/{fund-JAPOFTUG.js → fund-JF6A76YS.js} +16 -16
  64. package/dist/index.js +1 -1
  65. package/dist/{inspect-IEV75A42.js → inspect-NFNAA4LA.js} +17 -17
  66. package/dist/{install-WXTOHDWC.js → install-YQVM3SUW.js} +20 -21
  67. package/dist/{install-WXTOHDWC.js.map → install-YQVM3SUW.js.map} +1 -1
  68. package/dist/outcome-IUSYFJTN.js +22 -0
  69. package/dist/{publish-6QNARH7E.js → publish-O2I6IAEL.js} +20 -20
  70. package/dist/{read-UAZGZ4UL.js → read-UF7QVQOU.js} +21 -21
  71. package/dist/{run-AJNCOT5R.js → run-GDZWHNWZ.js} +30 -30
  72. package/dist/search-JVOHEF3E.js +23 -0
  73. package/dist/{send-F34ZDXDZ.js → send-SI254H3R.js} +11 -10
  74. package/dist/{send-F34ZDXDZ.js.map → send-SI254H3R.js.map} +1 -1
  75. package/dist/{session-4N4ZT3AH.js → session-GJZJEXLJ.js} +14 -14
  76. package/dist/{skill-heal-XBEK272G.js → skill-heal-BPFT22XS.js} +5 -6
  77. package/dist/{skill-heal-XBEK272G.js.map → skill-heal-BPFT22XS.js.map} +1 -1
  78. package/dist/{uninstall-BTKPHPDL.js → uninstall-7ZZG6WQ5.js} +6 -7
  79. package/dist/{uninstall-BTKPHPDL.js.map → uninstall-7ZZG6WQ5.js.map} +1 -1
  80. package/dist/update-FPSBITLB.js +315 -0
  81. package/dist/update-FPSBITLB.js.map +1 -0
  82. package/dist/{wallet-UL4P2JRO.js → wallet-NS7TYWNN.js} +5 -6
  83. package/dist/{wallet-WJ6UP5OU.js → wallet-TZVD2M4I.js} +9 -9
  84. package/docs/agent-permissions.md +11 -0
  85. package/docs/command-reference.md +47 -0
  86. package/package.json +1 -1
  87. package/skills/tenjin-publish/SKILL.md +15 -2
  88. package/dist/chunk-2I4QTOLB.js +0 -11
  89. package/dist/chunk-2I4QTOLB.js.map +0 -1
  90. package/dist/chunk-6RMEX74N.js.map +0 -1
  91. package/dist/chunk-ALUNME53.js.map +0 -1
  92. package/dist/chunk-IB63U6BM.js.map +0 -1
  93. package/dist/chunk-PZRAAAY2.js.map +0 -1
  94. package/dist/chunk-SFGXAZ3M.js.map +0 -1
  95. package/dist/chunk-Y7ERTA7D.js.map +0 -1
  96. package/dist/cli-3WZGLZDP.js.map +0 -1
  97. package/dist/doctor-EKVCP7JP.js +0 -27
  98. package/dist/outcome-FYOFDOUK.js +0 -22
  99. package/dist/search-EEKTW6VK.js +0 -23
  100. /package/dist/{buy-3DTBFZ4B.js.map → buy-X4VPHFUA.js.map} +0 -0
  101. /package/dist/{chunk-V5UHKC46.js.map → chunk-3NZCU6SD.js.map} +0 -0
  102. /package/dist/{chunk-OZHJ3FLR.js.map → chunk-47YKYDOF.js.map} +0 -0
  103. /package/dist/{chunk-4NTZETIL.js.map → chunk-BRAVLUGI.js.map} +0 -0
  104. /package/dist/{chunk-L3I2MVKR.js.map → chunk-IAR25V2E.js.map} +0 -0
  105. /package/dist/{chunk-6UY2UQMY.js.map → chunk-IFPKA32J.js.map} +0 -0
  106. /package/dist/{chunk-X2WZPGCF.js.map → chunk-NKN4YC5C.js.map} +0 -0
  107. /package/dist/{chunk-6BGYHARE.js.map → chunk-OWVVI4VQ.js.map} +0 -0
  108. /package/dist/{chunk-TUXKOIOU.js.map → chunk-SPUORKD7.js.map} +0 -0
  109. /package/dist/{chunk-CLOEU7RA.js.map → chunk-TXVC46SA.js.map} +0 -0
  110. /package/dist/{chunk-ROAK2DOX.js.map → chunk-WMFRCSNC.js.map} +0 -0
  111. /package/dist/{chunk-TDDN5GXR.js.map → chunk-WU5CZPLD.js.map} +0 -0
  112. /package/dist/{chunk-PZSUWDF2.js.map → chunk-XGZ5EVMB.js.map} +0 -0
  113. /package/dist/{chunk-MBKFZBB2.js.map → chunk-XXY77EZJ.js.map} +0 -0
  114. /package/dist/{config-WDGMZKHU.js.map → config-CNK7MYUR.js.map} +0 -0
  115. /package/dist/{doctor-EKVCP7JP.js.map → doctor-R7N7FUX5.js.map} +0 -0
  116. /package/dist/{edit-4UZQVFCK.js.map → edit-QSUEG7CL.js.map} +0 -0
  117. /package/dist/{fund-JAPOFTUG.js.map → fund-JF6A76YS.js.map} +0 -0
  118. /package/dist/{inspect-IEV75A42.js.map → inspect-NFNAA4LA.js.map} +0 -0
  119. /package/dist/{outcome-FYOFDOUK.js.map → outcome-IUSYFJTN.js.map} +0 -0
  120. /package/dist/{publish-6QNARH7E.js.map → publish-O2I6IAEL.js.map} +0 -0
  121. /package/dist/{read-UAZGZ4UL.js.map → read-UF7QVQOU.js.map} +0 -0
  122. /package/dist/{run-AJNCOT5R.js.map → run-GDZWHNWZ.js.map} +0 -0
  123. /package/dist/{search-EEKTW6VK.js.map → search-JVOHEF3E.js.map} +0 -0
  124. /package/dist/{session-4N4ZT3AH.js.map → session-GJZJEXLJ.js.map} +0 -0
  125. /package/dist/{wallet-UL4P2JRO.js.map → wallet-NS7TYWNN.js.map} +0 -0
  126. /package/dist/{wallet-WJ6UP5OU.js.map → wallet-TZVD2M4I.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/doctor.ts"],"sourcesContent":["import { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { resolveSkillsSource } from '../lib/skills-source';\nimport { CliError } from '../lib/errors';\nimport {\n CLI_SKILL_NAMES,\n HOSTED_SKILL_NAME,\n anyTenjinSkill,\n cliSkillsWired,\n detectHarnesses,\n harnessFlagFor,\n harnessInPlay,\n harnessReads,\n harnessRequested,\n missingCliSkills,\n onPath,\n readAllWiring,\n readSkillFile,\n shadowedCliSkills,\n} from '../lib/skill-wiring';\nimport type {\n DirState,\n HarnessTarget,\n HarnessWiring,\n NotInvocableReason,\n} from '../lib/skill-wiring';\nimport { fetchJson } from '../lib/http';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { tryOriginOf, trimSlash } from '../lib/url';\nimport { configPath, sessionPath } from '../lib/paths';\nimport { toMoney } from '../lib/money';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { isSessionPresentable, readSessionFile, scopeSatisfies } from '../lib/session-present';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { permissionsPointer, recommendedPermissions } from '../lib/permissions';\nimport type { PartialConfig } from '../lib/config';\nimport type { ErrorCode } from '../schemas';\nimport type { Io } from '../lib/output';\nimport type {\n PassphraseOverrides,\n WalletDescription,\n WalletProvider,\n WalletVerification,\n} from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * One environment/reachability check. The doctor agent builds the check list\n * against this shape without changing it: `required` drives the exit code (exit\n * 0 iff every required check is ok), `status` drives the TTY rendering, and a\n * `fix` is mandatory on every failure (spec 10). Warn-level checks never fail\n * the command.\n */\nexport interface CheckResult {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n /**\n * Optional structured payload for machine consumers, so `--json` carries the\n * check's findings as data instead of only as the prose in `detail`. Additive\n * and per-check; the human renderer ignores it.\n */\n data?: unknown;\n}\n\n/** ~$20 in atomic USDC (6 decimals). Above this, the pocket-money wallet warns. */\nconst POCKET_MONEY_CEILING_ATOMIC = 20_000_000n;\n\n/**\n * `doctor` is an allowlisted verb an unattended agent runs on its own, and its\n * `fix:` lines reach that agent both on the TTY and in `error.details.checks`.\n * So they name the CONFIGURED base URL and the operator command that changes it,\n * never `--base-url`: the flag rides every allowlisted verb (see FLAG_CAVEAT in\n * lib/permissions), and a fix line telling the agent to pass it would be the CLI\n * coaching the exact move the skills forbid. `config set` is not allowlisted, so\n * pointing there routes the change through the operator by construction.\n */\nconst FIX_POINT_AT_TENJIN_API =\n 'Point the configured base URL at a Tenjin API (expected an OpenAPI document): `tenjin config set baseUrl <url>`.';\nconst FIX_CHECK_NETWORK_AND_BASE_URL =\n 'Check your network connection and the configured base URL (`tenjin config get baseUrl`).';\n\n/**\n * A CheckResult plus the error code to raise if it is a *required* failure. Only\n * required checks carry a `failCode`; the outcome step raises the first one, so\n * the failure envelope's `error.code` names what actually broke (api-contract\n * unreachable vs malformed differ) while still carrying the whole check list.\n */\ninterface BuiltCheck {\n result: CheckResult;\n failCode?: ErrorCode;\n}\n\nexport interface DoctorDeps {\n /** Environment for wallet-key detection and settings precedence. */\n env?: NodeJS.ProcessEnv;\n /** Injected fetch for the reachability checks; tests pass a canned stub. */\n fetchImpl?: typeof fetch;\n /** Inject the active wallet provider. When set, NO local fs/env is consulted —\n * the provider owns its own describe() and diagnostics(), so a remote provider's\n * checks can't be contaminated by a stale local wallet file. */\n provider?: WalletProvider;\n /** Home directory root for the skill-wiring check. Defaults to os.homedir(); tests\n * (and `install`, which reuses these checks) inject their own. */\n homeDir?: string;\n /** PATH probe for the `claude`/`codex` binaries, half of harness detection. Defaults\n * to probing `env.PATH`, so a test passing `env: {}` detects neither. */\n which?: (bin: string) => boolean;\n /** Clock seam (ms since epoch) for the session-expiry check. */\n now?: () => number;\n /** Packaged skills to compare the wired copies against; defaults to this build's. */\n skillsSourceDir?: string;\n /**\n * Passphrase seams for the wallet verification (#70), which reads the OS\n * credential store. Tests inject a platform with no store, or a stubbed exec,\n * so no assertion here depends on what is in the developer's real keychain.\n */\n walletPassphrase?: Omit<PassphraseOverrides, 'isTTY'>;\n}\n\n/**\n * The full check list plus the first required failure, if any. `install` reuses\n * this to run the doctor checks as its last step and EMBED the summary without\n * throwing (D39: doctor is diagnostics, it never blocks the caller); `runDoctor`\n * wraps it and turns a required failure into the thrown failure envelope.\n */\nexport interface DoctorChecks {\n checks: CheckResult[];\n failure?: { code: ErrorCode; result: CheckResult };\n}\n\nexport async function collectDoctorChecks(\n ctx: CommandContext,\n deps: DoctorDeps = {},\n): Promise<DoctorChecks> {\n const env = deps.env ?? process.env;\n const { config, check: configCheck } = await loadConfigForDoctor(ctx.dataDir);\n const settings = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env });\n const baseUrl = settings.baseUrl.value;\n\n const built: BuiltCheck[] = [\n checkNode(),\n configCheck,\n await checkApiContract(baseUrl, ctx.flags.timeout, deps.fetchImpl),\n await checkReadPath(baseUrl, ctx.flags.timeout, deps.fetchImpl),\n await checkSearchContract(baseUrl, ctx.flags.timeout, deps.fetchImpl),\n await checkSkills(\n deps.homeDir ?? homedir(),\n deps.which ?? ((bin) => onPath(bin, env)),\n config.install?.harness ?? [],\n deps.skillsSourceDir,\n ),\n await checkSession(ctx.dataDir, deps.now ?? Date.now, tryOriginOf(baseUrl)),\n ];\n\n // The wallet/custody/balance checks all come from the ACTIVE provider: it owns\n // describe() and diagnostics(), so doctor never runs its own fs/env probe.\n for (const result of await checkWallet(ctx, deps, env, settings.rpcUrl.value)) {\n built.push({ result });\n }\n\n const checks = built.map((b) => b.result);\n const firstFail = built.find((b) => b.result.required && b.result.status === 'fail');\n if (firstFail === undefined) return { checks };\n return { checks, failure: { code: firstFail.failCode ?? 'INTERNAL', result: firstFail.result } };\n}\n\nexport async function runDoctor(\n ctx: CommandContext,\n deps: DoctorDeps = {},\n): Promise<CommandResult> {\n const { checks, failure } = await collectDoctorChecks(ctx, deps);\n if (failure !== undefined) {\n const r = failure.result;\n // The allowlist rides on the FAILURE envelope too. An operator whose fresh\n // install is broken is the likeliest one to be reading doctor output at all,\n // and the earlier version dropped the block on exactly that path while the\n // comment below claimed otherwise. The human failure path still renders only\n // the error and its fix (that is emitFailure's contract, not doctor's), so\n // the machine payload is where this has to land.\n throw new CliError(failure.code, r.detail, {\n ...(r.fix !== undefined ? { fix: r.fix } : {}),\n details: { checks, permissions: recommendedPermissions() },\n });\n }\n\n // The discoverability surface for the auto-mode denial problem (#33), now one\n // line rather than the ~60 that used to bury the check list this command was\n // run for: an operator whose agent just got denied still learns the allowlist\n // exists and where to get it. It reports nothing about the local machine, so it\n // is deliberately NOT a check: it can never pass or fail. `--json` is unchanged\n // and still carries the whole recommendation as data.\n return {\n data: { status: 'pass', checks, permissions: recommendedPermissions() },\n humanLines: [...renderDoctorHuman(ctx.io, checks), '', permissionsPointer()],\n };\n}\n\nfunction checkNode(): BuiltCheck {\n const version = process.versions.node;\n const major = Number.parseInt(version.split('.')[0] ?? '0', 10);\n if (major >= 22) {\n return { result: { name: 'node', status: 'ok', required: true, detail: `Node ${version}` } };\n }\n return {\n result: {\n name: 'node',\n status: 'fail',\n required: true,\n detail: `Node ${version} is unsupported (need >= 22)`,\n fix: 'Install Node 22 or newer',\n },\n failCode: 'NODE_UNSUPPORTED',\n };\n}\n\n/**\n * loadRawConfig throws CONFIG_INVALID on a bad file (which we convert into a\n * failing check) but the config value is also needed for baseUrl/rpcUrl\n * resolution; an invalid file falls back to {} so the reachability checks still\n * run and appear in the list, and config is reported as the first required fail.\n */\nasync function loadConfigForDoctor(\n dataDir: string,\n): Promise<{ config: PartialConfig; check: BuiltCheck }> {\n try {\n const config = await loadRawConfig(dataDir);\n const detail =\n Object.keys(config).length === 0\n ? 'No config file; using defaults'\n : `Config at ${configPath(dataDir)} is valid`;\n return { config, check: { result: { name: 'config', status: 'ok', required: true, detail } } };\n } catch (err) {\n if (err instanceof CliError && err.code === 'CONFIG_INVALID') {\n return {\n config: {},\n check: {\n result: {\n name: 'config',\n status: 'fail',\n required: true,\n detail: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n },\n failCode: 'CONFIG_INVALID',\n },\n };\n }\n throw err;\n }\n}\n\nasync function checkApiContract(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl?: typeof fetch,\n): Promise<BuiltCheck> {\n const url = `${trimSlash(baseUrl)}/openapi.json`;\n const res = await fetchJson(url, { timeoutMs, fetchImpl });\n if (!res.ok) {\n const malformed = res.kind === 'invalid-json';\n return {\n result: {\n name: 'api-contract',\n status: 'fail',\n required: true,\n detail: malformed\n ? `OpenAPI document at ${url} was not valid JSON`\n : `Could not reach the Tenjin API at ${url}: ${res.message}`,\n fix: malformed ? FIX_POINT_AT_TENJIN_API : FIX_CHECK_NETWORK_AND_BASE_URL,\n },\n failCode: malformed ? 'CONTRACT_MISMATCH' : 'API_UNREACHABLE',\n };\n }\n const version = infoVersion(res.json);\n if (version === undefined) {\n return {\n result: {\n name: 'api-contract',\n status: 'fail',\n required: true,\n detail: `OpenAPI document at ${url} is missing a string info.version`,\n fix: FIX_POINT_AT_TENJIN_API,\n },\n failCode: 'CONTRACT_MISMATCH',\n };\n }\n return {\n result: {\n name: 'api-contract',\n status: 'ok',\n required: true,\n detail: `Tenjin API ${version} at ${baseUrl}`,\n },\n };\n}\n\n/**\n * WARN-level (never fails doctor): is the A2 search endpoint advertised in the\n * OpenAPI doc? Absent means the deployment predates A2 (the buy/search path will\n * not work against it yet). Warn-only because doctor's job is a working READ path,\n * and search is additive.\n */\nasync function checkSearchContract(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl?: typeof fetch,\n): Promise<BuiltCheck> {\n const url = `${trimSlash(baseUrl)}/openapi.json`;\n const res = await fetchJson(url, { timeoutMs, fetchImpl });\n if (!res.ok) {\n return {\n result: {\n name: 'search-contract',\n status: 'warn',\n required: false,\n detail: `Could not confirm the search endpoint at ${url}`,\n fix: 'Check the configured base URL (`tenjin config get baseUrl`); search/buy need the A2 endpoints deployed.',\n },\n };\n }\n const present = hasSearchPath(res.json);\n return {\n result: present\n ? {\n name: 'search-contract',\n status: 'ok',\n required: false,\n detail: 'Search endpoint advertised',\n }\n : {\n name: 'search-contract',\n status: 'warn',\n required: false,\n detail: 'This deployment does not advertise POST /api/agent/search (A2 not deployed)',\n fix: 'search/buy need A2 deployed; point the configured base URL at a deploy that has it (`tenjin config set baseUrl <url>`).',\n },\n };\n}\n\nfunction hasSearchPath(json: unknown): boolean {\n if (!isRecord(json)) return false;\n const paths = json.paths;\n return isRecord(paths) && '/api/agent/search' in paths;\n}\n\n/**\n * WARN-level (never fails doctor): is the harness skill wiring usable? #35 was\n * invisible without a screen recording, because the publish skill was on disk yet\n * the model never saw it and only the hosted skill answered publish asks.\n *\n * Verdicts are per DIRECTORY, never unioned across them — in EITHER direction.\n * Unioning the problems contradicts itself on a real machine: a Claude-only install\n * leaves a stray hosted skill in ~/.agents/skills, and flat-mapping announced both\n * CLI skills \"missing\" in the same sentence that listed them wired. Unioning the\n * successes is the same bug inverted, and worse: Claude Code reads ~/.claude/skills\n * and Codex reads ~/.agents/skills, so a wired .agents cannot answer for .claude,\n * and asking whether SOME directory is wired reported `ok` on a machine where\n * `tenjin-publish` was unreachable from Claude Code — exactly the #35 shape.\n *\n * So each directory is judged alone, and only when a harness on this machine\n * actually reads it (`harnessReads`, the probes `install` picks targets with). That\n * gate is what keeps a leftover mirror quiet: a hosted-only ~/.agents/skills with no\n * Codex is nobody's problem, while a hosted-only ~/.claude/skills with Claude Code\n * installed is the bug.\n *\n * Warn and never required: a CI or server machine legitimately has no harness, so\n * this must not move the exit code.\n */\n/**\n * `requested` is the `--harness` set a past `install` recorded (config `install.harness`).\n * It joins detection in deciding which directories are in play, and rides in the data as\n * its own field so `harnessPresent` keeps meaning \"a harness detected here reads this\".\n */\nasync function checkSkills(\n home: string,\n which: (bin: string) => boolean,\n requested: readonly HarnessTarget[],\n skillsSourceDir?: string,\n): Promise<BuiltCheck> {\n const present = detectHarnesses(home, which);\n const wiring = await readAllWiring(home);\n const data = {\n directories: wiring.map((w) => ({\n ...w,\n harnessPresent: harnessReads(home, w.dir, present),\n requested: harnessRequested(home, w.dir, requested),\n })),\n };\n const inPlay = wiring.filter((w) => anyTenjinSkill(w));\n\n if (inPlay.length === 0) {\n // Same fixFor path every other branch uses, over the same harnessInPlay\n // predicate (detected OR requested) — filtering on `requested` alone named\n // only the recorded directory and left a DETECTED one unwired, which just\n // swapped which directory the first command missed. Gated on\n // `requested.length > 0` so a machine with no record at all keeps the plain\n // `tenjin install` rather than newly spelling out a detected harness that\n // nobody asked to see named.\n const targeted =\n requested.length > 0\n ? wiring.filter((w) => harnessInPlay(home, w.dir, present, requested))\n : [];\n return {\n result: {\n name: 'skills',\n status: 'warn',\n required: false,\n detail: `No Tenjin skills wired under ${home} (looked in .claude/skills and .agents/skills)`,\n fix: targeted.length > 0 ? fixFor(home, targeted) : 'tenjin install',\n data,\n },\n };\n }\n\n // Every directory in play must carry BOTH CLI skills, model-invocable. Anything less\n // is the defect, whether it is shadowed, half-installed, hosted-only or absent; a\n // directory neither detected nor asked for is described but never warned about.\n const broken = wiring.filter(\n (w) => harnessInPlay(home, w.dir, present, requested) && !cliSkillsWired(w),\n );\n if (broken.length > 0) {\n return {\n result: {\n name: 'skills',\n status: 'warn',\n required: false,\n detail: `${broken.map(describeProblem).join('; ')}. Full state: ${describeWiring(inPlay)}`,\n fix: fixFor(home, broken),\n data,\n },\n };\n }\n\n // Wired is not the same as CURRENT. `npm i -g tenjin-cli` updates the binary and\n // nothing else, so the copies install wrote stay at whatever version wrote them\n // until someone re-runs install, and every check above passes the whole time.\n //\n // EVERY directory, not just the ones in play. The checks above ask what a\n // harness on this machine reads; this one has to cover what the self-heal\n // writes, which is any directory holding one of our adapters. A ~/.agents/skills\n // that fell out of play (a fallback install, then Claude Code arrives) is where\n // the heal keeps working and, when it cannot, keeps quiet: reporting a narrower\n // set than it writes would leave a stale directory nothing ever names.\n const { stale, verifiable } = await compareWiredSkills(\n wiring.map((w) => w.dir),\n skillsSourceDir,\n );\n if (!verifiable) {\n return {\n result: {\n name: 'skills',\n status: 'warn',\n required: false,\n detail: `${CLI_SKILL_NAMES.join(' + ')} wired, but this build's packaged copies could not be read, so whether they are current is unknown`,\n fix: 'Reinstall the CLI: `npm i -g tenjin-cli`, then `tenjin install`.',\n data,\n },\n };\n }\n if (stale.length > 0) {\n return {\n result: {\n name: 'skills',\n status: 'warn',\n required: false,\n detail: `${CLI_SKILL_NAMES.join(' + ')} wired but not from this CLI build (${stale.join(', ')}); agents are reading an older version's instructions`,\n // fixFor, like every neighbouring branch: a plain `tenjin install` targets\n // DETECTED harnesses only, so for a directory that exists because someone\n // passed --harness it would be a fix that never clears the warning.\n fix: fixFor(\n home,\n wiring.filter((w) => stale.includes(w.dir)),\n ),\n data,\n },\n };\n }\n\n return {\n result: {\n name: 'skills',\n status: 'ok',\n required: false,\n detail: `${CLI_SKILL_NAMES.join(' + ')} wired: ${describeWiring(inPlay)}`,\n data,\n },\n };\n}\n\n/**\n * How the wired CLI adapter skills compare to the packaged ones.\n *\n * `verifiable` is false when this build cannot read its own packaged copies, which\n * is a broken package rather than evidence of no drift; reporting that as current\n * would make the check quietly green on exactly the install doctor should describe.\n *\n * Only the ADAPTERS are compared: the hosted mirror is a copy of\n * tenjin.blog/skills.md that an operator may legitimately have re-fetched newer\n * than this package ships.\n *\n * This is also where a skill the post-command self-heal could NOT rewrite\n * surfaces. That writer stays silent about its failures on purpose: a cause it\n * cannot clear (an unwritable skills directory) would otherwise print the same\n * line on every command forever. Stale here means exactly that, and the fix names\n * the harness. For the handoff to hold, the CALLER has to pass every directory\n * the heal can reach, not only the ones a detected harness reads.\n */\nasync function compareWiredSkills(\n dirs: readonly string[],\n sourceDir?: string,\n): Promise<{ stale: string[]; verifiable: boolean }> {\n let source: string;\n try {\n source = sourceDir ?? resolveSkillsSource(fileURLToPath(new URL('.', import.meta.url)));\n } catch {\n return { stale: [], verifiable: false };\n }\n // Read once, not once per directory.\n const packaged = new Map<string, Buffer>();\n for (const name of CLI_SKILL_NAMES) {\n const read = await readSkillFile(join(source, name, 'SKILL.md'));\n if (read.kind === 'ok') packaged.set(name, read.bytes);\n }\n if (packaged.size !== CLI_SKILL_NAMES.length) return { stale: [], verifiable: false };\n\n const stale: string[] = [];\n for (const dir of dirs) {\n for (const name of CLI_SKILL_NAMES) {\n // Guarded: a pipe or device at this path would otherwise block the whole\n // diagnostic. Anything but a readable regular file is the wiring check's\n // business, not this one's.\n const onDisk = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (onDisk.kind !== 'ok') continue;\n if (!packaged.get(name)!.equals(onDisk.bytes)) {\n stale.push(dir);\n break;\n }\n }\n }\n return { stale, verifiable: true };\n}\n\n/** What is wrong in ONE directory, naming the directory and the skills. */\nfunction describeProblem(w: HarnessWiring): string {\n const shadowed = shadowedCliSkills(w);\n const missing = missingCliSkills(w);\n const parts: string[] = [];\n // Grouped BY REASON, not into one clause: the two claims differ in strength. A\n // readable file with the flag set is a fact; an unreadable one is a disjunction,\n // because the whole reason we cannot assert the flag is that we could not read it.\n // Merging them would spread that hedge onto a skill we know the answer for.\n const unreadable = shadowed.filter((n) => reasonFor(w, n) === 'unreadable');\n const disabled = shadowed.filter((n) => reasonFor(w, n) !== 'unreadable');\n if (disabled.length > 0) {\n parts.push(\n `${disabled.join(', ')} installed but not model-invocable (disable-model-invocation: true)`,\n );\n }\n if (unreadable.length > 0) {\n parts.push(\n `${unreadable.join(', ')} installed but not model-invocable (unreadable or disable-model-invocation: true)`,\n );\n }\n // Naming both by name reads as a half-install; when NEITHER is there the state is\n // \"this harness has no CLI skills at all\", which is a different sentence.\n if (missing.length === CLI_SKILL_NAMES.length) {\n parts.push(\n w.state === 'hosted-only'\n ? `the hosted ${HOSTED_SKILL_NAME} skill is here but neither CLI skill is wired`\n : 'neither CLI skill is wired',\n );\n } else if (missing.length > 0) parts.push(`${missing.join(', ')} missing`);\n return `${w.dir}: ${parts.join(' and ')}`;\n}\n\nfunction reasonFor(w: HarnessWiring, name: string): NotInvocableReason | undefined {\n return w.skills.find((s) => s.name === name)?.reason;\n}\n\n/** Is the hosted zero-install mirror in THIS directory? */\nfunction hostedHere(w: HarnessWiring): boolean {\n return w.skills.find((s) => s.name === HOSTED_SKILL_NAME)?.present === true;\n}\n\n/**\n * A fix that can actually clear the warning. A bare `tenjin install` only targets\n * the directories detection picks, so a problem in ~/.agents/skills on a\n * Claude-only machine needs `--harness shared` spelled out.\n */\nfunction fixFor(home: string, dirs: HarnessWiring[]): string {\n const flags = [...new Set(dirs.map((w) => harnessFlagFor(home, w.dir)))];\n return `tenjin install ${flags.map((f) => `--harness ${f}`).join(' ')}`;\n}\n\n/** One-line per-directory summary: `<dir> -> <skills> (<posture>)`. */\nfunction describeWiring(wiring: HarnessWiring[]): string {\n return wiring\n .map((w) => {\n const parts = w.skills\n .filter((s) => s.present)\n .map((s) =>\n s.modelInvocable === false ? `${s.name} [${s.reason ?? 'shadowed'}]` : s.name,\n );\n return `${w.dir} -> ${parts.join(', ')} (${posture(w)})`;\n })\n .join('; ');\n}\n\n/**\n * The precedence half of the `wired` posture is only true when there is a mirror\n * here to take precedence OVER. `classify` keys `wired` off the two CLI skills\n * alone, so a directory whose mirror was deleted is `wired` with no `tenjin` in it,\n * and the unconditional string claimed a file the same line had just not listed.\n */\nfunction posture(w: HarnessWiring): string {\n if (w.state !== 'wired') return POSTURE[w.state];\n return hostedHere(w)\n ? 'CLI skills wired, take precedence over the hosted mirror'\n : 'CLI skills wired';\n}\n\nconst POSTURE: Record<DirState, string> = {\n empty: 'no Tenjin skills',\n 'hosted-only': 'hosted skill only, no CLI skills here',\n partial: 'only one CLI skill',\n // \"at least one\": a directory with one CLI skill shadowed and the other absent\n // classifies as `shadowed` too, and \"CLI skills present\" would be false there.\n shadowed: 'at least one CLI skill present but not model-invocable',\n wired: 'CLI skills wired, take precedence over the hosted mirror',\n};\n\n/**\n * The delegated session key `tenjin read` presents to recover a piece this wallet\n * already owns (`tenjin session start --scope read` mints it). Never required and\n * never a fail — `read` works without one — so ABSENT is `ok`: the normal\n * posture, not a defect. So are the states that are ordinary decay rather than\n * damage: an older CLI's file, a spent 24h expiry, a scope that does not cover\n * reading. One command re-mints all of them, and a check that yellowed on them\n * would be permanently yellow on any machine that ever minted a key.\n *\n * A genuine fault still warns, and the states are kept apart on purpose. A 0600 file\n * that is now group-readable, or one whose contents no longer parse, is a TAMPER\n * signal on a wallet-derived credential; `loadSessionFile` fails closed on both\n * and collapses them to \"no session\", which is the right instruction for a caller\n * that can re-mint and exactly the wrong report for the verb an operator runs\n * when something looks wrong. `readSessionFile` keeps them distinguishable and\n * this is the one caller that needs them.\n *\n * An unreadable file (EACCES after a `sudo` run, EIO) warns rather than throwing:\n * doctor is diagnostics, and a session cache nobody asked about must never take\n * down the run that was going to explain the rest of the machine.\n *\n * Reports address / origin / scope / expiry and nothing else. The delegation and\n * the private JWK never reach this output — doctor's payload is the single most\n * likely thing in this CLI to be pasted into an issue.\n */\nasync function checkSession(\n dataDir: string,\n now: () => number,\n origin: string | null,\n): Promise<BuiltCheck> {\n const warn = (detail: string, data?: unknown): BuiltCheck => ({\n result: {\n name: 'session',\n status: 'warn',\n required: false,\n detail,\n fix: 'tenjin session start --scope read',\n ...(data !== undefined ? { data } : {}),\n },\n });\n\n const state = await readSessionFile(dataDir);\n if (state.kind === 'absent') {\n return {\n result: {\n name: 'session',\n status: 'ok',\n required: false,\n detail:\n 'No session key; `tenjin read` delivers free and locally-cached pieces (`tenjin session start --scope read` adds owned-piece recovery)',\n },\n };\n }\n if (state.kind === 'loosened') {\n return warn(\n `Session key at ${sessionPath(dataDir)} is mode 0${state.mode.toString(8)}, not 0600, so it is refused; it holds a wallet-derived credential and was changed out of band. Delete it and re-mint`,\n );\n }\n // Same standing as `absent`: a cache this CLI cannot use, re-minted by one\n // command. A failing check here meant a permanent post-update warning.\n if (state.kind === 'outdated') {\n return {\n result: {\n name: 'session',\n status: 'ok',\n required: false,\n detail: `Cached session key at ${sessionPath(dataDir)} predates this CLI version (no \\`${state.field}\\`) and is not used; \\`tenjin session start --scope read\\` mints a current one`,\n },\n };\n }\n if (state.kind === 'corrupt') {\n return warn(`Session key at ${sessionPath(dataDir)} could not be parsed (${state.reason})`);\n }\n if (state.kind === 'unreadable') {\n return warn(`Session key at ${sessionPath(dataDir)} could not be read: ${state.message}`);\n }\n\n const file = state.file;\n // A base URL that is not an http(s) origin cannot be compared against, and this\n // is the diagnostic verb: it reports that and keeps going. The `config` check\n // above owns the fix for the value itself.\n if (origin === null) {\n return {\n result: {\n name: 'session',\n status: 'warn',\n required: false,\n detail: `Session key was minted for ${file.origin}, but the configured base URL is not an http(s) origin, so it cannot be matched`,\n fix: 'Set an absolute http(s) base URL: `tenjin config set baseUrl <url>`.',\n data: { address: file.address, origin: file.origin, scope: file.scope, exp: file.exp },\n },\n };\n }\n const data = { address: file.address, origin: file.origin, scope: file.scope, exp: file.exp };\n if (file.origin !== origin) {\n return warn(\n `Session key was minted for ${file.origin}, but the configured base URL is ${origin}; it is not presented off its own origin`,\n data,\n );\n }\n // Expiry and scope are DESIGNED DECAY, not faults. A delegation lives 24h by\n // construction, so warning on a spent one made every machine that ever ran\n // `tenjin session start` permanently yellow for behaving exactly as intended —\n // the same permanent-warning trap `outdated` above was already pulled out of.\n // Both are re-minted by the one command named in the detail. An expiry that\n // does not PARSE is a different thing and stays a warning: that is a malformed\n // file, not a spent one.\n if (!Number.isFinite(Date.parse(file.exp))) {\n return warn(\n `Session key for ${file.address} carries an unparseable expiry (exp ${file.exp})`,\n data,\n );\n }\n if (!scopeSatisfies(file.scope, 'read')) {\n return {\n result: {\n name: 'session',\n status: 'ok',\n required: false,\n detail: `Session key has scope ${file.scope}, which does not cover reading; \\`tenjin session start --scope read\\` mints one that does`,\n data,\n },\n };\n }\n if (!isSessionPresentable(file, now(), 'read', origin)) {\n return {\n result: {\n name: 'session',\n status: 'ok',\n required: false,\n detail:\n 'Session key expired (normal after 24h); mint one with `tenjin session start --scope read` when you want free re-reads of owned pieces',\n data,\n },\n };\n }\n return {\n result: {\n name: 'session',\n status: 'ok',\n required: false,\n detail: `Session key ${file.address}, scope ${file.scope}, for ${file.origin}, expires ${file.exp}`,\n data,\n },\n };\n}\n\nasync function checkReadPath(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl?: typeof fetch,\n): Promise<BuiltCheck> {\n // The shipped public read path. The A2 search-contract check is a B2 follow-up.\n // Probe the UNFILTERED listing: the server logs every nonblank first-page `q`\n // as agent search demand, so a `q` here would fabricate that demand into the\n // experiment this CLI exists to measure. Never add a `q` to this probe.\n const url = `${trimSlash(baseUrl)}/api/articles?limit=1`;\n const res = await fetchJson(url, { timeoutMs, fetchImpl });\n if (!res.ok) {\n return {\n result: {\n name: 'read-path',\n status: 'fail',\n required: true,\n detail: `Read path ${url} failed: ${res.message}`,\n fix: FIX_CHECK_NETWORK_AND_BASE_URL,\n },\n failCode: 'API_UNREACHABLE',\n };\n }\n const items = isRecord(res.json) ? res.json.items : undefined;\n if (!Array.isArray(items)) {\n return {\n result: {\n name: 'read-path',\n status: 'fail',\n required: true,\n detail: `Read path ${url} did not return an items array`,\n fix: 'Point the configured base URL at a Tenjin API: `tenjin config set baseUrl <url>`.',\n },\n failCode: 'API_UNREACHABLE',\n };\n }\n return {\n result: { name: 'read-path', status: 'ok', required: true, detail: `Read path OK at ${url}` },\n };\n}\n\n/**\n * Diagnose the wallet the CLI would actually use, entirely through the ACTIVE\n * provider. An injected provider owns everything — no local file or env is touched.\n * With no injected provider we do ONE cheap fs/env probe purely to decide whether\n * any credential exists: none → emit the \"no wallet\" warn WITHOUT importing the\n * wallet lib (that import statically pulls viem, and a no-wallet run must not parse\n * it). Otherwise the provider describes itself (address + source), PROVES the\n * credential can sign when it can do so without prompting (#70), reports its own\n * custody warnings, and the balance probes describe()'s address. A custody problem\n * (bad key, provider refusal) is warn-level, never a hard fail.\n */\nasync function checkWallet(\n ctx: CommandContext,\n deps: DoctorDeps,\n env: NodeJS.ProcessEnv,\n rpcUrl: string,\n): Promise<CheckResult[]> {\n const provider = deps.provider ?? (await resolveLocalProviderOrNull(ctx, env, deps));\n if (provider === null) return [noWalletCheck()];\n\n const { describeWallet } = await import('../lib/wallet');\n let desc: WalletDescription;\n try {\n desc = await describeWallet(provider);\n } catch (err) {\n if (err instanceof CliError && err.code === 'WALLET_MISSING') return [noWalletCheck()];\n return [walletWarn(err)];\n }\n\n const checks: CheckResult[] = [walletCheck(desc, await verifyWallet(provider))];\n // Custody warnings are the provider's own (perms, env-shadow for the local\n // provider; none for a remote one). Render each as a warn check; the fix text,\n // when there is one, is carried inline in the warning string.\n for (const warning of (await provider.diagnostics()).warnings) {\n checks.push({ name: 'wallet-custody', status: 'warn', required: false, detail: warning });\n }\n checks.push(await checkBalance(desc.address, rpcUrl));\n return checks;\n}\n\n/**\n * The active local provider, or null when no credential exists at all. The null\n * path never imports the wallet lib, keeping a no-wallet doctor run off viem.\n */\nasync function resolveLocalProviderOrNull(\n ctx: CommandContext,\n env: NodeJS.ProcessEnv,\n deps: DoctorDeps,\n): Promise<WalletProvider | null> {\n const envKey = env.TENJIN_WALLET_KEY;\n const envKeySet = typeof envKey === 'string' && envKey.length > 0;\n if (!envKeySet && !(await walletFileExists(ctx.dataDir))) return null;\n const { resolveWalletProvider } = await import('../lib/wallet');\n return resolveWalletProvider(ctx, {\n ...(deps.walletPassphrase !== undefined ? { passphrase: deps.walletPassphrase } : {}),\n });\n}\n\n/**\n * Ask the provider to prove the credential can sign (#70). A provider without a\n * `verify` is not a failure and not a pass: it is the `unverified` state, same as\n * a keystore whose passphrase only a human could supply. A provider that throws\n * is treated the same way — doctor reports what it could not establish and keeps\n * going; it never turns a diagnostic's own failure into a verdict about the\n * wallet.\n */\nasync function verifyWallet(provider: WalletProvider): Promise<WalletVerification> {\n if (provider.verify === undefined) {\n return {\n status: 'unverified',\n detail: `provider \"${provider.id}\" cannot verify without a key`,\n };\n }\n try {\n return await provider.verify();\n } catch (err) {\n return {\n status: 'unverified',\n detail: `verification could not run (${err instanceof Error ? err.message : String(err)})`,\n };\n }\n}\n\n/**\n * The wallet check, with the verification folded INTO its status rather than\n * reported beside it. #70 was exactly a green `wallet` line above an unopenable\n * keystore, so an `ok` here has to mean the key is usable, not merely that a file\n * parsed. Still never `required` and never a `fail`: a wallet nobody can open is\n * a real problem, but `read` and `search` work without one, so it must not move\n * the exit code.\n */\nfunction walletCheck(desc: WalletDescription, v: WalletVerification): CheckResult {\n const head = `Wallet ${desc.address} (${desc.credentialSource})`;\n if (v.status === 'broken') {\n return {\n name: 'wallet',\n status: 'warn',\n required: false,\n detail: `${head}: ${v.detail}`,\n fix: v.fix,\n };\n }\n if (v.status === 'unverified') {\n return {\n name: 'wallet',\n status: 'warn',\n required: false,\n detail: `${head} present, not verified: ${v.detail}`,\n fix: 'Set TENJIN_WALLET_PASSPHRASE, or store the passphrase in your OS credential store, so doctor can prove the keystore still opens.',\n };\n }\n return { name: 'wallet', status: 'ok', required: false, detail: `${head}, ${v.detail}` };\n}\n\nfunction noWalletCheck(): CheckResult {\n return {\n name: 'wallet',\n status: 'warn',\n required: false,\n detail: 'No wallet; needed only for buy/publish',\n fix: 'tenjin wallet create',\n data: { credential: 'absent' },\n };\n}\n\n/**\n * Is this the check that says there is no credential at all? `install` prints its\n * own line for that state and drops the duplicate, so it has to recognise THIS\n * check and not merely one named `wallet`: a warn about a credential that exists\n * and does not work (an unopenable keystore, an invalid TENJIN_WALLET_KEY) shares\n * the name and is the one wallet state nothing else in install's output carries.\n */\nexport function isNoWalletCheck(c: CheckResult): boolean {\n return c.name === 'wallet' && isRecord(c.data) && c.data.credential === 'absent';\n}\n\nfunction walletWarn(err: unknown): CheckResult {\n return {\n name: 'wallet',\n status: 'warn',\n required: false,\n detail: err instanceof Error ? err.message : String(err),\n ...(err instanceof CliError && err.fix !== undefined ? { fix: err.fix } : {}),\n };\n}\n\n/**\n * Balance is best-effort: a zero balance is a fundable warning and an RPC flake\n * must never fail doctor. viem loads only here, via a lazy import, so a doctor\n * run without a wallet never parses the viem chunk.\n */\nasync function checkBalance(address: string, rpcUrl: string): Promise<CheckResult> {\n try {\n const { getUsdcBalance } = await import('../lib/usdc');\n const balance = await getUsdcBalance(address as `0x${string}`, rpcUrl);\n if (balance === 0n) {\n return {\n name: 'balance',\n status: 'warn',\n required: false,\n detail: 'Wallet USDC balance is 0',\n fix: 'Fund it with `tenjin fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.',\n };\n }\n const money = toMoney(balance.toString());\n // Pocket-money posture (roadmap B2): a plaintext-adjacent local key should\n // hold only small change, so a balance over ~$20 is a warn, not an error.\n if (balance > POCKET_MONEY_CEILING_ATOMIC) {\n return {\n name: 'balance',\n status: 'warn',\n required: false,\n detail: `Balance ${money.usd} USDC is above the ~$20 pocket-money ceiling`,\n fix: 'Keep only small change in the CLI wallet; sweep the excess to cold storage.',\n };\n }\n return {\n name: 'balance',\n status: 'ok',\n required: false,\n detail: `Balance ${money.usd} USDC (${money.atomic} atomic)`,\n };\n } catch (err) {\n return {\n name: 'balance',\n status: 'warn',\n required: false,\n detail: `Could not read balance: ${err instanceof Error ? err.message : String(err)}`,\n fix: 'Check rpcUrl or retry; a balance read failure never fails doctor.',\n };\n }\n}\n\nexport function renderDoctorHuman(io: Io, checks: CheckResult[]): string[] {\n const nameWidth = Math.max(...checks.map((c) => c.name.length));\n const lines: string[] = [];\n for (const c of checks) {\n const icon =\n c.status === 'ok'\n ? paint(io, 'green', '✓')\n : c.status === 'warn'\n ? paint(io, 'yellow', '!')\n : paint(io, 'red', '✗');\n // `detail` and `fix` interpolate SERVER-sourced strings (the OpenAPI\n // info.version, a provider's error text), so a newline or ANSI in a hostile\n // deployment's version string could forge extra lines here — including a\n // convincing closing pointer at a URL of its choosing. Sanitize at the render\n // seam: output.ts exempts doctor on the assumption it only paints its OWN\n // text, which has not been true since these lines began carrying server text.\n lines.push(\n `${icon} ${c.name.padEnd(nameWidth)} ${paint(io, 'dim', sanitizeForTerminal(c.detail))}`,\n );\n if (c.status !== 'ok' && c.fix !== undefined) {\n lines.push(` ${paint(io, 'dim', `fix: ${sanitizeForTerminal(c.fix)}`)}`);\n }\n }\n return lines;\n}\n\n/**\n * Color for stderr, honoring NO_COLOR and the target's color depth: styleText\n * takes the stderr stream when it is a genuine Stream (it throws on anything\n * else, so a test/redirected sink falls back to the default plain check).\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\nfunction infoVersion(json: unknown): string | undefined {\n if (!isRecord(json)) return undefined;\n const info = json.info;\n if (!isRecord(info)) return undefined;\n return typeof info.version === 'string' ? info.version : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,cAAc;AACvB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,qBAAqB;AAmE9B,IAAM,8BAA8B;AAWpC,IAAM,0BACJ;AACF,IAAM,iCACJ;AAmDF,eAAsB,oBACpB,KACA,OAAmB,CAAC,GACG;AACvB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,EAAE,QAAQ,OAAO,YAAY,IAAI,MAAM,oBAAoB,IAAI,OAAO;AAC5E,QAAM,WAAW,gBAAgB,EAAE,Q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,UAAU,QAAQ,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC;AACrF,SAAO,UAAU,QAAQ,IAAI;AAC/B;AAEA,SAAS,YAAY,MAAmC;AACtD,MAAI,CAAC,SAAS,IAAI,EAAG,QAAO;AAC5B,QAAM,OAAO,KAAK;AAClB,MAAI,CAAC,SAAS,IAAI,EAAG,QAAO;AAC5B,SAAO,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;AAC3D;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;","names":["data"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/config.ts","../src/lib/ids.ts","../src/lib/money.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { configPath } from './paths';\nimport { HARNESS_TARGETS } from './skill-wiring';\nimport { writeFileAtomic } from './atomic-json';\n\n/** A non-negative integer string in USDC atomic units (6-decimal base). */\nconst atomicString = z.string().regex(/^\\d+$/, 'expected an atomic USDC integer string');\n\n/** The publish consent mode (B3, D38). `full-auto` is loosening-gated, below. */\nexport const PublishModeSchema = z.enum(['review', 'auto', 'full-auto']);\nexport type PublishMode = z.infer<typeof PublishModeSchema>;\n\n/**\n * Validate a publish-mode value at a command edge (`--mode`, `--publish-mode`):\n * an unrecognized value is USAGE (exit 2), never silently dropped. `flagName` is\n * woven into the message so the failing flag is named.\n */\nexport function parsePublishModeFlag(value: string, flagName: string): PublishMode {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The publish block (B3): `mode` governs the confirm cascade a `publish` runs,\n * `defaultPrice` is the atomic USDC price a card is published at when no\n * per-publish price is given. Stored atomic like the spend keys.\n */\nconst PublishConfigSchema = z.object({\n mode: PublishModeSchema,\n defaultPrice: atomicString,\n});\n\n/**\n * What the harness WebSearch hook does when the agent is about to search the web\n * (see lib/hook-scripts.ts). `auto` asks Tenjin first and mentions a tested\n * answer when one exists, `remind` says the marketplace is there without sending\n * the query anywhere, `off` leaves the installed hook inert.\n */\nexport const SearchHookModeSchema = z.enum(['auto', 'remind', 'off']);\nexport type SearchHookMode = z.infer<typeof SearchHookModeSchema>;\n\n/**\n * Validate a search-hook mode at a command edge (`--search-hooks`), the same way\n * publish-mode values are validated: an unrecognized value is USAGE, never a\n * silent fallback to the default.\n */\nexport function parseSearchHookModeFlag(value: string, flagName: string): SearchHookMode {\n const parsed = SearchHookModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"auto\", \"remind\", or \"off\".',\n });\n}\n\n/** Whether the Stop hook may raise an open loop at the end of a turn. */\nexport const StopNagModeSchema = z.enum(['on', 'off']);\nexport type StopNagMode = z.infer<typeof StopNagModeSchema>;\n\nexport function parseStopNagFlag(value: string, flagName: string): StopNagMode {\n const parsed = StopNagModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid ${flagName} ${JSON.stringify(value)}`, {\n fix: 'Use \"on\" or \"off\".',\n });\n}\n\n/**\n * The harness-hook block. BOTH keys are read by the installed scripts at run\n * time, which is what makes them runtime toggles rather than install-time\n * choices: `tenjin config set hooks.searchMode off` or `hooks.stopNag off`\n * silences a hook immediately, with no re-install and nothing to unwire. The\n * scripts stay registered and no-op, which is also what lets turning one back on\n * be a single `config set`.\n */\nconst HooksConfigSchema = z.object({\n searchMode: SearchHookModeSchema,\n stopNag: StopNagModeSchema,\n});\n\n/**\n * What `install` recorded about its OWN targets. `harness` is the explicit\n * `--harness` set of the last install that passed the flag, and it exists so\n * `doctor` keeps judging a directory the user named by hand: detection cannot see a\n * harness this CLI does not probe for, and without the record such a directory is a\n * target for one run and invisible to every later check. Written by `install`, not a\n * `config set` key.\n */\nconst InstallConfigSchema = z.object({\n harness: z.array(z.enum(HARNESS_TARGETS)),\n});\n\n/**\n * The persisted config shape. Spend keys are stored atomic (accepted as decimal\n * USD at the command edge, see lib/money); `confirm` is the stored form\n * \"always\" | \"above:<atomic>\". These are client-enforced guardrails, not a\n * security boundary — any process that runs the CLI can also edit this file.\n */\nexport const ConfigSchema = z.object({\n maxAutoSpend: atomicString,\n sessionBudget: atomicString,\n confirm: z.union([z.literal('always'), z.string().regex(/^above:\\d+$/)]),\n /**\n * Hard per-send cap for `tenjin send`, NOT satisfiable by --yes or a prompt\n * (the spend-policy posture): an atomic amount caps each send, \"0\" disables\n * the verb entirely, and \"none\" = explicitly uncapped (send exists to drain\n * the wallet, but uncapped is an opt-in, never a default). The key has NO\n * usable default: absent from config.json, `tenjin send` refuses until it is\n * set (see resolveSendMaxAmount). Client-enforced like every spend key (see\n * the note above).\n */\n sendMaxAmount: z.union([z.literal('none'), atomicString]),\n allowlistCreators: z.array(z.string()),\n baseUrl: z.url(),\n rpcUrl: z.url(),\n /**\n * Evaluation-cohort opt-in (spec 09 §3): when true, search sends\n * X-Tenjin-Eval-Cohort: 1 and the server stores the generalized question for\n * 90 days. Off by default; no query text is retained server-side without it.\n */\n evalCohort: z.boolean(),\n publish: PublishConfigSchema,\n install: InstallConfigSchema,\n hooks: HooksConfigSchema,\n});\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/**\n * Values as they may appear in config.json — every known key optional; absent =\n * default. `.passthrough()` PRESERVES unknown keys through load + persist: without\n * it an older binary's `config set` would strip (and re-serialize away) any newer\n * block a later CLI wrote, e.g. B3's `publish.*`. Known keys are still validated;\n * unknown keys ride along untouched.\n */\nexport const RawConfigSchema = ConfigSchema.partial()\n // The publish block is itself partial + passthrough: `config set publish.mode`\n // writes only the one subkey, and a subkey a newer CLI adds (e.g. publish.*\n // beyond mode/defaultPrice) survives an older binary's set, same reason the\n // outer object passes unknown keys through.\n .extend({\n publish: PublishConfigSchema.partial().passthrough().optional(),\n install: InstallConfigSchema.partial().passthrough().optional(),\n hooks: HooksConfigSchema.partial().passthrough().optional(),\n })\n .passthrough();\nexport type PartialConfig = z.infer<typeof RawConfigSchema>;\n\n/**\n * The resolved-view sentinel for an absent sendMaxAmount. Never a persistable\n * value (ConfigSchema rejects it, and `config set` has no way to produce it);\n * while the resolved value is this sentinel, `tenjin send` refuses —\n * require-set-before-first-send.\n */\nexport const SEND_MAX_UNSET = 'unset';\n\nexport const CONFIG_DEFAULTS: Config = {\n maxAutoSpend: '0',\n sessionBudget: '0',\n confirm: 'always',\n // A type placeholder only, never honored: Config requires every key (and\n // CONFIG_KEYS derives from these). resolveSendMaxAmount never reads it — an\n // absent key resolves to SEND_MAX_UNSET and `tenjin send` refuses until the\n // cap is set. '0' (send disabled) rather than 'none' (uncapped) so that if a\n // future caller ever DOES read the cap through loadConfig/fileOrDefault, the\n // leak fails closed instead of silently running uncapped.\n sendMaxAmount: '0',\n allowlistCreators: [],\n baseUrl: 'https://tenjin.blog',\n rpcUrl: 'https://mainnet.base.org',\n evalCohort: false,\n publish: { mode: 'review', defaultPrice: '100000' },\n install: { harness: [] },\n // `auto` is the default because the hook exists to be useful without being\n // asked for; the disclosure and the undo ride the install output, and `off`\n // leaves the installed script inert without touching settings.json.\n hooks: { searchMode: 'auto', stopNag: 'on' },\n};\n\n/**\n * Scalar keys `config get/set/list` render one line each. The nested blocks are\n * excluded: `publish` and `hooks` are addressed by their dotted keys (see\n * PUBLISH_CONFIG_KEYS / HOOKS_CONFIG_KEYS), and `install` is a record `install`\n * writes about itself rather than a setting to hand-edit, so none is ever a bare\n * scalar.\n */\nexport type ScalarConfigKey = Exclude<keyof Config, 'publish' | 'install' | 'hooks'>;\nconst NESTED_CONFIG_KEYS: ReadonlySet<string> = new Set(['publish', 'install', 'hooks']);\nexport const CONFIG_KEYS = (Object.keys(CONFIG_DEFAULTS) as Array<keyof Config>).filter(\n (key): key is ScalarConfigKey => !NESTED_CONFIG_KEYS.has(key),\n);\n\n/** The dotted keys `config get/set` accept for the nested publish block. */\nexport const PUBLISH_CONFIG_KEYS = ['publish.mode', 'publish.defaultPrice'] as const;\nexport type PublishConfigKey = (typeof PUBLISH_CONFIG_KEYS)[number];\n\n/** The dotted keys `config get/set` accept for the nested hooks block. */\nexport const HOOKS_CONFIG_KEYS = ['hooks.searchMode', 'hooks.stopNag'] as const;\nexport type HooksConfigKey = (typeof HOOKS_CONFIG_KEYS)[number];\n\n/**\n * Read and validate config.json WITHOUT applying defaults, so provenance can\n * distinguish \"present in file\" from \"absent\". Missing file is fine (returns\n * {}); malformed JSON or a failed schema is CONFIG_INVALID with a fix.\n */\nexport async function loadRawConfig(dir: string): Promise<PartialConfig> {\n const path = configPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return {};\n throw new CliError('CONFIG_INVALID', `Could not read config at ${path}`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `Config at ${path} is not valid JSON`, {\n fix: `Fix the JSON syntax in ${path}, or delete it to restore defaults.`,\n cause: err,\n });\n }\n const parsed = RawConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `Config at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it to restore defaults.`,\n details: parsed.error.issues,\n });\n }\n return parsed.data;\n}\n\n/** File values merged over defaults — the effective persisted config. The nested\n * publish block is merged per-subkey so a file that sets only publish.mode keeps\n * the default defaultPrice (a shallow spread would drop it). */\nexport async function loadConfig(dir: string): Promise<Config> {\n const raw = await loadRawConfig(dir);\n return {\n ...CONFIG_DEFAULTS,\n ...raw,\n publish: {\n mode: raw.publish?.mode ?? CONFIG_DEFAULTS.publish.mode,\n defaultPrice: raw.publish?.defaultPrice ?? CONFIG_DEFAULTS.publish.defaultPrice,\n },\n install: { harness: raw.install?.harness ?? CONFIG_DEFAULTS.install.harness },\n hooks: {\n searchMode: raw.hooks?.searchMode ?? CONFIG_DEFAULTS.hooks.searchMode,\n stopNag: raw.hooks?.stopNag ?? CONFIG_DEFAULTS.hooks.stopNag,\n },\n };\n}\n\nexport type Provenance = 'default' | 'file' | 'project' | 'env' | 'flag';\n\nexport interface ResolvedSetting<T> {\n value: T;\n source: Provenance;\n}\n\n/**\n * The per-project `.tenjin.json` layer (B3, D38): publish overrides discovered by\n * walking up from cwd, plus whether that file is gitignored. `gitignored` gates\n * `full-auto` — a committed file requesting it is downgraded (loosening gate).\n */\nexport interface ProjectPublishLayer {\n publish?: { mode?: PublishMode; defaultPrice?: string };\n gitignored: boolean;\n}\n\n/** publish.mode resolution: value, source, and the downgrade warning (if any). */\nexport interface PublishModeResolution {\n value: PublishMode;\n source: Provenance;\n /** Set when a committed `.tenjin.json`'s `full-auto` was downgraded to `auto`. */\n downgradedWarning?: string;\n}\n\n/** Effective value + where it came from, per key. What `config` (bare) renders. */\nexport interface EffectiveSettings {\n maxAutoSpend: ResolvedSetting<string>;\n sessionBudget: ResolvedSetting<string>;\n confirm: ResolvedSetting<string>;\n sendMaxAmount: ResolvedSetting<string>;\n allowlistCreators: ResolvedSetting<string[]>;\n baseUrl: ResolvedSetting<string>;\n rpcUrl: ResolvedSetting<string>;\n evalCohort: ResolvedSetting<boolean>;\n publishMode: PublishModeResolution;\n publishDefaultPrice: ResolvedSetting<string>;\n hooksSearchMode: ResolvedSetting<SearchHookMode>;\n hooksStopNag: ResolvedSetting<StopNagMode>;\n}\n\n/** CLI flags that participate in settings precedence (`--base-url`). */\nexport interface SettingsFlags {\n baseUrl?: string;\n}\n\nexport interface ResolveSettingsInput {\n /** Raw file values (present keys only) — from loadRawConfig, not loadConfig. */\n config: PartialConfig;\n flags: SettingsFlags;\n env: NodeJS.ProcessEnv;\n /** The nearest `.tenjin.json` layer, when one was found (see publish-settings). */\n project?: ProjectPublishLayer;\n}\n\n/**\n * Apply precedence flag > env > file > default per key, returning each effective\n * value with its source. In B1 only baseUrl has flag/env overrides\n * (`--base-url`, TENJIN_BASE_URL); the rest resolve file-or-default. B3 adds the\n * publish keys, which additionally fold in the per-project `.tenjin.json` layer.\n */\nexport function resolveSettings(input: ResolveSettingsInput): EffectiveSettings {\n const { config, flags, env, project } = input;\n return {\n maxAutoSpend: fileOrDefault('maxAutoSpend', config),\n sessionBudget: fileOrDefault('sessionBudget', config),\n confirm: fileOrDefault('confirm', config),\n sendMaxAmount: resolveSendMaxAmount(config),\n allowlistCreators: fileOrDefault('allowlistCreators', config),\n baseUrl: resolveBaseUrl(config, flags, env),\n rpcUrl: fileOrDefault('rpcUrl', config),\n evalCohort: fileOrDefault('evalCohort', config),\n publishMode: resolvePublishMode({ config, project, env }),\n publishDefaultPrice: resolvePublishDefaultPrice({ config, project }),\n hooksSearchMode: resolveHooksSearchMode(config),\n hooksStopNag: resolveHooksStopNag(config),\n };\n}\n\n/** hooks.stopNag: file or default, same shape as hooks.searchMode. */\nfunction resolveHooksStopNag(config: PartialConfig): ResolvedSetting<StopNagMode> {\n const fromFile = config.hooks?.stopNag;\n if (fromFile !== undefined) return { value: fromFile, source: 'file' };\n return { value: CONFIG_DEFAULTS.hooks.stopNag, source: 'default' };\n}\n\n/** hooks.searchMode: file or default. No env, flag, or project layer, because the\n * installed hook script reads the global file directly and has no CLI edge. */\nfunction resolveHooksSearchMode(config: PartialConfig): ResolvedSetting<SearchHookMode> {\n const fromFile = config.hooks?.searchMode;\n if (fromFile !== undefined) return { value: fromFile, source: 'file' };\n return { value: CONFIG_DEFAULTS.hooks.searchMode, source: 'default' };\n}\n\n/**\n * The loosening gate (D38): a committed (not-gitignored) `.tenjin.json` requesting\n * `full-auto` is downgraded to `auto`, never silently honored — cloning a repo\n * must not enable auto-publish. `full-auto` from global config / env / flag (all\n * inherently local, not cloned) is always honored.\n */\nconst FULL_AUTO_DOWNGRADE_WARNING =\n 'Ignoring publish.mode \"full-auto\" from a committed .tenjin.json (cloning a repo must not enable auto-publish); using \"auto\". Add .tenjin.json to .gitignore to opt in.';\n\nfunction coercePublishMode(raw: string | undefined): PublishMode | undefined {\n if (raw === undefined || raw.length === 0) return undefined;\n const parsed = PublishModeSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/**\n * Resolve publish.mode through global file < project `.tenjin.json` < env\n * (TENJIN_PUBLISH_MODE) < flag (`--mode`). Total: an invalid env/flag value is\n * ignored (validation lives at the command edge, like baseUrl). The project\n * layer's `full-auto` is gated on that file being gitignored.\n */\nexport function resolvePublishMode(input: {\n config: PartialConfig;\n project?: ProjectPublishLayer;\n env: NodeJS.ProcessEnv;\n flag?: string;\n}): PublishModeResolution {\n const { config, project, env, flag } = input;\n let winner: PublishModeResolution = { value: CONFIG_DEFAULTS.publish.mode, source: 'default' };\n\n const fromFile = config.publish?.mode;\n if (fromFile !== undefined) winner = { value: fromFile, source: 'file' };\n\n if (project !== undefined && project.publish?.mode !== undefined) {\n const fromProject = project.publish.mode;\n if (fromProject === 'full-auto' && !project.gitignored) {\n winner = { value: 'auto', source: 'project', downgradedWarning: FULL_AUTO_DOWNGRADE_WARNING };\n } else {\n winner = { value: fromProject, source: 'project' };\n }\n }\n\n const fromEnv = coercePublishMode(env.TENJIN_PUBLISH_MODE);\n if (fromEnv !== undefined) winner = { value: fromEnv, source: 'env' };\n\n const fromFlag = coercePublishMode(flag);\n if (fromFlag !== undefined) winner = { value: fromFlag, source: 'flag' };\n\n return winner;\n}\n\n/** Resolve publish.defaultPrice (atomic) through global file < project < default. */\nexport function resolvePublishDefaultPrice(input: {\n config: PartialConfig;\n project?: ProjectPublishLayer;\n}): ResolvedSetting<string> {\n const { config, project } = input;\n let result: ResolvedSetting<string> = {\n value: CONFIG_DEFAULTS.publish.defaultPrice,\n source: 'default',\n };\n if (config.publish?.defaultPrice !== undefined) {\n result = { value: config.publish.defaultPrice, source: 'file' };\n }\n if (project?.publish?.defaultPrice !== undefined) {\n result = { value: project.publish.defaultPrice, source: 'project' };\n }\n return result;\n}\n\n/** Persist a full, validated config via the atomic writer (0700 dir, 0644 file). */\nexport async function writeConfig(dir: string, config: Config): Promise<void> {\n const validated = ConfigSchema.parse(config);\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o700,\n });\n}\n\n/**\n * sendMaxAmount deliberately bypasses fileOrDefault: it has no usable default\n * (the operator's require-set-before-first-send posture). Absent from\n * config.json it resolves to the SEND_MAX_UNSET sentinel with source 'default',\n * which `tenjin send` refuses outright — the cap must be set to an amount, \"0\"\n * (disable), or an explicit \"none\" (uncapped opt-in) before the first send.\n */\nfunction resolveSendMaxAmount(config: PartialConfig): ResolvedSetting<string> {\n if (config.sendMaxAmount !== undefined) return { value: config.sendMaxAmount, source: 'file' };\n return { value: SEND_MAX_UNSET, source: 'default' };\n}\n\nfunction fileOrDefault<K extends keyof Config>(\n key: K,\n config: PartialConfig,\n): ResolvedSetting<Config[K]> {\n const fromFile = config[key];\n // PartialConfig[K] is Config[K] | undefined; narrowing an indexed access of a\n // type parameter doesn't refine K, so assert the excluded-undefined type.\n if (fromFile !== undefined) return { value: fromFile as Config[K], source: 'file' };\n return { value: CONFIG_DEFAULTS[key], source: 'default' };\n}\n\nfunction resolveBaseUrl(\n config: PartialConfig,\n flags: SettingsFlags,\n env: NodeJS.ProcessEnv,\n): ResolvedSetting<string> {\n if (flags.baseUrl !== undefined && flags.baseUrl.length > 0) {\n return { value: flags.baseUrl, source: 'flag' };\n }\n const fromEnv = env.TENJIN_BASE_URL;\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return { value: fromEnv, source: 'env' };\n }\n if (config.baseUrl !== undefined) return { value: config.baseUrl, source: 'file' };\n return { value: CONFIG_DEFAULTS.baseUrl, source: 'default' };\n}\n\nfunction isNotFound(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code?: unknown }).code === 'ENOENT'\n );\n}\n","/**\n * The shared identity patterns for server-controlled values that become file\n * paths, URL segments, or terminal output. One definition so a future change\n * (e.g. accepting uppercase ids) cannot be applied in one command and missed in\n * another. SLUG_RE must match the server's slugify charset (lib/posts.ts:\n * lowercase a-z0-9 groups joined by single hyphens, no leading/trailing hyphen).\n */\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n/** A non-negative atomic USDC integer string (6-decimal base units). */\nexport const ATOMIC_RE = /^\\d{1,39}$/;\n","import { CliError } from './errors';\nimport { ATOMIC_RE } from './ids';\nimport type { Money } from '../schemas';\n\n/** USDC is a 6-decimal token; one dollar is 1_000_000 atomic units. */\nconst USDC_DECIMALS = 6;\n\n/**\n * Decimal USD at the CLI edge -> atomic USDC string (O1). Accepts \"0\", \"0.25\",\n * \"5\"; rejects negatives, non-numeric input, and more than 6 decimal places as\n * USAGE so a fat-fingered amount fails loudly instead of truncating money.\n * String math throughout — a float would lose precision at the 6th decimal.\n */\nexport function parseUsdToAtomic(input: string): string {\n const trimmed = input.trim();\n if (!/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n throw new CliError('USAGE', `Invalid USD amount: ${JSON.stringify(input)}`, {\n fix: 'Pass a non-negative decimal like 0.25 or 5.',\n });\n }\n const [whole, frac = ''] = trimmed.split('.');\n if (frac.length > USDC_DECIMALS) {\n throw new CliError(\n 'USAGE',\n `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,\n {\n fix: 'USDC supports at most 6 decimal places (micro-dollars).',\n },\n );\n }\n const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, '0')}`);\n return atomic.toString();\n}\n\n/**\n * Atomic USDC string -> decimal USD string, trailing zeros trimmed (\"250000\" ->\n * \"0.25\", \"5000000\" -> \"5\", \"0\" -> \"0\"). Throws INTERNAL on a malformed atomic\n * value: atomic strings come from validated config or on-chain reads, so a bad\n * one is a bug, not user input.\n */\nexport function atomicToUsd(atomic: string): string {\n const trimmed = atomic.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new CliError('INTERNAL', `Malformed atomic amount: ${JSON.stringify(atomic)}`);\n }\n const value = BigInt(trimmed);\n const base = 10n ** BigInt(USDC_DECIMALS);\n const whole = value / base;\n const frac = (value % base).toString().padStart(USDC_DECIMALS, '0').replace(/0+$/, '');\n return frac.length > 0 ? `${whole}.${frac}` : whole.toString();\n}\n\n/**\n * Whether an atomic price would actually cost something: true paid, false free,\n * null when the string is not an atomic amount at all and so cannot answer.\n *\n * A Tenjin piece may be priced at zero and is then delivered by `read` with no\n * payment, so \"there is a price field\" and \"there is a purchase to make\" are\n * different questions. The third state is not decoration: only the wire schema\n * enforces ATOMIC_RE, and the local search store types `price` as a bare string,\n * so a hand-edited or half-written entry can hold \"-1\" or \"0.1\". Those must not\n * read as \"free\", or corrupt local data would start refusing honest reports.\n * Never throws, which is why the check is a regex and not a BigInt compare.\n *\n * Matched against the RAW string, with no trimming. The contract carries the\n * canonical form and nothing else, so \" 0 \" did not come off the wire; padding is\n * evidence the value was edited, and normalizing it away would launder a corrupt\n * entry into a confident \"free\" and hand back the false refusal this avoids.\n */\nexport function isPaidPrice(atomic: string): boolean | null {\n if (!ATOMIC_RE.test(atomic)) return null;\n return /[1-9]/.test(atomic);\n}\n\n/** Dual-form money object for machine output. */\nexport function toMoney(atomic: string): Money {\n return { atomic, usd: atomicToUsd(atomic) };\n}\n\n/**\n * Canonical USD for human COPY (a price a person reads): always at least two\n * decimals (\"0.10\", \"5.00\"), keeping any finer precision below a cent\n * (\"0.000001\"). Distinct from `atomicToUsd`, which trims to the shortest exact\n * form for machine output; use this only where a dollar amount is shown to a human.\n */\nexport function formatUsdDisplay(atomic: string): string {\n const [whole, frac = ''] = atomicToUsd(atomic).split('.');\n return `${whole}.${frac.padEnd(2, '0')}`;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAQzB,I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AQ;AACtB,QAAM,QAAQ,QAAQ,MAAM,SAAS,EAAE,SAAS,eAAe,GAAG,EAAE,QAAQ,OAAO,EAAE;AACrF,SAAO,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,MAAM,SAAS;AAC/D;AAmBO,SAAS,YAAY,QAAgC;AAC1D,MAAI,CAAC,UAAU,KAAK,MAAM,EAAG,QAAO;AACpC,SAAO,QAAQ,KAAK,MAAM;AAC5B;AAGO,SAAS,QAAQ,QAAuB;AAC7C,SAAO,EAAE,QAAQ,KAAK,YAAY,MAAM,EAAE;AAC5C;AAQO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,YAAY,MAAM,EAAE,MAAM,GAAG;AACxD,SAAO,GAAG,KAAK,IAAI,KAAK,OAAO,GAAG,GAAG,CAAC;AACxC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { styleText } from 'node:util';\nimport { Stream } from 'node:stream';\nimport { CliError } from './errors';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY fact. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` is the real terminal fact; the separate `--json` flag (passed to the\n * emit functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output.\n */\nexport interface Io {\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(command: string, data: unknown): SuccessEnvelope {\n return { schemaVersion: SCHEMA_VERSION, command, ok: true, data };\n}\n\nexport function buildFailureEnvelope(command: string, err: CliError): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return { schemaVersion: SCHEMA_VERSION, command, ok: false, error };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them an\n // interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees the\n // count but not WHICH lines tripped. Every other details shape stays machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n // eslint-disable-next-line no-control-regex\n .replace(/\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt } = f as { check?: unknown; line?: unknown; excerpt?: unknown };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n rendered.push(paint(io, 'dim', ` ${check} (line ${line}): ${sanitizeForTerminal(excerpt)}`));\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\n/**\n * Color a human line for stdout (the human surface now). styleText emits ANSI only\n * when the target stream is color-capable (a real TTY with color depth) and honors\n * NO_COLOR/FORCE_COLOR natively. The `stream` option is passed only when stdout is\n * a genuine Stream; a test/redirected sink is not one, so it falls back to the\n * default capability check and comes out plain.\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","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discrimin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