tenjin-cli 0.1.0-alpha.11 → 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 (131) hide show
  1. package/README.md +236 -596
  2. package/dist/{buy-THMVOPUH.js → buy-X4VPHFUA.js} +20 -20
  3. package/dist/{chunk-GKV6VZSZ.js → chunk-3NZCU6SD.js} +7 -7
  4. package/dist/chunk-3NZCU6SD.js.map +1 -0
  5. package/dist/{chunk-Y7ERTA7D.js → chunk-3P3ES4XU.js} +4 -6
  6. package/dist/chunk-3P3ES4XU.js.map +1 -0
  7. package/dist/{chunk-OZHJ3FLR.js → chunk-47YKYDOF.js} +5 -5
  8. package/dist/{chunk-IXTENA2H.js → chunk-6JKD46OJ.js} +12 -10
  9. package/dist/{chunk-IXTENA2H.js.map → chunk-6JKD46OJ.js.map} +1 -1
  10. package/dist/chunk-736DW4V3.js +65 -0
  11. package/dist/chunk-736DW4V3.js.map +1 -0
  12. package/dist/{chunk-IB63U6BM.js → chunk-B676GPS2.js} +34 -11
  13. package/dist/chunk-B676GPS2.js.map +1 -0
  14. package/dist/{chunk-4NTZETIL.js → chunk-BRAVLUGI.js} +2 -2
  15. package/dist/{chunk-UY6CGULW.js → chunk-CA3JV7FX.js} +2 -2
  16. package/dist/{chunk-UY6CGULW.js.map → chunk-CA3JV7FX.js.map} +1 -1
  17. package/dist/{chunk-ALUNME53.js → chunk-ELVDOTU7.js} +50 -66
  18. package/dist/chunk-ELVDOTU7.js.map +1 -0
  19. package/dist/{chunk-IAFYUFIC.js → chunk-GCGMXA2O.js} +13 -11
  20. package/dist/{chunk-IAFYUFIC.js.map → chunk-GCGMXA2O.js.map} +1 -1
  21. package/dist/{chunk-XWHXX2BI.js → chunk-IAR25V2E.js} +6 -6
  22. package/dist/{chunk-6UY2UQMY.js → chunk-IFPKA32J.js} +4 -4
  23. package/dist/{chunk-JTYIX6OD.js → chunk-IGHSLJUF.js} +6 -4
  24. package/dist/{chunk-JTYIX6OD.js.map → chunk-IGHSLJUF.js.map} +1 -1
  25. package/dist/{chunk-2SDUV6MQ.js → chunk-IKAJSA7E.js} +12 -10
  26. package/dist/{chunk-2SDUV6MQ.js.map → chunk-IKAJSA7E.js.map} +1 -1
  27. package/dist/{chunk-NUF2PKJO.js → chunk-J6FUAIRR.js} +4 -6
  28. package/dist/{chunk-NUF2PKJO.js.map → chunk-J6FUAIRR.js.map} +1 -1
  29. package/dist/{chunk-CNUXRXI2.js → chunk-JVBMPU5G.js} +5 -7
  30. package/dist/{chunk-CNUXRXI2.js.map → chunk-JVBMPU5G.js.map} +1 -1
  31. package/dist/{chunk-VWY3U732.js → chunk-L4XNT3UW.js} +21 -16
  32. package/dist/chunk-L4XNT3UW.js.map +1 -0
  33. package/dist/{chunk-EDVI7RRD.js → chunk-NKN4YC5C.js} +6 -6
  34. package/dist/{chunk-EDVI7RRD.js.map → chunk-NKN4YC5C.js.map} +1 -1
  35. package/dist/{chunk-P74I3WH4.js → chunk-OC3EIDCP.js} +3 -5
  36. package/dist/{chunk-P74I3WH4.js.map → chunk-OC3EIDCP.js.map} +1 -1
  37. package/dist/{chunk-E6YOODH7.js → chunk-OE36HRWG.js} +31 -5
  38. package/dist/{chunk-E6YOODH7.js.map → chunk-OE36HRWG.js.map} +1 -1
  39. package/dist/chunk-OUJDDY5L.js +189 -0
  40. package/dist/chunk-OUJDDY5L.js.map +1 -0
  41. package/dist/{chunk-6BGYHARE.js → chunk-OWVVI4VQ.js} +15 -15
  42. package/dist/{chunk-4TCU3YRD.js → chunk-OXUJ3FXU.js} +5 -1
  43. package/dist/{chunk-4TCU3YRD.js.map → chunk-OXUJ3FXU.js.map} +1 -1
  44. package/dist/{chunk-PZRAAAY2.js → chunk-PAOVPSP6.js} +10 -3
  45. package/dist/chunk-PAOVPSP6.js.map +1 -0
  46. package/dist/{chunk-3GSZUADW.js → chunk-SPUORKD7.js} +3 -3
  47. package/dist/{chunk-UFPJBS4C.js → chunk-T4UWMVKV.js} +9 -7
  48. package/dist/{chunk-UFPJBS4C.js.map → chunk-T4UWMVKV.js.map} +1 -1
  49. package/dist/{chunk-GUUAYR3K.js → chunk-TXVC46SA.js} +8 -8
  50. package/dist/chunk-TXVC46SA.js.map +1 -0
  51. package/dist/{chunk-SFGXAZ3M.js → chunk-UUARTUY2.js} +42 -9
  52. package/dist/chunk-UUARTUY2.js.map +1 -0
  53. package/dist/{chunk-ZE7KOO7A.js → chunk-WMFRCSNC.js} +8 -8
  54. package/dist/{chunk-TDDN5GXR.js → chunk-WU5CZPLD.js} +5 -5
  55. package/dist/{chunk-RSBN67PA.js → chunk-WVHPGQH5.js} +4 -6
  56. package/dist/{chunk-RSBN67PA.js.map → chunk-WVHPGQH5.js.map} +1 -1
  57. package/dist/{chunk-PZSUWDF2.js → chunk-XGZ5EVMB.js} +2 -2
  58. package/dist/{chunk-O25VWJCG.js → chunk-XXY77EZJ.js} +24 -24
  59. package/dist/{chunk-OCN27NJV.js → chunk-YMUJZWHB.js} +10 -8
  60. package/dist/{chunk-OCN27NJV.js.map → chunk-YMUJZWHB.js.map} +1 -1
  61. package/dist/{cli-Y2HBOSGK.js → cli-XK5JZWU6.js} +51 -146
  62. package/dist/cli-XK5JZWU6.js.map +1 -0
  63. package/dist/{config-WDGMZKHU.js → config-CNK7MYUR.js} +7 -7
  64. package/dist/doctor-R7N7FUX5.js +27 -0
  65. package/dist/{edit-E7N6F3OY.js → edit-QSUEG7CL.js} +19 -19
  66. package/dist/{fund-OKK627GL.js → fund-JF6A76YS.js} +16 -16
  67. package/dist/index.js +1 -1
  68. package/dist/{inspect-573WHEV4.js → inspect-NFNAA4LA.js} +17 -17
  69. package/dist/{install-SQAYMNQC.js → install-YQVM3SUW.js} +20 -21
  70. package/dist/{install-SQAYMNQC.js.map → install-YQVM3SUW.js.map} +1 -1
  71. package/dist/outcome-IUSYFJTN.js +22 -0
  72. package/dist/{publish-N5U4XYVA.js → publish-O2I6IAEL.js} +20 -20
  73. package/dist/{read-PJ7Z6UGF.js → read-UF7QVQOU.js} +21 -21
  74. package/dist/{run-FSO3MMXN.js → run-GDZWHNWZ.js} +30 -30
  75. package/dist/search-JVOHEF3E.js +23 -0
  76. package/dist/{send-F34ZDXDZ.js → send-SI254H3R.js} +11 -10
  77. package/dist/{send-F34ZDXDZ.js.map → send-SI254H3R.js.map} +1 -1
  78. package/dist/{session-4N4ZT3AH.js → session-GJZJEXLJ.js} +14 -14
  79. package/dist/{skill-heal-XBEK272G.js → skill-heal-BPFT22XS.js} +5 -6
  80. package/dist/{skill-heal-XBEK272G.js.map → skill-heal-BPFT22XS.js.map} +1 -1
  81. package/dist/{uninstall-BTKPHPDL.js → uninstall-7ZZG6WQ5.js} +6 -7
  82. package/dist/{uninstall-BTKPHPDL.js.map → uninstall-7ZZG6WQ5.js.map} +1 -1
  83. package/dist/update-FPSBITLB.js +315 -0
  84. package/dist/update-FPSBITLB.js.map +1 -0
  85. package/dist/{wallet-UL4P2JRO.js → wallet-NS7TYWNN.js} +5 -6
  86. package/dist/{wallet-WJ6UP5OU.js → wallet-TZVD2M4I.js} +9 -9
  87. package/docs/agent-permissions.md +13 -2
  88. package/docs/command-reference.md +251 -0
  89. package/docs/safety-model.md +45 -0
  90. package/package.json +1 -1
  91. package/skills/tenjin/SKILL.md +3 -3
  92. package/skills/tenjin-publish/SKILL.md +27 -11
  93. package/skills/tenjin-search/SKILL.md +14 -13
  94. package/dist/chunk-2I4QTOLB.js +0 -11
  95. package/dist/chunk-2I4QTOLB.js.map +0 -1
  96. package/dist/chunk-ALUNME53.js.map +0 -1
  97. package/dist/chunk-GKV6VZSZ.js.map +0 -1
  98. package/dist/chunk-GUUAYR3K.js.map +0 -1
  99. package/dist/chunk-IB63U6BM.js.map +0 -1
  100. package/dist/chunk-PZRAAAY2.js.map +0 -1
  101. package/dist/chunk-SFGXAZ3M.js.map +0 -1
  102. package/dist/chunk-VWY3U732.js.map +0 -1
  103. package/dist/chunk-Y7ERTA7D.js.map +0 -1
  104. package/dist/cli-Y2HBOSGK.js.map +0 -1
  105. package/dist/doctor-CSIWKWM2.js +0 -27
  106. package/dist/outcome-W3KYGF23.js +0 -22
  107. package/dist/search-ZWOP4EGK.js +0 -23
  108. /package/dist/{buy-THMVOPUH.js.map → buy-X4VPHFUA.js.map} +0 -0
  109. /package/dist/{chunk-OZHJ3FLR.js.map → chunk-47YKYDOF.js.map} +0 -0
  110. /package/dist/{chunk-4NTZETIL.js.map → chunk-BRAVLUGI.js.map} +0 -0
  111. /package/dist/{chunk-XWHXX2BI.js.map → chunk-IAR25V2E.js.map} +0 -0
  112. /package/dist/{chunk-6UY2UQMY.js.map → chunk-IFPKA32J.js.map} +0 -0
  113. /package/dist/{chunk-6BGYHARE.js.map → chunk-OWVVI4VQ.js.map} +0 -0
  114. /package/dist/{chunk-3GSZUADW.js.map → chunk-SPUORKD7.js.map} +0 -0
  115. /package/dist/{chunk-ZE7KOO7A.js.map → chunk-WMFRCSNC.js.map} +0 -0
  116. /package/dist/{chunk-TDDN5GXR.js.map → chunk-WU5CZPLD.js.map} +0 -0
  117. /package/dist/{chunk-PZSUWDF2.js.map → chunk-XGZ5EVMB.js.map} +0 -0
  118. /package/dist/{chunk-O25VWJCG.js.map → chunk-XXY77EZJ.js.map} +0 -0
  119. /package/dist/{config-WDGMZKHU.js.map → config-CNK7MYUR.js.map} +0 -0
  120. /package/dist/{doctor-CSIWKWM2.js.map → doctor-R7N7FUX5.js.map} +0 -0
  121. /package/dist/{edit-E7N6F3OY.js.map → edit-QSUEG7CL.js.map} +0 -0
  122. /package/dist/{fund-OKK627GL.js.map → fund-JF6A76YS.js.map} +0 -0
  123. /package/dist/{inspect-573WHEV4.js.map → inspect-NFNAA4LA.js.map} +0 -0
  124. /package/dist/{outcome-W3KYGF23.js.map → outcome-IUSYFJTN.js.map} +0 -0
  125. /package/dist/{publish-N5U4XYVA.js.map → publish-O2I6IAEL.js.map} +0 -0
  126. /package/dist/{read-PJ7Z6UGF.js.map → read-UF7QVQOU.js.map} +0 -0
  127. /package/dist/{run-FSO3MMXN.js.map → run-GDZWHNWZ.js.map} +0 -0
  128. /package/dist/{search-ZWOP4EGK.js.map → search-JVOHEF3E.js.map} +0 -0
  129. /package/dist/{session-4N4ZT3AH.js.map → session-GJZJEXLJ.js.map} +0 -0
  130. /package/dist/{wallet-UL4P2JRO.js.map → wallet-NS7TYWNN.js.map} +0 -0
  131. /package/dist/{wallet-WJ6UP5OU.js.map → wallet-TZVD2M4I.js.map} +0 -0
