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
@@ -0,0 +1 @@
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 * `note` is the free docs lookup before a search, for a client that\n * also lists `note`: the line comes after the search. `augment` is the\n * same offer for a client that does not, with the `augmentUrl` that\n * client fetches. `offer` is every other line. This build shows only a\n * `note` after a search; any other free offer before one, `augment`\n * included, runs silent.\n */\n delivery: z.enum(['offer', 'augment', 'note']).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`. `note` asks for `delivery: \"note\"` on the free docs lookup\n * before a search, whose line this build shows after the search, in place of\n * the `augment` an older build fetched. `catalog` takes Tenjin's reviewed\n * 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. `headers` asks for a spec's `request.headers`, the fixed\n * headers the catalog sets on a service's call (a provider's beta opt-in),\n * with the pins those headers unlock: `buildSpecRequest` sends them, and a\n * build without the token is never sent a spec it would refuse as strict.\n * `bazaar` widens discovery to the open Bazaar and is sent only while\n * `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = [\n 'catalog',\n 'spec',\n 'label',\n 'fields',\n 'jobs',\n 'headers',\n 'note',\n];\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' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA4BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACtD,cAAc,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACzD,SAAS;AACX,CAAC;AAQD,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,YAAY,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EACpC,OAAO,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EAC/B,SAAS,iBAAE,MAAM,iBAAE,OAAO,EAAE,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE;AAAA,EAC5C,YAAY,i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U,OACN,gCAAgC,SAAS,MAAM,MAC/C,gCAAgC,SAAS,MAAM,KAAK,MAAM,IAAI,MAAM,MAAM,OAAO;AAAA,MACvF,GAAI,UAAU,OAAO,EAAE,WAAW,MAAM,KAAK,IAAI,CAAC;AAAA,IACpD;AAAA,EACF;AACA,QAAM,SAAS,OAAO,UAAU,SAAS,IAAI;AAC7C,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,EAAE,QAAQ,UAAU,QAAQ,yDAAyD;AAAA,EAC9F;AACA,SAAO,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":[]}
@@ -15,11 +15,11 @@ import {
15
15
  } from "./chunk-2I4QTOLB.js";
16
16
  import {
17
17
  DEFAULT_MAX_AUTO_SPEND
18
- } from "./chunk-2GNOFONN.js";
18
+ } from "./chunk-2M2VPI2E.js";
19
19
  import {
20
20
  DEFAULT_RPC_URL,
21
21
  rememberingBalanceReader
22
- } from "./chunk-DW4YTVR3.js";
22
+ } from "./chunk-WXA2BWTE.js";
23
23
  import {
24
24
  writeFileAtomic
25
25
  } from "./chunk-7WEQQJLG.js";
@@ -390,4 +390,4 @@ export {
390
390
  aliveMain,
391
391
  markSessionServed
392
392
  };
393
- //# sourceMappingURL=chunk-WOM257PW.js.map
393
+ //# sourceMappingURL=chunk-NDGZDTSJ.js.map
@@ -36,7 +36,6 @@ function codexRouterEvent(raw) {
36
36
  ...call,
37
37
  eventName: "PostToolUse",
38
38
  nativeOutcome: text === "" ? { error: "Web search returned no results" } : null,
39
- search: text === void 0 || split.entry.tool !== "WebSearch" ? null : { raw: {}, results: [] },
40
39
  savedPdf: null
41
40
  };
42
41
  }
@@ -47,18 +46,8 @@ function codexResponse(response) {
47
46
  if (response === null || typeof response !== "object") return null;
48
47
  const { hookSpecificOutput: output, systemMessage } = response;
49
48
  const message = typeof systemMessage === "string" ? { systemMessage } : {};
50
- const specific = codexSpecific(output);
51
- if (specific === null) return Object.keys(message).length > 0 ? message : null;
52
- return { hookSpecificOutput: specific, ...message };
53
- }
54
- function codexSpecific(output) {
55
- if (output === void 0) return null;
56
- if (output.updatedToolOutput !== void 0) {
57
- const results = output.updatedToolOutput.results;
58
- if (typeof results?.[0] !== "string") return null;
59
- return { hookEventName: "PostToolUse", additionalContext: results[0] };
60
- }
61
- return output;
49
+ if (output === void 0) return Object.keys(message).length > 0 ? message : null;
50
+ return { hookSpecificOutput: output, ...message };
62
51
  }
