tenjin-cli 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (191) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +575 -50
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-FMDBZ4NY.js +44 -0
  6. package/dist/candidate-7LAELUQD.js +23 -0
  7. package/dist/ccip-RPPPKTJR.js +19 -0
  8. package/dist/{ccip-FXWZDDF5.js → ccip-ZGGWQN4X.js} +6 -5
  9. package/dist/chunk-2GSRYTZS.js +127 -0
  10. package/dist/chunk-2GSRYTZS.js.map +1 -0
  11. package/dist/chunk-2I4QTOLB.js +11 -0
  12. package/dist/chunk-2I4QTOLB.js.map +1 -0
  13. package/dist/chunk-36X2CA3N.js +311 -0
  14. package/dist/chunk-36X2CA3N.js.map +1 -0
  15. package/dist/{chunk-F5DZJLU3.js → chunk-47PP7TAG.js} +1441 -634
  16. package/dist/chunk-47PP7TAG.js.map +1 -0
  17. package/dist/chunk-5JMKIDMM.js +316 -0
  18. package/dist/chunk-5JMKIDMM.js.map +1 -0
  19. package/dist/chunk-5JXAZP7H.js +206 -0
  20. package/dist/chunk-5JXAZP7H.js.map +1 -0
  21. package/dist/chunk-5SE6BJRP.js +135 -0
  22. package/dist/chunk-5SE6BJRP.js.map +1 -0
  23. package/dist/chunk-6BZLSRNU.js +149 -0
  24. package/dist/chunk-6BZLSRNU.js.map +1 -0
  25. package/dist/{chunk-PAAL45FJ.js → chunk-7FK2UN2T.js} +3410 -412
  26. package/dist/chunk-7FK2UN2T.js.map +1 -0
  27. package/dist/chunk-7WDY4AXV.js +14620 -0
  28. package/dist/chunk-7WDY4AXV.js.map +1 -0
  29. package/dist/chunk-A6KCZPNQ.js +83 -0
  30. package/dist/chunk-A6KCZPNQ.js.map +1 -0
  31. package/dist/chunk-AWQ6A4CI.js +341 -0
  32. package/dist/chunk-AWQ6A4CI.js.map +1 -0
  33. package/dist/chunk-BJJ5BQO6.js +162 -0
  34. package/dist/chunk-BJJ5BQO6.js.map +1 -0
  35. package/dist/chunk-BUDHTDKL.js +612 -0
  36. package/dist/chunk-BUDHTDKL.js.map +1 -0
  37. package/dist/chunk-DKQMJTG7.js +188 -0
  38. package/dist/chunk-DKQMJTG7.js.map +1 -0
  39. package/dist/chunk-FKSAUOJU.js +137 -0
  40. package/dist/chunk-FKSAUOJU.js.map +1 -0
  41. package/dist/chunk-GECSWJ7O.js +1645 -0
  42. package/dist/chunk-GECSWJ7O.js.map +1 -0
  43. package/dist/chunk-GSDZRCGF.js +105 -0
  44. package/dist/chunk-GSDZRCGF.js.map +1 -0
  45. package/dist/chunk-JSSIMGQT.js +174 -0
  46. package/dist/chunk-JSSIMGQT.js.map +1 -0
  47. package/dist/chunk-KYH4KPE5.js +1357 -0
  48. package/dist/chunk-KYH4KPE5.js.map +1 -0
  49. package/dist/chunk-KYQVEKP5.js +209 -0
  50. package/dist/chunk-KYQVEKP5.js.map +1 -0
  51. package/dist/chunk-KZAAWQNP.js +6199 -0
  52. package/dist/chunk-KZAAWQNP.js.map +1 -0
  53. package/dist/{chunk-SXQQ2ZSR.js → chunk-M2O56UK7.js} +243 -75
  54. package/dist/chunk-M2O56UK7.js.map +1 -0
  55. package/dist/chunk-MD7WGYYI.js +125 -0
  56. package/dist/chunk-MD7WGYYI.js.map +1 -0
  57. package/dist/chunk-MJZZTKCC.js +323 -0
  58. package/dist/chunk-MJZZTKCC.js.map +1 -0
  59. package/dist/chunk-O6CAUZGY.js +317 -0
  60. package/dist/chunk-O6CAUZGY.js.map +1 -0
  61. package/dist/chunk-P74I3WH4.js +204 -0
  62. package/dist/chunk-P74I3WH4.js.map +1 -0
  63. package/dist/chunk-POF7HPRV.js +145 -0
  64. package/dist/chunk-POF7HPRV.js.map +1 -0
  65. package/dist/chunk-POJRB2AE.js +83 -0
  66. package/dist/chunk-POJRB2AE.js.map +1 -0
  67. package/dist/{chunk-FIYZLITH.js → chunk-PZRAAAY2.js} +107 -18
  68. package/dist/chunk-PZRAAAY2.js.map +1 -0
  69. package/dist/chunk-PZSUWDF2.js +35 -0
  70. package/dist/chunk-PZSUWDF2.js.map +1 -0
  71. package/dist/chunk-QW2Q2KAH.js +27 -0
  72. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  73. package/dist/chunk-R2VLGNFD.js +181 -0
  74. package/dist/chunk-R2VLGNFD.js.map +1 -0
  75. package/dist/{chunk-CPUZRZ2A.js → chunk-RBJPAZFI.js} +25 -170
  76. package/dist/chunk-RBJPAZFI.js.map +1 -0
  77. package/dist/chunk-S5RYMCV6.js +70 -0
  78. package/dist/chunk-S5RYMCV6.js.map +1 -0
  79. package/dist/chunk-SGK2B724.js +67 -0
  80. package/dist/chunk-SGK2B724.js.map +1 -0
  81. package/dist/chunk-STND72DS.js +242 -0
  82. package/dist/chunk-STND72DS.js.map +1 -0
  83. package/dist/chunk-TEL27PR5.js +124 -0
  84. package/dist/chunk-TEL27PR5.js.map +1 -0
  85. package/dist/chunk-TWRYSGAW.js +134 -0
  86. package/dist/chunk-TWRYSGAW.js.map +1 -0
  87. package/dist/{chunk-WOHCAMDQ.js → chunk-U5S527PP.js} +1887 -1029
  88. package/dist/chunk-U5S527PP.js.map +1 -0
  89. package/dist/chunk-UHTVXQ2O.js +140 -0
  90. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  91. package/dist/chunk-UOJRKQTZ.js +213 -0
  92. package/dist/chunk-UOJRKQTZ.js.map +1 -0
  93. package/dist/chunk-V4WWTZHZ.js +233 -0
  94. package/dist/chunk-V4WWTZHZ.js.map +1 -0
  95. package/dist/chunk-VRRLTZ2Q.js +651 -0
  96. package/dist/chunk-VRRLTZ2Q.js.map +1 -0
  97. package/dist/{chunk-TX5T3LKJ.js → chunk-W6R3HAAG.js} +21 -17
  98. package/dist/{chunk-TX5T3LKJ.js.map → chunk-W6R3HAAG.js.map} +1 -1
  99. package/dist/chunk-X3OOVSPX.js +154 -0
  100. package/dist/chunk-X3OOVSPX.js.map +1 -0
  101. package/dist/chunk-XJN5WUKL.js +204 -0
  102. package/dist/chunk-XJN5WUKL.js.map +1 -0
  103. package/dist/chunk-Y7ERTA7D.js +146 -0
  104. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  105. package/dist/chunk-YLYINX2H.js +7806 -0
  106. package/dist/chunk-YLYINX2H.js.map +1 -0
  107. package/dist/chunk-ZQIQ55KK.js +51 -0
  108. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  109. package/dist/chunk-ZUAQRIVP.js +1369 -0
  110. package/dist/chunk-ZUAQRIVP.js.map +1 -0
  111. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  112. package/dist/chunk-ZXTAQYNA.js.map +1 -0
  113. package/dist/{cli-LMHGCZ5S.js → cli-HK2XAWNW.js} +438 -177
  114. package/dist/cli-HK2XAWNW.js.map +1 -0
  115. package/dist/config-LYCHHNAJ.js +26 -0
  116. package/dist/config-LYCHHNAJ.js.map +1 -0
  117. package/dist/dist-U4M6QCKE.js +2842 -0
  118. package/dist/dist-U4M6QCKE.js.map +1 -0
  119. package/dist/doctor-2KPUQURC.js +27 -0
  120. package/dist/doctor-2KPUQURC.js.map +1 -0
  121. package/dist/edit-TST3OCKQ.js +38 -0
  122. package/dist/edit-TST3OCKQ.js.map +1 -0
  123. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  124. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-TPTHVPBB.js +35 -0
  127. package/dist/inspect-TPTHVPBB.js.map +1 -0
  128. package/dist/install-PT3XEDJ6.js +1869 -0
  129. package/dist/install-PT3XEDJ6.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-NPNSF2Q7.js +22 -0
  132. package/dist/outcome-NPNSF2Q7.js.map +1 -0
  133. package/dist/publish-XP5SEWST.js +41 -0
  134. package/dist/publish-XP5SEWST.js.map +1 -0
  135. package/dist/read-D4VXRWOG.js +158 -0
  136. package/dist/read-D4VXRWOG.js.map +1 -0
  137. package/dist/run-3IPGEXW7.js +16902 -0
  138. package/dist/run-3IPGEXW7.js.map +1 -0
  139. package/dist/search-YOBD6VDI.js +24 -0
  140. package/dist/search-YOBD6VDI.js.map +1 -0
  141. package/dist/{secp256k1-35YNNB6F.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-BWNP6WN4.js +223 -0
  144. package/dist/send-BWNP6WN4.js.map +1 -0
  145. package/dist/session-GZEZBOMI.js +88 -0
  146. package/dist/session-GZEZBOMI.js.map +1 -0
  147. package/dist/skill-heal-OK6YALW6.js +85 -0
  148. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  149. package/dist/usdc-4VCDHFWX.js +38 -0
  150. package/dist/usdc-4VCDHFWX.js.map +1 -0
  151. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  152. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  153. package/dist/wallet-5RHDFPN2.js +32 -0
  154. package/dist/wallet-5RHDFPN2.js.map +1 -0
  155. package/dist/wallet-YEGQBWWL.js +42 -0
  156. package/dist/wallet-YEGQBWWL.js.map +1 -0
  157. package/docs/agent-permissions.md +281 -0
  158. package/package.json +26 -17
  159. package/skills/tenjin/SKILL.md +364 -0
  160. package/skills/tenjin-publish/SKILL.md +219 -0
  161. package/skills/tenjin-search/SKILL.md +335 -0
  162. package/dist/chunk-376LHMK2.js +0 -100
  163. package/dist/chunk-376LHMK2.js.map +0 -1
  164. package/dist/chunk-CPUZRZ2A.js.map +0 -1
  165. package/dist/chunk-F5DZJLU3.js.map +0 -1
  166. package/dist/chunk-FIYZLITH.js.map +0 -1
  167. package/dist/chunk-LTTRND4A.js +0 -135
  168. package/dist/chunk-LTTRND4A.js.map +0 -1
  169. package/dist/chunk-PAAL45FJ.js.map +0 -1
  170. package/dist/chunk-QHIEYBLV.js +0 -320
  171. package/dist/chunk-QHIEYBLV.js.map +0 -1
  172. package/dist/chunk-SXQQ2ZSR.js.map +0 -1
  173. package/dist/chunk-WOHCAMDQ.js.map +0 -1
  174. package/dist/chunk-ZPZFPVDN.js +0 -67
  175. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  176. package/dist/cli-LMHGCZ5S.js.map +0 -1
  177. package/dist/config-XVXZ3V2Q.js +0 -206
  178. package/dist/config-XVXZ3V2Q.js.map +0 -1
  179. package/dist/doctor-MVLZRVPU.js +0 -338
  180. package/dist/doctor-MVLZRVPU.js.map +0 -1
  181. package/dist/usdc-OQUOFF6R.js +0 -18
  182. package/dist/wallet-NRKWLKHX.js +0 -153
  183. package/dist/wallet-NRKWLKHX.js.map +0 -1
  184. package/dist/wallet-QUWK2PA4.js +0 -22
  185. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  186. /package/dist/{ccip-FXWZDDF5.js.map → _esm-N4KAVXQR.js.map} +0 -0
  187. /package/dist/{chunk-3IMLRUZE.js.map → buy-FMDBZ4NY.js.map} +0 -0
  188. /package/dist/{secp256k1-35YNNB6F.js.map → candidate-7LAELUQD.js.map} +0 -0
  189. /package/dist/{usdc-OQUOFF6R.js.map → ccip-RPPPKTJR.js.map} +0 -0
  190. /package/dist/{wallet-QUWK2PA4.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  191. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/edit.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, type PublishMode } from '../lib/config';\nimport { UUID_RE } from '../lib/ids';\nimport { scan, type ScanContext, type ScanFinding } from '../lib/scan';\nimport { deriveProjectMarkers } from '../lib/scan-context';\nimport { sanitizeForTerminal } from '../lib/output';\nimport {\n deriveCard,\n missingSentences,\n parseAppliesToFlags,\n parseFrontmatter,\n type CardFlags,\n type ResourceCardInput,\n} from '../lib/card';\nimport {\n buildPostUpdateBody,\n getOwnPost,\n updatePost,\n type OwnPost,\n type OwnPostCard,\n type PostUpdateInput,\n type ResourceCardUpdate,\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 edit <postId>`: the agent-side twin of the web answer-card panel. With\n * no change flags it READS the owner-scoped post and prints it; with change flags\n * it merge-updates via `PUT /api/posts/<id>` — omitted key = keep, `--clear` sends\n * the explicit null (or the empty container) the server's merge clears on, and an\n * array flag REPLACES the stored array wholesale (`--add-question` is the append\n * convenience that reads first and sends the merged array).\n *\n * The gates are publish's, deliberately: the same deterministic scan over the new\n * body + card text (a live secret hard-blocks in every mode) and the same\n * publish.mode consent cascade, because an edit ships content to the same public\n * page a publish does.\n *\n * Unlike publish, the wallet is touched BEFORE consent, and that is a real\n * tradeoff, not a technicality: the before→after summary the user approves can\n * only be built from the stored post, and reading it is owner-scoped. The read\n * changes nothing on the server and burns no nonce, but on first use it\n * establishes a session key, so one wallet signature and a delegation persisted to\n * `~/.tenjin/session.json` precede any approval. What that delegation can DO is\n * scoped to the run: a no-flag show mints `read`, and only an invocation that\n * intends to write asks for `read+write`. We accept the remaining cost, because\n * the alternative is asking a human to approve a diff we cannot show them.\n *\n * Exit codes: 0 success (and the read-only show), 2 usage, 3 needs_confirmation /\n * non-bypassable publish_blocked, 4 a write failure after approval.\n */\n\nexport interface EditArgs {\n /** The post uuid to edit. */\n postId: string;\n /** Card array flags: REPLACE the stored array wholesale. */\n question?: string[];\n task?: string[];\n /** Append convenience: read the stored array, add, dedupe, send the merged array. */\n addQuestion?: string[];\n addTask?: 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 /** Post fields. */\n title?: string;\n /** Post price, decimal USD at the edge (O1). */\n price?: string;\n /** A Markdown file whose body (frontmatter stripped) replaces the stored body. */\n body?: string;\n excerpt?: string;\n /** Card fields to clear (repeatable); see CLEAR_FIELDS. */\n clear?: string[];\n yes?: boolean;\n /** Raw `--mode` (review|auto|full-auto); validated at the edge (USAGE on a bad value). */\n mode?: string;\n}\n\nexport interface EditDeps {\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 runEdit(\n args: EditArgs,\n ctx: CommandContext,\n deps: EditDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const cwd = deps.cwd ?? process.cwd();\n\n if (!UUID_RE.test(args.postId)) {\n throw new CliError('USAGE', `Invalid post id: ${JSON.stringify(args.postId)}`, {\n fix: 'Pass the post uuid from `tenjin publish`’s receipt or your desk.',\n });\n }\n // A mistyped --mode must never silently land on a looser mode and apply an edit\n // unconfirmed; validate it at the edge, exactly as publish does.\n if (args.mode !== undefined) parsePublishModeFlag(args.mode, '--mode');\n // Every edge check that can fail on the FLAGS alone runs before the wallet: a\n // typo must cost nothing, not a signature and a round trip.\n rejectEmptyValues(args);\n assertAppendExclusivity(args);\n const clears = parseClears(args);\n const cardFlags = cardFlagsFrom(args);\n const priceAtomic = args.price !== undefined ? parseUsdToAtomic(args.price) : undefined;\n const bodyFile = args.body !== undefined ? await readBodyFile(args.body) : undefined;\n const wantsChange = hasChangeFlags(args);\n\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 // Least privilege, decided before the wallet is asked for anything: a show is a\n // READ, so it mints a read-scoped delegation rather than leaving a write-capable\n // one on disk for a command that never writes. A cached read+write session still\n // serves it, so this costs no extra signature.\n const auth = resolveWriteAuth({\n signer,\n baseUrl: runtime.baseUrl,\n dataDir: ctx.dataDir,\n scope: wantsChange ? 'read+write' : 'read',\n ...(deps.useSession !== undefined ? { useSession: deps.useSession } : {}),\n env,\n });\n const client = {\n baseUrl: runtime.baseUrl,\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n const stored = await getOwnPost(args.postId, auth, client);\n if (!wantsChange) return showReceipt(stored);\n\n // The append path merges onto the STORED array (exact-string dedupe) and sends\n // the result: the server replaces arrays wholesale, so there is no append there.\n if (args.addQuestion !== undefined && args.addQuestion.length > 0) {\n cardFlags.question = appendUnique(storedList(stored, 'questionsAnswered'), args.addQuestion);\n }\n if (args.addTask !== undefined && args.addTask.length > 0) {\n cardFlags.task = appendUnique(storedList(stored, 'tasksSupported'), args.addTask);\n }\n\n // deriveCard validates the set fields against the server's bounds and reports\n // them under the same dotted `resource.<field>` keys the server would.\n const intent: PostUpdateInput = {\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(bodyFile !== undefined ? { bodyMd: bodyFile.body } : {}),\n ...(args.excerpt !== undefined ? { excerpt: args.excerpt } : {}),\n ...(priceAtomic !== undefined ? { priceAtomic } : {}),\n ...withClears(deriveCard({}, cardFlags), clears, stored.resource),\n };\n\n // Diff before deciding anything: a no-op edit is not an edit. With nothing left\n // after pruning there is nothing to confirm, nothing new to scan, and no reason\n // to burn a nonce on a write that changes nothing. Exit 0 with the current post.\n const { input, lines: changes } = diffUpdate(stored, intent);\n if (changes.length === 0) return noChangeReceipt(stored);\n // Bounds-check the pruned body here so a miss is USAGE before the consent\n // prompt; updatePost rebuilds the same body for the wire (pure, so identical).\n buildPostUpdateBody(input);\n\n const settings = await resolvePublishSettings({\n dataDir: ctx.dataDir,\n cwd,\n ...(args.mode !== undefined ? { flag: args.mode } : {}),\n env,\n });\n writeModeNotices(\n ctx.io.stderr,\n settings,\n env,\n 'each edit asks you once. Set auto to apply clean edits automatically',\n );\n\n // Gate parity with publish (#38): the source project's own git remote slugs are\n // private-by-default, so text quoting them warns. Markers derive from the\n // CONTENT's project — the body file's own directory when there is one, else the\n // working directory — never from wherever the shell happens to be.\n const markerRoot = args.body !== undefined ? dirname(resolve(cwd, args.body)) : cwd;\n const scanContext: ScanContext = { projectMarkers: await deriveProjectMarkers(markerRoot) };\n // The scan covers exactly what this edit SHIPS: the typed text behind the keys\n // that survived pruning, plus the body file only when the body itself survived.\n // Scanning the raw flags instead would block on a value that prunes away — a\n // secret already public in the stored scope, restated verbatim, would refuse an\n // unrelated title change while the same flags alone exit 0. A secret in a\n // surviving value still blocks in every mode, never cleared by --yes.\n const findings = dedupeFindings([\n ...(input.bodyMd !== undefined ? scan(bodyFile?.raw ?? '', scanContext) : []),\n ...scan(shippedTypedText(args, input), scanContext),\n ]);\n const blocking = findings.filter((f) => f.severity === 'block');\n const warns = findings.filter((f) => f.severity === 'warn');\n if (blocking.length > 0) {\n throw new CliError('PUBLISH_BLOCKED', blockMessage(blocking), {\n fix: 'Remove the secret from the new content (it is never masked away by --yes), then re-run.',\n details: { mode: settings.mode, findings: blocking.map(publicFinding) },\n });\n }\n\n const notes = editNotes(args, stored, bodyFile, clears);\n for (const line of [...notes, ...changes]) ctx.io.stderr.write(`${line}\\n`);\n\n if (needsConfirmation(settings.mode, warns.length) && args.yes !== true) {\n throw new CliError('NEEDS_CONFIRMATION', confirmMessage(warns.length, changes.length), {\n fix: 'Review the changes, then re-run with --yes.',\n details: {\n mode: settings.mode,\n postId: stored.id,\n title: sanitizeForTerminal(stored.title),\n changes,\n ...(notes.length > 0 ? { notes } : {}),\n findings: warns.map(publicFinding),\n },\n });\n }\n\n const updated = await updatePost(args.postId, input, auth, client);\n return updateReceipt(updated, changes, notes, settings.mode);\n}\n\n// ---------------------------------------------------------------------------\n// Receipts.\n// ---------------------------------------------------------------------------\n\n/** The read half of the loop: the stored post + card, owner view. */\nfunction showReceipt(post: OwnPost): CommandResult {\n const price = toMoney(post.price);\n const card = post.resource;\n const lines = [\n `${sanitizeForTerminal(post.title)} (${sanitizeForTerminal(post.status)}), ${price.usd} USD (${price.atomic} atomic)`,\n `url: ${sanitizeForTerminal(post.url)}`,\n ...(hasText(post.excerpt) ? [`excerpt: ${preview(post.excerpt)}`] : []),\n ...cardLines(card),\n eligibilityLine(card),\n ];\n return { data: post, humanLines: lines };\n}\n\n/**\n * The applied-update receipt. `changes` (and `notes`) are mirrored INTO the data\n * as well as printed, the way publish mirrors its stderr warnings into the\n * receipt: an MCP client gets a discard sink for stderr, so a summary that lives\n * only there is a summary it can never show the user. `changes: []` is the\n * unambiguous machine signal that nothing was written.\n */\nfunction updateReceipt(\n post: OwnPost,\n changes: string[],\n notes: string[],\n mode: PublishMode,\n): CommandResult {\n const card = post.resource;\n const lines = [\n `Updated ${sanitizeForTerminal(post.title)} → ${sanitizeForTerminal(post.url)}`,\n eligibilityLine(card),\n ...(post.warnings ?? []).map((w) => `warning: ${sanitizeForTerminal(w)}`),\n ];\n return {\n // `mode` is echoed because a per-call --mode (or the MCP `mode` argument) is\n // otherwise invisible in a transcript: the receipt would look identical\n // whether the caller loosened the gate for this run or not.\n data: { ...post, mode, changes, ...(notes.length > 0 ? { notes } : {}) },\n humanLines: lines,\n };\n}\n\n/** Nothing to write: the post as it stands, and an empty change list to prove it. */\nfunction noChangeReceipt(post: OwnPost): CommandResult {\n return {\n data: { ...post, changes: [] },\n humanLines: [\n `No changes: every value given already matches ${sanitizeForTerminal(post.title)}. Nothing was written.`,\n ],\n };\n}\n\n/** The card fields that are set, one per line; nothing for a post with no card. */\nfunction cardLines(card: OwnPostCard | undefined): string[] {\n if (card === undefined) return [];\n const lines: string[] = [];\n const list = (label: string, values: string[] | null | undefined): void => {\n if (values !== undefined && values !== null && values.length > 0) {\n lines.push(\n `${label} (${values.length}): ${values.map((v) => sanitizeForTerminal(v)).join(' | ')}`,\n );\n }\n };\n list('questionsAnswered', card.questionsAnswered);\n list('tasksSupported', card.tasksSupported);\n for (const [label, value] of [\n ['scope', card.scope],\n ['exclusions', card.exclusions],\n ['artifactType', card.artifactType],\n ['temporalMode', card.temporalMode],\n ['asOf', card.asOf],\n ['validUntil', card.validUntil],\n ['provenance', card.provenanceSummary],\n ['methodology', card.methodologySummary],\n ['supersedesPostId', card.supersedesPostId],\n ] as const) {\n if (hasText(value)) lines.push(`${label}: ${preview(value)}`);\n }\n if (card.appliesTo !== undefined && card.appliesTo !== null) {\n for (const [key, values] of Object.entries(card.appliesTo)) {\n lines.push(\n `appliesTo ${sanitizeForTerminal(key)}: ${values.map((v) => sanitizeForTerminal(v)).join(', ')}`,\n );\n }\n }\n return lines;\n}\n\nfunction eligibilityLine(card: OwnPostCard | undefined): string {\n if (card === undefined) return 'No answer card (browse-only document).';\n const missing = missingSentences(card.cacheEligibleMissing).map(sanitizeForTerminal);\n if (card.cacheEligible) return 'Answer card is search-eligible.';\n return missing.length > 0\n ? `Answer card not search-eligible yet: ${missing.join(' ')}`\n : 'Answer card is not search-eligible.';\n}\n\n// ---------------------------------------------------------------------------\n// The before→after summary.\n// ---------------------------------------------------------------------------\n\n/**\n * Diff what the flags ASK for against what is stored, and return both the terse\n * summary and an input pruned to the fields that actually move.\n *\n * Pruning is not cosmetic. A card key that rides along unchanged still counts as a\n * card write server-side, which re-runs the embedding for a card nobody edited;\n * and on a post with NO card, a lone `scope: null` mints an all-default card row,\n * turning a browse-only document into a card-bearing one. Comparing first and\n * sending only the difference is what keeps `edit` idempotent.\n */\nfunction diffUpdate(\n stored: OwnPost,\n intent: PostUpdateInput,\n): { input: PostUpdateInput; lines: string[] } {\n const lines: string[] = [];\n const input: PostUpdateInput = {};\n\n // Both sides trimmed, because the server trims these before storing them: an\n // untrimmed compare would call \" x\" a change from \"x\" forever.\n const title = intent.title?.trim();\n if (title !== undefined && title !== stored.title) {\n input.title = title;\n lines.push(`title: ${preview(stored.title)} → ${preview(title)}`);\n }\n if (intent.priceAtomic !== undefined && intent.priceAtomic !== stored.price) {\n const before = toMoney(stored.price);\n const after = toMoney(intent.priceAtomic);\n input.priceAtomic = intent.priceAtomic;\n lines.push(\n `price: ${before.usd} USD (${before.atomic} atomic) → ${after.usd} USD (${after.atomic} atomic)`,\n );\n }\n if (intent.bodyMd !== undefined && intent.bodyMd !== stored.bodyMd) {\n input.bodyMd = intent.bodyMd;\n lines.push(`body: ${(stored.bodyMd ?? '').length} → ${intent.bodyMd.length} characters`);\n }\n const excerpt = intent.excerpt?.trim();\n if (excerpt !== undefined && excerpt !== (stored.excerpt ?? '')) {\n input.excerpt = excerpt;\n lines.push(`excerpt: ${preview(stored.excerpt)} → ${preview(excerpt)}`);\n }\n\n const card = diffCard(stored.resource, intent.resource);\n lines.push(...card.lines);\n if (card.card !== undefined) input.resource = card.card;\n\n // Empty means EMPTY: the caller reads no lines as \"this edit is a no-op\" and\n // skips the write, so a sentinel line here would report a change that isn't one.\n return { input, lines };\n}\n\n/**\n * How each card key is diffed. The Record over `keyof ResourceCardUpdate` is the\n * point: adding a field to the card type without saying how it diffs is a compile\n * error here, not a field that silently never reaches the wire. `none` marks a\n * field no flag and no clear can set today, so it can never appear in `next`;\n * giving one a flag means moving it to a real pass.\n */\ntype CardPass = 'list' | 'iso' | 'scalar' | 'map' | 'none';\nconst CARD_PASS = {\n questionsAnswered: 'list',\n tasksSupported: 'list',\n asOf: 'iso',\n validUntil: 'iso',\n scope: 'scalar',\n exclusions: 'scalar',\n artifactType: 'scalar',\n temporalMode: 'scalar',\n provenanceSummary: 'scalar',\n methodologySummary: 'scalar',\n supersedesPostId: 'scalar',\n appliesTo: 'map',\n mediaType: 'none',\n maintenanceCadence: 'none',\n reproductionMinutes: 'none',\n estimatedPaidInputCost: 'none',\n} as const satisfies Record<keyof ResourceCardUpdate, CardPass>;\n\n/** The card keys assigned to one pass, as a union of literal keys. */\ntype KeysIn<P extends CardPass> = {\n [K in keyof typeof CARD_PASS]: (typeof CARD_PASS)[K] extends P ? K : never;\n}[keyof typeof CARD_PASS];\n\nfunction keysIn<P extends CardPass>(pass: P): KeysIn<P>[] {\n return Object.entries(CARD_PASS)\n .filter(([, value]) => value === pass)\n .map(([key]) => key) as KeysIn<P>[];\n}\n\n/** The two card keys whose flag name differs from the field name. */\nconst CARD_LABEL: Partial<Record<keyof ResourceCardUpdate, string>> = {\n provenanceSummary: 'provenance',\n methodologySummary: 'methodology',\n};\nfunction cardLabel(key: keyof ResourceCardUpdate): string {\n return CARD_LABEL[key] ?? key;\n}\n\n/**\n * The card half of the diff. Every comparison treats an ABSENT stored value as\n * already-cleared, which is what makes clearing a field on a cardless post the\n * no-op it should be rather than a card-creating write.\n */\nfunction diffCard(\n stored: OwnPostCard | undefined,\n next: ResourceCardUpdate | undefined,\n): { card?: ResourceCardUpdate; lines: string[] } {\n const lines: string[] = [];\n const card: Record<string, unknown> = {};\n const keep = (key: keyof ResourceCardUpdate, value: unknown, line: string): void => {\n card[key] = value;\n lines.push(line);\n };\n if (next === undefined) return { lines };\n\n // Lists replace wholesale, so order counts; an absent stored list reads as empty.\n for (const key of keysIn('list')) {\n const after = next[key];\n if (after === undefined) continue;\n const old = stored?.[key] ?? [];\n if (sameList(old, after)) continue;\n const added = after.filter((v) => !old.includes(v));\n const detail =\n after.length === 0 ? ' (cleared)' : added.length > 0 ? ` (new: ${previewList(added)})` : '';\n keep(key, after, `${key}: ${old.length} → ${after.length}${detail}`);\n }\n\n // The timestamps compare as INSTANTS and are sent canonicalized. The server\n // echoes a timestamptz through toISOString(), while a flag carries whatever the\n // user typed, so \"2026-07-01T00:00:00Z\" and \"2026-07-01T00:00:00.000Z\" are the\n // same moment spelled two ways — comparing the spellings would re-write the\n // field on every single run.\n for (const key of keysIn('iso')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = isoInstant(stored?.[key]);\n const to = isoInstant(after);\n if (from === to) continue;\n keep(key, to, `${key}: ${preview(from)} → ${to === null ? '(cleared)' : preview(to)}`);\n }\n\n for (const key of keysIn('scalar')) {\n const after = next[key];\n if (after === undefined) continue;\n const from = stored?.[key] ?? null;\n if (from === after) continue;\n keep(\n key,\n after,\n `${cardLabel(key)}: ${preview(from)} → ${after === null ? '(cleared)' : preview(after)}`,\n );\n }\n\n // appliesTo is one value, not a key count: a same-size swap (products=Base →\n // products=Vercel) has identical counts on both sides, so a count compare would\n // call a real change a no-op and a count RENDER would print it as one.\n for (const key of keysIn('map')) {\n const after = next[key];\n if (after === undefined) continue;\n const before = stored?.[key] ?? {};\n if (sameAppliesTo(before, after)) continue;\n keep(key, after, `${key}: ${appliesToPreview(before)} → ${appliesToPreview(after)}`);\n }\n\n return { ...(Object.keys(card).length > 0 ? { card: card as ResourceCardUpdate } : {}), lines };\n}\n\n/**\n * A timestamp as its canonical instant, so two spellings of one moment compare\n * equal. An unparseable value (never from a flag — validateIso ran — but possible\n * from a future server format) passes through rather than being silently dropped.\n */\nfunction isoInstant(value: string | null | undefined): string | null {\n if (value === undefined || value === null) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? new Date(ms).toISOString() : value;\n}\n\n/** Map equality: keys order-insensitive, each key's values order-sensitive. */\nfunction sameAppliesTo(a: Record<string, string[]>, b: Record<string, string[]>): boolean {\n const aKeys = Object.keys(a).sort();\n const bKeys = Object.keys(b).sort();\n if (!sameList(aKeys, bKeys)) return false;\n return aKeys.every((key) => sameList(a[key] ?? [], b[key] ?? []));\n}\n\n/** The advisory notes a --body edit needs, in the order a human reads them. */\nfunction editNotes(\n args: EditArgs,\n stored: OwnPost,\n bodyFile: BodyFile | undefined,\n clears: ClearField[],\n): string[] {\n if (bodyFile === undefined) return [];\n const notes: string[] = [];\n if (bodyFile.hadFrontmatter) {\n notes.push(\n 'note: frontmatter in the body file was ignored; metadata changes only through flags.',\n );\n }\n if (args.excerpt === undefined) {\n notes.push(\n `note: the excerpt stays as-is (${preview(stored.excerpt)}) and remains lexically indexed; the server does not re-derive it. Pass --excerpt to change it.`,\n );\n }\n // Only when asOf really is staying put: a run that clears it is already saying\n // so in the summary, and both lines together would contradict each other.\n const asOfMoves = args.asOf !== undefined || clears.includes('asOf');\n if (stored.resource?.temporalMode === 'snapshot' && !asOfMoves) {\n notes.push(\n `note: asOf is unchanged (${preview(stored.resource.asOf)}) on this snapshot card, and search freshness gating uses it. Pass --as-of to move it.`,\n );\n }\n return notes;\n}\n\n// ---------------------------------------------------------------------------\n// Flag parsing + validation.\n// ---------------------------------------------------------------------------\n\n/** The card fields `--clear` accepts, named as the flag that sets each one. */\nconst CLEAR_FIELDS = [\n 'scope',\n 'exclusions',\n 'asOf',\n 'validUntil',\n 'provenance',\n 'methodology',\n 'supersedesPostId',\n 'questionsAnswered',\n 'tasksSupported',\n 'appliesTo',\n] as const;\ntype ClearField = (typeof CLEAR_FIELDS)[number];\n\n/** clear name → the card key it targets. */\nconst CLEAR_KEY = {\n scope: 'scope',\n exclusions: 'exclusions',\n asOf: 'asOf',\n validUntil: 'validUntil',\n provenance: 'provenanceSummary',\n methodology: 'methodologySummary',\n supersedesPostId: 'supersedesPostId',\n questionsAnswered: 'questionsAnswered',\n tasksSupported: 'tasksSupported',\n appliesTo: 'appliesTo',\n} as const satisfies Record<ClearField, keyof ResourceCardUpdate>;\n\n/**\n * clear name → the value that clears its key server-side. Each value is typed as\n * the card field it lands on, so sending the wrong shape (a null where the merge\n * clears with `[]`, or an `[]` where it wants null) is a compile error, not a\n * validation_failed discovered in production.\n */\nconst CLEAR_VALUE: { [F in ClearField]: ResourceCardUpdate[(typeof CLEAR_KEY)[F]] } = {\n scope: null,\n exclusions: null,\n asOf: null,\n validUntil: null,\n provenance: null,\n methodology: null,\n supersedesPostId: null,\n questionsAnswered: [],\n tasksSupported: [],\n appliesTo: {},\n};\n\n/** clear name → the set-flags that would contradict it in the same invocation. */\nconst CLEAR_CONFLICTS: Record<ClearField, Array<keyof EditArgs>> = {\n scope: ['scope'],\n exclusions: ['exclusions'],\n asOf: ['asOf'],\n validUntil: ['validUntil'],\n provenance: ['provenance'],\n methodology: ['methodology'],\n supersedesPostId: [],\n questionsAnswered: ['question', 'addQuestion'],\n tasksSupported: ['task', 'addTask'],\n appliesTo: ['appliesTo'],\n};\n\n/** The CLI spelling of each arg key, for error messages. */\nconst FLAG_NAME: Record<string, string> = {\n question: '--question',\n task: '--task',\n addQuestion: '--add-question',\n addTask: '--add-task',\n scope: '--scope',\n exclusions: '--exclusions',\n appliesTo: '--applies-to',\n asOf: '--as-of',\n validUntil: '--valid-until',\n artifactType: '--artifact-type',\n temporalMode: '--temporal-mode',\n provenance: '--provenance',\n methodology: '--methodology',\n title: '--title',\n price: '--price',\n body: '--body',\n excerpt: '--excerpt',\n};\n\nconst CHANGE_KEYS: Array<keyof EditArgs> = [\n 'question',\n 'task',\n 'addQuestion',\n 'addTask',\n 'scope',\n 'exclusions',\n 'appliesTo',\n 'asOf',\n 'validUntil',\n 'artifactType',\n 'temporalMode',\n 'provenance',\n 'methodology',\n 'title',\n 'price',\n 'body',\n 'excerpt',\n 'clear',\n];\n\nfunction hasChangeFlags(args: EditArgs): boolean {\n return CHANGE_KEYS.some((key) => {\n const value = args[key];\n return Array.isArray(value) ? value.length > 0 : value !== undefined;\n });\n}\n\n/**\n * An explicit empty value is refused for every set-flag: `--scope \"\"` reads as\n * \"clear the scope\", but only `--clear scope` sends the null that clears it, and a\n * silently-sent empty string would set a blank field instead. One spelling per\n * intent, no ambiguity.\n */\nfunction rejectEmptyValues(args: EditArgs): void {\n for (const [key, flag] of Object.entries(FLAG_NAME)) {\n const value = args[key as keyof EditArgs];\n const empties =\n typeof value === 'string'\n ? [value]\n : Array.isArray(value)\n ? value.filter((v) => typeof v === 'string')\n : [];\n for (const v of empties) {\n if (v.trim().length === 0) {\n const clearable = (CLEAR_FIELDS as readonly string[]).includes(clearNameFor(key));\n throw new CliError('USAGE', `${flag} cannot be empty.`, {\n fix: clearable\n ? `Pass a value, or clear the field with \\`--clear ${clearNameFor(key)}\\`.`\n : 'Pass a value, or omit the flag to keep the stored one.',\n });\n }\n }\n }\n}\n\n/** The `--clear` name a set-flag arg key corresponds to (identity where they match). */\nfunction clearNameFor(key: string): string {\n if (key === 'question' || key === 'addQuestion') return 'questionsAnswered';\n if (key === 'task' || key === 'addTask') return 'tasksSupported';\n return key;\n}\n\nfunction assertAppendExclusivity(args: EditArgs): void {\n const both = (a: string[] | undefined, b: string[] | undefined): boolean =>\n a !== undefined && a.length > 0 && b !== undefined && b.length > 0;\n if (both(args.question, args.addQuestion)) {\n throw new CliError('USAGE', 'Pass either --question or --add-question, not both.', {\n fix: '--question replaces the stored questions; --add-question appends to them.',\n });\n }\n if (both(args.task, args.addTask)) {\n throw new CliError('USAGE', 'Pass either --task or --add-task, not both.', {\n fix: '--task replaces the stored tasks; --add-task appends to them.',\n });\n }\n}\n\nfunction parseClears(args: EditArgs): ClearField[] {\n const raw = args.clear ?? [];\n const out: ClearField[] = [];\n for (const name of raw) {\n if (!(CLEAR_FIELDS as readonly string[]).includes(name)) {\n throw new CliError('USAGE', `Cannot clear ${JSON.stringify(name)}.`, {\n fix: `Clearable fields: ${CLEAR_FIELDS.join(', ')}.`,\n });\n }\n const field = name as ClearField;\n for (const key of CLEAR_CONFLICTS[field]) {\n const value = args[key];\n const given = Array.isArray(value) ? value.length > 0 : value !== undefined;\n if (given) {\n throw new CliError(\n 'USAGE',\n `--clear ${field} contradicts ${FLAG_NAME[key as string] ?? String(key)}.`,\n { fix: 'Set the field or clear it, not both in the same run.' },\n );\n }\n }\n if (!out.includes(field)) out.push(field);\n }\n return out;\n}\n\nfunction cardFlagsFrom(args: EditArgs): 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 card this edit ASKS for: the validated set fields plus the clears. Built\n * from an allowlist (deriveCard's output keys and CLEAR_KEY) and never from a\n * spread of the GET, so a server-owned key (cacheEligible, cacheEligibleMissing,\n * schemaVersion) cannot reach a strictObject body that would reject it.\n *\n * What actually protects the server's D14 invariant (no card row on a browse-only\n * post) is diffCard: it defaults an absent stored value to already-cleared, so a\n * clear on a post with no card compares equal and prunes away. Dropping the clears\n * here as well is a deliberate redundant backstop, one step earlier and local to\n * the one condition that matters, because the cost of that invariant breaking is a\n * plain document silently becoming card-bearing.\n */\nfunction withClears(\n set: ResourceCardInput | undefined,\n clears: ClearField[],\n stored: OwnPostCard | undefined,\n): { resource?: ResourceCardUpdate } {\n const applicable = stored !== undefined ? clears : [];\n if (set === undefined && applicable.length === 0) return {};\n const card: Record<string, unknown> = { ...(set ?? {}) };\n for (const name of applicable) {\n card[CLEAR_KEY[name]] = CLEAR_VALUE[name];\n }\n return Object.keys(card).length > 0 ? { resource: card as ResourceCardUpdate } : {};\n}\n\ninterface BodyFile {\n /** The whole file, frontmatter included; what the scan reads. */\n raw: string;\n /** The Markdown below the frontmatter; what becomes bodyMd. */\n body: string;\n hadFrontmatter: boolean;\n}\n\nasync function readBodyFile(file: string): Promise<BodyFile> {\n let raw: string;\n try {\n raw = 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 edit <id> --body post.md`.',\n cause: err,\n });\n }\n const { frontmatter, body } = parseFrontmatter(raw);\n return { raw, body, hadFrontmatter: Object.keys(frontmatter).length > 0 };\n}\n\nfunction storedList(post: OwnPost, key: 'questionsAnswered' | 'tasksSupported'): string[] {\n return post.resource?.[key] ?? [];\n}\n\n/** Append, preserving order, skipping exact-string duplicates already stored. */\nfunction appendUnique(stored: string[], additions: string[]): string[] {\n const out = [...stored];\n for (const item of additions) {\n if (!out.includes(item)) out.push(item);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Scan input + message shaping (publish's, over the edit's new content).\n// ---------------------------------------------------------------------------\n\n/**\n * The text this invocation actually SHIPS, and only that. Two filters, each\n * closing a way the gate could fire on text the edit does not publish:\n *\n * - the key must have survived pruning. A flag whose value already matches the\n * stored one changes nothing, so its text is not \"new content\" at all; blocking\n * on it refuses an edit over a secret that is already public and that no flag\n * here can remove.\n * - the value must be one the user TYPED. The append path contributes its added\n * strings, never the merged array it sends, for the same reason.\n *\n * Everything that does ship is scanned, so a secret in a surviving value blocks in\n * every mode, never cleared by --yes.\n */\nfunction shippedTypedText(args: EditArgs, input: PostUpdateInput): string {\n const parts: string[] = [];\n const add = (v: string | undefined): void => {\n if (v !== undefined) parts.push(v);\n };\n if (input.title !== undefined) add(args.title);\n if (input.excerpt !== undefined) add(args.excerpt);\n\n const card = input.resource;\n if (card === undefined) return parts.join('\\n');\n if (card.scope !== undefined) add(args.scope);\n if (card.exclusions !== undefined) add(args.exclusions);\n if (card.provenanceSummary !== undefined) add(args.provenance);\n if (card.methodologySummary !== undefined) add(args.methodology);\n if (card.asOf !== undefined) add(args.asOf);\n if (card.validUntil !== undefined) add(args.validUntil);\n if (card.questionsAnswered !== undefined) {\n for (const item of args.question ?? args.addQuestion ?? []) add(item);\n }\n if (card.tasksSupported !== undefined) {\n for (const item of args.task ?? args.addTask ?? []) add(item);\n }\n if (card.appliesTo !== undefined && args.appliesTo !== undefined) {\n // The parsed values, matching what actually ships on the card.\n for (const values of Object.values(parseAppliesToFlags(args.appliesTo))) parts.push(...values);\n }\n return parts.join('\\n');\n}\n\nfunction blockMessage(blocking: ScanFinding[]): string {\n return `Edit blocked: the new content contains ${describeFindings(blocking)}.`;\n}\n\nfunction confirmMessage(warnCount: number, changeCount: number): string {\n return warnCount > 0\n ? `Edit needs confirmation: ${changeCount} change(s), ${warnCount} finding(s).`\n : `Edit needs confirmation: ${changeCount} change(s).`;\n}\n\n// ---------------------------------------------------------------------------\n// Small formatting helpers.\n// ---------------------------------------------------------------------------\n\nconst PREVIEW_MAX = 60;\n/** A whole rendered line's budget: a max-size card is 8 keys × 20 × 120 chars. */\nconst LINE_MAX = 200;\n\n/** Terminal-safe, whitespace-collapsed, and capped: the one place values are cut. */\nfunction clip(value: string, max = PREVIEW_MAX): string {\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n return clean.length > max ? `${clean.slice(0, max)}…` : clean;\n}\n\n/** A short, terminal-safe rendering of a stored or new value for the summary. */\nfunction preview(value: string | null | undefined): string {\n if (value === undefined || value === null || value.length === 0) return '(unset)';\n const clean = sanitizeForTerminal(value).replace(/\\s+/g, ' ').trim();\n if (clean.length === 0) return '(unset)';\n return clean.length > PREVIEW_MAX\n ? `${JSON.stringify(clean.slice(0, PREVIEW_MAX))}…`\n : JSON.stringify(clean);\n}\n\nfunction previewList(values: string[]): string {\n return values.map((v) => preview(v)).join(', ');\n}\n\n/**\n * `products=Base|Vercel, runtimes=node` — the VALUES, so a swap reads as a swap.\n * Every value takes the same 60-char cap the rest of the summary uses, and the\n * whole rendering is capped too: a full-size card would otherwise put ~19KB on one\n * stderr line.\n */\nfunction appliesToPreview(appliesTo: Record<string, string[]>): string {\n const entries = Object.entries(appliesTo);\n if (entries.length === 0) return '(unset)';\n const rendered = entries\n .map(([key, values]) => `${clip(key)}=${values.map((v) => clip(v)).join('|')}`)\n .join(', ');\n return clip(rendered, LINE_MAX);\n}\n\nfunction sameList(a: string[], b: string[]): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nfunction hasText(value: string | null | undefined): boolean {\n return typeof value === 'string' && value.trim().length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AA2GjC,eAAsB,QACpB,MACA,KACA,OAAiB,CAAC,GACM;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AAEpC,MAAI,CAAC,QAAQ,KAAK,KAAK,MAAM,GAAG;AAC9B,UAAM,IAAI,SAAS,SAAS,oBAAoB,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI;AAAA,MAC7E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AAGA,MAAI,KAAK,SAAS,OAAW,sBAAqB,KAAK,MAAM,QAAQ;AAGrE,oBAAkB,IAAI;AACtB,0BAAwB,IAAI;AAC5B,QAAM,SAAS,YAAY,IAAI;AAC/B,QAAM,YAAY,cAAc,IAAI;AACpC,QAAM,cAAc,KAAK,UAAU,SAAY,iBAAiB,KAAK,KAAK,IAAI;AAC9E,QAAM,WAAW,KAAK,SAAS,SAAY,MAAM,aAAa,KAAK,IAAI,IAAI;AAC3E,QAAM,cAAc,eAAe,IAAI;AAEvC,QAAM,UAAU,MAAM,uBAAuB,GAAG;AAChD,QAAM,WAAW;AAAA,IACf;AAAA,IACA,KAAK,aA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EAAE,KAAK,GAAG,CAAC,EAAE,EAC7E,KAAK,IAAI;AACZ,SAAO,KAAK,UAAU,QAAQ;AAChC;AAEA,SAAS,SAAS,GAAa,GAAsB;AACnD,SAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC,GAAG,MAAM,MAAM,EAAE,CAAC,CAAC;AAC9D;AAEA,SAAS,QAAQ,OAA2C;AAC1D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS;AAC5D;","names":[]}
@@ -0,0 +1,188 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ package_default
4
+ } from "./chunk-A6KCZPNQ.js";
5
+
6
+ // src/lib/client-meta.ts
7
+ var TENJIN_USER_AGENT = `tenjin-cli/${package_default.version} (+https://tenjin.blog)`;
8
+
9
+ // src/lib/http.ts
10
+ function applyUserAgent(headers) {
11
+ headers.set("user-agent", TENJIN_USER_AGENT);
12
+ return headers;
13
+ }
14
+ function withUserAgent(callerHeaders) {
15
+ return Object.fromEntries(applyUserAgent(new Headers(callerHeaders ?? {})).entries());
16
+ }
17
+ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
18
+ "sign-in-with-x",
19
+ "payment-signature",
20
+ "x-payment",
21
+ "tenjin-session-delegation"
22
+ ]);
23
+ function carriesSignedMaterial(headers) {
24
+ return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
25
+ }
26
+ async function fetchJson(url, opts) {
27
+ const doFetch = opts.fetchImpl ?? fetch;
28
+ const controller = new AbortController();
29
+ let timedOut = false;
30
+ const timer = setTimeout(() => {
31
+ timedOut = true;
32
+ controller.abort();
33
+ }, opts.timeoutMs);
34
+ try {
35
+ let res;
36
+ try {
37
+ res = await doFetch(url, {
38
+ signal: controller.signal,
39
+ headers: withUserAgent(opts.headers)
40
+ });
41
+ } catch (err) {
42
+ return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
43
+ }
44
+ const requestId = res.headers.get("x-request-id") ?? void 0;
45
+ if (!res.ok) {
46
+ return {
47
+ ok: false,
48
+ kind: "http",
49
+ status: res.status,
50
+ ...requestId !== void 0 ? { requestId } : {},
51
+ message: `Request to ${url} failed with status ${res.status}`
52
+ };
53
+ }
54
+ let json;
55
+ try {
56
+ json = await res.json();
57
+ } catch (err) {
58
+ if (timedOut) return timeoutFailure(url, opts.timeoutMs);
59
+ if (err instanceof SyntaxError) {
60
+ return {
61
+ ok: false,
62
+ kind: "invalid-json",
63
+ status: res.status,
64
+ ...requestId !== void 0 ? { requestId } : {},
65
+ message: `Response from ${url} was not valid JSON`
66
+ };
67
+ }
68
+ return {
69
+ ok: false,
70
+ kind: "network",
71
+ status: res.status,
72
+ ...requestId !== void 0 ? { requestId } : {},
73
+ message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
74
+ };
75
+ }
76
+ return {
77
+ ok: true,
78
+ status: res.status,
79
+ json,
80
+ ...requestId !== void 0 ? { requestId } : {}
81
+ };
82
+ } finally {
83
+ clearTimeout(timer);
84
+ }
85
+ }
86
+ function timeoutFailure(url, timeoutMs) {
87
+ return {
88
+ ok: false,
89
+ kind: "timeout",
90
+ message: `Request to ${url} timed out after ${timeoutMs}ms`
91
+ };
92
+ }
93
+ function prepareRequest(url, opts) {
94
+ try {
95
+ let body;
96
+ const merged = new Headers(opts.headers ?? {});
97
+ if (opts.jsonBody !== void 0) {
98
+ body = JSON.stringify(opts.jsonBody);
99
+ merged.set("content-type", "application/json");
100
+ }
101
+ const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
102
+ if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
103
+ const headers = Object.fromEntries(applyUserAgent(merged).entries());
104
+ const signed = carriesSignedMaterial(headers);
105
+ return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };
106
+ } catch (err) {
107
+ return {
108
+ ok: false,
109
+ kind: "network",
110
+ message: `Request to ${url} failed: ${errorMessage(err)}`
111
+ };
112
+ }
113
+ }
114
+ async function httpRequest(url, opts) {
115
+ const doFetch = opts.fetchImpl ?? fetch;
116
+ const controller = new AbortController();
117
+ let timedOut = false;
118
+ const timer = setTimeout(() => {
119
+ timedOut = true;
120
+ controller.abort();
121
+ }, opts.timeoutMs);
122
+ try {
123
+ const prepared = prepareRequest(url, opts);
124
+ if (!prepared.ok) return prepared;
125
+ const { headers, body, signed, pinned } = prepared;
126
+ let res;
127
+ try {
128
+ res = await doFetch(url, {
129
+ method: opts.method ?? "GET",
130
+ headers,
131
+ body,
132
+ signal: controller.signal,
133
+ ...pinned ? { redirect: "manual" } : {}
134
+ });
135
+ } catch (err) {
136
+ return timedOut ? timeoutFailure(url, opts.timeoutMs) : { ok: false, kind: "network", message: `Request to ${url} failed: ${errorMessage(err)}` };
137
+ }
138
+ const requestId = res.headers.get("x-request-id") ?? void 0;
139
+ if (pinned && res.status >= 300 && res.status < 400) {
140
+ return {
141
+ ok: false,
142
+ kind: "blocked-redirect",
143
+ status: res.status,
144
+ ...requestId !== void 0 ? { requestId } : {},
145
+ message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
146
+ };
147
+ }
148
+ let text;
149
+ try {
150
+ text = await res.text();
151
+ } catch (err) {
152
+ if (timedOut) return timeoutFailure(url, opts.timeoutMs);
153
+ return {
154
+ ok: false,
155
+ kind: "network",
156
+ status: res.status,
157
+ ...requestId !== void 0 ? { requestId } : {},
158
+ message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
159
+ };
160
+ }
161
+ let json;
162
+ if (text.length > 0) {
163
+ try {
164
+ json = JSON.parse(text);
165
+ } catch {
166
+ json = void 0;
167
+ }
168
+ }
169
+ return {
170
+ ok: true,
171
+ status: res.status,
172
+ header: (name) => res.headers.get(name) ?? void 0,
173
+ json,
174
+ ...requestId !== void 0 ? { requestId } : {}
175
+ };
176
+ } finally {
177
+ clearTimeout(timer);
178
+ }
179
+ }
180
+ function errorMessage(err) {
181
+ return err instanceof Error ? err.message : String(err);
182
+ }
183
+
184
+ export {
185
+ fetchJson,
186
+ httpRequest
187
+ };
188
+ //# sourceMappingURL=chunk-DKQMJTG7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/client-meta.ts","../src/lib/http.ts"],"sourcesContent":["import pkg from '../../package.json';\n\n/**\n * The CLI's identity on every HTTP request, sent as the standard `User-Agent`\n * header from the shared transport (`http.ts`). The server's\n * `parseUserAgentProduct()` (tenjin PR #544) reads the leading RFC 9110 product\n * token (`tenjin-cli/<version>`) for canonical attribution; `X-Tenjin-Client` is\n * retired and this CLI sends it nowhere.\n */\nexport const TENJIN_USER_AGENT = `tenjin-cli/${pkg.version} (+https://tenjin.blog)`;\n","import { CliError } from './errors';\nimport { TENJIN_USER_AGENT } from './client-meta';\n\n/**\n * The single JSON client the whole CLI grows on: `doctor` uses it in B1, `search`\n * reuses it in B2. It never throws on a transport/protocol failure — it returns a\n * discriminated result so callers decide how each failure class maps to a check\n * or an error. `fetchImpl` is injectable so tests never touch the network.\n */\nexport interface FetchJsonOptions {\n /** Abort the request after this many milliseconds. */\n timeoutMs: number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** Optional request headers, merged onto the User-Agent this module always sends. */\n headers?: Record<string, string>;\n}\n\n/**\n * The one place the identity is written; both transports funnel their Headers\n * through it, so a third entry point cannot ship without it. `.set` on a Headers\n * object is what makes it total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated.\n */\nfunction applyUserAgent(headers: Headers): Headers {\n headers.set('user-agent', TENJIN_USER_AGENT);\n return headers;\n}\n\n/** The same write for `fetchJson`'s plain-object headers; Headers.entries() is lowercase-keyed. */\nfunction withUserAgent(callerHeaders?: Record<string, string>): Record<string, string> {\n return Object.fromEntries(applyUserAgent(new Headers(callerHeaders ?? {})).entries());\n}\n\n/** A successful 2xx whose body parsed as JSON. */\nexport interface FetchJsonSuccess {\n ok: true;\n status: number;\n json: unknown;\n /** The server's `x-request-id`, when it sent one — useful in error reports. */\n requestId?: string;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `http` (a non-2xx\n * status), `invalid-json` (2xx but the body was not JSON).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'http' | 'invalid-json' | 'blocked-redirect';\n status?: number;\n requestId?: string;\n message: string;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect. `resource-ref`\n * pins the invariant — \"nothing signed may leave for a host the user did not\n * configure\" — but `assertOnBaseOrigin` only checks the URL the caller asked\n * for, and `fetch`'s default `redirect: 'follow'` re-sends request headers\n * verbatim to the new host (Node strips only `Authorization`). A 3xx anywhere on\n * the configured origin would therefore hand a signature BOUND TO THE REAL\n * DOMAIN to whoever `Location` points at, replayable against it for the\n * signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * All three wallet-signed families this CLI sends are here: the SIWX auth\n * header, the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance even\n * though `read-client` pins v2), and `tenjin-session-delegation` — a REUSABLE\n * session-lifetime SIWX signature `session-key` attaches to every session-signed\n * write, which makes it the most replayable credential of the set. The RFC 9421\n * `Signature`/`Signature-Input` pair riding alongside it is deliberately absent:\n * it covers method, URL, and body digest, so it is not usefully replayable at\n * another host.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\nexport type FetchJsonResult = FetchJsonSuccess | FetchJsonFailure;\n\nexport async function fetchJson(url: string, opts: FetchJsonOptions): Promise<FetchJsonResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n // The timer stays armed until the body is fully consumed (cleared in the outer\n // finally), so a server that sends headers then stalls the body still trips the\n // deadline instead of hanging forever on res.json().\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n let res: Response;\n try {\n res = await doFetch(url, {\n signal: controller.signal,\n headers: withUserAgent(opts.headers),\n });\n } catch (err) {\n // A timeout is a network failure the AbortController induced; distinguish it\n // from an organic one so the caller can say \"timed out\" rather than a raw\n // AbortError message.\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n if (!res.ok) {\n return {\n ok: false,\n kind: 'http',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed with status ${res.status}`,\n };\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (err) {\n // The body read can fail three ways. A timeout wins first: the abort fires\n // synchronously with `timedOut`, so any abort-induced rejection here is our\n // deadline. Otherwise a SyntaxError is a genuine parse failure (invalid\n // JSON); anything else is a transport failure mid-body (network).\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (err instanceof SyntaxError) {\n return {\n ok: false,\n kind: 'invalid-json',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Response from ${url} was not valid JSON`,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n\n return {\n ok: true,\n status: res.status,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status. Unlike fetchJson (2xx-only), the B2 read/pay flow needs\n * the body on a 402 (the leak-safe preview) and a 409 (the owned-re-pay gate),\n * and search/outcome need a 4xx validation envelope. A transport/timeout failure\n * still returns the discriminated FetchJsonFailure so callers map it uniformly.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT';\n timeoutMs: number;\n headers?: Record<string, string>;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact (`fetchRead`: the\n * 200 is written to the library as an entitlement record under the\n * server-chosen id/slug), following a cross-origin redirect would let\n * another host's bytes be recorded as if the configured origin served them.\n * Off by default so search/outcome/publish/doctor keep normal transport.\n */\n blockRedirects?: boolean;\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n }\n const wantsAccept = opts.method === 'POST' || opts.method === 'PUT' || body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return { ok: true, headers, body, signed, pinned: signed || opts.blockRedirects === true };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers,\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n return timedOut\n ? timeoutFailure(url, opts.timeoutMs)\n : { ok: false, kind: 'network', message: `Request to ${url} failed: ${errorMessage(err)}` };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n try {\n text = await res.text();\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an `http` status (server reachable but errored — commonly 5xx)\n * is API_UNREACHABLE, and a 2xx that failed to parse when JSON was required is a\n * CONTRACT_MISMATCH. Callers that need a check-specific code (doctor) build their\n * own CliError; this is the default B2's passthrough leans on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'invalid-json'\n ? 'CONTRACT_MISMATCH'\n : 'API_UNREACHABLE';\n return new CliError(code, failure.message, {\n ...(opts.fix !== undefined ? { fix: opts.fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"],"mappings":";;;;;;AASO,IAAM,oBAAoB,cAAc,gBAAI,OAAO;;;ACe1D,SAAS,eAAe,SAA2B;AACjD,UAAQ,IAAI,cAAc,iBAAiB;AAC3C,SAAO;AACT;AAGA,SAAS,cAAc,eAAgE;AACrF,SAAO,OAAO,YAAY,eAAe,IAAI,QAAQ,iBAAiB,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;AACtF;AAoDA,IAAM,qBAAqB,oBAAI,IAAI;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,sBAAsB,SAA0C;AACvE,SAAO,OAAO,KAAK,OAAO,EAAE,KAAK,CAAC,SAAS,mBAAmB,IAAI,KAAK,YAAY,CAAC,CAAC;AACvF;AAIA,eAAsB,UAAU,KAAa,MAAkD;AAC7F,QAAM,UAAU,KAAK,aAAa;AAClC,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI,WAAW;AAIf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,eAAW,MAAM;AAAA,EACnB,GAAG,KAAK,SAAS;AAEjB,MAAI;AACF,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,QAAQ,KAAK;AAAA,QACvB,QAAQ,WAAW;AAAA,QACnB,SAAS,cAAc,KAAK,OAAO;AAAA,MACrC,CAAC;AAAA,IACH,SAAS,KAAK;AAIZ,aAAO,WACH,eAAe,KAAK,KAAK,SAAS,IAClC,EAAE,IAAI,OAAO,MAAM,WAAW,SAAS,cAAc,GAAG,YAAY,aAAa,GAAG,CAAC,GAAG;AAAA,IAC9F;AAEA,UAAM,YAAY,IAAI,QAAQ,IAAI,cAAc,KAAK;AAErD,QAAI,CAAC,IAAI,IAAI;AACX,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM;AA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AAKrD,QAAI,UAAU,IAAI,UAAU,OAAO,IAAI,SAAS,KAAK;AACnD,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,QAAQ,IAAI;AAAA,QACZ,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,QAC/C,SAAS,SACL,cAAc,GAAG,oBAAoB,IAAI,MAAM,sHAE/C,cAAc,GAAG,oBAAoB,IAAI,MAAM;AAAA,MAErD;AAAA,IACF;AAIA,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,SAAS,KAAK;AACZ,UAAI,SAAU,QAAO,eAAe,KAAK,KAAK,SAAS;AACvD,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,QAAQ,IAAI;AAAA,QACZ,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,QAC/C,SAAS,cAAc,GAAG,4CAA4C,aAAa,GAAG,CAAC;AAAA,MACzF;AAAA,IACF;AACA,QAAI;AACJ,QAAI,KAAK,SAAS,GAAG;AACnB,UAAI;AACF,eAAO,KAAK,MAAM,IAAI;AAAA,MACxB,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,IAAI;AAAA,MACZ,QAAQ,CAAC,SAAS,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,MAC3C;AAAA,MACA,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjD;AAAA,EACF,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AA8BA,SAAS,aAAa,KAAsB;AAC1C,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;","names":[]}
@@ -0,0 +1,137 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/lock.ts
4
+ import { mkdirSync, rmSync } from "fs";
5
+ import { writeFile } from "fs/promises";
6
+ import { join } from "path";
7
+ var owned = /* @__PURE__ */ new Set();
8
+ function ownsAnyLock() {
9
+ return owned.size > 0;
10
+ }
11
+ function releaseOwnedLocks() {
12
+ for (const path of owned) {
13
+ try {
14
+ rmSync(path, { recursive: true, force: true });
15
+ } catch {
16
+ }
17
+ }
18
+ owned.clear();
19
+ }
20
+ var DEFAULTS = { timeoutMs: 5e3, retryMs: 25 };
21
+ var LockTimeoutError = class extends Error {
22
+ lockPath;
23
+ constructor(lockPath, timeoutMs) {
24
+ super(
25
+ `Timed out waiting for lock at ${lockPath} after ${timeoutMs}ms; if no other tenjin process is running, remove that directory and retry.`
26
+ );
27
+ this.name = "LockTimeoutError";
28
+ this.lockPath = lockPath;
29
+ }
30
+ };
31
+ async function withFileLock(lockPath, fn, opts = {}) {
32
+ const { timeoutMs, retryMs } = { ...DEFAULTS, ...opts };
33
+ const metaPath = join(lockPath, "meta");
34
+ const deadline = Date.now() + timeoutMs;
35
+ for (; ; ) {
36
+ try {
37
+ mkdirSync(lockPath);
38
+ owned.add(lockPath);
39
+ break;
40
+ } catch (err) {
41
+ if (!isEexist(err)) throw err;
42
+ if (Date.now() >= deadline) throw new LockTimeoutError(lockPath, timeoutMs);
43
+ await delay(retryMs);
44
+ }
45
+ }
46
+ await writeFile(metaPath, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })).catch(
47
+ () => void 0
48
+ );
49
+ try {
50
+ return await fn();
51
+ } finally {
52
+ try {
53
+ rmSync(lockPath, { recursive: true, force: true });
54
+ owned.delete(lockPath);
55
+ } catch (err) {
56
+ opts.onReleaseError?.(lockPath, err);
57
+ }
58
+ }
59
+ }
60
+ function isEexist(err) {
61
+ return typeof err === "object" && err !== null && err.code === "EEXIST";
62
+ }
63
+ function delay(ms) {
64
+ return new Promise((resolve) => setTimeout(resolve, ms));
65
+ }
66
+
67
+ // src/lib/policy.ts
68
+ function normCreator(value) {
69
+ return value.trim().toLowerCase();
70
+ }
71
+ function evaluateSpendPolicy(policy, req) {
72
+ if (req.maxPriceAtomic !== void 0 && req.amountAtomic > req.maxPriceAtomic) {
73
+ return {
74
+ decision: "deny",
75
+ reason: "price_cap_exceeded",
76
+ message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`
77
+ };
78
+ }
79
+ if (policy.allowlistCreators.length > 0) {
80
+ const allowed = policy.allowlistCreators.map(normCreator);
81
+ if (!allowed.includes(normCreator(req.creator))) {
82
+ return {
83
+ decision: "deny",
84
+ reason: "not_allowlisted",
85
+ message: `Creator "${req.creator}" is not in allowlistCreators.`
86
+ };
87
+ }
88
+ }
89
+ if (policy.sessionBudgetAtomic > 0n) {
90
+ const projected = req.sessionSpentAtomic + req.amountAtomic;
91
+ if (projected > policy.sessionBudgetAtomic) {
92
+ return {
93
+ decision: "deny",
94
+ reason: "session_budget_exceeded",
95
+ message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`
96
+ };
97
+ }
98
+ }
99
+ if (req.amountAtomic > policy.maxAutoSpendAtomic) {
100
+ return {
101
+ decision: "confirm",
102
+ reason: "above_auto_spend",
103
+ message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`
104
+ };
105
+ }
106
+ if (policy.confirm.mode === "always") {
107
+ return {
108
+ decision: "confirm",
109
+ reason: "confirm_always",
110
+ message: 'confirm policy is "always"; confirmation required.'
111
+ };
112
+ }
113
+ if (req.amountAtomic > policy.confirm.thresholdAtomic) {
114
+ return {
115
+ decision: "confirm",
116
+ reason: "above_confirm_threshold",
117
+ message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`
118
+ };
119
+ }
120
+ return { decision: "allow", reason: "within_policy", message: "within spend policy" };
121
+ }
122
+ function parseConfirmPolicy(stored) {
123
+ if (stored === "always") return { mode: "always" };
124
+ const m = /^above:(\d+)$/.exec(stored);
125
+ if (m && m[1] !== void 0) return { mode: "above", thresholdAtomic: BigInt(m[1]) };
126
+ return { mode: "always" };
127
+ }
128
+
129
+ export {
130
+ ownsAnyLock,
131
+ releaseOwnedLocks,
132
+ LockTimeoutError,
133
+ withFileLock,
134
+ evaluateSpendPolicy,
135
+ parseConfirmPolicy
136
+ };
137
+ //# sourceMappingURL=chunk-FKSAUOJU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/lock.ts","../src/lib/policy.ts"],"sourcesContent":["import { mkdirSync, rmSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Locks this process currently holds. Ownership starts the instant `mkdir`\n * succeeds and ends when the release has removed the directory, so there is no\n * window where a lock is on disk and unaccounted for. A removal that FAILS keeps\n * the lock owned: the directory is still on disk, no successor can claim the path\n * while it exists, and a signal-time release gets another attempt. The one place\n * ownership is dropped without a successful removal is `releaseOwnedLocks`, which\n * runs only as the process exits, where a claim held by a dying process helps\n * nobody.\n *\n * It exists because the default signal action terminates WITHOUT running\n * `finally`: without this, one Ctrl-C leaves a lock nothing will ever clean and\n * every later run of the same command times out on it.\n */\nconst owned = new Set<string>();\n\n/** Does this process hold any lock right now? */\nexport function ownsAnyLock(): boolean {\n return owned.size > 0;\n}\n\n/**\n * Synchronously attempt to release every lock this process holds. BEST EFFORT: a\n * path that refuses to be removed is left on disk and the next run's timeout names\n * it. Safe to call from a signal handler, and a no-op when this process holds\n * none, so a run merely QUEUED behind another cannot remove that other run's lock.\n */\nexport function releaseOwnedLocks(): void {\n for (const path of owned) {\n // NEVER throws. This runs inside a signal handler, and a throw there is an\n // uncaught exception: the process dies with code 1 and a stack trace instead\n // of the diagnostic and exit 130 the handler promises. One lock we could not\n // remove must not cost the report, or the exit code, or the other locks.\n try {\n rmSync(path, { recursive: true, force: true });\n } catch {\n // Left behind; the next run's timeout names the path.\n }\n }\n owned.clear();\n}\n\nexport interface FileLockOptions {\n /** Give up acquiring after this long (ms). */\n timeoutMs?: number;\n /** Poll interval between acquisition attempts (ms). */\n retryMs?: number;\n /**\n * Called when the lock could not be removed on release. The protected work\n * succeeded, so this is not a failure of the command; it is a leftover that will\n * block later runs, and the caller is the only one able to say so.\n */\n onReleaseError?: (lockPath: string, err: unknown) => void;\n}\n\nconst DEFAULTS = { timeoutMs: 5000, retryMs: 25 };\n\n/** Thrown when the lock cannot be acquired within `timeoutMs`. Carries the lock\n * path so a caller can surface the manual-recovery step in its own error contract. */\nexport class LockTimeoutError extends Error {\n readonly lockPath: string;\n constructor(lockPath: string, timeoutMs: number) {\n super(\n `Timed out waiting for lock at ${lockPath} after ${timeoutMs}ms; if no other tenjin process is running, remove that directory and retry.`,\n );\n this.name = 'LockTimeoutError';\n this.lockPath = lockPath;\n }\n}\n\n/**\n * Minimal cross-process mutex: the lock IS a directory, and mkdir is atomic, so a\n * second holder gets EEXIST and retries with backoff until `timeoutMs`, then\n * throws LockTimeoutError. There is deliberately NO auto-steal of a \"stale\" lock:\n * concurrent waiters each judging a lock stale could remove a fresh holder's\n * directory and lose its update. A crashed holder's lock is recovered by hand (the\n * timeout error names the path); the pid+acquiredAt meta exists only to make that\n * manual call diagnosable. Always released in the finally.\n *\n * ⚠ MIRRORED, MUST UPDATE TOGETHER. The generated WebSearch hook script in\n * lib/hook-scripts.ts (`withStoreLock`) reimplements this protocol byte for byte,\n * because it runs as a standalone .mjs outside the CLI and cannot import this\n * module, yet writes the same searches.json. If you change what the lock IS\n * (directory vs file), where it lives, or the no-stale-steal rule, change it\n * there too. Two writers of one file that disagree about the mutex have no mutex.\n * lib/hook-scripts.test.ts pins the two together and fails loudly on drift.\n */\nexport async function withFileLock<T>(\n lockPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const { timeoutMs, retryMs } = { ...DEFAULTS, ...opts };\n const metaPath = join(lockPath, 'meta');\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n // SYNCHRONOUS, for the same reason the release is: `await mkdir` finishes the\n // syscall before the continuation records ownership, so between the two the\n // directory is on disk and unclaimed. A signal there exits without removing\n // it and, with no stale recovery, nothing ever will. mkdirSync and the add\n // are one uninterruptible step.\n mkdirSync(lockPath);\n owned.add(lockPath); // owned from here, released only in the finally below\n break; // acquired\n } catch (err) {\n if (!isEexist(err)) throw err;\n if (Date.now() >= deadline) throw new LockTimeoutError(lockPath, timeoutMs);\n await delay(retryMs);\n }\n }\n await writeFile(metaPath, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })).catch(\n () => undefined,\n );\n try {\n return await fn();\n } finally {\n // SYNCHRONOUS, and in this order, because both are load-bearing. A signal\n // handler cannot run between two synchronous statements, so there is no instant\n // where the lock is on disk but unclaimed (a signal would exit without removing\n // it, and with no stale recovery nothing ever would) nor one where it is\n // claimed after release (a signal would remove whatever SUCCESSOR had since\n // acquired the path). An `await` here reopens the first window: `rm` yields, the\n // handler runs, sees no ownership, and leaves the directory behind.\n //\n // With no stealing, nothing else ever removes or replaces this directory, so\n // the lock here is provably the one we created — the unconditional rm is sound.\n try {\n rmSync(lockPath, { recursive: true, force: true });\n owned.delete(lockPath);\n } catch (err) {\n // KEEP ownership when the removal fails: the successor-steal risk only\n // exists once the directory is gone and someone else can take the path, so a\n // removal that failed leaves it on disk and still ours, and a signal-time\n // release gets another attempt. That only helps while THIS process lives,\n // though; once it exits normally the leftover blocks every later run, so the\n // caller is told rather than left to discover it as a timeout.\n opts.onReleaseError?.(lockPath, err);\n }\n }\n}\n\nfunction isEexist(err: unknown): boolean {\n return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'EEXIST';\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\n/** How a `confirm` gate is configured (parsed from the stored config string). */\nexport type ConfirmPolicy = { mode: 'always' } | { mode: 'above'; thresholdAtomic: bigint };\n\nexport interface SpendPolicy {\n /** Amounts at or below this auto-approve WITHOUT a prompt (still subject to the\n * confirm gate below). Default 0 → nothing auto-approves. */\n maxAutoSpendAtomic: bigint;\n /** Rolling local ceiling on cumulative session spend. 0 = disabled (no ceiling). */\n sessionBudgetAtomic: bigint;\n /** When a human confirmation is requested. */\n confirm: ConfirmPolicy;\n /** Creators (handle or 0x-address, lowercased) auto-payment is restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\nexport type PolicyReason =\n | 'within_policy'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always'\n | 'above_confirm_threshold';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Evaluate one spend against the policy. Hard gates run first (price cap →\n * allowlist → session budget); only if all pass is the confirm gate consulted. A\n * spend at or below `maxAutoSpend` that the confirm policy would not prompt for is\n * the only `allow`; everything else within the hard gates is `confirm`.\n */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (policy.sessionBudgetAtomic > 0n) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`,\n };\n }\n\n if (policy.confirm.mode === 'always') {\n return {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'confirm policy is \"always\"; confirmation required.',\n };\n }\n\n if (req.amountAtomic > policy.confirm.thresholdAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_confirm_threshold',\n message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/** Parse the stored `confirm` config value (\"always\" | \"above:<atomic>\"). */\nexport function parseConfirmPolicy(stored: string): ConfirmPolicy {\n if (stored === 'always') return { mode: 'always' };\n const m = /^above:(\\d+)$/.exec(stored);\n if (m && m[1] !== undefined) return { mode: 'above', thresholdAtomic: BigInt(m[1]) };\n // The config schema already constrains this; a malformed value here is a bug,\n // so fail closed to the safest interpretation rather than throwing mid-buy.\n return { mode: 'always' };\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AAgBrB,IAAM,QAAQ,oBAAI,IAAY;AAGvB,SAAS,cAAuB;AACrC,SAAO,MAAM,OAAO;AACtB;AAQO,SAAS,oBAA0B;AACxC,aAAW,QAAQ,OAAO;AAKxB,QAAI;AACF,aAAO,MAAM,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,IAC/C,QAAQ;AAAA,IAER;AAAA,EACF;AACA,QAAM,MAAM;AACd;AAeA,IAAM,WAAW,EAAE,WAAW,KAAM,SAAS,GAAG;AAIzC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACT,YAAY,UAAkB,WAAmB;AAC/C;AAAA,MACE,iCAAiC,QAAQ,UAAU,SAAS;AAAA,IAC9D;AACA,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAmBA,eAAsB,aACpB,UACA,IACA,OAAwB,CAAC,GACb;AACZ,QAAM,EAAE,WAAW,QAAQ,IAAI,EAAE,GAAG,UAAU,GAAG,KAAK;AACtD,QAAM,WAAW,KAAK,UAAU,MAAM;AACtC,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,aAAS;AACP,QAAI;AAMF,gBAAU,QAAQ;AAClB,YAAM,IAAI,QAAQ;AAClB;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,CAAC,SAAS,GAAG,EAAG,OAAM;AAC1B,UAAI,KAAK,IAAI,KAAK,SAAU,OAAM,IAAI,iBAAiB,UAAU,SAAS;AAC1E,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AACA,QAAM,UAAU,UAAU,KAAK,UAAU,EAAE,KAAK,QAAQ,KAAK,YAAY,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE;AA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