@@ -1,22 +1,22 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  fetchRead
4
- } from "./chunk-ZE7KOO7A.js";
4
+ } from "./chunk-WMFRCSNC.js";
5
5
  import {
6
6
  headingOutline
7
7
  } from "./chunk-SGK2B724.js";
8
8
  import {
9
9
  resolveResourceRef
10
- } from "./chunk-6UY2UQMY.js";
10
+ } from "./chunk-IFPKA32J.js";
11
11
  import {
12
12
  sanitizeForTerminal
13
- } from "./chunk-IB63U6BM.js";
13
+ } from "./chunk-B676GPS2.js";
14
14
  import {
15
15
  resolveContextSettings
16
- } from "./chunk-JTYIX6OD.js";
16
+ } from "./chunk-IGHSLJUF.js";
17
17
  import {
18
18
  toMoney
19
- } from "./chunk-ALUNME53.js";
19
+ } from "./chunk-736DW4V3.js";
20
20
 
21
21
  // src/commands/inspect.ts
22
22
  async function runInspect(args, ctx, deps = {}) {
@@ -146,4 +146,4 @@ function freshness(card) {
146
146
  export {
147
147
  runInspect
148
148
  };
149
- //# sourceMappingURL=chunk-XWHXX2BI.js.map
149
+ //# sourceMappingURL=chunk-IAR25V2E.js.map
@@ -1,16 +1,16 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  findStoredCandidate
4
- } from "./chunk-4NTZETIL.js";
4
+ } from "./chunk-BRAVLUGI.js";
5
5
  import {
6
6
  SLUG_RE,
7
7
  UUID_RE
8
- } from "./chunk-ALUNME53.js";
8
+ } from "./chunk-736DW4V3.js";
9
9
  import {
10
10
  CliError,
11
11
  external_exports,
12
12
  writeFileAtomic
13
- } from "./chunk-PZRAAAY2.js";
13
+ } from "./chunk-PAOVPSP6.js";
14
14
 
15
15
  // src/lib/library.ts
16
16
  import { createHash } from "crypto";
@@ -210,4 +210,4 @@ export {
210
210
  assertOnBaseOrigin,
211
211
  resolveResourceRef
212
212
  };
213
- //# sourceMappingURL=chunk-6UY2UQMY.js.map
213
+ //# sourceMappingURL=chunk-IFPKA32J.js.map
@@ -2,19 +2,21 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  parseConfirmPolicy
4
4
  } from "./chunk-FKSAUOJU.js";
5
+ import {
6
+ parseUsdToAtomic
7
+ } from "./chunk-736DW4V3.js";
5
8
  import {
6
9
  PublishModeSchema,
7
10
  SEND_MAX_UNSET,
8
11
  loadRawConfig,
9
- parseUsdToAtomic,
10
12
  resolvePublishDefaultPrice,
11
13
  resolvePublishMode,
12
14
  resolveSettings
13
- } from "./chunk-ALUNME53.js";
15
+ } from "./chunk-ELVDOTU7.js";
14
16
  import {
15
17
  CliError,
16
18
  external_exports
17
- } from "./chunk-PZRAAAY2.js";
19
+ } from "./chunk-PAOVPSP6.js";
18
20
 
19
21
  // src/lib/settings.ts
20
22
  import { execFile } from "child_process";
@@ -158,4 +160,4 @@ export {
158
160
  resolvePublishSettings,
159
161
  loadProjectConfig
160
162
  };