63
52
 
64
53
  export {
@@ -66,4 +55,4 @@ export {
66
55
  codexSession,
67
56
  codexResponse
68
57
  };
69
- //# sourceMappingURL=chunk-SFASB5FL.js.map
58
+ //# sourceMappingURL=chunk-P3LFTKE7.js.map
@@ -0,0 +1 @@
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 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 * A Claude-shaped answer as Codex takes it: `hookSpecificOutput` as it is (a\n * deny, or a line after the call in `additionalContext`, such as a free\n * lookup noted on a search), and `systemMessage`, the line for the user (an\n * unpaid routing fee, a deposit): Codex takes it on every event and shows it\n * as a warning (openai/codex `hooks/src/events/*.rs`, CLI 0.157.1). Nothing\n * else survives, because Codex refuses an answer carrying a field it does not\n * 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 if (output === undefined) return Object.keys(message).length > 0 ? message : null;\n return { hookSpecificOutput: output, ...message };\n}\n"],"mappings":";;;;;;;AAWO,SAAS,iBAAiB,KAAgC;AAC/D,QAAM,QAAQ,OAAO,GAAG;AACxB,MAAI,UAAU,QAAQ,MAAM,UAAU,UAAa,MAAM,QAAQ,SAAS,IAAK,QAAO;AACtF,QAAM,SAAS;AAAA,IACb,WAAW,MAAM;AAAA,IACjB,GAAI,MAAM,MAAM,EAAE,KAAK,MAAM,IAAI,IAAI,CAAC;AAAA,IACtC,GAAI,MAAM,YAAY,SAAS,SAAY,EAAE,gBAAgB,MAAM,WAAW,KAAK,IAAI,CAAC;AAAA,EAC1F;AACA,MAAI,MAAM,UAAU,YAAY,MAAM,WAAW;AAC/C,WAAO,EAAE,MAAM,UAAU,GAAG,QAAQ,QAAQ,MAAM,OAAO;AAC3D,QAAM,OAAO,MAAM;AACnB,QAAM,YAAa,IAAiC;AACpD,MAAI,MAAM,SAAS,YAAY,cAAc,QAAQ,OAAO,cAAc,SAAU,QAAO;AAC3F,QAAM,QAAQ,YAAY,SAAoC;AAC9D,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,OAAO;AAAA,IACX,GAAG;AAAA,IACH,MAAM,MAAM,MAAM;AAAA,IAClB,SAAS,MAAM;AAAA,IACf,GAAI,MAAM,SAAS,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC;AAAA,IAClD,SAAS,MAAM;AAAA,IACf,GAAI,KAAK,WAAW,SAAY,EAAE,WAAW,KAAK,OAAO,IAAI,CAAC;AAAA,EAChE;AACA,MAAI,MAAM,UAAU,cAAe,QAAO,EAAE,MAAM,UAAU,GAAG,KAAK;AACpE,MAAI,MAAM,UAAU,aAAc,QAAO;AACzC,QAAM,OAAO,KAAK,QAAQ;AAC1B,SAAO;AAAA,IACL,MAAM;AAAA,IACN,GAAG;AAAA,IACH,WAAW;AAAA,IACX,eAAe,SAAS,KAAK,EAAE,OAAO,iCAAiC,IAAI;AAAA,IAC3E,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,aAAa,WAA2B;AACtD,SAAO,SAAS,SAAS;AAC3B;AAWO,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,MAAI,WAAW,OAAW,QAAO,OAAO,KAAK,OAAO,EAAE,SAAS,IAAI,UAAU;AAC7E,SAAO,EAAE,oBAAoB,QAAQ,GAAG,QAAQ;AAClD;","names":[]}
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
 
3
3
  // package.json
4
4
  var name = "tenjin-cli";
5
- var version = "0.1.0-alpha.32";
5
+ var version = "0.1.0-alpha.33";
6
6
  var type = "module";
7
7
  var description = "The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.";
