tenjin-cli 0.1.0-alpha.32 → 0.1.0-alpha.33

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 (165) hide show
  1. package/README.md +42 -23
  2. package/dist/{_esm-RLLC72MS.js → _esm-BIN7VY2L.js} +2 -2
  3. package/dist/{alive-MROUMFH3.js → alive-GSOWKUOY.js} +4 -4
  4. package/dist/{auto-update-OPWMRZLS.js → auto-update-Y24UL56V.js} +5 -3
  5. package/dist/{chunk-2GNOFONN.js → chunk-2M2VPI2E.js} +2 -2
  6. package/dist/chunk-2M2VPI2E.js.map +1 -0
  7. package/dist/{chunk-VUGQTZ2L.js → chunk-2RWB7RKE.js} +89 -33
  8. package/dist/chunk-2RWB7RKE.js.map +1 -0
  9. package/dist/{chunk-OTWLERSW.js → chunk-36RVGZNY.js} +2 -2
  10. package/dist/{chunk-B7EM4GGF.js → chunk-3GNJXKIT.js} +2 -2
  11. package/dist/{chunk-DRDUIZIA.js → chunk-4K7TQHNP.js} +4 -4
  12. package/dist/{chunk-SYOS5CAC.js → chunk-4YOZGGTZ.js} +73 -2
  13. package/dist/chunk-4YOZGGTZ.js.map +1 -0
  14. package/dist/{chunk-AD226HDR.js → chunk-A5GKIG5O.js} +5 -5
  15. package/dist/{chunk-JEVQ5LKO.js → chunk-AGMVASXZ.js} +3 -3
  16. package/dist/{chunk-ADV4LDTB.js → chunk-BF4XHEQK.js} +12 -2
  17. package/dist/chunk-BF4XHEQK.js.map +1 -0
  18. package/dist/{chunk-IDTRSAHE.js → chunk-C2Q76BVM.js} +48 -49
  19. package/dist/chunk-C2Q76BVM.js.map +1 -0
  20. package/dist/{chunk-VJUVFZ2D.js → chunk-FVIGCDSV.js} +1 -1
  21. package/dist/chunk-FVIGCDSV.js.map +1 -0
  22. package/dist/{chunk-QF3LSMGS.js → chunk-GTTUCOPD.js} +2 -2
  23. package/dist/{chunk-3DIL66VX.js → chunk-HGGWCP7W.js} +2 -2
  24. package/dist/{chunk-D5TOQSO4.js → chunk-HMWYAUA6.js} +10 -6
  25. package/dist/{chunk-D5TOQSO4.js.map → chunk-HMWYAUA6.js.map} +1 -1
  26. package/dist/{chunk-445VQTVM.js → chunk-IE7P2BZE.js} +2 -2
  27. package/dist/{chunk-VOZA6O7K.js → chunk-ILNIZ5I2.js} +190 -96
  28. package/dist/chunk-ILNIZ5I2.js.map +1 -0
  29. package/dist/{chunk-TF5HCP33.js → chunk-INTFHMU4.js} +4 -4
  30. package/dist/{chunk-HREHWL32.js → chunk-J57UC3DD.js} +2 -2
  31. package/dist/{chunk-AV5NZMYO.js → chunk-KM7RY2ZS.js} +2 -2
  32. package/dist/{chunk-TAW4UFFF.js → chunk-L6JEXB3E.js} +132 -132
  33. package/dist/chunk-L6JEXB3E.js.map +1 -0
  34. package/dist/{chunk-E7LGOMH6.js → chunk-LRW6S53P.js} +4 -3
  35. package/dist/chunk-LRW6S53P.js.map +1 -0
  36. package/dist/{chunk-PKHI276N.js → chunk-LXAYUOXI.js} +18 -9
  37. package/dist/chunk-LXAYUOXI.js.map +1 -0
  38. package/dist/{chunk-WOM257PW.js → chunk-NDGZDTSJ.js} +3 -3
  39. package/dist/{chunk-SFASB5FL.js → chunk-P3LFTKE7.js} +3 -14
  40. package/dist/chunk-P3LFTKE7.js.map +1 -0
  41. package/dist/{chunk-YUY4SAGM.js → chunk-RVPYTUP4.js} +5 -5
  42. package/dist/chunk-RVPYTUP4.js.map +1 -0
  43. package/dist/{chunk-GAKUQHKA.js → chunk-TC2WZLSC.js} +3 -3
  44. package/dist/{chunk-D3ZURCG7.js → chunk-TKPF35W6.js} +2 -2
  45. package/dist/{chunk-I5TDIUKM.js → chunk-U3IKUGRP.js} +23 -5
  46. package/dist/chunk-U3IKUGRP.js.map +1 -0
  47. package/dist/{chunk-BI673VEJ.js → chunk-UXZONNEQ.js} +3 -3
  48. package/dist/{chunk-PJNENX2A.js → chunk-WFSPCCVW.js} +2 -2
  49. package/dist/{chunk-PJNENX2A.js.map → chunk-WFSPCCVW.js.map} +1 -1
  50. package/dist/{chunk-DW4YTVR3.js → chunk-WXA2BWTE.js} +6 -2
  51. package/dist/chunk-WXA2BWTE.js.map +1 -0
  52. package/dist/{chunk-JRZBBPO6.js → chunk-ZDZERB6L.js} +56 -228
  53. package/dist/chunk-ZDZERB6L.js.map +1 -0
  54. package/dist/{chunk-G75OPGAK.js → chunk-ZNNXRNFD.js} +5 -3
  55. package/dist/chunk-ZNNXRNFD.js.map +1 -0
  56. package/dist/{chunk-CISYM4EO.js → chunk-ZURZHELF.js} +2 -2
  57. package/dist/{cli-FB4LOA5A.js → cli-E36SPKBW.js} +44 -44
  58. package/dist/{cli-FB4LOA5A.js.map → cli-E36SPKBW.js.map} +1 -1
  59. package/dist/{codex-event-TYVES3UX.js → codex-event-ZO2GEFE6.js} +2 -2
  60. package/dist/{codex-host-WW4H2SKT.js → codex-host-KECJVTA2.js} +3 -3
  61. package/dist/{codex-install-2C623HPW.js → codex-install-HQZDGFXW.js} +90 -47
  62. package/dist/codex-install-HQZDGFXW.js.map +1 -0
  63. package/dist/{config-HOVJFEKD.js → config-HY2E4GGW.js} +8 -8
  64. package/dist/{doctor-NKU4V5OV.js → doctor-I6XQEKWD.js} +42 -31
  65. package/dist/doctor-I6XQEKWD.js.map +1 -0
  66. package/dist/{fund-WEBHTZGN.js → fund-2QRO7OJL.js} +16 -11
  67. package/dist/{fund-WEBHTZGN.js.map → fund-2QRO7OJL.js.map} +1 -1
  68. package/dist/{hook-command-ZA2PNKS6.js → hook-command-2UBCSZG6.js} +12 -13
  69. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  70. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  71. package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
  72. package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
  73. package/dist/{hosts-AV5MHBAU.js → hosts-DVQJ32QC.js} +2 -2
  74. package/dist/index.js +16 -15
  75. package/dist/index.js.map +1 -1
  76. package/dist/{install-PT4EZS4R.js → install-ILUX5C4A.js} +24 -17
  77. package/dist/{install-identity-5A4OE6YC.js → install-identity-TZKGY6LQ.js} +7 -7
  78. package/dist/{install-wallet-SAAPKB73.js → install-wallet-5M4OTYLX.js} +13 -13
  79. package/dist/isows-native-Q2UDIVPT.js +9 -0
  80. package/dist/isows-native-Q2UDIVPT.js.map +1 -0
  81. package/dist/{mcp-HAWKCTPQ.js → mcp-LE4DUS22.js} +23 -24
  82. package/dist/{mcp-HAWKCTPQ.js.map → mcp-LE4DUS22.js.map} +1 -1
  83. package/dist/{package-SR2WB6MK.js → package-IJFGMWEV.js} +2 -2
  84. package/dist/{pay-OXC3WKYV.js → pay-WCG3IH4R.js} +13 -13
  85. package/dist/{payments-3KHMP2MG.js → payments-HFPPWHTV.js} +6 -6
  86. package/dist/{plugin-registration-N3GRIZVM.js → plugin-registration-PZFI5GZW.js} +18 -17
  87. package/dist/{runtime-UVNUA3AS.js → runtime-UZOKSUZX.js} +145 -27
  88. package/dist/runtime-UZOKSUZX.js.map +1 -0
  89. package/dist/{runtime-fetch-EKFRNR6Z.js → runtime-fetch-ZSSSK72Y.js} +5 -2
  90. package/dist/{runtime-layout-BDWZG2TQ.js → runtime-layout-WIDILZ6K.js} +2 -2
  91. package/dist/{send-HMKJLT34.js → send-GCVEAQKL.js} +8 -8
  92. package/dist/{status-RWXIIWYS.js → status-HCVAOCN7.js} +10 -10
  93. package/dist/{status-line-77XYZP7E.js → status-line-OPCXDHL2.js} +6 -6
  94. package/dist/{uninstall-D5G67UJH.js → uninstall-BAWRBXXQ.js} +19 -18
  95. package/dist/{uninstall-D5G67UJH.js.map → uninstall-BAWRBXXQ.js.map} +1 -1
  96. package/dist/{update-LRNOEGSB.js → update-CACXLQLR.js} +20 -17
  97. package/dist/{usdc-D6X7EIQ2.js → usdc-VG4CIOUK.js} +4 -4
  98. package/dist/{viemAdapter-By13KInL-RL742ETX.js → viemAdapter-By13KInL-DOFTEIJV.js} +2 -2
  99. package/dist/{wallet-XFYC27BR.js → wallet-QL4UUXEZ.js} +11 -11
  100. package/docs/agent-permissions.md +16 -12
  101. package/docs/troubleshooting.md +5 -5
  102. package/package.json +4 -4
  103. package/scripts/installers/install.ps1 +67 -0
  104. package/scripts/installers/install.sh +68 -0
  105. package/dist/_esm-C5CRWCYU.js +0 -3737
  106. package/dist/_esm-C5CRWCYU.js.map +0 -1
  107. package/dist/chunk-2GNOFONN.js.map +0 -1
  108. package/dist/chunk-ADV4LDTB.js.map +0 -1
  109. package/dist/chunk-DW4YTVR3.js.map +0 -1
  110. package/dist/chunk-E7LGOMH6.js.map +0 -1
  111. package/dist/chunk-G75OPGAK.js.map +0 -1
  112. package/dist/chunk-I5TDIUKM.js.map +0 -1
  113. package/dist/chunk-IDTRSAHE.js.map +0 -1
  114. package/dist/chunk-JRZBBPO6.js.map +0 -1
  115. package/dist/chunk-PKHI276N.js.map +0 -1
  116. package/dist/chunk-SFASB5FL.js.map +0 -1
  117. package/dist/chunk-SYOS5CAC.js.map +0 -1
  118. package/dist/chunk-TAW4UFFF.js.map +0 -1
  119. package/dist/chunk-VJUVFZ2D.js.map +0 -1
  120. package/dist/chunk-VOZA6O7K.js.map +0 -1
  121. package/dist/chunk-VUGQTZ2L.js.map +0 -1
  122. package/dist/chunk-YUY4SAGM.js.map +0 -1
  123. package/dist/codex-install-2C623HPW.js.map +0 -1
  124. package/dist/doctor-NKU4V5OV.js.map +0 -1
  125. package/dist/runtime-UVNUA3AS.js.map +0 -1
  126. /package/dist/{_esm-RLLC72MS.js.map → _esm-BIN7VY2L.js.map} +0 -0
  127. /package/dist/{alive-MROUMFH3.js.map → alive-GSOWKUOY.js.map} +0 -0
  128. /package/dist/{auto-update-OPWMRZLS.js.map → auto-update-Y24UL56V.js.map} +0 -0
  129. /package/dist/{chunk-OTWLERSW.js.map → chunk-36RVGZNY.js.map} +0 -0
  130. /package/dist/{chunk-B7EM4GGF.js.map → chunk-3GNJXKIT.js.map} +0 -0
  131. /package/dist/{chunk-DRDUIZIA.js.map → chunk-4K7TQHNP.js.map} +0 -0
  132. /package/dist/{chunk-AD226HDR.js.map → chunk-A5GKIG5O.js.map} +0 -0
  133. /package/dist/{chunk-JEVQ5LKO.js.map → chunk-AGMVASXZ.js.map} +0 -0
  134. /package/dist/{chunk-QF3LSMGS.js.map → chunk-GTTUCOPD.js.map} +0 -0
  135. /package/dist/{chunk-3DIL66VX.js.map → chunk-HGGWCP7W.js.map} +0 -0
  136. /package/dist/{chunk-445VQTVM.js.map → chunk-IE7P2BZE.js.map} +0 -0
  137. /package/dist/{chunk-TF5HCP33.js.map → chunk-INTFHMU4.js.map} +0 -0
  138. /package/dist/{chunk-HREHWL32.js.map → chunk-J57UC3DD.js.map} +0 -0
  139. /package/dist/{chunk-AV5NZMYO.js.map → chunk-KM7RY2ZS.js.map} +0 -0
  140. /package/dist/{chunk-WOM257PW.js.map → chunk-NDGZDTSJ.js.map} +0 -0
  141. /package/dist/{chunk-GAKUQHKA.js.map → chunk-TC2WZLSC.js.map} +0 -0
  142. /package/dist/{chunk-D3ZURCG7.js.map → chunk-TKPF35W6.js.map} +0 -0
  143. /package/dist/{chunk-BI673VEJ.js.map → chunk-UXZONNEQ.js.map} +0 -0
  144. /package/dist/{chunk-CISYM4EO.js.map → chunk-ZURZHELF.js.map} +0 -0
  145. /package/dist/{codex-event-TYVES3UX.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
  146. /package/dist/{codex-host-WW4H2SKT.js.map → codex-host-KECJVTA2.js.map} +0 -0
  147. /package/dist/{config-HOVJFEKD.js.map → config-HY2E4GGW.js.map} +0 -0
  148. /package/dist/{hook-command-ZA2PNKS6.js.map → hook-command-2UBCSZG6.js.map} +0 -0
  149. /package/dist/{hosts-AV5MHBAU.js.map → hosts-DVQJ32QC.js.map} +0 -0
  150. /package/dist/{install-PT4EZS4R.js.map → install-ILUX5C4A.js.map} +0 -0
  151. /package/dist/{install-identity-5A4OE6YC.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
  152. /package/dist/{install-wallet-SAAPKB73.js.map → install-wallet-5M4OTYLX.js.map} +0 -0
  153. /package/dist/{package-SR2WB6MK.js.map → package-IJFGMWEV.js.map} +0 -0
  154. /package/dist/{pay-OXC3WKYV.js.map → pay-WCG3IH4R.js.map} +0 -0
  155. /package/dist/{payments-3KHMP2MG.js.map → payments-HFPPWHTV.js.map} +0 -0
  156. /package/dist/{plugin-registration-N3GRIZVM.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
  157. /package/dist/{runtime-fetch-EKFRNR6Z.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
  158. /package/dist/{runtime-layout-BDWZG2TQ.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
  159. /package/dist/{send-HMKJLT34.js.map → send-GCVEAQKL.js.map} +0 -0
  160. /package/dist/{status-RWXIIWYS.js.map → status-HCVAOCN7.js.map} +0 -0
  161. /package/dist/{status-line-77XYZP7E.js.map → status-line-OPCXDHL2.js.map} +0 -0
  162. /package/dist/{update-LRNOEGSB.js.map → update-CACXLQLR.js.map} +0 -0
  163. /package/dist/{usdc-D6X7EIQ2.js.map → usdc-VG4CIOUK.js.map} +0 -0
  164. /package/dist/{viemAdapter-By13KInL-RL742ETX.js.map → viemAdapter-By13KInL-DOFTEIJV.js.map} +0 -0
  165. /package/dist/{wallet-XFYC27BR.js.map → wallet-QL4UUXEZ.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\nimport type { Harness } from './names';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\n/** A display name the server gives a capability, sent because this build\n * lists `label`. Shown exactly as given; absent, a surface says\n * {@link UNLABELLED}. */\nconst LabelSchema = z.string().min(1).max(32);\n\n/** What a surface names a lookup whose decision carries no `label`. */\nexport const UNLABELLED = 'Tenjin lookup';\n\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n label: LabelSchema.optional(),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When a Tenjin list service does the\n * task the gate picked, or no task fits and a listed x402 service could do the\n * step, the server names that one service: who sells it, where, for how much,\n * and the input it takes. A Tenjin list service arrives here under its catalog\n * id, because this build sends `catalog`. The candidate is the seller's own\n * listing, so every field is data for the host to judge, never an instruction;\n * the host builds the `input` and the tool call pays through the same `runPay`\n * path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/** A field name a job reads from an answer or writes into a poll body. */\nconst JobField = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);\n\n/** A body field whose value names a state: Treza's `status: \"running\"`. */\nconst JobFieldStateSchema = z.strictObject({\n field: JobField,\n values: z.array(z.string().min(1).max(64)).min(1).max(8),\n});\n\n/** A poll body value naming a field of the call's input or of the submit's\n * answer; any other value is sent as written. */\nexport const POLL_REFERENCE = /^\\$(input|result)\\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;\n\n/**\n * HOW A CALL WHOSE SELLER ANSWERS BEFORE THE RESULT IS READY IS FINISHED, sent\n * on a spec only because this build asks for it (`accepts: [\"jobs\"]`): where\n * the status is (a field or header of the submit's answer, or one fixed URL),\n * how a poll is sent, what says it is still running or failed, how often and\n * how long to poll, and how many hours the job can be resumed. `always`: the\n * seller never answers inline. A poll is never signed: the take's one payment\n * is its submit. Every field is the server's: the poll and complete URLs are\n * still checked here against the submit's host (`jobs.ts`).\n */\nexport const JobSchema = z\n .strictObject({\n pollUrl: z.union([\n z\n .strictObject({\n field: JobField.optional(),\n header: z\n .string()\n .regex(/^[A-Za-z0-9-]{1,64}$/)\n .optional(),\n })\n .refine((at) => at.field !== undefined || at.header !== undefined, 'a field or a header'),\n z.strictObject({ fixed: z.string().min(1).max(2_048) }),\n ]),\n /** Sent once like a poll after the result is saved, never after a save\n * that failed: it frees the seller's copy (AiSpace's `/complete`). Its\n * answer is ignored. */\n completeUrl: z.strictObject({ fixed: z.string().min(1).max(2_048) }).optional(),\n pollMethod: z.enum(['GET', 'POST']),\n pollBody: z\n .record(JobField, z.unknown())\n .refine(\n (body) =>\n Object.values(body).every(\n (value) =>\n typeof value !== 'string' || !value.startsWith('$') || POLL_REFERENCE.test(value),\n ),\n 'a $ value is $input.<field> or $result.<field>',\n )\n .optional(),\n running: z.union([\n z.strictObject({ httpStatus: z.array(z.number().int().min(200).max(299)).min(1).max(8) }),\n JobFieldStateSchema,\n ]),\n failed: JobFieldStateSchema.optional(),\n everyS: z.number().int().min(1).max(30),\n maxWaitS: z.number().int().min(1).max(600),\n keepH: z.number().int().min(1).max(48),\n always: z.literal(true).optional(),\n })\n .refine((job) => !job.pollBody || job.pollMethod === 'POST', 'only a POST poll has a body');\nexport type Job = z.infer<typeof JobSchema>;\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n /** The display name, on a catalog service's spec; a Bazaar spec has none. */\n label: LabelSchema.optional(),\n /** The input field that takes a pending search's query or fetch's URL. */\n holds: z\n .strictObject({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n /** What a paid result is. `media` means its files (bytes, links or inline\n * base64) are saved locally; absent on a Bazaar spec. */\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n /** Fixed request headers the catalog decides for this service (a\n * provider's beta opt-in, say), never the agent. The call refuses a name\n * this client signs or sets itself; `accept` and `content-type` stay its own. */\n headers: z\n .record(z.string().min(1).max(64), z.string().min(1).max(1_024))\n .refine((headers) => Object.keys(headers).length <= 8, 'at most 8 headers')\n .optional(),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n /** How a call answered before its result is ready is finished. */\n job: JobSchema.optional(),\n /** A media service that runs several takes of one call: `count` up to `max`. */\n takes: z.strictObject({ max: z.number().int().min(2).max(5) }).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any other service it\n * lists, and each option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only beside a\n * discovered offer, to a build that lists `catalog` in `accepts`. Each option\n * is a real offer: its own id, its own spec in `specs`, and its own one\n * payment, so `request({id, choice})` runs exactly the spec\n * `request({id: option.id})` would. `all` runs every option side by side, one\n * payment each. The set is the server's data: changing it is a deploy there,\n * not a release here. `input` names the open fields the options share, the\n * only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's answer\n * when a query with no id found a service nobody curated. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n /**\n * HOW THE OFFER IS DELIVERED, sent because this build lists `fields`.\n * `augment` is the free docs lookup before a search: the client shows no\n * line and puts what `augmentUrl` returns above the search's own\n * results. `offer` is every line the client shows. Absent (a server\n * from before the token), a free curated offer before a search is read\n * as `augment`, as builds before this one did.\n */\n delivery: z.enum(['offer', 'augment']).optional(),\n augmentUrl: z.string().url().max(2_048).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\n/**\n * ONE ROW OF THE TOOL LIST, as the free browse answers it: the tool's id, its\n * display name (a list entry's upstream name runs to 120 characters), what it\n * does, its price as the server writes it, and its kind. Strict like every\n * answer here, with the server's own bounds. The id is the one field the model\n * sends back, so its alphabet is pinned; the text is flattened to one line\n * where it is shown (`tool.ts`).\n */\nconst BrowseRowSchema = z.strictObject({\n id: z\n .string()\n .min(1)\n .max(200)\n .regex(/^[A-Za-z0-9._:-]+$/),\n label: z.string().min(1).max(120),\n does: z.string().min(1).max(500),\n price: z.string().min(1).max(32),\n free: z.boolean(),\n kind: z.string().min(1).max(120),\n});\nexport type BrowseRow = z.infer<typeof BrowseRowSchema>;\n\nconst BrowseResponseSchema = z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n rows: z.array(BrowseRowSchema).max(200),\n});\nexport type BrowseResponse = z.infer<typeof BrowseResponseSchema>;\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool' | 'browse';\n\n/**\n * What this client can act on beyond the curated answers, sent on every call.\n * Each token names one kind of feature this build parses and runs, and the\n * server ignores a token it does not know, so the list only ever grows.\n * `label` takes each catalog service's display name on its spec and both\n * `execute` answers, and the offer line that starts at it. `fields` takes\n * each spec's `holds` and `output`, and the hook `execute`'s `delivery` and\n * `augmentUrl`. `catalog` takes Tenjin's reviewed list of third-party services as\n * `discovered` offers under their catalog ids, with each spec's `holds` and\n * `output`, and `choices`, a set of options the user picks between or runs\n * all of, beside a discovered offer from a compare group. A build that sends\n * `discovered` in its place gets the same services under their\n * `discovered:tenjin:` ids. `spec` asks for each offered service's request\n * spec beside its line, and for the picked service's spec in place of a\n * decision on a query with no id, which only a build that parses them can\n * take: the decision schemas are strict. `jobs` asks for each spec's `job`,\n * for the services that never answer inline, and for `count` on a media\n * offer's line. `bazaar` widens discovery to the open Bazaar and is sent only\n * while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['catalog', 'spec', 'label', 'fields', 'jobs'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[]; harness?: Harness } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n ...(extras.harness !== undefined ? { harness: extras.harness } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** The free browse of the tool list: `browse` is the need, or `\"\"` for every\n * tool by kind. No gate call and no Jev on the server. */\nexport function buildBrowseBody(request: {\n browse: string;\n accepts: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n browse: request.browse,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** A browse row's id, answered with that tool's spec under a fresh offer id. */\nexport function buildToolSpecBody(request: {\n tool: string;\n accepts: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n tool: request.tool,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n return { success: schemaFor(kind).safeParse(value).success };\n}\n\nfunction schemaFor(kind: CallKind) {\n return kind === 'hook'\n ? HookResponseSchema\n : kind === 'tool'\n ? ToolResponseSchema\n : BrowseResponseSchema;\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n /**\n * The host asking. The server filters out the lookups that host's own tools\n * already do, and nothing else: never payment, limits or the fee. Absent is\n * `claude`, and every production caller sends it.\n */\n harness?: Harness;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n /** What this route's calls deposited into the routing channel and the\n * router took, 0n for none: the caller says so once, where it is read. */\n deposited?: () => bigint;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/**\n * THE TWO FREE READS OF THE TOOL LIST. `{browse}` lists the tools that fit a\n * need (or all of them, by kind, for `\"\"`), and `{tool}` answers a browse\n * row's id with that tool's spec under a fresh offer id, exactly as a query\n * with no id is answered. Neither makes a gate call on the server, neither is\n * charged the routing fee, and neither pays anything here, so both always take\n * the free path: `deps.route` is never read.\n */\nexport async function requestBrowse(\n browse: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<BrowseResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildBrowseBody({\n browse,\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n BrowseResponseSchema,\n );\n}\n\n/** `{tool}`: a browse row's spec, kept by the caller under the answer's id. */\nexport async function requestToolSpec(\n tool: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<ToolResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildToolSpecBody({\n tool,\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n ToolResponseSchema,\n );\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. `running`: paid, and the seller was still\n * rendering when the call ended. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid' | 'running';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl' | 'harness'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome, deps.harness ?? 'claude'),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome, harness?: Harness): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n ...(harness !== undefined ? { harness } : {}),\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &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,EAAE,QAAQ,WAAW,UAAU,OAAO,KAAmB;AAClE;AAIA,SAAS,QAAQ,MAAyD;AACxE,MAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AACtD,QAAM,QAAS,KAA6B;AAC5C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAUrD,SAAS,cAAc,SAAoC;AAChE,SACE,QAAQ,SAAS,aACjB,QAAQ,WAAW,UACnB,QAAQ,cAAc,UACtB,CAAC,YAAY,IAAI,QAAQ,UAAU,QAAQ,EAAE;AAEjD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/codex-event.ts"],"sourcesContent":["import { decode, splitWebrun } from '../adapters/codex-wire';\nimport type { HookEvent } from './hooks';\n\n/**\n * A Codex hook event as the router's arms read it: the root session's prompt,\n * and any `webrun` call holding a plain search or a URL open, read as that one\n * entry ({@link splitWebrun}) with the rest of the call beside it. A child's\n * task is ciphertext. Everything else is null. Codex has no\n * PostToolUseFailure and returns one text for the whole call, so the\n * after-call arm reads a shortfall only from an empty result.\n */\nexport function codexRouterEvent(raw: unknown): HookEvent | null {\n const input = decode(raw);\n if (input === null || input.agent !== undefined || input.session.length > 200) return null;\n const common = {\n sessionId: input.session,\n ...(input.cwd ? { cwd: input.cwd } : {}),\n ...(input.transcript?.path !== undefined ? { transcriptPath: input.transcript.path } : {}),\n };\n if (input.event === 'prompt' && input.prompt !== undefined)\n return { kind: 'prompt', ...common, prompt: input.prompt };\n const tool = input.tool;\n const toolInput = (raw as { tool_input?: unknown }).tool_input;\n if (tool?.name !== 'webrun' || toolInput === null || typeof toolInput !== 'object') return null;\n const split = splitWebrun(toolInput as Record<string, unknown>);\n if (split === null) return null;\n const call = {\n ...common,\n tool: split.entry.tool,\n pending: split.entry,\n ...(split.rest !== null ? { rest: split.rest } : {}),\n targets: split.targets,\n ...(tool.callId !== undefined ? { toolUseId: tool.callId } : {}),\n };\n if (input.event === 'tool.before') return { kind: 'native', ...call };\n if (input.event !== 'tool.after') return null;\n const text = tool.result?.text;\n return {\n kind: 'shortfall',\n ...call,\n eventName: 'PostToolUse',\n nativeOutcome: text === '' ? { error: 'Web search returned no results' } : null,\n search:\n text === undefined || split.entry.tool !== 'WebSearch' ? null : { raw: {}, results: [] },\n savedPdf: null,\n };\n}\n\n/** Where a Codex session's local state lives, never shared with Claude's. */\nexport function codexSession(sessionId: string): string {\n return `codex:${sessionId}`;\n}\n\n/**\n * Codex cannot replace a tool's output, so free docs ride beside the result as\n * `additionalContext`. The one other field kept is `systemMessage`, the line\n * for the user (an unpaid routing fee, a deposit): Codex takes it on every\n * event and shows it as a warning (openai/codex `hooks/src/events/*.rs`, CLI\n * 0.157.1). Nothing else in a Claude-shaped answer survives, because Codex\n * refuses an answer carrying a field it does not know.\n */\nexport function codexResponse(response: unknown): unknown {\n if (response === null || typeof response !== 'object') return null;\n const { hookSpecificOutput: output, systemMessage } = response as {\n hookSpecificOutput?: Record<string, unknown>;\n systemMessage?: unknown;\n };\n const message = typeof systemMessage === 'string' ? { systemMessage } : {};\n const specific = codexSpecific(output);\n if (specific === null) return Object.keys(message).length > 0 ? message : null;\n return { hookSpecificOutput: specific, ...message };\n}\n\nfunction codexSpecific(\n output: Record<string, unknown> | undefined,\n): Record<string, unknown> | null {\n if (output === undefined) return null;\n if (output.updatedToolOutput !== undefined) {\n const results = (output.updatedToolOutput as { results?: unknown[] }).results;\n if (typeof results?.[0] !== 'string') return null;\n return { hookEventName: 'PostToolUse', additionalContext: results[0] };\n }\n return output;\n}\n"],"mapp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AAC,GAAG,SAAS,CAAC,EAAE;AAAA,IACzF,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,aAAa,WAA2B;AACtD,SAAO,SAAS,SAAS;AAC3B;AAUO,SAAS,cAAc,UAA4B;AACxD,MAAI,aAAa,QAAQ,OAAO,aAAa,SAAU,QAAO;AAC9D,QAAM,EAAE,oBAAoB,QAAQ,cAAc,IAAI;AAItD,QAAM,UAAU,OAAO,kBAAkB,WAAW,EAAE,cAAc,IAAI,CAAC;AACzE,QAAM,WAAW,cAAc,MAAM;AACrC,MAAI,aAAa,KAAM,QAAO,OAAO,KAAK,OAAO,EAAE,SAAS,IAAI,UAAU;AAC1E,SAAO,EAAE,oBAAoB,UAAU,GAAG,QAAQ;AACpD;AAEA,SAAS,cACP,QACgC;AAChC,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI,OAAO,sBAAsB,QAAW;AAC1C,UAAM,UAAW,OAAO,kBAA8C;AACtE,QAAI,OAAO,UAAU,CAAC,MAAM,SAAU,QAAO;AAC7C,WAAO,EAAE,eAAe,eAAe,mBAAmB,QAAQ,CAAC,EAAE;AAAA,EACvE;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/runtime-fetch.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { open, rm } from 'node:fs/promises';\nimport { join, posix, win32 } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * WHAT THE RUNTIME DOWNLOADS, AND HOW: Node's own release archive and the npm\n * tarball of a tenjin-cli version, over https only, streamed to disk while\n * hashed, capped in size and time, and unpacked by the system's `tar` in exec\n * form. The checksums themselves are the caller's: the pin in `package.json`\n * for Node, the registry's `dist.integrity` for a tarball.\n */\n\n/** The oldest glibc Node 24's prebuilt Linux binaries run on. */\nconst MIN_GLIBC = [2, 28] as const;\n\n/** Node's release archives, by `nodeKey`. Anything else has no pinned build. */\nconst KEYS = new Set([\n 'darwin-arm64',\n 'darwin-x64',\n 'linux-x64',\n 'linux-arm64',\n 'win-x64',\n 'win-arm64',\n]);\n\nfunction glibcAtLeast(glibc: string, min: readonly [number, number]): boolean {\n const m = /^(\\d+)\\.(\\d+)/.exec(glibc);\n if (m === null) return false;\n const major = Number(m[1]);\n const minor = Number(m[2]);\n return major > min[0] || (major === min[0] && minor >= min[1]);\n}\n\n/**\n * The release-archive key for this machine, or null where Tenjin pins no Node:\n * musl (no glibc version at all), a glibc older than 2.28, and every platform\n * and architecture outside the six keys. A Rosetta x64 Node asks for\n * `darwin-x64`, which runs under Rosetta too.\n */\nexport function nodeKey(\n platform: NodeJS.Platform,\n arch: string,\n glibc: string | null | undefined,\n): string | null {\n const os = platform === 'win32' ? 'win' : platform;\n const key = `${os}-${arch}`;\n if (!KEYS.has(key)) return null;\n if (platform === 'linux' && (typeof glibc !== 'string' || !glibcAtLeast(glibc, MIN_GLIBC))) {\n return null;\n }\n return key;\n}\n\n/**\n * Why Tenjin pins no Node for this machine, or null when it pins one: the\n * platform and architecture, and on Linux the C library that rules it out.\n * Said by install and doctor so the cause is named, never a pinned key.\n */\nexport function unpinnedPlatform(\n platform: NodeJS.Platform,\n arch: string,\n glibc: string | null | undefined,\n): string | null {\n if (nodeKey(platform, arch, glibc) !== null) return null;\n const key = `${platform === 'win32' ? 'win' : platform}-${arch}`;\n if (platform !== 'linux' || !KEYS.has(key)) return key;\n return typeof glibc === 'string'\n ? `${key} with glibc ${glibc}, older than ${MIN_GLIBC.join('.')}`\n : `${key} with musl, not glibc`;\n}\n\n/** The glibc this Node runs on, or null: musl, or a report that cannot be read. */\nexport function runningGlibc(): string | null {\n try {\n const report = process.report.getReport() as { header?: { glibcVersionRuntime?: string } };\n return report.header?.glibcVersionRuntime ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface NodeArtifact {\n key: string;\n url: string;\n /** The archive's name in the release, the name `SHASUMS256.txt` lists. */\n file: string;\n /** The one archive member the runtime keeps: the `node` binary. */\n member: string;\n}\n\nexport function nodeArtifact(version: string, key: string): NodeArtifact {\n const base = `node-v${version}-${key}`;\n const windows = key.startsWith('win-');\n const file = `${base}.${windows ? 'zip' : 'tar.gz'}`;\n return {\n key,\n url: `https://nodejs.org/dist/v${version}/${file}`,\n file,\n member: windows ? `${base}/node.exe` : `${base}/bin/node`,\n };\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * Stream `url` into a fresh file under `dir`, hashing as it goes. Refuses a URL\n * (or a redirect's final URL) that is not https, aborts past `maxBytes` or\n * `timeoutMs`, and unlinks the file on any failure, so a caller never finds a\n * half download. A transport failure (the fetch, or reading the body) is\n * `NETWORK_ERROR`, and the caller adds its fix; a write to disk that fails\n * (ENOSPC, EACCES) is not the network's, and says which file and why.\n */\nexport async function download(\n url: string,\n o: {\n dir: string;\n maxBytes: number;\n timeoutMs: number;\n hash: 'sha256' | 'sha512';\n fetchImpl?: typeof fetch;\n },\n): Promise<{ file: string; digest: Buffer }> {\n if (!isHttps(url)) {\n throw new CliError('UPDATE_FAILED', `refused to download ${url}: only https is allowed`);\n }\n const file = join(o.dir, `dl-${randomBytes(6).toString('hex')}`);\n const handle = await open(file, 'wx', 0o600);\n let closed = false;\n try {\n let res: Response;\n try {\n res = await (o.fetchImpl ?? fetch)(url, { signal: AbortSignal.timeout(o.timeoutMs) });\n } catch (err) {\n throw new CliError('NETWORK_ERROR', `could not download ${url}: ${messageOf(err)}`, {\n cause: err,\n });\n }\n if (res.url !== '' && !isHttps(res.url)) {\n throw new CliError('UPDATE_FAILED', `refused ${url}: it redirected to ${res.url}`);\n }\n if (!res.ok || res.body === null) {\n throw new CliError('NETWORK_ERROR', `could not download ${url}: HTTP ${res.status}`);\n }\n const tooLarge = () =>\n new CliError('UPDATE_FAILED', `the download from ${url} is larger than ${o.maxBytes} bytes`);\n if (Number(res.headers.get('content-length') ?? 0) > o.maxBytes) throw tooLarge();\n const hash = createHash(o.hash);\n let size = 0;\n try {\n for await (const chunk of res.body as AsyncIterable<Uint8Array>) {\n size += chunk.byteLength;\n if (size > o.maxBytes) throw tooLarge();\n hash.update(chunk);\n try {\n await handle.write(chunk);\n } catch (err) {\n throw new CliError('UPDATE_FAILED', `could not write ${file}: ${codeOf(err)}`, {\n cause: err,\n });\n }\n }\n } catch (err) {\n if (err instanceof CliError) throw err;\n throw new CliError('NETWORK_ERROR', `could not download ${url}: ${messageOf(err)}`, {\n cause: err,\n });\n }\n await handle.close();\n closed = true;\n return { file, digest: hash.digest() };\n } catch (err) {\n if (!closed) await handle.close().catch(() => undefined);\n await rm(file, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/** A file-system error's errno code (ENOSPC, EACCES), or its message when it has none. */\nfunction codeOf(err: unknown): string {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' ? code : messageOf(err);\n}\n\nfunction messageOf(err: unknown): string {\n if (err instanceof Error) {\n return err.name === 'TimeoutError' ? 'it timed out' : err.message;\n }\n return String(err);\n}\n\n/** How `extract` runs `tar`: exec form, no shell, in `cwd`. A seam for tests. */\nexport type ExtractSpawn = (\n command: string,\n args: string[],\n o: { cwd: string },\n) => Promise<{ code: number | null; stderr: string }>;\n\nconst spawnTar: ExtractSpawn = (command, args, o) =>\n new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: o.cwd,\n shell: false,\n stdio: ['ignore', 'ignore', 'pipe'],\n windowsHide: true,\n });\n let stderr = '';\n child.stderr.setEncoding('utf8');\n child.stderr.on('data', (chunk: string) => {\n if (stderr.length < 4096) stderr += chunk;\n });\n child.on('error', reject);\n child.on('close', (code) => resolve({ code, stderr }));\n });\n\n/**\n * Unpack `archive` into `dest` with the system's `tar`: `tar -xzf` on POSIX,\n * and on Windows `System32\\tar.exe -xf`, which is bsdtar and reads a `.zip`\n * (Git's GNU tar, earlier on many PATHs, does not). `member` limits it to one\n * file, `strip` drops leading folders. A non-zero exit throws with what tar said.\n *\n * TAR RUNS IN THE ARCHIVE'S FOLDER and is given names relative to it. bsdtar\n * reads its argv in the ANSI code page, so a user folder named outside it\n * (Cyrillic on cp1252, an emoji) would reach it as `?`; the working directory\n * goes to Windows as a wide string, and the names it is given are the\n * runtime's own ASCII ones.\n */\nexport async function extract(\n archive: string,\n dest: string,\n o: { member?: string; strip?: number; platform?: NodeJS.Platform; spawnImpl?: ExtractSpawn } = {},\n): Promise<void> {\n const windows = (o.platform ?? process.platform) === 'win32';\n const command = windows\n ? win32.join(process.env.SystemRoot ?? 'C:\\\\Windows', 'System32', 'tar.exe')\n : 'tar';\n const path = windows ? win32 : posix;\n const cwd = path.dirname(archive);\n const into = path.relative(cwd, dest);\n const args = [\n windows ? '-xf' : '-xzf',\n path.basename(archive),\n '-C',\n into === '' ? '.' : into.startsWith('..') || path.isAbsolute(into) ? dest : into,\n ...(o.strip !== undefined && o.strip > 0 ? [`--strip-components=${o.strip}`] : []),\n ...(o.member !== undefined ? [o.member] : []),\n ];\n const run = await (o.spawnImpl ?? spawnTar)(command, args, { cwd });\n if (run.code !== 0) {\n const said = run.stderr.trim().slice(0, 300);\n throw new Error(`tar could not unpack ${archive} (exit ${run.code})${said ? `: ${said}` : ''}`);\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,YAAY,mBAAmB;AACxC,SAAS,MAAM,UAAU;AACzB,SAAS,MAAM,OAAO,aAAa;AAYnC,IAAM,YAAY,CAAC,GAAG,EAAE;AAGxB,IAAM,OAAO,oBAAI,IAAI;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,aAAa,OAAe,KAAyC;AAC5E,QAAM,IAAI,gBAAgB,KAAK,KAAK;AACpC,MAAI,MAAM,KAAM,QAAO;AACvB,QAAM,QAAQ,OAAO,EAAE,CAAC,CAAC;AACzB,QAAM,QAAQ,OAAO,EAAE,CAAC,CAAC;AACzB,SAAO,QAAQ,IAAI,CAAC,K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ACtC,CAAC;AACD,QAAM,GAAG,SAAS,MAAM;AACxB,QAAM,GAAG,SAAS,CAAC,SAAS,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC;AACvD,CAAC;AAcH,eAAsB,QACpB,SACA,MACA,IAA+F,CAAC,GACjF;AACf,QAAM,WAAW,EAAE,YAAY,QAAQ,cAAc;AACrD,QAAM,UAAU,UACZ,MAAM,KAAK,QAAQ,IAAI,cAAc,eAAe,YAAY,SAAS,IACzE;AACJ,QAAM,OAAO,UAAU,QAAQ;AAC/B,QAAM,MAAM,KAAK,QAAQ,OAAO;AAChC,QAAM,OAAO,KAAK,SAAS,KAAK,IAAI;AACpC,QAAM,OAAO;AAAA,IACX,UAAU,QAAQ;AAAA,IAClB,KAAK,SAAS,OAAO;AAAA,IACrB;AAAA,IACA,SAAS,KAAK,MAAM,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,IAAI,IAAI,OAAO;AAAA,IAC5E,GAAI,EAAE,UAAU,UAAa,EAAE,QAAQ,IAAI,CAAC,sBAAsB,EAAE,KAAK,EAAE,IAAI,CAAC;AAAA,IAChF,GAAI,EAAE,WAAW,SAAY,CAAC,EAAE,MAAM,IAAI,CAAC;AAAA,EAC7C;AACA,QAAM,MAAM,OAAO,EAAE,aAAa,UAAU,SAAS,MAAM,EAAE,IAAI,CAAC;AAClE,MAAI,IAAI,SAAS,GAAG;AAClB,UAAM,OAAO,IAAI,OAAO,KAAK,EAAE,MAAM,GAAG,GAAG;AAC3C,UAAM,IAAI,MAAM,wBAAwB,OAAO,UAAU,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,KAAK,EAAE,EAAE;AAAA,EAChG;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/plugin-folder.ts","../src/lib/install-location.ts"],"sourcesContent":["import { lstat, readdir, readFile, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { PLUGIN_NAME } from './names';\nimport { MOD_FILES, OWNER_MARKER, PLUGIN_FILES, type ModSources } from './plugin-files';\n\n/**\n * THE FOLDER FALLBACK: the plugin as a folder under a config dir's `skills/`,\n * which Claude Code loads in place as `tenjin@skills-dir` with no `claude`\n * command at all (lab, 2026-10-09: the manifest's name wins over the folder's).\n * `install` writes it only where it cannot run `claude plugin`.\n *\n * OWNERSHIP RULES. Only `tenjin-router/` is ever touched, never `skills/tenjin`,\n * where tenjin.sh tells readers to drop its hosted skill. The folder is ours\n * only when it is a real directory (never followed through a link) whose\n * manifest names `tenjin` and carries the `tenjin-cli` marker. Inside it, only\n * the paths in {@link PLUGIN_FILES} are written or unlinked, so a user's own\n * `skills/` or `commands/` there survive every update and uninstall, and a\n * listed path whose parent inside the folder is a link is never written or\n * unlinked, so a linked `skills/tenjin-pay` keeps the user's file behind it.\n */\n\nexport const FOLDER_NAME = 'tenjin-router';\n\n/**\n * The mod's files from a plugin folder that carries them (the package's own\n * `dist/hosts/claude/tenjin`), or undefined when any is missing: the folder\n * fallback then writes the legs and the server without the mod.\n */\nexport async function readModSources(pluginDir: string): Promise<ModSources | undefined> {\n const entries = await Promise.all(\n MOD_FILES.map(async (path) => [path, await readFile(join(pluginDir, path), 'utf8')] as const),\n ).catch(() => null);\n return entries === null ? undefined : (Object.fromEntries(entries) as ModSources);\n}\n\n/** `<base>/skills/tenjin-router`, for a config dir or a project's `.claude`. */\nexport function pluginFolderPath(base: string): string {\n return join(base, 'skills', FOLDER_NAME);\n}\n\nexport type FolderState = 'absent' | 'ours' | 'foreign';\n\nexport async function inspectPluginFolder(dir: string): Promise<FolderState> {\n const entry = await lstat(dir).catch(() => null);\n if (entry === null) return 'absent';\n if (!entry.isDirectory() || entry.isSymbolicLink()) return 'foreign';\n try {\n const manifest = JSON.parse(\n await readFile(join(dir, '.claude-plugin', 'plugin.json'), 'utf8'),\n ) as { name?: unknown; metadata?: Record<string, unknown> };\n const marked =\n manifest.metadata !== null &&\n typeof manifest.metadata === 'object' &&\n OWNER_MARKER in manifest.metadata;\n return manifest.name === PLUGIN_NAME && marked ? 'ours' : 'foreign';\n } catch {\n return 'foreign';\n }\n}\n\n/**\n * The first parent of `path` inside `dir` that exists and is not a real\n * directory, relative to `dir`, or null when every parent is real or absent.\n */\nasync function linkedParent(dir: string, path: string): Promise<string | null> {\n const parents: string[] = [];\n for (let d = dirname(path); d !== '.'; d = dirname(d)) parents.unshift(d);\n for (const parent of parents) {\n const entry = await lstat(join(dir, parent)).catch(() => null);\n if (entry === null) return null;\n if (entry.isSymbolicLink() || !entry.isDirectory()) return parent;\n }\n return null;\n}\n\nexport interface FolderWrite {\n path: string;\n state: 'written' | 'refused';\n reason?: string;\n}\n\n/**\n * Write the listed files, each atomically (a temp file in its own directory,\n * renamed over the file), the manifest last. A folder that exists and is not\n * ours is refused and reported, never overwritten.\n */\nexport async function writePluginFolder(\n dir: string,\n files: Record<string, string>,\n): Promise<FolderWrite> {\n const state = await inspectPluginFolder(dir);\n if (state === 'foreign') {\n return {\n path: dir,\n state: 'refused',\n reason: `${dir} exists and is not a folder this CLI wrote, so it was left as it is`,\n };\n }\n for (const path of PLUGIN_FILES) {\n const linked = await linkedParent(dir, path);\n if (linked !== null) {\n return {\n path: dir,\n state: 'refused',\n reason: `${join(dir, linked)} is a link or not a folder, so nothing in ${dir} was written`,\n };\n }\n }\n try {\n for (const path of PLUGIN_FILES) {\n const body = files[path];\n if (body === undefined) continue;\n await writeFileAtomic(join(dir, path), body);\n }\n } catch (err) {\n return {\n path: dir,\n state: 'refused',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n return { path: dir, state: 'written' };\n}\n\nexport interface FolderRemoval {\n path: string;\n /** False when there was no folder of ours to remove. */\n removed: boolean;\n /** What is left in the folder that is not ours, relative to it. */\n left: string[];\n reason?: string;\n}\n\n/**\n * Unlink the listed files, remove the subfolders they leave empty, deepest\n * first, and the folder itself only when it is then empty. Never recursive.\n */\nexport async function removePluginFolder(dir: string): Promise<FolderRemoval> {\n const state = await inspectPluginFolder(dir);\n if (state === 'absent') return { path: dir, removed: false, left: [] };\n if (state === 'foreign') {\n return {\n path: dir,\n removed: false,\n left: [],\n reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`,\n };\n }\n for (const path of PLUGIN_FILES) {\n if ((await linkedParent(dir, path)) === null) await rm(join(dir, path), { force: true });\n }\n // Every ancestor of every file, deepest first: a nested skill directory\n // leaves its parent behind otherwise.\n const subdirs = [\n ...new Set(\n PLUGIN_FILES.flatMap((p) => {\n const out: string[] = [];\n for (let d = dirname(p); d !== '.'; d = dirname(d)) out.push(d);\n return out;\n }),\n ),\n ].sort((a, b) => b.split('/').length - a.split('/').length);\n for (const sub of subdirs) await rmdir(join(dir, sub)).catch(() => undefined);\n const left = await listFiles(dir);\n if (left.length === 0) await rmdir(dir).catch(() => undefined);\n return { path: dir, removed: true, left };\n}\n\nasync function listFiles(dir: string): Promise<string[]> {\n const out: string[] = [];\n const walk = async (current: string): Promise<void> => {\n for (const entry of await readdir(current, { withFileTypes: true }).catch(() => [])) {\n const path = join(current, entry.name);\n if (entry.isDirectory()) await walk(path);\n else out.push(relative(dir, path).split(sep).join('/'));\n }\n };\n await walk(dir);\n return out.sort();\n}\n","import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { delimiter, dirname, join, sep } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * WHERE this build is installed, and what that implies about replacing it.\n *\n * Its own module because it answers a different question from the command that\n * uses it: \"what IS this install\" rather than \"how do I replace it\". The\n * refusal set is the load-bearing part, and it got re-cut in three consecutive\n * reviews while it was expressed positionally inside the command body.\n */\n\n/** Managers a global install can be handed back to. yarn is deliberately absent\n * from the delegable set: see the yarn entry in REFUSALS. */\nexport type Delegable = 'npm' | 'pnpm' | 'bun';\n\n/**\n * One reason `npm install -g` would not actually replace THIS build.\n *\n * Each entry carries the three properties that decide WHEN it is evaluated,\n * because expressing them by where the line sat is what made this set get\n * re-cut three times: a missing entry, then a copy on the wrong side of the\n * fetch, then a duplicate that could not run. Declaring them means adding a\n * refusal is a matter of answering three questions, not of guessing a position.\n */\ninterface Refusal {\n /** Does this install location refuse? Pure filesystem, never the network. */\n test: (moduleDir: string) => boolean;\n error: (spec: string, moduleDir: string) => CliError;\n /**\n * Does the fix string name the version the registry just resolved? This is\n * also what decides whether the entry may run BEFORE the fetch: one that does\n * not need a version is evaluated first, so an offline user in a checkout is\n * told they are in a checkout rather than told to go debug their network.\n */\n needsVersion: boolean;\n /**\n * Does it apply to `--check`? Everything here is a reason not to WRITE, and\n * `--check` only reports, so today nothing does. An entry that ever answers\n * yes is one whose test says the REPORT would be wrong, not the install.\n */\n appliesToCheck: boolean;\n}\n\n/**\n * Ordered most-specific first: a checkout and an npx cache are recognizable\n * before any question of which manager or which tree, and the manager entry\n * precedes the global/local one because a pnpm or bun store has its own layout\n * that `isGlobalTree` is not written for.\n */\nexport const REFUSALS: readonly Refusal[] = [\n {\n test: isSourceCheckout,\n error: () =>\n new CliError('REFUSED', 'tenjin-cli is running from a source checkout, not an install', {\n fix: 'Update the checkout instead: git pull && pnpm install',\n }),\n needsVersion: false,\n appliesToCheck: false,\n },\n {\n test: (moduleDir) => moduleDir.split(sep).includes('_npx'),\n error: (spec) =>\n new CliError('REFUSED', 'tenjin-cli is running from the npx cache, not an install', {\n // Writing a global here would \"succeed\" and change nothing: the next\n // `npx tenjin` still resolves its own cached copy.\n fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`,\n }),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // The ONLY manager still refused. `yarn global add` is yarn-1 only, and\n // berry dropped global installs altogether, so there is no one command this\n // can drive across the versions a user might have. Every other manager is\n // delegated to rather than refused (see MANAGERS).\n test: (moduleDir) => classifyManager(moduleDir) === 'yarn',\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli was installed with yarn, whose global install exists only in yarn 1',\n { fix: `yarn global add ${spec}` },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // Scoped to npm on purpose: the prefix-vs-project-root test is written for\n // npm's layout. pnpm's global store and bun's global dir both keep a\n // package.json beside `node_modules`, so an unscoped test would read either\n // as a project-local install and refuse the very case we now delegate.\n test: (moduleDir) => classifyManager(moduleDir) === 'npm' && !isGlobalTree(moduleDir),\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli is a project-local dependency, not a global install',\n {\n fix: `Update it where it is declared: npm i ${spec}`,\n },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n];\n\n/**\n * Evaluate the refusal set, once per stage. `spec` is null before the registry\n * has been asked and the resolved `tenjin-cli@<version>` after, which is what\n * selects the eligible entries: every entry runs in exactly one stage, so no\n * refusal can be reached twice or, as in round three, be written twice and\n * reached once.\n */\nexport function refuse(moduleDir: string, opts: { check: boolean; spec: string | null }): void {\n for (const entry of REFUSALS) {\n if (opts.check && !entry.appliesToCheck) continue;\n if (entry.needsVersion !== (opts.spec !== null)) continue;\n if (entry.test(moduleDir)) throw entry.error(opts.spec ?? '', moduleDir);\n }\n}\n\n/**\n * The published package ships `dist/`, `docs/`, and `skills/` with no `src/`\n * beside them (the `files` array), so a `src/` next to the nearest package.json\n * means a checkout, whose version number says nothing about what HEAD holds.\n * Same test skill-heal uses to keep its hands off working-tree skills.\n */\nexport function isSourceCheckout(moduleDir: string): boolean {\n let dir = moduleDir;\n for (let i = 0; i < 8; i += 1) {\n if (existsSync(join(dir, 'package.json'))) return existsSync(join(dir, 'src'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\n/**\n * Is this a GLOBAL npm tree? A global install sits under a prefix directory that\n * is not itself a package (`<prefix>/lib/node_modules/tenjin-cli` on POSIX,\n * `<prefix>\\node_modules\\tenjin-cli` on win32), while a project-local one sits\n * under the project root, which by definition has a package.json. That parent is\n * the whole test, which is why it holds for homebrew, nvm, volta and a\n * user-set `npm config prefix` alike without this code enumerating any of them.\n */\nexport function isGlobalTree(moduleDir: string): boolean {\n const segs = moduleDir.split(sep);\n const i = segs.lastIndexOf('node_modules');\n if (i <= 0) return false;\n return !existsSync(join(segs.slice(0, i).join(sep), 'package.json'));\n}\n\n/**\n * Which package manager owns this install, read off the on-disk path. Node\n * resolved the bin symlink before loading us, so the segments name the real\n * store: pnpm's virtual store keeps a literal `.pnpm` segment (or\n * `pnpm/global` for older layouts), bun installs under `.bun`, yarn under\n * `.yarn` or `yarn/global`. Everything else is treated as npm's tree; that\n * covers nvm and volta, both of which route `npm i -g` correctly.\n */\nexport function classifyManager(moduleDir: string): Delegable | 'yarn' {\n const segs = moduleDir.split(sep);\n const pair = (a: string, b: string): boolean => segs.includes(a) && segs.includes(b);\n if (segs.includes('.pnpm') || pair('pnpm', 'global')) return 'pnpm';\n if (segs.includes('.bun')) return 'bun';\n if (segs.includes('.yarn') || pair('yarn', 'global')) return 'yarn';\n return 'npm';\n}\n\n/**\n * How to perform a global install with each manager we delegate to.\n *\n * `scriptSuffixes` is what a PATH shim may resolve to that Node can run\n * directly, which is how win32 is served without a shell: npm and pnpm ship as\n * JS, so the child becomes `node <script>`. An empty list means the binary is\n * native (bun), where spawning it by name already works on every platform.\n */\nexport const MANAGERS: Record<\n Delegable,\n {\n bin: string;\n scriptSuffixes: readonly string[];\n /** Ships beside the running node, as npm does inside the Node distribution. */\n besideNode: boolean;\n args: (spec: string) => string[];\n manual: (spec: string) => string;\n }\n> = {\n npm: {\n bin: 'npm',\n scriptSuffixes: ['npm-cli.js'],\n besideNode: true,\n args: (spec) => ['install', '-g', '--ignore-scripts', spec],\n manual: (spec) => `npm i -g ${spec}`,\n },\n pnpm: {\n bin: 'pnpm',\n // corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.\n scriptSuffixes: ['.cjs', '.js'],\n besideNode: false,\n args: (spec) => ['add', '-g', '--ignore-scripts', spec],\n manual: (spec) => `pnpm add -g ${spec}`,\n },\n bun: {\n bin: 'bun',\n scriptSuffixes: [],\n besideNode: false,\n // No --ignore-scripts: bun's flag surface for it is not stable across the\n // versions in the wild, and an unknown flag would fail the install outright.\n args: (spec) => ['add', '-g', spec],\n manual: (spec) => `bun add -g ${spec}`,\n },\n};\n\n/**\n * npm's own entry script, so the child can be `node npm-cli.js` rather than the\n * `npm` shim.\n *\n * On win32 the shim is `npm.cmd`, which Node refuses to spawn without\n * `shell: true`, and `shell: true` is exactly what this command must not do —\n * it would hand back the argv safety the pinned version buys.\n *\n * Deliberately NOT \"npm ships inside the Node distribution\". That is a property\n * of the installer, not of Node: Homebrew's plain `node` formula keeps only\n * corepack in the keg and puts npm at the brew prefix, so a probe relative to\n * `process.execPath` alone returns null on one of the most common macOS setups.\n * So the layout is searched, not assumed — beside the running binary first\n * (official tarball and installer, nvm, volta, versioned brew kegs), then off\n * PATH, where on POSIX the `npm` shim is itself a symlink to `npm-cli.js` and on\n * win32 `npm.cmd` has `node_modules` beside it. Still null when npm cannot be\n * found at all; the caller then falls back to the bare shim, which works\n * everywhere but win32 and fails closed there into UPDATE_FAILED carrying the\n * manual command.\n */\nexport function resolveNpmCli(\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n return resolveManagerScript('npm', execPath, env);\n}\n\n/**\n * The JS entry script for `manager`, or null when it has none to find (a native\n * binary, or a shim this cannot see through). Null means \"spawn the bare name\",\n * which works everywhere but win32 and fails closed there.\n */\nexport function resolveManagerScript(\n manager: Delegable,\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const plan = MANAGERS[manager];\n if (plan.scriptSuffixes.length === 0) return null;\n const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;\n return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);\n}\n\n/** A manager's script relative to a directory holding `node` or its own shim. */\nfunction scriptNear(dir: string, bin: string): string | null {\n const candidates = [\n join(dir, 'node_modules', bin, 'bin', `${bin}-cli.js`),\n join(dir, '..', 'lib', 'node_modules', bin, 'bin', `${bin}-cli.js`),\n ];\n return candidates.find(isFile) ?? null;\n}\n\n/**\n * Walk PATH for the manager's shim and turn it into its script. Probes the\n * PATHEXT extensions on win32 for the same reason `onPath` in skill-wiring.ts\n * does: the real file there is `npm.cmd`, never a bare `npm`.\n */\nfunction scriptOnPath(\n bin: string,\n suffixes: readonly string[],\n env: NodeJS.ProcessEnv,\n): string | null {\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (!isFile(join(part, `${bin}${ext}`))) continue;\n // POSIX package managers link the shim straight at the script, which is\n // what makes this layout-independent rather than a longer guess list.\n //\n // The endsWith is a CORRECTNESS check, not a security guard: it asks \"did\n // this symlink land on npm's script or on something else\", and a shim\n // pointed elsewhere returns null, which falls back to spawning that same\n // retargeted shim anyway. PATH poisoning is out of scope by construction —\n // an attacker ahead of npm on PATH owns every tool the user runs, and the\n // pre-existing fallback `spawn('npm', ...)` resolved through the same PATH.\n const real = realpathOrNull(join(part, `${bin}${ext}`));\n if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;\n const near = scriptNear(part, bin);\n if (near !== null) return near;\n }\n }\n return null;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nfunction realpathOrNull(p: string): string | null {\n try {\n return realpathSync(p);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,SAAS,UAAU,IAAI,aAAa;AACpD,SAAS,SAAS,MAAM,UAAU,WAAW;AAqBtC,IAAM,cAAc;AAO3B,eAAsB,eAAe,WAAoD;AACvF,QAAM,UAAU,MAAM,QAAQ;AAAA,IAC5B,UAAU,IAAI,OAAO,SAAS,CAAC,MAAM,MAAM,SAAS,KAAK,WAAW,IAAI,GAAG,MAAM,CAAC,CAAU;AAAA,EAC9F,EAAE,MAA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irname","dirname","join"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { WriteStream } from 'node:tty';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;;;ACMnB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;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