161
- //# sourceMappingURL=chunk-JTYIX6OD.js.map
163
+ //# sourceMappingURL=chunk-IGHSLJUF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type { Provenance, ProjectPublishLayer, PublishMode } from './config';\nimport { parseUsdToAtomic } from './money';\nimport { parseConfirmPolicy, type SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /**\n * Hard per-send cap for `tenjin send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n return {\n baseUrl: s.baseUrl.value,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: BigInt(s.sessionBudget.value),\n confirm: parseConfirmPolicy(s.confirm.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const homeDir = deps.homeDir ?? homedir();\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n const candidate = join(dir, PROJECT_CONFIG_FILE);\n if (await pathExists(candidate)) {\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n return candidate;\n }\n }\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). Shared with the candidate command's\n * repo-root walk so the two `.git`/file probes stay one implementation. */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAmC9B,eAAsB,uBAAuB,KAAgD;AAC3F,QAAM,SAAS,MAAM,cAAc,IAAI,OAAO;AAC9C,QAAM,IAAI,gBAAgB,EAAE,QAAQ,OAAO,EAAE,SAAS,IAAI,MAAM,QAAQ,GAAG,KAAK,QAAQ,IAAI,CAAC;AAC7F,SAAO;AAAA,IACL,SAAS,EAAE,QAAQ;AAAA,IACnB,QAAQ,EAAE,OAAO;AAAA,IACjB,YAAY,EAAE,WAAW;AAAA,IACzB,qBACE,EAAE,cAAc,UAAU,iBACtB,iBACA,EAAE,cAAc,UAAU,SACxB,OACA,OAAO,EAAE,cAAc,KAAK;AAAA,IACpC,QAAQ;AAAA,MACN,oBAAoB,OAAO,EAAE,aAAa,KAAK;AAAA,MAC/C,qBAAqB,OAAO,EAAE,cAAc,KAAK;AAAA,MACjD,SAAS,mBAAmB,EAAE,QAAQ,KAAK;AAAA,MAC3C,mBAAmB,EAAE,kBAAkB;AAAA,IACzC;AAAA,EACF;AACF;AAa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O;AAAA,MACT;AAAA,IACF;AACA,QAAI,MAAM,WAAW,KAAK,KAAK,MAAM,CAAC,EAAG,QAAO;AAChD,QAAI,QAAQ,QAAS,QAAO;AAC5B,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK,QAAO;AAC3B,UAAM;AAAA,EACR;AACF;AAOA,eAAe,sBAAsB,UAAoC;AACvE,QAAM,MAAM,QAAQ,SAAS;AAC7B,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI;AACF,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQ,QAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type { Provenance, ProjectPublishLayer, PublishMode } from './config';\nimport { parseUsdToAtomic } from './money';\nimport { parseConfirmPolicy, type SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /**\n * Hard per-send cap for `tenjin send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n return {\n baseUrl: s.baseUrl.value,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: BigInt(s.sessionBudget.value),\n confirm: parseConfirmPolicy(s.confirm.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const homeDir = deps.homeDir ?? homedir();\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n const candidate = join(dir, PROJECT_CONFIG_FILE);\n if (await pathExists(candidate)) {\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n return candidate;\n }\n }\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). Shared with the candidate command's\n * repo-root walk so the two `.git`/file probes stay one implementation. */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAmC9B,eAAsB,uBAAuB,KAAgD;AAC3F,QAAM,SAAS,MAAM,cAAc,IAAI,OAAO;AAC9C,QAAM,IAAI,gBAAgB,EAAE,QAAQ,OAAO,EAAE,SAAS,IAAI,MAAM,QAAQ,GAAG,KAAK,QAAQ,IAAI,CAAC;AAC7F,SAAO;AAAA,IACL,SAAS,EAAE,QAAQ;AAAA,IACnB,QAAQ,EAAE,OAAO;AAAA,IACjB,YAAY,EAAE,WAAW;AAAA,IACzB,qBACE,EAAE,cAAc,UAAU,iBACtB,iBACA,EAAE,cAAc,UAAU,SACxB,OACA,OAAO,EAAE,cAAc,KAAK;AAAA,IACpC,QAAQ;AAAA,MACN,oBAAoB,OAAO,EAAE,aAAa,KAAK;AAAA,MAC/C,qBAAqB,OAAO,EAAE,cAAc,KAAK;AAAA,MACjD,SAAS,mBAAmB,EAAE,QAAQ,KAAK;AAAA,MAC3C,mBAAmB,EAAE,kBAAkB;AAAA,IACzC;AAAA,EACF;AACF;AAaO,IAAM,sBAAsB;AAUnC,IAAM,sBAAsB,iBACzB,OAAO;AAAA,EACN,SAAS,iBACN,OAAO;AAAA,IACN,MAAM,kBAAkB,SAAS;AAAA,IACjC,cAAc,iBAAE,OAAO,EAAE,SAAS;AAAA,EACpC,CAAC,EACA,YAAY,EACZ,SAAS;AACd,CAAC,EACA,YAAY;AAoCf,eAAsB,uBACpB,OACA,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M,MAAM,QAAQ,SAAS;AAC7B,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI;AACF,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQ,QAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -16,38 +16,40 @@ import {
16
16
  resolveWriteAuth,
17
17
  scan,
18
18
  writeModeNotices
19
- } from "./chunk-IAFYUFIC.js";
19
+ } from "./chunk-GCGMXA2O.js";
20
20
  import {
21
21
  headingOutline
22
22
  } from "./chunk-SGK2B724.js";
23
23
  import {
24
24
  loadSearches,
25
25
  markSearchResolved
26
- } from "./chunk-4NTZETIL.js";
26
+ } from "./chunk-BRAVLUGI.js";
27
27
  import {
28
28
  describeWallet,
29
29
  resolveWalletProvider
30
- } from "./chunk-CNUXRXI2.js";
30
+ } from "./chunk-JVBMPU5G.js";
31
31
  import {
32
32
  trimSlash
33
- } from "./chunk-PZSUWDF2.js";
33
+ } from "./chunk-XGZ5EVMB.js";
34
34
  import {
35
35
  sanitizeForTerminal,
36
36
  sanitizeWireText
37
- } from "./chunk-IB63U6BM.js";
37
+ } from "./chunk-B676GPS2.js";
38
38
  import {
39
39
  resolveContextSettings,
40
40
  resolvePublishSettings
41
- } from "./chunk-JTYIX6OD.js";
41
+ } from "./chunk-IGHSLJUF.js";
42
42
  import {
43
43
  UUID_RE,
44
- parsePublishModeFlag,
45
44
  parseUsdToAtomic,
46
45
  toMoney
47
- } from "./chunk-ALUNME53.js";
46
+ } from "./chunk-736DW4V3.js";
47
+ import {
48
+ parsePublishModeFlag
49
+ } from "./chunk-ELVDOTU7.js";
48
50
  import {
49
51
  CliError
50
- } from "./chunk-PZRAAAY2.js";
52
+ } from "./chunk-PAOVPSP6.js";
51
53
 
52
54
  // src/commands/publish.ts
53
55
  import { readFile } from "fs/promises";