8
8
  var repository = {
@@ -49,18 +49,18 @@ var tenjinRuntime = {
49
49
  var files = [
50
50
  "dist",
51
51
  "docs",
52
+ "scripts/installers",
52
53
  "NOTICE.md"
53
54
  ];
54
55
  var packageManager = "pnpm@11.11.0";
55
56
  var scripts = {
56
- build: "rm -rf dist && tsup",
57
+ build: "rm -rf dist .bundle-meta && tsup",
57
58
  test: "vitest run",
58
59
  typecheck: "tsc --noEmit",
59
60
  lint: "eslint .",
60
61
  format: "prettier --write .",
61
62
  "format:check": "prettier --check .",
62
63
  check: "pnpm run build && pnpm run test",
63
- "sync:skill": "node scripts/sync-skill.mjs",
64
64
  "pack-smoke": "bash scripts/pack-smoke.sh",
65
65
  changeset: "changeset",
66
66
  prepublishOnly: "pnpm run build",
@@ -89,7 +89,7 @@ var devDependencies = {
89
89
  "typescript-eslint": "^8",
90
90
  viem: "^2.53.1",
91
91
  vitest: "^4.1.9",
92
- zod: "^4.4.3"
92
+ zod: "^4.6.6"
93
93
  };
94
94
  var package_default = {
95
95
  name,
@@ -127,4 +127,4 @@ export {
127
127
  devDependencies,
128
128
  package_default
129
129
  };
130
- //# sourceMappingURL=chunk-YUY4SAGM.js.map
130
+ //# sourceMappingURL=chunk-RVPYTUP4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.33\",\n \"type\": \"module\",\n \"description\": \"The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.sh/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"claude-code\",\n \"coding-agents\",\n \"tool-router\",\n \"ai-agents\",\n \"agent-tools\",\n \"mcp\",\n \"x402\",\n \"usdc\",\n \"base\",\n \"micropayments\",\n \"agent-payments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=22.0.0\"\n },\n \"tenjinRuntime\": {\n \"node\": {\n \"version\": \"24.22.1\",\n \"sha256\": {\n \"darwin-arm64\": \"89c682593d76cd44233fa53b1563264e7de9cbb189cad169135c5b4fadfbc0a7\",\n \"darwin-x64\": \"d132557e7ee2b85af08b0c8c34338e65c6430f2238d01f727728ef42dc83b035\",\n \"linux-x64\": \"eb6728e77c576a35162c122c45ccadf224d89ff00abc8dae46cc2897c6002d7c\",\n \"linux-arm64\": \"33c37be234ba8bee041961047b19160f4d7d0f164e8e246f78bdd10feff148b3\",\n \"win-x64\": \"d2046d28c2c3dcd211ac5145c0bf30e2047ef9dfb306693c8c6e2eccd8b95fa5\",\n \"win-arm64\": \"a0c807319fede24c4a0d8f84564c82a619bd313b16b10c007c383c2609e99171\"\n }\n }\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"scripts/installers\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"rm -rf dist .bundle-meta && tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"githooks\": \"git config core.hooksPath .githooks\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^3.0.3\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.32.0\",\n \"@types/node\": \"^22.20.5\",\n \"@x402/core\": \"2.28.0\",\n \"@x402/evm\": \"2.28.0\",\n \"@x402/extensions\": \"2.28.0\",\n \"@x402/fetch\": \"2.28.0\",\n \"ajv\": \"^8.20.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"lean-qr\": \"^2.7.4\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.6.6\"\n }\n}\n"],"mappings":";;;AACE,WAAQ;AACR,cAAW;AACX,WAAQ;AACR,kBAAe;AACf,iBAAc;AAAA,EACZ,MAAQ;AAAA,EACR,KAAO;AACT;AACA,eAAY;AACZ,WAAQ;AACR,eAAY;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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 -9,7 +9,7 @@ import {
9
9
  http,
10
10
  serializeTransaction,
11
11
  toRlp
12
- } from "./chunk-PJNENX2A.js";
12
+ } from "./chunk-WFSPCCVW.js";
13
13
  import {
14
14
  InvalidAddressError,
15
15
  concatHex,
@@ -23,7 +23,7 @@ import {
23
23
  } from "./chunk-2GP3HRYK.js";
24
24
  import {
25
25
  USDC_ADDRESS
26
- } from "./chunk-DW4YTVR3.js";
26
+ } from "./chunk-WXA2BWTE.js";
27
27
 
28
28
  // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.6.7/node_modules/viem/_esm/op-stack/contracts.js
29
29
  var contracts = {
@@ -319,4 +319,4 @@ export {
319
319
  prepareUsdcSend,
320
320
  broadcastUsdcSend
321
321
  };
322
- //# sourceMappingURL=chunk-GAKUQHKA.js.map
322
+ //# sourceMappingURL=chunk-TC2WZLSC.js.map
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  FileClientChannelStorage
4
- } from "./chunk-QF3LSMGS.js";
4
+ } from "./chunk-GTTUCOPD.js";
5
5
  import {
6
6
  payerDir
7
7
  } from "./chunk-HDPUXS3Z.js";
@@ -26,4 +26,4 @@ async function channelCredit(dataDir, address) {
26
26
  export {
27
27
  channelCredit
28
28
  };
29
- //# sourceMappingURL=chunk-D3ZURCG7.js.map
29
+ //# sourceMappingURL=chunk-TKPF35W6.js.map
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  emitNotice
4
- } from "./chunk-VJUVFZ2D.js";
4
+ } from "./chunk-FVIGCDSV.js";
5
5
  import {
6
6
  package_default
7
- } from "./chunk-YUY4SAGM.js";
7
+ } from "./chunk-RVPYTUP4.js";
8
8
  import {
9
9
  loadConfig
10
- } from "./chunk-2GNOFONN.js";
10
+ } from "./chunk-2M2VPI2E.js";
11
11
  import {
12
12
  external_exports
13
13
  } from "./chunk-SNNSAGMT.js";