@@ -349,4 +351,4 @@ function confirmMessage(warnCount, priceUsd) {
349
351
  export {
350
352
  runPublish
351
353
  };
352
- //# sourceMappingURL=chunk-2SDUV6MQ.js.map
354
+ //# sourceMappingURL=chunk-IKAJSA7E.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/publish.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag } from '../lib/config';\nimport { loadSearches, markSearchResolved, type StoredSearch } from '../lib/search-store';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal, sanitizeWireText } from '../lib/output';\nimport { trimSlash } from '../lib/url';\nimport {\n deriveCard,\n localCardEligibility,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type Frontmatter,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n publishPost,\n EXCERPT_MAX_LENGTH,\n PUBLISH_STATUSES,\n type PublishInput,\n type PublishStatus,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin publish <file.md>`: read the Markdown, parse\n * frontmatter for post + answer-card fields, run the deterministic scan (every\n * mode), gate on the D38\n * consent cascade, then write via the session key (minted on first use) or the\n * plain-SIWX fallback and return a compact receipt. The ordering is the point and\n * is enforced here: scan and consent BEFORE any wallet touch or network write.\n *\n * Exit codes: 0 success (incl. an ineligible-but-published card), 2 usage, 3\n * needs_confirmation / non-bypassable publish_blocked, 4 a write failure after\n * approval.\n */\n\nexport interface PublishArgs {\n /** The Markdown file to publish. */\n file?: string;\n /** The search this publish answers; closes its open loop. */\n searchId?: string;\n draft?: boolean;\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n /** Top-level post price, decimal USD at the edge (O1). */\n price?: string;\n /** The public preview text; overrides frontmatter `excerpt`. Absent, the server\n * derives one from the body's leading prose. */\n excerpt?: string;\n question?: string[];\n task?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n}\n\nexport interface PublishDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runPublish(\n args: PublishArgs,\n ctx: CommandContext,\n deps: PublishDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n // Validate --mode at the edge (USAGE, exit 2) BEFORE any consent resolution: a\n // typo like `--mode Review` must never be silently dropped onto a looser mode\n // and publish unconfirmed. Mirrors install's --publish-mode edge check.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n validateSearchId(args);\n\n const raw = await readSource(args);\n // Read the named search ONCE, here: it prefills the card's question below, and\n // whether it was found decides what the post-publish close reports. Local read,\n // and a missing store reads as no entry rather than failing the publish.\n const storedSearch =\n args.searchId !== undefined\n ? ((await loadSearches(ctx.dataDir)).find((s) => s.searchId === args.searchId) ?? null)\n : null;\n const { frontmatter, body } = parseFrontmatter(raw);\n\n const status = resolveStatus(args, frontmatter);\n const title = resolveTitle(frontmatter, body);\n const tags = resolveTags(frontmatter);\n const excerpt = resolveExcerpt(args, frontmatter);\n const handle = expectString(frontmatter, 'handle');\n // The named search's question prefills questionsAnswered, but only as a\n // fallback: an explicit --question OR a frontmatter questionsAnswered still\n // wins. That phrasing is what the next searcher will send.\n const cardFlags = cardFlagsFrom(args);\n const wanted = storedSearch?.question;\n const prefillQuestion = wanted === undefined ? undefined : cardQuestion(wanted);\n const roomForPrefill =\n cardFlags.question === undefined && frontmatter.questionsAnswered === undefined;\n if (prefillQuestion !== undefined && roomForPrefill) cardFlags.question = [prefillQuestion];\n // A prefill that was WANTED, had room, and was dropped anyway is the one case a\n // caller cannot infer: the card simply comes back without the question it asked\n // for. Reported on both surfaces, because --json never sees the stderr line.\n const prefill: PrefillOutcome =\n wanted === undefined || !roomForPrefill\n ? 'none'\n : prefillQuestion !== undefined\n ? 'applied'\n : 'dropped-too-long';\n if (prefill === 'dropped-too-long') {\n ctx.io.stderr.write(\n `The searched question is longer than ${CARD_QUESTION_MAX} characters, so it was not added to the answer card; pass --question to set a shorter one.\\n`,\n );\n }\n const card = deriveCard(frontmatter, cardFlags);\n\n // The consent cascade + resolved price (global < project < env < flag), with the\n // full-auto loosening gate. Its downgrade warnings go to stderr, not the receipt.\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n // The resolver's downgrade warnings, a mistyped env mode, and the one-line\n // explainer for an unconfigured mode: all stderr, all invisible to --json.\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each publish asks you once. Set auto to publish clean scans automatically',\n );\n const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);\n\n // The scan runs in EVERY mode (D38): it gates the gate, it does not replace it.\n // Scan the whole file AND the derived card's text, so a secret reaches the same\n // gates whether it arrives in the body, in frontmatter, or via a card-authoring\n // flag (--provenance, --scope, …) — the card ships to the PUBLIC card, so a flag\n // secret must block exactly like an in-file one. Dedupe by check+excerpt so a\n // frontmatter value (present in both raw and the card) is not double-counted.\n // The scan context carries the source project's git remote slugs (offline FS\n // read, best-effort): a draft quoting its own project's repo/org warns as a\n // private-by-default reference (open-questions publishing-safety check-set).\n // Markers derive from the DRAFT's project, not the shell's cwd (review r5): a\n // file publish walks up from the file's own directory, so the process cwd is\n // unrelated to where the draft actually lives.\n const markerRoot = args.file !== undefined ? dirname(resolve(cwd, args.file)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n const findings = dedupeFindings([\n ...scan(raw, scanContext),\n ...scan(cardScanText(card), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n\n const eligibility = localCardEligibility(card);\n const price = toMoney(priceAtomic);\n\n // A hard-block finding refuses in EVERY mode and is never clearable by --yes or\n // full-auto — the same non-bypassable posture as buy's price cap.\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the file (it is never masked away by --yes), then re-run.',\n details: {\n mode: settings.mode,\n findings: blocking.map(publicFinding),\n price: { atomic: price.atomic, usd: price.usd },\n },\n });\n }\n\n // --yes clears the soft findings and the review confirm alike.\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, price.usd), {\n fix: 'Review the findings, then re-run with --yes (or resolve the source and re-run).',\n details: {\n mode: settings.mode,\n price: { atomic: price.atomic, usd: price.usd },\n findings: warns.map(publicFinding),\n card: eligibility,\n target: { status, titlePreview: sanitizeForTerminal(title ?? '(untitled draft)') },\n },\n });\n }\n\n // Approved (or nothing to confirm): from here a wallet is required. The write\n // base URL is resolved through the shared settings seam and used for BOTH the\n // SIWX/session header domain and the POST host, so the two never diverge.\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n // A publish always writes.\n scope: 'read+write',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n\n const input: PublishInput = {\n ...(title !== undefined ? { title } : {}),\n bodyMd: body,\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(tags !== undefined ? { tags } : {}),\n priceAtomic,\n ...(handle !== undefined ? { handle } : {}),\n status,\n ...(card !== undefined ? { resource: card } : {}),\n };\n\n const result = await publishPost(input, auth, {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // A DRAFT answered nobody. It parks the piece privately, so it clears no parked\n // loop: the draft is still the pending answer, and the later real publish is\n // what resolves it.\n const parksPrivately = status === 'draft';\n\n let searchInfo: SearchReceipt | undefined;\n if (args.searchId !== undefined) {\n searchInfo = await closeNamedSearch(ctx, args.searchId, storedSearch, parksPrivately, prefill);\n }\n return receipt(result, runtime.baseUrl, searchInfo);\n}\n\n/**\n * What `--search-id` did, as a machine field. `--json` suppresses every stderr\n * note below, so without this an agent that named a search had no way to learn\n * whether its loop actually closed — the same silent-flag failure the draft note\n * fixes for a human.\n */\ninterface SearchReceipt {\n id: string;\n closed: boolean;\n prefill: PrefillOutcome;\n}\n\n/**\n * What became of the searched question as a card entry. `none` covers both \"no\n * stored question\" and \"the draft named its own\", which are the cases where\n * nothing was expected; `dropped-too-long` is the one a caller has to be told.\n */\ntype PrefillOutcome = 'applied' | 'dropped-too-long' | 'none';\n\n/**\n * `--search-id` at the edge: a uuid, refused before any wallet touch so a typo\n * costs a message rather than a signing prompt.\n */\nfunction validateSearchId(args: PublishArgs): void {\n if (args.searchId === undefined) return;\n if (!UUID_RE.test(args.searchId)) {\n throw new CliError('USAGE', `Invalid --search-id: ${JSON.stringify(args.searchId)}.`, {\n fix: 'Pass the searchId from a prior `tenjin search` (a uuid).',\n });\n }\n}\n\n/**\n * Close the loop a `--search-id` file publish named, and say what happened in\n * both registers: a stderr line for a human, the returned receipt for `--json`.\n *\n * Two outcomes close nothing, and neither is an error — the piece is already\n * published, and bookkeeping never fails the write that ran. A `--draft` parks\n * privately and answers nobody, and an unknown id (aged out of the local store,\n * or from another machine) has no loop here to close.\n *\n * `closed: true` describes the LOOP, not this call: `markSearchResolved` keeps\n * the first resolution, so a search an `outcome` already closed reports closed\n * here too, which is what the caller is actually asking about. It reports the\n * OUTCOME of the write rather than the intent to write, so a swallowed lock\n * timeout comes back as `closed: false` and a stderr line instead of a receipt\n * claiming a close that never landed.\n */\nasync function closeNamedSearch(\n ctx: CommandContext,\n searchId: string,\n stored: StoredSearch | null,\n parksPrivately: boolean,\n prefill: PrefillOutcome,\n): Promise<SearchReceipt> {\n const open = (reason: string): SearchReceipt => {\n ctx.io.stderr.write(`${reason}\\n`);\n return { id: searchId, closed: false, prefill };\n };\n if (parksPrivately) return open(`Saved as a draft, so search ${searchId} stays open.`);\n if (stored === null) {\n return open(`Published, but search ${searchId} is not in the local store.`);\n }\n const outcome = await markSearchResolved(ctx.dataDir, searchId, 'publish');\n if (outcome === 'failed') {\n return open(\n `Published, but the local record for search ${searchId} could not be updated, so the open-loop reminder may repeat. Close it with \\`tenjin outcome --search-id ${searchId} --status used\\`.`,\n );\n }\n // `not-found` here means the entry was evicted between the read above and this\n // write: nothing was closed, so nothing claims to have been.\n if (outcome === 'not-found') {\n return open(`Published, but search ${searchId} is no longer in the local store.`);\n }\n return { id: searchId, closed: true, prefill };\n}\n\n/** The Markdown to publish. A missing path is USAGE before any wallet touch. */\nasync function readSource(args: PublishArgs): Promise<string> {\n if (args.file === undefined) {\n throw new CliError('USAGE', 'Nothing to publish.', {\n fix: 'Pass a Markdown file, e.g. `tenjin publish post.md`.',\n });\n }\n return readMarkdown(args.file);\n}\n\nfunction receipt(\n result: Awaited<ReturnType<typeof publishPost>>,\n baseUrl: string,\n searchInfo?: SearchReceipt,\n): CommandResult {\n const price = toMoney(result.priceAtomic);\n const missing = missingSentences(result.cacheEligibleMissing).map(sanitizeForTerminal);\n const cacheEligible = result.cacheEligible ?? false;\n const deskUrl = `${trimSlash(baseUrl)}/desk`;\n const title = sanitizeForTerminal(result.title);\n // status and url are server-sent open strings (posts-api declares both as bare\n // z.string()), so they get the same treatment as the title beside them: this\n // line is what an author reads to learn where their piece went.\n const human = [\n `Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD → ${sanitizeForTerminal(result.url)}`,\n cacheEligible\n ? 'Answer card is search-eligible.'\n : missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Published as a browse-only document (no answer card).',\n ...(searchInfo?.closed === true ? [`Closed the loop on search ${searchInfo.id}.`] : []),\n ...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n data: {\n resourceId: result.resourceId,\n url: result.url,\n status: result.status,\n price,\n cacheEligible,\n missing,\n deskUrl,\n ...(searchInfo !== undefined ? { search: searchInfo } : {}),\n ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),\n },\n humanLines: human,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Field resolution.\n// ---------------------------------------------------------------------------\n\nasync function readMarkdown(file: string): Promise<string> {\n try {\n return await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin publish post.md`.',\n cause: err,\n });\n }\n}\n\nfunction resolveStatus(args: PublishArgs, frontmatter: Frontmatter): PublishStatus {\n if (args.draft === true) return 'draft';\n const fm = frontmatter.status;\n if (fm === undefined) return 'published';\n if (typeof fm !== 'string' || !(PUBLISH_STATUSES as readonly string[]).includes(fm)) {\n throw new CliError('USAGE', `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {\n fix: 'Use status: draft | published | unlisted, or pass --draft.',\n });\n }\n return fm as PublishStatus;\n}\n\nfunction resolveTitle(frontmatter: Frontmatter, body: string): string | undefined {\n const fm = frontmatter.title;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter title must be a single string.');\n }\n return fm.trim();\n }\n // Fall back to the first heading (level 1 preferred) so a plain `# Title` post\n // needs no frontmatter.\n const headings = headingOutline(body);\n const h1 = headings.find((h) => h.level === 1) ?? headings[0];\n return h1?.text;\n}\n\n/** The server's per-item bound on `questionsAnswered` (mirrored by deriveCard). */\nconst CARD_QUESTION_MAX = 200;\n\n/**\n * A stored question as a card entry, or undefined when it cannot be one.\n *\n * Dropped rather than cut over the item bound: a search question may run to the\n * server's 512, and a prefill that fails card validation would turn a publish\n * that was fine into a usage error the caller never asked for. Truncating is\n * worse still — half a question is a different question, and this text is what\n * the next searcher matches against.\n */\nfunction cardQuestion(raw: string): string | undefined {\n const question = sanitizeWireText(raw);\n return question.length > 0 && question.length <= CARD_QUESTION_MAX ? question : undefined;\n}\n\n/**\n * The public preview text: `--excerpt` over frontmatter `excerpt`, or undefined\n * to let the server derive one from the body's leading prose.\n *\n * The bound is checked HERE as well as in the request builder, because the\n * builder runs after a wallet signature has been collected and this is the edge:\n * a too-long excerpt should cost a message, not a signing prompt. Refused rather\n * than truncated — a silently cut preview is a different preview, and the whole\n * point of setting one is controlling exactly what a non-buyer reads. Sanitized\n * before the bound for the same reason the builder is: the stripped text is what\n * ships, so it is what the length has to describe.\n */\nfunction resolveExcerpt(args: PublishArgs, frontmatter: Frontmatter): string | undefined {\n const raw = args.excerpt ?? expectString(frontmatter, 'excerpt');\n if (raw === undefined) return undefined;\n const excerpt = sanitizeWireText(raw);\n if (excerpt.length > EXCERPT_MAX_LENGTH) {\n throw new CliError(\n 'USAGE',\n `excerpt must be at most ${EXCERPT_MAX_LENGTH} characters (got ${excerpt.length}).`,\n { fix: `Shorten it to ${EXCERPT_MAX_LENGTH} characters or fewer.` },\n );\n }\n return excerpt;\n}\n\nfunction resolveTags(frontmatter: Frontmatter): string[] | undefined {\n const fm = frontmatter.tags;\n if (fm === undefined) return undefined;\n if (typeof fm === 'string') return [fm];\n if (Array.isArray(fm)) return fm;\n throw new CliError('USAGE', 'frontmatter tags must be a list of strings.');\n}\n\nfunction expectString(frontmatter: Frontmatter, key: string): string | undefined {\n const fm = frontmatter[key];\n if (fm === undefined) return undefined;\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', `frontmatter ${key} must be a single string.`);\n }\n return fm;\n}\n\nfunction resolvePrice(args: PublishArgs, frontmatter: Frontmatter, defaultAtomic: string): string {\n if (args.price !== undefined) return parseUsdToAtomic(args.price);\n const fm = frontmatter.price;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter price must be a decimal-USD string, e.g. \"0.10\".');\n }\n return parseUsdToAtomic(fm);\n }\n return defaultAtomic;\n}\n\nfunction cardFlagsFrom(args: PublishArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The derived card's free-text values as one newline-joined document, so the scan\n * covers card-flag input (which never touches the file) at the same severity as\n * the body. Empty when there is no card.\n */\nfunction cardScanText(card: ResourceCardInput | undefined): string {\n if (card === undefined) return '';\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n add(card.scope);\n add(card.exclusions);\n add(card.provenanceSummary);\n add(card.methodologySummary);\n add(card.mediaType);\n add(card.maintenanceCadence);\n add(card.asOf);\n add(card.validUntil);\n add(card.estimatedPaidInputCost);\n if (card.questionsAnswered !== undefined) parts.push(...card.questionsAnswered);\n if (card.tasksSupported !== undefined) parts.push(...card.tasksSupported);\n if (card.appliesTo !== undefined) {\n for (const values of Object.values(card.appliesTo)) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Finding + message shaping.\n// ---------------------------------------------------------------------------\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Publish blocked: the file contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, priceUsd: string): string {\n return warnCount > 0\n ? `Publish needs confirmation: ${warnCount} finding(s), price $${priceUsd}.`\n : `Publish needs confirmation: price $${priceUsd}.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AA2FjC,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAIpC,MAAI,KAAK,SAAS,OAAW,sBAAqB,KAAK,MAAM,QAAQ;AACrE,mBAAiB,IAAI;A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AAK;AACd,MAAI,KAAK,UAAU;AACnB,MAAI,KAAK,iBAAiB;AAC1B,MAAI,KAAK,kBAAkB;AAC3B,MAAI,KAAK,SAAS;AAClB,MAAI,KAAK,kBAAkB;AAC3B,MAAI,KAAK,IAAI;AACb,MAAI,KAAK,UAAU;AACnB,MAAI,KAAK,sBAAsB;AAC/B,MAAI,KAAK,sBAAsB,OAAW,OAAM,KAAK,GAAG,KAAK,iBAAiB;AAC9E,MAAI,KAAK,mBAAmB,OAAW,OAAM,KAAK,GAAG,KAAK,cAAc;AACxE,MAAI,KAAK,cAAc,QAAW;AAChC,eAAW,UAAU,OAAO,OAAO,KAAK,SAAS,EAAG,OAAM,KAAK,GAAG,MAAM;AAAA,EAC1E;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAMA,SAAS,aAAa,UAAiC;AACrD,SAAO,sCAAsC,iBAAiB,QAAQ,CAAC;AACzE;AAEA,SAAS,eAAe,WAAmB,UAA0B;AACnE,SAAO,YAAY,IACf,+BAA+B,SAAS,uBAAuB,QAAQ,MACvE,sCAAsC,QAAQ;AACpD;","names":[]}
1
+ {"version":3,"sources":["../src/commands/publish.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { resolveContextSettings, resolvePublishSettings } from '../lib/settings';\nimport { parsePublishModeFlag } from '../lib/config';\nimport { loadSearches, markSearchResolved, type StoredSearch } from '../lib/search-store';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal, sanitizeWireText } from '../lib/output';\nimport { trimSlash } from '../lib/url';\nimport {\n deriveCard,\n localCardEligibility,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type Frontmatter,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n publishPost,\n EXCERPT_MAX_LENGTH,\n PUBLISH_STATUSES,\n type PublishInput,\n type PublishStatus,\n} from '../lib/posts-api';\nimport {\n dedupeFindings,\n describeFindings,\n needsConfirmation,\n publicFinding,\n resolveWriteAuth,\n writeModeNotices,\n} from '../lib/consent';\nimport { describeWallet, resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin publish <file.md>`: read the Markdown, parse\n * frontmatter for post + answer-card fields, run the deterministic scan (every\n * mode), gate on the D38\n * consent cascade, then write via the session key (minted on first use) or the\n * plain-SIWX fallback and return a compact receipt. The ordering is the point and\n * is enforced here: scan and consent BEFORE any wallet touch or network write.\n *\n * Exit codes: 0 success (incl. an ineligible-but-published card), 2 usage, 3\n * needs_confirmation / non-bypassable publish_blocked, 4 a write failure after\n * approval.\n */\n\nexport interface PublishArgs {\n /** The Markdown file to publish. */\n file?: string;\n /** The search this publish answers; closes its open loop. */\n searchId?: string;\n draft?: boolean;\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n /** Top-level post price, decimal USD at the edge (O1). */\n price?: string;\n /** The public preview text; overrides frontmatter `excerpt`. Absent, the server\n * derives one from the body's leading prose. */\n excerpt?: string;\n question?: string[];\n task?: string[];\n scope?: string;\n exclusions?: string;\n appliesTo?: string[];\n asOf?: string;\n validUntil?: string;\n artifactType?: string;\n temporalMode?: string;\n provenance?: string;\n methodology?: string;\n}\n\nexport interface PublishDeps {\n fetchImpl?: typeof fetch;\n provider?: WalletProvider;\n /** Force the plain-SIWX write path (default: session key unless TENJIN_NO_SESSION=1). */\n useSession?: boolean;\n /** Environment seam (mode, base-url, TENJIN_NO_SESSION); defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n /** Working directory for the `.tenjin.json` walk; defaults to process.cwd(). */\n cwd?: string;\n}\n\nexport async function runPublish(\n args: PublishArgs,\n ctx: CommandContext,\n deps: PublishDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n // Validate --mode at the edge (USAGE, exit 2) BEFORE any consent resolution: a\n // typo like `--mode Review` must never be silently dropped onto a looser mode\n // and publish unconfirmed. Mirrors install's --publish-mode edge check.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n validateSearchId(args);\n\n const raw = await readSource(args);\n // Read the named search ONCE, here: it prefills the card's question below, and\n // whether it was found decides what the post-publish close reports. Local read,\n // and a missing store reads as no entry rather than failing the publish.\n const storedSearch =\n args.searchId !== undefined\n ? ((await loadSearches(ctx.dataDir)).find((s) => s.searchId === args.searchId) ?? null)\n : null;\n const { frontmatter, body } = parseFrontmatter(raw);\n\n const status = resolveStatus(args, frontmatter);\n const title = resolveTitle(frontmatter, body);\n const tags = resolveTags(frontmatter);\n const excerpt = resolveExcerpt(args, frontmatter);\n const handle = expectString(frontmatter, 'handle');\n // The named search's question prefills questionsAnswered, but only as a\n // fallback: an explicit --question OR a frontmatter questionsAnswered still\n // wins. That phrasing is what the next searcher will send.\n const cardFlags = cardFlagsFrom(args);\n const wanted = storedSearch?.question;\n const prefillQuestion = wanted === undefined ? undefined : cardQuestion(wanted);\n const roomForPrefill =\n cardFlags.question === undefined && frontmatter.questionsAnswered === undefined;\n if (prefillQuestion !== undefined && roomForPrefill) cardFlags.question = [prefillQuestion];\n // A prefill that was WANTED, had room, and was dropped anyway is the one case a\n // caller cannot infer: the card simply comes back without the question it asked\n // for. Reported on both surfaces, because --json never sees the stderr line.\n const prefill: PrefillOutcome =\n wanted === undefined || !roomForPrefill\n ? 'none'\n : prefillQuestion !== undefined\n ? 'applied'\n : 'dropped-too-long';\n if (prefill === 'dropped-too-long') {\n ctx.io.stderr.write(\n `The searched question is longer than ${CARD_QUESTION_MAX} characters, so it was not added to the answer card; pass --question to set a shorter one.\\n`,\n );\n }\n const card = deriveCard(frontmatter, cardFlags);\n\n // The consent cascade + resolved price (global < project < env < flag), with the\n // full-auto loosening gate. Its downgrade warnings go to stderr, not the receipt.\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n // The resolver's downgrade warnings, a mistyped env mode, and the one-line\n // explainer for an unconfigured mode: all stderr, all invisible to --json.\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each publish asks you once. Set auto to publish clean scans automatically',\n );\n const priceAtomic = resolvePrice(args, frontmatter, settings.defaultPriceAtomic);\n\n // The scan runs in EVERY mode (D38): it gates the gate, it does not replace it.\n // Scan the whole file AND the derived card's text, so a secret reaches the same\n // gates whether it arrives in the body, in frontmatter, or via a card-authoring\n // flag (--provenance, --scope, …) — the card ships to the PUBLIC card, so a flag\n // secret must block exactly like an in-file one. Dedupe by check+excerpt so a\n // frontmatter value (present in both raw and the card) is not double-counted.\n // The scan context carries the source project's git remote slugs (offline FS\n // read, best-effort): a draft quoting its own project's repo/org warns as a\n // private-by-default reference (open-questions publishing-safety check-set).\n // Markers derive from the DRAFT's project, not the shell's cwd (review r5): a\n // file publish walks up from the file's own directory, so the process cwd is\n // unrelated to where the draft actually lives.\n const markerRoot = args.file !== undefined ? dirname(resolve(cwd, args.file)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n const findings = dedupeFindings([\n ...scan(raw, scanContext),\n ...scan(cardScanText(card), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n\n const eligibility = localCardEligibility(card);\n const price = toMoney(priceAtomic);\n\n // A hard-block finding refuses in EVERY mode and is never clearable by --yes or\n // full-auto — the same non-bypassable posture as buy's price cap.\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the file (it is never masked away by --yes), then re-run.',\n details: {\n mode: settings.mode,\n findings: blocking.map(publicFinding),\n price: { atomic: price.atomic, usd: price.usd },\n },\n });\n }\n\n // --yes clears the soft findings and the review confirm alike.\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, price.usd), {\n fix: 'Review the findings, then re-run with --yes (or resolve the source and re-run).',\n details: {\n mode: settings.mode,\n price: { atomic: price.atomic, usd: price.usd },\n findings: warns.map(publicFinding),\n card: eligibility,\n target: { status, titlePreview: sanitizeForTerminal(title ?? '(untitled draft)') },\n },\n });\n }\n\n // Approved (or nothing to confirm): from here a wallet is required. The write\n // base URL is resolved through the shared settings seam and used for BOTH the\n // SIWX/session header domain and the POST host, so the two never diverge.\n const runtime = await resolveContextSettings(ctx);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n await describeWallet(provider); // surfaces WALLET_MISSING with its own fix\n const signer = await provider.getSigner();\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n // A publish always writes.\n scope: 'read+write',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n\n const input: PublishInput = {\n ...(title !== undefined ? { title } : {}),\n bodyMd: body,\n ...(excerpt !== undefined ? { excerpt } : {}),\n ...(tags !== undefined ? { tags } : {}),\n priceAtomic,\n ...(handle !== undefined ? { handle } : {}),\n status,\n ...(card !== undefined ? { resource: card } : {}),\n };\n\n const result = await publishPost(input, auth, {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n // A DRAFT answered nobody. It parks the piece privately, so it clears no parked\n // loop: the draft is still the pending answer, and the later real publish is\n // what resolves it.\n const parksPrivately = status === 'draft';\n\n let searchInfo: SearchReceipt | undefined;\n if (args.searchId !== undefined) {\n searchInfo = await closeNamedSearch(ctx, args.searchId, storedSearch, parksPrivately, prefill);\n }\n return receipt(result, runtime.baseUrl, searchInfo);\n}\n\n/**\n * What `--search-id` did, as a machine field. `--json` suppresses every stderr\n * note below, so without this an agent that named a search had no way to learn\n * whether its loop actually closed — the same silent-flag failure the draft note\n * fixes for a human.\n */\ninterface SearchReceipt {\n id: string;\n closed: boolean;\n prefill: PrefillOutcome;\n}\n\n/**\n * What became of the searched question as a card entry. `none` covers both \"no\n * stored question\" and \"the draft named its own\", which are the cases where\n * nothing was expected; `dropped-too-long` is the one a caller has to be told.\n */\ntype PrefillOutcome = 'applied' | 'dropped-too-long' | 'none';\n\n/**\n * `--search-id` at the edge: a uuid, refused before any wallet touch so a typo\n * costs a message rather than a signing prompt.\n */\nfunction validateSearchId(args: PublishArgs): void {\n if (args.searchId === undefined) return;\n if (!UUID_RE.test(args.searchId)) {\n throw new CliError('USAGE', `Invalid --search-id: ${JSON.stringify(args.searchId)}.`, {\n fix: 'Pass the searchId from a prior `tenjin search` (a uuid).',\n });\n }\n}\n\n/**\n * Close the loop a `--search-id` file publish named, and say what happened in\n * both registers: a stderr line for a human, the returned receipt for `--json`.\n *\n * Two outcomes close nothing, and neither is an error — the piece is already\n * published, and bookkeeping never fails the write that ran. A `--draft` parks\n * privately and answers nobody, and an unknown id (aged out of the local store,\n * or from another machine) has no loop here to close.\n *\n * `closed: true` describes the LOOP, not this call: `markSearchResolved` keeps\n * the first resolution, so a search an `outcome` already closed reports closed\n * here too, which is what the caller is actually asking about. It reports the\n * OUTCOME of the write rather than the intent to write, so a swallowed lock\n * timeout comes back as `closed: false` and a stderr line instead of a receipt\n * claiming a close that never landed.\n */\nasync function closeNamedSearch(\n ctx: CommandContext,\n searchId: string,\n stored: StoredSearch | null,\n parksPrivately: boolean,\n prefill: PrefillOutcome,\n): Promise<SearchReceipt> {\n const open = (reason: string): SearchReceipt => {\n ctx.io.stderr.write(`${reason}\\n`);\n return { id: searchId, closed: false, prefill };\n };\n if (parksPrivately) return open(`Saved as a draft, so search ${searchId} stays open.`);\n if (stored === null) {\n return open(`Published, but search ${searchId} is not in the local store.`);\n }\n const outcome = await markSearchResolved(ctx.dataDir, searchId, 'publish');\n if (outcome === 'failed') {\n return open(\n `Published, but the local record for search ${searchId} could not be updated, so the open-loop reminder may repeat. Close it with \\`tenjin outcome --search-id ${searchId} --status used\\`.`,\n );\n }\n // `not-found` here means the entry was evicted between the read above and this\n // write: nothing was closed, so nothing claims to have been.\n if (outcome === 'not-found') {\n return open(`Published, but search ${searchId} is no longer in the local store.`);\n }\n return { id: searchId, closed: true, prefill };\n}\n\n/** The Markdown to publish. A missing path is USAGE before any wallet touch. */\nasync function readSource(args: PublishArgs): Promise<string> {\n if (args.file === undefined) {\n throw new CliError('USAGE', 'Nothing to publish.', {\n fix: 'Pass a Markdown file, e.g. `tenjin publish post.md`.',\n });\n }\n return readMarkdown(args.file);\n}\n\nfunction receipt(\n result: Awaited<ReturnType<typeof publishPost>>,\n baseUrl: string,\n searchInfo?: SearchReceipt,\n): CommandResult {\n const price = toMoney(result.priceAtomic);\n const missing = missingSentences(result.cacheEligibleMissing).map(sanitizeForTerminal);\n const cacheEligible = result.cacheEligible ?? false;\n const deskUrl = `${trimSlash(baseUrl)}/desk`;\n const title = sanitizeForTerminal(result.title);\n // status and url are server-sent open strings (posts-api declares both as bare\n // z.string()), so they get the same treatment as the title beside them: this\n // line is what an author reads to learn where their piece went.\n const human = [\n `Published ${title} (${sanitizeForTerminal(result.status)}) for ${price.usd} USD → ${sanitizeForTerminal(result.url)}`,\n cacheEligible\n ? 'Answer card is search-eligible.'\n : missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Published as a browse-only document (no answer card).',\n ...(searchInfo?.closed === true ? [`Closed the loop on search ${searchInfo.id}.`] : []),\n ...result.warnings.map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n data: {\n resourceId: result.resourceId,\n url: result.url,\n status: result.status,\n price,\n cacheEligible,\n missing,\n deskUrl,\n ...(searchInfo !== undefined ? { search: searchInfo } : {}),\n ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),\n },\n humanLines: human,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Field resolution.\n// ---------------------------------------------------------------------------\n\nasync function readMarkdown(file: string): Promise<string> {\n try {\n return await readFile(file, 'utf8');\n } catch (err) {\n throw new CliError('USAGE', `Could not read ${JSON.stringify(file)}`, {\n fix: 'Pass a path to a readable Markdown file, e.g. `tenjin publish post.md`.',\n cause: err,\n });\n }\n}\n\nfunction resolveStatus(args: PublishArgs, frontmatter: Frontmatter): PublishStatus {\n if (args.draft === true) return 'draft';\n const fm = frontmatter.status;\n if (fm === undefined) return 'published';\n if (typeof fm !== 'string' || !(PUBLISH_STATUSES as readonly string[]).includes(fm)) {\n throw new CliError('USAGE', `Invalid status ${JSON.stringify(fm)} in frontmatter.`, {\n fix: 'Use status: draft | published | unlisted, or pass --draft.',\n });\n }\n return fm as PublishStatus;\n}\n\nfunction resolveTitle(frontmatter: Frontmatter, body: string): string | undefined {\n const fm = frontmatter.title;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter title must be a single string.');\n }\n return fm.trim();\n }\n // Fall back to the first heading (level 1 preferred) so a plain `# Title` post\n // needs no frontmatter.\n const headings = headingOutline(body);\n const h1 = headings.find((h) => h.level === 1) ?? headings[0];\n return h1?.text;\n}\n\n/** The server's per-item bound on `questionsAnswered` (mirrored by deriveCard). */\nconst CARD_QUESTION_MAX = 200;\n\n/**\n * A stored question as a card entry, or undefined when it cannot be one.\n *\n * Dropped rather than cut over the item bound: a search question may run to the\n * server's 512, and a prefill that fails card validation would turn a publish\n * that was fine into a usage error the caller never asked for. Truncating is\n * worse still — half a question is a different question, and this text is what\n * the next searcher matches against.\n */\nfunction cardQuestion(raw: string): string | undefined {\n const question = sanitizeWireText(raw);\n return question.length > 0 && question.length <= CARD_QUESTION_MAX ? question : undefined;\n}\n\n/**\n * The public preview text: `--excerpt` over frontmatter `excerpt`, or undefined\n * to let the server derive one from the body's leading prose.\n *\n * The bound is checked HERE as well as in the request builder, because the\n * builder runs after a wallet signature has been collected and this is the edge:\n * a too-long excerpt should cost a message, not a signing prompt. Refused rather\n * than truncated — a silently cut preview is a different preview, and the whole\n * point of setting one is controlling exactly what a non-buyer reads. Sanitized\n * before the bound for the same reason the builder is: the stripped text is what\n * ships, so it is what the length has to describe.\n */\nfunction resolveExcerpt(args: PublishArgs, frontmatter: Frontmatter): string | undefined {\n const raw = args.excerpt ?? expectString(frontmatter, 'excerpt');\n if (raw === undefined) return undefined;\n const excerpt = sanitizeWireText(raw);\n if (excerpt.length > EXCERPT_MAX_LENGTH) {\n throw new CliError(\n 'USAGE',\n `excerpt must be at most ${EXCERPT_MAX_LENGTH} characters (got ${excerpt.length}).`,\n { fix: `Shorten it to ${EXCERPT_MAX_LENGTH} characters or fewer.` },\n );\n }\n return excerpt;\n}\n\nfunction resolveTags(frontmatter: Frontmatter): string[] | undefined {\n const fm = frontmatter.tags;\n if (fm === undefined) return undefined;\n if (typeof fm === 'string') return [fm];\n if (Array.isArray(fm)) return fm;\n throw new CliError('USAGE', 'frontmatter tags must be a list of strings.');\n}\n\nfunction expectString(frontmatter: Frontmatter, key: string): string | undefined {\n const fm = frontmatter[key];\n if (fm === undefined) return undefined;\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', `frontmatter ${key} must be a single string.`);\n }\n return fm;\n}\n\nfunction resolvePrice(args: PublishArgs, frontmatter: Frontmatter, defaultAtomic: string): string {\n if (args.price !== undefined) return parseUsdToAtomic(args.price);\n const fm = frontmatter.price;\n if (fm !== undefined) {\n if (typeof fm !== 'string') {\n throw new CliError('USAGE', 'frontmatter price must be a decimal-USD string, e.g. \"0.10\".');\n }\n return parseUsdToAtomic(fm);\n }\n return defaultAtomic;\n}\n\nfunction cardFlagsFrom(args: PublishArgs): CardFlags {\n return {\n ...(args.question !== undefined && args.question.length > 0 ? { question: args.question } : {}),\n ...(args.task !== undefined && args.task.length > 0 ? { task: args.task } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n ...(args.exclusions !== undefined ? { exclusions: args.exclusions } : {}),\n ...(args.asOf !== undefined ? { asOf: args.asOf } : {}),\n ...(args.validUntil !== undefined ? { validUntil: args.validUntil } : {}),\n ...(args.artifactType !== undefined ? { artifactType: args.artifactType } : {}),\n ...(args.temporalMode !== undefined ? { temporalMode: args.temporalMode } : {}),\n ...(args.provenance !== undefined ? { provenance: args.provenance } : {}),\n ...(args.methodology !== undefined ? { methodology: args.methodology } : {}),\n ...(args.appliesTo !== undefined && args.appliesTo.length > 0\n ? { appliesTo: parseAppliesToFlags(args.appliesTo) }\n : {}),\n };\n}\n\n/**\n * The derived card's free-text values as one newline-joined document, so the scan\n * covers card-flag input (which never touches the file) at the same severity as\n * the body. Empty when there is no card.\n */\nfunction cardScanText(card: ResourceCardInput | undefined): string {\n if (card === undefined) return '';\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n add(card.scope);\n add(card.exclusions);\n add(card.provenanceSummary);\n add(card.methodologySummary);\n add(card.mediaType);\n add(card.maintenanceCadence);\n add(card.asOf);\n add(card.validUntil);\n add(card.estimatedPaidInputCost);\n if (card.questionsAnswered !== undefined) parts.push(...card.questionsAnswered);\n if (card.tasksSupported !== undefined) parts.push(...card.tasksSupported);\n if (card.appliesTo !== undefined) {\n for (const values of Object.values(card.appliesTo)) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Finding + message shaping.\n// ---------------------------------------------------------------------------\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Publish blocked: the file contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, priceUsd: string): string {\n return warnCount > 0\n ? `Publish needs confirmation: ${warnCount} finding(s), price $${priceUsd}.`\n : `Publish needs confirmation: price $${priceUsd}.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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AE,WAAW,oBAAoB,KAAK,SAAS,EAAE,IACjD,CAAC;AAAA,EACP;AACF;AAOA,SAAS,aAAa,MAA6C;AACjE,MAAI,SAAS,OAAW,QAAO;AAC/B,QAAM,QAAkB,CAAC;AACzB,QAAM,MAAM,CAAC,MAAgC;AAC3C,QAAI,MAAM,OAAW,OAAM,KAAK,CAAC;AAAA,EACnC;AACA,MAAI,KAAK,KAAK;AACd,MAAI,KAAK,UAAU;AACnB,MAAI,KAAK,iBAAiB;AAC1B,MAAI,KAAK,kBAAkB;AAC3B,MAAI,KAAK,SAAS;AAClB,MAAI,KAAK,kBAAkB;AAC3B,MAAI,KAAK,IAAI;AACb,MAAI,KAAK,UAAU;AACnB,MAAI,KAAK,sBAAsB;AAC/B,MAAI,KAAK,sBAAsB,OAAW,OAAM,KAAK,GAAG,KAAK,iBAAiB;AAC9E,MAAI,KAAK,mBAAmB,OAAW,OAAM,KAAK,GAAG,KAAK,cAAc;AACxE,MAAI,KAAK,cAAc,QAAW;AAChC,eAAW,UAAU,OAAO,OAAO,KAAK,SAAS,EAAG,OAAM,KAAK,GAAG,MAAM;AAAA,EAC1E;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAMA,SAAS,aAAa,UAAiC;AACrD,SAAO,sCAAsC,iBAAiB,QAAQ,CAAC;AACzE;AAEA,SAAS,eAAe,WAAmB,UAA0B;AACnE,SAAO,YAAY,IACf,+BAA+B,SAAS,uBAAuB,QAAQ,MACvE,sCAAsC,QAAQ;AACpD;","names":[]}
@@ -2,13 +2,11 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  sessionPath
4
4
  } from "./chunk-ZQIQ55KK.js";
5
- import {
6
- hasCode
7
- } from "./chunk-2I4QTOLB.js";
8
5
  import {
9
6
  CliError,
10
- external_exports
11
- } from "./chunk-PZRAAAY2.js";
7
+ external_exports,
8
+ hasCode
9
+ } from "./chunk-PAOVPSP6.js";
12
10
 
13
11
  // src/lib/session-present.ts
14
12
  import { createHash, randomBytes, webcrypto } from "crypto";
@@ -204,4 +202,4 @@ export {
204
202
  isSessionPresentable,
205
203
  isSessionUsable
206
204
  };
207
- //# sourceMappingURL=chunk-NUF2PKJO.js.map
205
+ //# sourceMappingURL=chunk-J6FUAIRR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IAAM,cAAc;AAcpB,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE,OAAO;AAAA;AAAA,EAEjC,SAAS,iBAAE,OAAO;AAAA;A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AM;AACzD;","names":[]}
1
+ {"version":3,"sources":["../src/lib/session-present.ts"],"sourcesContent":["import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split exists so `tenjin read` can present an owner's session key on a cold\n * 402 while its import graph stays test-pinned clear of the wallet. What that\n * pin establishes is exactly two things: read cannot mint a session, and read\n * cannot pay (a P-256 key cannot produce the secp256k1/EIP-712 signature an\n * EIP-3009 transfer authorization needs). It says nothing about what an\n * already-minted delegation is worth to whoever holds it — see `origin` below,\n * and the tier note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET has no body to cover at all,\n * so content-digest drops out of the covered set. As a union, \"GET with a body\"\n * and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache and run `tenjin session start --scope read`; a write command re-establishes on its own.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends.\n const digest = req.method === 'GET' ? undefined : contentDigest(req.body);\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,iBAAiB;AACnD,SAAS,UAAU,YAAY;AAgCxB,SAAS,eAAe,QAAgB,UAAiC;AAC9E,MAAI,WAAW,SAAU,QAAO;AAChC,SAAO,aAAa,UAAU,WAAW;AAC3C;AAGA,IAAM,cAAc;AAcpB,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnB,GAAG,iBAAE,OAAO,EAAE,IAAI,CAAC;AACrB,CAAC,EACA,YAAY;AAGf,IAAM,oBAAoB,iBAAE,OAAO;AAAA;AAAA,EAEjC,SAAS,iBAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAalB,QAAQ,iBAAE,OAAO;AAAA;AAAA,EAEjB,YAAY,iBAAE,OAAO;AAAA;AAAA,EAErB,KAAK,iBAAE,OAA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SAAO,EAAE,MAAM,MAAM,MAAM,OAAO,KAAK;AACzC;AAGA,SAAS,QAAQ,OAAgB,MAAuC;AACtE,MAAI,MAAe;AACnB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAI,CAAC,OAAO,OAAO,KAAK,GAAG,EAAG,QAAO;AACrC,UAAO,IAAqC,GAAG;AAAA,EACjD;AACA,SAAO;AACT;AAGA,eAAsB,gBAAgB,KAA0C;AAC9E,QAAM,QAAQ,MAAM,gBAAgB,GAAG;AACvC,MAAI,MAAM,SAAS,KAAM,QAAO,MAAM;AAItC,MAAI,MAAM,SAAS,cAAc;AAC/B,UAAM,IAAI,SAAS,YAAY,uCAAuC,YAAY,GAAG,CAAC,IAAI;AAAA,MACxF,KAAK,6BAA6B,YAAY,GAAG,CAAC;AAAA,MAClD,OAAO,MAAM;AAAA,IACf,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,SAAS,UAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AASO,SAAS,qBACd,MACA,KACA,UACA,QACS;AACT,MAAI,KAAK,WAAW,OAAQ,QAAO;AACnC,MAAI,CAAC,eAAe,KAAK,OAAO,QAAQ,EAAG,QAAO;AAClD,QAAM,QAAQ,KAAK,MAAM,KAAK,GAAG;AACjC,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,SAAO,MAAM,QAAQ;AACvB;AAGO,SAAS,gBACd,MACA,SACA,KACA,UACA,QACS;AACT,MAAI,KAAK,YAAY,QAAQ,YAAY,EAAG,QAAO;AACnD,SAAO,qBAAqB,MAAM,KAAK,UAAU,MAAM;AACzD;","names":[]}
@@ -5,10 +5,10 @@ import {
5
5
  readWalletRecord,
6
6
  walletFileMode,
7
7
  writeWalletRecord
8
- } from "./chunk-Y7ERTA7D.js";
8
+ } from "./chunk-3P3ES4XU.js";
9
9
  import {
10
10
  emitNotice
11
- } from "./chunk-IB63U6BM.js";
11
+ } from "./chunk-B676GPS2.js";
12
12
  import {
13
13
  evaluateSpendPolicy,
14
14
  withFileLock
@@ -20,15 +20,13 @@ import {
20
20
  spendLedgerPath,
21
21
  walletPath
22
22
  } from "./chunk-ZQIQ55KK.js";
23
- import {
24
- hasCode
25
- } from "./chunk-2I4QTOLB.js";
26
23
  import {
27
24
  CliError,
28
25
  external_exports,
29
26
  fsyncDir,
27
+ hasCode,
30
28
  writeFileAtomic
31
- } from "./chunk-PZRAAAY2.js";
29
+ } from "./chunk-PAOVPSP6.js";
32
30
  import {
33
31
  hashAuthorization,
34
32
  hashMessage,
@@ -1642,4 +1640,4 @@ export {
1642
1640
  @noble/ciphers/esm/utils.js:
1643
1641
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1644
1642
  */
1645
- //# sourceMappingURL=chunk-CNUXRXI2.js.map
1643
+ //# sourceMappingURL=chunk-JVBMPU5G.js.map