@@ -28,6 +28,7 @@ var NUDGE_OPT_OUT = "TENJIN_NO_UPDATE_CHECK";
28
28
  var CHECK_INTERVAL_MS = 864e5;
29
29
  var FETCH_TIMEOUT_MS = 1500;
30
30
  var DIST_TAGS_URL = "https://registry.npmjs.org/-/package/tenjin-cli/dist-tags";
31
+ var PACKUMENT_URL = "https://registry.npmjs.org/tenjin-cli";
31
32
  var TagEntrySchema = external_exports.object({
32
33
  checkedAtMs: external_exports.number(),
33
34
  /** The version the tag named. Absent when the answer was unusable. */
@@ -144,6 +145,22 @@ async function fetchDistTags(opts) {
144
145
  const parsed = DistTagsSchema.safeParse(json);
145
146
  return parsed.success ? parsed.data : null;
146
147
  }
148
+ async function fetchPublishTime(version, opts) {
149
+ let json;
150
+ try {
151
+ const res = await (opts.fetchImpl ?? fetch)(PACKUMENT_URL, {
152
+ signal: AbortSignal.timeout(opts.timeoutMs),
153
+ headers: { accept: "application/json" }
154
+ });
155
+ if (!res.ok) return null;
156
+ json = await res.json();
157
+ } catch {
158
+ return null;
159
+ }
160
+ const raw = json?.time?.[version];
161
+ const at = typeof raw === "string" ? Date.parse(raw) : NaN;
162
+ return { publishedAt: Number.isNaN(at) ? null : at };
163
+ }
147
164
  async function resolveLatest(current, deps) {
148
165
  const tags = await fetchDistTags({ fetchImpl: deps.fetchImpl, timeoutMs: FETCH_TIMEOUT_MS });
149
166
  return tags === null ? null : { latest: resolveTarget(current, tags) };
@@ -170,6 +187,7 @@ export {
170
187
  readUpdateSignal,
171
188
  channelTag,
172
189
  resolveTarget,
173
- fetchDistTags
190
+ fetchDistTags,
191
+ fetchPublishTime
174
192
  };
175
- //# sourceMappingURL=chunk-I5TDIUKM.js.map
193
+ //# sourceMappingURL=chunk-U3IKUGRP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/update-check.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport pkg from '../../package.json';\nimport { writeFileAtomic } from './atomic-json';\nimport { loadConfig } from './config';\nimport type { UpdateMode } from './config';\nimport { emitNotice } from './output';\nimport type { Io } from './output';\nimport type { UpdateAvailable } from '../schemas';\nimport { updateCheckPath } from './paths';\nimport { isNewer, parseVersion } from './version-order';\n\n/**\n * \"A newer tenjin-cli exists\", asked of npm at most once a day and reported\n * three ways: one dim stderr line for a human at a terminal, `updateAvailable`\n * on the JSON envelope, and a line on the generated hook scripts' output.\n *\n * It REPORTS and never installs. Installing needs a deferred-activation window,\n * and Tenjin's runtime is that window (versions side by side, a running session\n * keeps its own), so `update.mode auto` installs from lib/auto-update, which\n * the session hooks start; `auto` reports here exactly as `nudge` does. After a\n * switch the running version equals `latest`, so this line goes quiet by itself.\n *\n * Everything here is subordinate to the command that ran: the fetch happens\n * AFTER the envelope is written, it never touches stdout, it never changes an\n * exit code, and every failure it can have (offline, slow registry, junk JSON, a\n * tag that does not exist) is swallowed. CI skips the whole thing: a build log\n * can act on none of it. `update.mode off` is the opt-out and silences all three\n * surfaces, including the request to npm.\n */\n\n/**\n * Silences this check for one process, cache write and registry request\n * included. Set by `update` on the `install --refresh` children it spawns: their\n * data dirs come out of a settings file this CLI does not own, and this check is\n * the one thing in a refresh that would CREATE such a directory — `writeCache`\n * mkdirs the tree — where the refresh itself only converges what exists.\n */\nexport const NUDGE_OPT_OUT = 'TENJIN_NO_UPDATE_CHECK';\n\nconst CHECK_INTERVAL_MS = 86_400_000; // 24h\nconst FETCH_TIMEOUT_MS = 1500;\nconst DIST_TAGS_URL = 'https://registry.npmjs.org/-/package/tenjin-cli/dist-tags';\nconst PACKUMENT_URL = 'https://registry.npmjs.org/tenjin-cli';\n\n/** What is known about ONE dist-tag: when it was asked, and what it said. */\nconst TagEntrySchema = z.object({\n checkedAtMs: z.number(),\n /** The version the tag named. Absent when the answer was unusable. */\n latest: z.string().optional(),\n /** When the nudge was last PRINTED for this tag. Absent until one has been. */\n notifiedAtMs: z.number().optional(),\n});\n\n/**\n * The cache is a pure optimization, so a bad one is re-fetched, never repaired.\n * Keyed by dist-tag: an entry this build did not ask about is carried forward\n * untouched rather than evicted.\n */\nconst CacheSchema = z.object({\n schemaVersion: z.literal(1),\n tags: z.record(z.string(), TagEntrySchema),\n /**\n * The resolved \"you could upgrade\" fact, written whenever it changes and\n * cleared when it stops being true.\n *\n * Denormalized from `tags` on purpose: the generated hook scripts are\n * standalone .mjs that cannot import this module and do not know which\n * version is running, so a per-tag entry would leave them unable to tell an\n * upgrade from a match. Storing the comparison's ANSWER is what lets a hook\n * report it without reimplementing any of it.\n */\n signal: z.object({ current: z.string(), latest: z.string() }).optional(),\n});\ntype Cache = z.infer<typeof CacheSchema>;\n\n/** `{\"latest\":\"1.2.3\",\"alpha\":\"1.3.0-alpha.1\"}` — tag names are not fixed. */\nconst DistTagsSchema = z.record(z.string(), z.string());\n\nexport interface UpdateCheckDeps {\n dir: string;\n io: Io;\n /** The global --json flag; ANDed with io.isTTY exactly as the emit path does. */\n json: boolean;\n env?: NodeJS.ProcessEnv;\n /** Clock seam (ms since epoch) for deterministic TTL tests. */\n now?: () => number;\n /** Override global fetch (tests inject a stub returning canned Responses). */\n fetchImpl?: typeof fetch;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** Resolved update.mode; defaults to reading the config file. */\n mode?: UpdateMode;\n}\n\n/**\n * Print the update nudge if one is due. NEVER rejects — the caller awaits it\n * between a command's output and its exit, so a throw here would replace a\n * finished command's result with an internal error.\n */\nexport async function maybeUpdate(deps: UpdateCheckDeps): Promise<void> {\n try {\n const env = deps.env ?? process.env;\n // Never in CI, in either mode: a build log cannot act on a nudge, and a\n // build machine must not silently acquire a different binary mid-pipeline.\n if (env.CI !== undefined && env.CI.length > 0) return;\n if (env[NUDGE_OPT_OUT] === '1') return;\n\n const mode = deps.mode ?? (await loadConfig(deps.dir)).update.mode;\n if (mode === 'off') return;\n\n const nowMs = (deps.now ?? Date.now)();\n const current = deps.currentVersion ?? pkg.version;\n const path = updateCheckPath(deps.dir);\n const tag = channelTag(current);\n if (tag === null) return; // a version this build cannot parse follows no channel\n\n // Only this tag's entry answers this binary's question; the other channel's\n // is neither used nor disturbed.\n const cached = await readCache(path);\n const entry = cached?.tags[tag];\n const fresh = entry !== undefined && nowMs - entry.checkedAtMs < CHECK_INTERVAL_MS;\n\n // Resolved through the same function `tenjin update` uses, so the nudge can\n // never advertise a version the command would decline to install, nor stay\n // quiet about one it would.\n //\n // Only a registry that could not be ASKED returns without caching; an answer\n // this build cannot use has still been answered, and moves the clock below.\n let latest: string | null;\n if (fresh) {\n latest = entry.latest ?? null;\n } else {\n const answer = await resolveLatest(current, deps);\n if (answer === null) return;\n latest = answer.latest;\n }\n\n const upgradeable = latest !== null && isNewer(latest, current);\n\n // Once a day means once a day, not once per FETCH: a fresh cache would\n // otherwise repeat the same line on every command for 24h. The two clocks are\n // separate because they answer separate questions — when we last asked npm,\n // and when we last interrupted the human.\n //\n // `human` is part of `due` for the second of those: this code now runs on\n // every surface, to feed the envelope signal, so without it an agent run\n // would stamp the nudge clock having printed nothing and leave a shared\n // machine's terminal quiet for 24h.\n const human = deps.io.isTTY && !deps.json;\n const notifiedAtMs = entry?.notifiedAtMs;\n const due =\n human &&\n upgradeable &&\n (notifiedAtMs === undefined || nowMs - notifiedAtMs >= CHECK_INTERVAL_MS);\n\n // Carried forward when nothing is printed: the day since the last nudge does\n // not restart just because the registry was asked again.\n const nudgedAtMs = due ? nowMs : notifiedAtMs;\n\n // Carries the agent-visible half of the answer, so a hook or an envelope can\n // report it without knowing which version is running.\n const signal = upgradeable && latest !== null ? { current, latest } : undefined;\n const signalChanged =\n cached?.signal?.current !== signal?.current || cached?.signal?.latest !== signal?.latest;\n\n // Nothing learned and nothing said means nothing to write. Deliberately NOT\n // locked: two concurrent CLI processes can both nudge, and one duplicated\n // line is cheaper than a lock on the exit path of every command.\n if (!fresh || due || signalChanged) {\n await writeCache(path, {\n schemaVersion: 1,\n ...(signal !== undefined ? { signal } : {}),\n // Read-modify-write: the tag this run did not ask about keeps whatever it\n // knew, including its own nudge clock.\n tags: {\n ...cached?.tags,\n [tag]: {\n checkedAtMs: fresh ? entry.checkedAtMs : nowMs,\n ...(latest !== null ? { latest } : {}),\n ...(nudgedAtMs !== undefined ? { notifiedAtMs: nudgedAtMs } : {}),\n },\n },\n });\n }\n\n // Named as the command, not the npm invocation it wraps: `update` prints the\n // right instructions itself for an install it cannot perform (a source\n // checkout, a yarn global), so this line is correct everywhere.\n if (due && latest !== null) {\n emitNotice(\n deps.io,\n `tenjin-cli ${latest} is available (you have ${current}). Update: run tenjin update`,\n { json: deps.json },\n );\n }\n } catch {\n // Unreachable by construction (every step below is already guarded); here so\n // that staying invisible does not depend on that remaining true.\n }\n}\n\n/**\n * What the last check learned, for the envelope. Cache only: this runs before\n * every command's output, so it may not fetch, may not block, and may not throw.\n * Null when nothing newer is known, when the cache is absent or stale-shaped, or\n * when `update.mode` is `off` — off silences BOTH surfaces, not just the line a\n * human sees.\n *\n * Reporting only: where Tenjin's runtime is set up, lib/auto-update installs in\n * the background; everywhere else the agent is told and decides for itself.\n */\nexport async function readUpdateSignal(\n dir: string,\n currentVersion?: string,\n): Promise<UpdateAvailable | null> {\n try {\n const current = currentVersion ?? pkg.version;\n const tag = channelTag(current);\n if (tag === null) return null;\n if ((await loadConfig(dir)).update.mode === 'off') return null;\n const cached = await readCache(updateCheckPath(dir));\n const latest = cached?.tags[tag]?.latest;\n if (latest === undefined || !isNewer(latest, current)) return null;\n return { current, latest };\n } catch {\n return null; // never the command's business\n }\n}\n\n/**\n * Which dist-tag this build follows, or null for a version string this package\n * has no channel for. Null rather than a default, because every caller's right\n * answer differs: the nudge goes quiet, and `tenjin update` refuses instead of\n * silently reporting a foreign build \"up to date\" against a tag it never\n * belonged to.\n *\n * Every build follows `latest`; see RELEASING.md, which changes with this.\n */\nexport function channelTag(version: string): 'latest' | null {\n return parseVersion(version) === null ? null : 'latest';\n}\n\n/**\n * The version this build can move to: whatever sits on the tag it follows.\n * Consulting a second tag added no reachable version and one way to be wrong: a\n * tag sitting ahead of `latest` could redirect the self-update to a build the\n * release line never promoted. Null both when that tag is absent and when it\n * names a version VERSION_RE rejects; `runUpdate` separates those, and neither\n * means the registry was unreachable.\n */\nexport function resolveTarget(current: string, tags: Record<string, string>): string | null {\n const channel = channelTag(current);\n if (channel === null) return null;\n const candidate = tags[channel];\n // Unparseable counts as absent: isNewer loses every comparison against junk,\n // so admitting one would read as \"up to date\" forever.\n if (candidate === undefined || parseVersion(candidate) === null) return null;\n return candidate;\n}\n\n/**\n * Ask the registry for tenjin-cli's whole dist-tag map. Returns null for every\n * failure there is, INCLUDING a response that arrives too late — the AbortSignal\n * is what bounds the delay a finished command can suffer. Nothing is written\n * here: a failed check caches nothing, so the next command retries rather than\n * going quiet for 24h over one dropped packet. The nudge passes its own short\n * budget; `tenjin update` passes the run's request timeout, because there the\n * fetch IS the command rather than a stowaway on someone else's exit path.\n *\n * The whole map rather than one tag, so a caller can tell an unreachable\n * registry (null) from one that answered without the tag it asked for (a map\n * that lacks the key) — two failures with two different fixes.\n */\nexport async function fetchDistTags(opts: {\n fetchImpl?: typeof fetch;\n timeoutMs: number;\n}): Promise<Record<string, string> | null> {\n const doFetch = opts.fetchImpl ?? fetch;\n let json: unknown;\n try {\n const res = await doFetch(DIST_TAGS_URL, { signal: AbortSignal.timeout(opts.timeoutMs) });\n if (!res.ok) return null;\n json = await res.json();\n } catch {\n return null;\n }\n const parsed = DistTagsSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * When the registry says `version` was published, in ms since the epoch, from\n * the packument's `time` map (the per-version document carries no time). Null\n * when the registry could not be asked; `{ publishedAt: null }` when it\n * answered with no time for that version, or one that does not parse. The\n * registry sets these times itself at publish, and a publisher cannot backdate\n * them, which is what lets `tenjin update --background` wait on one.\n */\nexport async function fetchPublishTime(\n version: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs: number },\n): Promise<{ publishedAt: number | null } | null> {\n let json: { time?: Record<string, unknown> } | null;\n try {\n const res = await (opts.fetchImpl ?? fetch)(PACKUMENT_URL, {\n signal: AbortSignal.timeout(opts.timeoutMs),\n headers: { accept: 'application/json' },\n });\n if (!res.ok) return null;\n json = (await res.json()) as typeof json;\n } catch {\n return null;\n }\n const raw = json?.time?.[version];\n const at = typeof raw === 'string' ? Date.parse(raw) : NaN;\n return { publishedAt: Number.isNaN(at) ? null : at };\n}\n\n/**\n * The nudge's one-shot: fetch, then resolve. Null when the registry could not be\n * asked; `{ latest: null }` when it answered with nothing usable.\n */\nasync function resolveLatest(\n current: string,\n deps: UpdateCheckDeps,\n): Promise<{ latest: string | null } | null> {\n const tags = await fetchDistTags({ fetchImpl: deps.fetchImpl, timeoutMs: FETCH_TIMEOUT_MS });\n return tags === null ? null : { latest: resolveTarget(current, tags) };\n}\n\nasync function writeCache(path: string, cache: Cache): Promise<void> {\n await writeFileAtomic(path, `${JSON.stringify(cache, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\nasync function readCache(path: string): Promise<Cache | null> {\n try {\n const parsed = CacheSchema.safeParse(JSON.parse(await readFile(path, 'utf8')));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\n// Version comparison lives in ./version-order, which the runtime's layout code\n// shares; re-exported so existing importers keep their path.\nexport { isNewer };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAsClB,IAAM,gBAAgB;AAE7B,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AACzB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAGtB,IAAM,iBAAiB,iBAAE,OAAO;AAAA,EAC9B,aAAa,iBAAE,OAAO;AAAA;AAAA,EAEtB,QAAQ,iBAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAE5B,cAAc,iBAAE,OAAO,EAAE,SAAS;AACpC,CAAC;AAOD,IAAM,cAAc,iBAAE,OAAO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3F,SAAO,SAAS,OAAO,OAAO,EAAE,QAAQ,cAAc,SAAS,IAAI,EAAE;AACvE;AAEA,eAAe,WAAW,MAAc,OAA6B;AACnE,QAAM,gBAAgB,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,IACjE,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;AAEA,eAAe,UAAU,MAAqC;AAC5D,MAAI;AACF,UAAM,SAAS,YAAY,UAAU,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC,CAAC;AAC7E,WAAO,OAAO,UAAU,OAAO,OAAO;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-V2LQLN5H.js";
5
5
  import {
6
6
  emitNotice
7
- } from "./chunk-VJUVFZ2D.js";
7
+ } from "./chunk-FVIGCDSV.js";
8
8
  import {
9
9
  STORE_TIMEOUTS,
10
10
  describeStoreLocation,
@@ -25,7 +25,7 @@ import {
25
25
  publicKeyToAddress,
26
26
  serializeSignature,
27
27
  serializeTransaction
28
- } from "./chunk-PJNENX2A.js";
28
+ } from "./chunk-WFSPCCVW.js";
29
29
  import {
30
30
  hmac,
31
31
  secp256k1,
@@ -1706,4 +1706,4 @@ export {
1706
1706
  @noble/ciphers/esm/utils.js:
1707
1707
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1708
1708
  */
1709
- //# sourceMappingURL=chunk-BI673VEJ.js.map
1709
+ //# sourceMappingURL=chunk-UXZONNEQ.js.map
@@ -5171,7 +5171,7 @@ async function getWebSocketRpcClient(url, options = {}) {
5171
5171
  const { keepAlive, reconnect } = options;
5172
5172
  return getSocketRpcClient({
5173
5173
  async getSocket({ onClose, onError, onOpen, onResponse }) {
5174
- const WebSocket = await import("./_esm-C5CRWCYU.js").then((module) => module.WebSocket);
5174
+ const WebSocket = await import("./isows-native-Q2UDIVPT.js").then((module) => module.WebSocket);
5175
5175
  const socket = new WebSocket(url);
5176
5176
  function onClose_() {
5177
5177
  socket.removeEventListener("close", onClose_);
@@ -11413,4 +11413,4 @@ export {
11413
11413
  serializeCompactSignature,
11414
11414
  signatureToCompactSignature
11415
11415
  };
11416
- //# sourceMappingURL=chunk-PJNENX2A.js.map
11416
+ //# sourceMappingURL=chunk-WFSPCCVW.js.map