@xiaoso/dsh-tool-plus 0.1.6 → 0.1.7-beta.1

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 (357) hide show
  1. package/THIRD_PARTY_NOTICES.md +9 -3
  2. package/lib/{abort-Cwwm4Err.mjs → abort-Caqff3M6.mjs} +2 -2
  3. package/lib/alibaba-coding-plan-DTupMiAi.mjs +73 -0
  4. package/lib/alibaba-token-plan-CHGyWOfX.mjs +46 -0
  5. package/lib/alibaba-token-plan-Dj3OZhEE.mjs +82 -0
  6. package/lib/{amazon-bedrock-TVMpUTRG.mjs → amazon-bedrock-DbFSYXfJ.mjs} +117 -38
  7. package/lib/{anthropic-BL6LFDQS.mjs → anthropic-CTJ3IQVa.mjs} +675 -166
  8. package/lib/anthropic-CXfWlp-x.mjs +105 -0
  9. package/lib/{aws-credentials-B20dliS7.mjs → anthropic-wire-CKuhDwZ1.mjs} +74 -14
  10. package/lib/{api-key-login-CIDnXeYd.mjs → api-key-validation-CGCJFbFr.mjs} +27 -68
  11. package/lib/{azure-openai-responses-BkhsLmN3.mjs → azure-openai-responses-ChFbWaGj.mjs} +27 -16
  12. package/lib/{browser-render-CmgvSNte.mjs → browser-render-9o0Rknop.mjs} +4 -4
  13. package/lib/bun-shim.mjs +71 -2
  14. package/lib/{bundled-references-ChZSPDFw.mjs → bundled-references-DY3EJxZV.mjs} +6 -5
  15. package/lib/cline-pass-Bwg3esu9.mjs +44 -0
  16. package/lib/cloudflare-ai-gateway-BupNXyKK.mjs +35 -0
  17. package/lib/cloudflare-ai-gateway-EWo0VkP5.mjs +44 -0
  18. package/lib/collapse-DOR8sOGf.mjs +2304 -0
  19. package/lib/coreweave-C82HrLpb.mjs +31 -0
  20. package/lib/coreweave-Ct8cF-da.mjs +14 -0
  21. package/lib/{cursor-B6HcmplF.mjs → cursor-B95LzVWV.mjs} +11 -3
  22. package/lib/{cursor-CRpLpaZ3.mjs → cursor-DJV_dcgB.mjs} +887 -1784
  23. package/lib/{cursor-B8m6SqAH.mjs → cursor-LKGjucn2.mjs} +48 -38
  24. package/lib/cursor-proto-B8Wj8bv9.mjs +10513 -0
  25. package/lib/{deterministic-id-D-yIV_eI.mjs → deterministic-id-CUEIMSqR.mjs} +1 -1
  26. package/lib/devin-BMTdx_hx.mjs +316 -0
  27. package/lib/{devin-DUAfvBsW.mjs → devin-DSp0Rw_E.mjs} +172 -86
  28. package/lib/devin-ExGIghmx.mjs +69 -0
  29. package/lib/devin-proto-Br8fdyNl.mjs +2888 -0
  30. package/lib/{dom-CawWi8fa.mjs → dom-DG3sPESc.mjs} +8 -8
  31. package/lib/effort-BdtQMN-_.mjs +23 -0
  32. package/lib/{error-C-f_Wnw4.mjs → error-CORgGg5a.mjs} +275 -154
  33. package/lib/{event-stream-Dh2guZxS.mjs → event-stream-ulcDenZD.mjs} +20 -4
  34. package/lib/{gemini-headers-DKUShltF.mjs → gemini-headers-Co9cVvex.mjs} +2 -2
  35. package/lib/{github-copilot-suDymKrx.mjs → github-copilot-Dstq1D3s.mjs} +69 -29
  36. package/lib/github-copilot-headers-DOh1gt_w.mjs +312 -0
  37. package/lib/gitlab-duo-DSCMrU0m.mjs +11 -0
  38. package/lib/google-CtsKkOQK.mjs +38 -0
  39. package/lib/google-antigravity-z-5KsEci.mjs +252 -0
  40. package/lib/{google-auth-DYJLM792.mjs → google-auth-ieLBaneO.mjs} +4 -4
  41. package/lib/{google-gemini-cli-8BT513Ul.mjs → google-gemini-cli-C6NE5mWz.mjs} +28 -54
  42. package/lib/{google-gemini-cli-D6cSmfvB.mjs → google-gemini-cli-CAIPSl7e.mjs} +23 -29
  43. package/lib/google-oauth-shared-DhMllAkt.mjs +53 -0
  44. package/lib/{google-shared-CVbHK5vZ.mjs → google-shared-B0aNCYEH.mjs} +140 -44
  45. package/lib/{google-validation-Cgbn3tWJ.mjs → google-validation-BEkNs-Bx.mjs} +1 -1
  46. package/lib/{google-vertex-Bui-ypAe.mjs → google-vertex-Bbd1tYNc.mjs} +8 -8
  47. package/lib/hosts-00rjRzUD.mjs +203 -0
  48. package/lib/id-AL5obQzR.mjs +71 -0
  49. package/lib/{idle-iterator-CYAxUkSD.mjs → idle-iterator-DlUkEfzW.mjs} +3 -3
  50. package/lib/index.mjs +598 -5275
  51. package/lib/kilo-ChJL54wq.mjs +81 -0
  52. package/lib/kimi-C2c_Zq8A.mjs +67 -0
  53. package/lib/{launch-BmgEUycu.mjs → launch-DKDH71En.mjs} +1 -1
  54. package/lib/markit-CmRfm4E2.mjs +9885 -0
  55. package/lib/models-DnXMYGcJ.mjs +381604 -0
  56. package/lib/muse-code-Di1VZmB1.mjs +143 -0
  57. package/lib/{ollama-Df9ce-Cp.mjs → ollama-B8ic3sEp.mjs} +15 -30
  58. package/lib/{openai-codex-CAVI3Me-.mjs → openai-codex-DuJNC99x.mjs} +29 -99
  59. package/lib/{openai-codex-responses-BcnOotRB.mjs → openai-codex-responses-BL29nh9K.mjs} +204 -116
  60. package/lib/{openai-completions-Bq4WT47M.mjs → openai-completions-BK2f2dBv.mjs} +152 -82
  61. package/lib/openai-configuration-update-xMYUjaK_.mjs +150 -0
  62. package/lib/{openai-reasoning-fallback-DXsfiSXO.mjs → openai-reasoning-fallback-BdB3RCbj.mjs} +106 -12
  63. package/lib/{openai-responses-Mq_-PjvE.mjs → openai-responses-CGQPlIIy.mjs} +76 -82
  64. package/lib/{perplexity-XgLF73E7.mjs → perplexity-TBjz3VMB.mjs} +52 -9
  65. package/lib/{pkce-BlQikGPu.mjs → pkce-BYjmugmw.mjs} +1 -1
  66. package/lib/protobuf-aab1UGVn.mjs +717 -0
  67. package/lib/{provider-response-C6vcbQyO.mjs → provider-response-SqKSkkUc.mjs} +1 -1
  68. package/lib/{proxy-D9lm7ONA.mjs → proxy-5nWqRL1f.mjs} +45 -5
  69. package/lib/{readability-Cpm-ocau.mjs → readability-uGhqb4GC.mjs} +2 -2
  70. package/lib/reference-CtvM4zLU.mjs +114 -0
  71. package/lib/{request-debug-HJMoJncL.mjs → request-debug-NQN0BjHH.mjs} +1 -1
  72. package/lib/{sanitize-text-CfcXzw5X.mjs → sanitize-text-BCf5KmCf.mjs} +1 -1
  73. package/lib/{scrapers-Cg5w77td.mjs → scrapers-BpqEnqNM.mjs} +12 -12
  74. package/lib/{src-BcD0_rQR.mjs → src-BwW51vA5.mjs} +979 -388
  75. package/lib/{sse-debug-CYdjOC96.mjs → sse-debug-B-tkLCPW.mjs} +1 -1
  76. package/lib/{stream-Bjq8wjfr.mjs → stream-B_7qN-bA.mjs} +3802 -2623
  77. package/lib/stream-markup-healing-DKT1lnkW.mjs +267 -0
  78. package/lib/{strict-tool-validation-imVLUcbI.mjs → strict-tool-validation-CBTz1dAA.mjs} +2 -2
  79. package/lib/taxonomy-DSIM99rS.mjs +15392 -0
  80. package/lib/{stream-markup-healing-DZ6bVDxH.mjs → thinking-CiLa2LFB.mjs} +31 -186
  81. package/lib/{turndown-DN7ByzEI.mjs → turndown-DrX1M4WG.mjs} +4 -4
  82. package/lib/{type-guards-B9VVjRDK.mjs → type-guards-CttAANEx.mjs} +1 -1
  83. package/lib/types/client/BashPlusCard.d.ts +53 -0
  84. package/lib/types/client/ToolPlusSection.d.ts +36 -0
  85. package/lib/types/client/forms.d.ts +42 -0
  86. package/lib/types/client/index.d.ts +29 -0
  87. package/lib/types/client/locales.d.ts +19 -0
  88. package/lib/types/client/rm-safe-status-text.d.ts +15 -0
  89. package/lib/types/client/rows.d.ts +107 -0
  90. package/lib/types/client/web-connection-rpc.d.ts +22 -0
  91. package/lib/types/config/fields.d.ts +85 -0
  92. package/lib/types/config/omp-settings.d.ts +21 -0
  93. package/lib/types/config/settings.d.ts +212 -0
  94. package/lib/types/config/truncate.d.ts +27 -0
  95. package/lib/types/host/browser-probe-rpc.d.ts +29 -0
  96. package/lib/types/index.d.ts +6 -0
  97. package/lib/types/tools/ast-edit/adapter/index.d.ts +26 -0
  98. package/lib/types/tools/ast-edit/adapter/sdk.d.ts +49 -0
  99. package/lib/types/tools/ast-grep/adapter/index.d.ts +31 -0
  100. package/lib/types/tools/ast-grep/adapter/sdk.d.ts +44 -0
  101. package/lib/types/tools/bash/adapter/spill.d.ts +34 -0
  102. package/lib/types/tools/bash/background.d.ts +40 -0
  103. package/lib/types/tools/bash/bash-executor.d.ts +102 -0
  104. package/lib/types/tools/bash/bash-interceptor.d.ts +33 -0
  105. package/lib/types/tools/bash/cd-workdir.d.ts +35 -0
  106. package/lib/types/tools/bash/logger.d.ts +18 -0
  107. package/lib/types/tools/bash/non-interactive-env.d.ts +5 -0
  108. package/lib/types/tools/bash/render.d.ts +46 -0
  109. package/lib/types/tools/bash/rm-safe-status.d.ts +62 -0
  110. package/lib/types/tools/bash/rm-safe.d.ts +18 -0
  111. package/lib/types/tools/bash/sanitize-text.d.ts +34 -0
  112. package/lib/types/tools/bash/shell-snapshot.d.ts +31 -0
  113. package/lib/types/tools/bash/shell-tokenize.d.ts +60 -0
  114. package/lib/types/tools/bash/streaming-output.d.ts +32 -0
  115. package/lib/types/tools/bash/trash-cli-main.d.ts +1 -0
  116. package/lib/types/tools/bash/trash-cli.d.ts +77 -0
  117. package/lib/types/tools/bash/types.d.ts +107 -0
  118. package/lib/types/tools/bash/which.d.ts +20 -0
  119. package/lib/types/tools/bash/windows-shell.d.ts +31 -0
  120. package/lib/types/tools/bash/yield.d.ts +71 -0
  121. package/lib/types/tools/edit/adapter/index.d.ts +57 -0
  122. package/lib/types/tools/edit/adapter/tools/auto-generated-guard.d.ts +10 -0
  123. package/lib/types/tools/edit/adapter/tools/output-meta.d.ts +34 -0
  124. package/lib/types/tools/edit/adapter/tools/plan-mode-guard.d.ts +21 -0
  125. package/lib/types/tools/glob/adapter/index.d.ts +52 -0
  126. package/lib/types/tools/grep/adapter/index.d.ts +53 -0
  127. package/lib/types/tools/grep/adapter/match-path.d.ts +1 -0
  128. package/lib/types/tools/hashline/native/diff-preview.d.ts +37 -0
  129. package/lib/types/tools/hashline/native/index.d.ts +109 -0
  130. package/lib/types/tools/hashline/native/normalize.d.ts +29 -0
  131. package/lib/types/tools/hashline/native/policy.d.ts +98 -0
  132. package/lib/types/tools/hashline/native/writer.d.ts +42 -0
  133. package/lib/types/tools/omp/browser/launch.d.ts +28 -0
  134. package/lib/types/tools/omp/browser/readable.d.ts +17 -0
  135. package/lib/types/tools/omp/config/settings-schema.d.ts +12 -0
  136. package/lib/types/tools/omp/config/settings.d.ts +59 -0
  137. package/lib/types/tools/omp/edit/apply-patch/parser.d.ts +34 -0
  138. package/lib/types/tools/omp/edit/details.d.ts +54 -0
  139. package/lib/types/tools/omp/edit/diff.d.ts +60 -0
  140. package/lib/types/tools/omp/edit/dispatch.d.ts +43 -0
  141. package/lib/types/tools/omp/edit/file-snapshot-store.d.ts +81 -0
  142. package/lib/types/tools/omp/edit/hashline/execute.d.ts +40 -0
  143. package/lib/types/tools/omp/edit/hashline/params.d.ts +6 -0
  144. package/lib/types/tools/omp/edit/modes/apply-patch.d.ts +25 -0
  145. package/lib/types/tools/omp/edit/modes/patch.d.ts +109 -0
  146. package/lib/types/tools/omp/edit/modes/replace.d.ts +151 -0
  147. package/lib/types/tools/omp/edit/normalize.d.ts +31 -0
  148. package/lib/types/tools/omp/edit/notebook.d.ts +50 -0
  149. package/lib/types/tools/omp/edit/read-file.d.ts +2 -0
  150. package/lib/types/tools/omp/edit/snapshot-details.d.ts +33 -0
  151. package/lib/types/tools/omp/extensibility/skills.d.ts +22 -0
  152. package/lib/types/tools/omp/internal-urls/index.d.ts +100 -0
  153. package/lib/types/tools/omp/internal-urls/local-protocol.d.ts +12 -0
  154. package/lib/types/tools/omp/internal-urls/parse.d.ts +31 -0
  155. package/lib/types/tools/omp/internal-urls/types.d.ts +189 -0
  156. package/lib/types/tools/omp/internal-urls/xd-protocol.d.ts +19 -0
  157. package/lib/types/tools/omp/markit/converters/docx.d.ts +6 -0
  158. package/lib/types/tools/omp/markit/converters/epub.d.ts +15 -0
  159. package/lib/types/tools/omp/markit/converters/pdf/index.d.ts +7 -0
  160. package/lib/types/tools/omp/markit/converters/pptx.d.ts +57 -0
  161. package/lib/types/tools/omp/markit/converters/xlsx.d.ts +25 -0
  162. package/lib/types/tools/omp/markit/index.d.ts +2 -0
  163. package/lib/types/tools/omp/markit/registry.d.ts +16 -0
  164. package/lib/types/tools/omp/markit/types.d.ts +30 -0
  165. package/lib/types/tools/omp/sdk.d.ts +103 -0
  166. package/lib/types/tools/omp/session/agent-storage.d.ts +154 -0
  167. package/lib/types/tools/omp/session/streaming-output.d.ts +244 -0
  168. package/lib/types/tools/omp/task/spawn-policy.d.ts +22 -0
  169. package/lib/types/tools/omp/tools/approval.d.ts +62 -0
  170. package/lib/types/tools/omp/tools/ast-edit.d.ts +73 -0
  171. package/lib/types/tools/omp/tools/ast-grep.d.ts +61 -0
  172. package/lib/types/tools/omp/tools/auto-generated-guard.d.ts +20 -0
  173. package/lib/types/tools/omp/tools/conflict-detect.d.ts +237 -0
  174. package/lib/types/tools/omp/tools/fetch.d.ts +103 -0
  175. package/lib/types/tools/omp/tools/file-recorder.d.ts +13 -0
  176. package/lib/types/tools/omp/tools/fs-cache-invalidation.d.ts +15 -0
  177. package/lib/types/tools/omp/tools/glob.d.ts +86 -0
  178. package/lib/types/tools/omp/tools/grep.d.ts +102 -0
  179. package/lib/types/tools/omp/tools/grouped-file-output.d.ts +70 -0
  180. package/lib/types/tools/omp/tools/index.d.ts +23 -0
  181. package/lib/types/tools/omp/tools/list-limit.d.ts +12 -0
  182. package/lib/types/tools/omp/tools/match-line-format.d.ts +11 -0
  183. package/lib/types/tools/omp/tools/output-meta.d.ts +160 -0
  184. package/lib/types/tools/omp/tools/path-utils.d.ts +326 -0
  185. package/lib/types/tools/omp/tools/plan-mode-guard.d.ts +33 -0
  186. package/lib/types/tools/omp/tools/read-archive.d.ts +16 -0
  187. package/lib/types/tools/omp/tools/read-format.d.ts +104 -0
  188. package/lib/types/tools/omp/tools/read-path-resolution.d.ts +19 -0
  189. package/lib/types/tools/omp/tools/read-selector.d.ts +27 -0
  190. package/lib/types/tools/omp/tools/read-sqlite.d.ts +16 -0
  191. package/lib/types/tools/omp/tools/read-summary.d.ts +15 -0
  192. package/lib/types/tools/omp/tools/read.d.ts +70 -0
  193. package/lib/types/tools/omp/tools/render-utils.d.ts +28 -0
  194. package/lib/types/tools/omp/tools/report-tool-issue.d.ts +149 -0
  195. package/lib/types/tools/omp/tools/resolve.d.ts +127 -0
  196. package/lib/types/tools/omp/tools/sqlite-reader.d.ts +114 -0
  197. package/lib/types/tools/omp/tools/tool-errors.d.ts +33 -0
  198. package/lib/types/tools/omp/tools/tool-result.d.ts +33 -0
  199. package/lib/types/tools/omp/tools/tool-timeouts.d.ts +57 -0
  200. package/lib/types/tools/omp/tools/write.d.ts +53 -0
  201. package/lib/types/tools/omp/tools/writethrough.d.ts +24 -0
  202. package/lib/types/tools/omp/utils/block-context.d.ts +35 -0
  203. package/lib/types/tools/omp/utils/cpuprofile.d.ts +51 -0
  204. package/lib/types/tools/omp/utils/edit-mode.d.ts +13 -0
  205. package/lib/types/tools/omp/utils/file-display-mode.d.ts +27 -0
  206. package/lib/types/tools/omp/utils/image-loading.d.ts +51 -0
  207. package/lib/types/tools/omp/utils/image-resize.d.ts +42 -0
  208. package/lib/types/tools/omp/utils/lang-from-path.d.ts +9 -0
  209. package/lib/types/tools/omp/utils/markit-cache.d.ts +23 -0
  210. package/lib/types/tools/omp/utils/markit.d.ts +30 -0
  211. package/lib/types/tools/omp/utils/profile-tree.d.ts +47 -0
  212. package/lib/types/tools/omp/utils/sample-profile.d.ts +67 -0
  213. package/lib/types/tools/omp/utils/sixel.d.ts +21 -0
  214. package/lib/types/tools/omp/utils/tools-manager.d.ts +11 -0
  215. package/lib/types/tools/omp/utils/turndown.d.ts +15 -0
  216. package/lib/types/tools/omp/utils/zip.d.ts +129 -0
  217. package/lib/types/tools/omp/web/browser-render.d.ts +50 -0
  218. package/lib/types/tools/omp/web/parallel.d.ts +68 -0
  219. package/lib/types/tools/omp/web/scrapers/artifacthub.d.ts +6 -0
  220. package/lib/types/tools/omp/web/scrapers/arxiv.d.ts +5 -0
  221. package/lib/types/tools/omp/web/scrapers/aur.d.ts +5 -0
  222. package/lib/types/tools/omp/web/scrapers/biorxiv.d.ts +5 -0
  223. package/lib/types/tools/omp/web/scrapers/bluesky.d.ts +5 -0
  224. package/lib/types/tools/omp/web/scrapers/brew.d.ts +5 -0
  225. package/lib/types/tools/omp/web/scrapers/cheatsh.d.ts +8 -0
  226. package/lib/types/tools/omp/web/scrapers/chocolatey.d.ts +5 -0
  227. package/lib/types/tools/omp/web/scrapers/choosealicense.d.ts +2 -0
  228. package/lib/types/tools/omp/web/scrapers/cisa-kev.d.ts +5 -0
  229. package/lib/types/tools/omp/web/scrapers/clojars.d.ts +5 -0
  230. package/lib/types/tools/omp/web/scrapers/coingecko.d.ts +5 -0
  231. package/lib/types/tools/omp/web/scrapers/crates-io.d.ts +5 -0
  232. package/lib/types/tools/omp/web/scrapers/crossref.d.ts +2 -0
  233. package/lib/types/tools/omp/web/scrapers/devto.d.ts +5 -0
  234. package/lib/types/tools/omp/web/scrapers/discogs.d.ts +8 -0
  235. package/lib/types/tools/omp/web/scrapers/discourse.d.ts +5 -0
  236. package/lib/types/tools/omp/web/scrapers/dockerhub.d.ts +5 -0
  237. package/lib/types/tools/omp/web/scrapers/docs-rs.d.ts +9 -0
  238. package/lib/types/tools/omp/web/scrapers/fdroid.d.ts +5 -0
  239. package/lib/types/tools/omp/web/scrapers/firefox-addons.d.ts +2 -0
  240. package/lib/types/tools/omp/web/scrapers/flathub.d.ts +2 -0
  241. package/lib/types/tools/omp/web/scrapers/github-gist.d.ts +5 -0
  242. package/lib/types/tools/omp/web/scrapers/github.d.ts +34 -0
  243. package/lib/types/tools/omp/web/scrapers/gitlab.d.ts +5 -0
  244. package/lib/types/tools/omp/web/scrapers/go-pkg.d.ts +5 -0
  245. package/lib/types/tools/omp/web/scrapers/hackage.d.ts +5 -0
  246. package/lib/types/tools/omp/web/scrapers/hackernews.d.ts +2 -0
  247. package/lib/types/tools/omp/web/scrapers/hex.d.ts +5 -0
  248. package/lib/types/tools/omp/web/scrapers/huggingface.d.ts +2 -0
  249. package/lib/types/tools/omp/web/scrapers/iacr.d.ts +5 -0
  250. package/lib/types/tools/omp/web/scrapers/index.d.ts +84 -0
  251. package/lib/types/tools/omp/web/scrapers/jetbrains-marketplace.d.ts +2 -0
  252. package/lib/types/tools/omp/web/scrapers/lemmy.d.ts +2 -0
  253. package/lib/types/tools/omp/web/scrapers/lobsters.d.ts +5 -0
  254. package/lib/types/tools/omp/web/scrapers/mastodon.d.ts +5 -0
  255. package/lib/types/tools/omp/web/scrapers/maven.d.ts +6 -0
  256. package/lib/types/tools/omp/web/scrapers/mdn.d.ts +2 -0
  257. package/lib/types/tools/omp/web/scrapers/metacpan.d.ts +5 -0
  258. package/lib/types/tools/omp/web/scrapers/musicbrainz.d.ts +5 -0
  259. package/lib/types/tools/omp/web/scrapers/npm.d.ts +5 -0
  260. package/lib/types/tools/omp/web/scrapers/nuget.d.ts +5 -0
  261. package/lib/types/tools/omp/web/scrapers/nvd.d.ts +5 -0
  262. package/lib/types/tools/omp/web/scrapers/ollama.d.ts +2 -0
  263. package/lib/types/tools/omp/web/scrapers/open-vsx.d.ts +5 -0
  264. package/lib/types/tools/omp/web/scrapers/opencorporates.d.ts +5 -0
  265. package/lib/types/tools/omp/web/scrapers/openlibrary.d.ts +5 -0
  266. package/lib/types/tools/omp/web/scrapers/orcid.d.ts +5 -0
  267. package/lib/types/tools/omp/web/scrapers/osv.d.ts +5 -0
  268. package/lib/types/tools/omp/web/scrapers/packagist.d.ts +5 -0
  269. package/lib/types/tools/omp/web/scrapers/pub-dev.d.ts +5 -0
  270. package/lib/types/tools/omp/web/scrapers/pubmed.d.ts +5 -0
  271. package/lib/types/tools/omp/web/scrapers/pypi.d.ts +5 -0
  272. package/lib/types/tools/omp/web/scrapers/rawg.d.ts +2 -0
  273. package/lib/types/tools/omp/web/scrapers/readthedocs.d.ts +2 -0
  274. package/lib/types/tools/omp/web/scrapers/reddit.d.ts +5 -0
  275. package/lib/types/tools/omp/web/scrapers/repology.d.ts +5 -0
  276. package/lib/types/tools/omp/web/scrapers/rfc.d.ts +5 -0
  277. package/lib/types/tools/omp/web/scrapers/rubygems.d.ts +5 -0
  278. package/lib/types/tools/omp/web/scrapers/searchcode.d.ts +2 -0
  279. package/lib/types/tools/omp/web/scrapers/sec-edgar.d.ts +5 -0
  280. package/lib/types/tools/omp/web/scrapers/semantic-scholar.d.ts +2 -0
  281. package/lib/types/tools/omp/web/scrapers/snapcraft.d.ts +2 -0
  282. package/lib/types/tools/omp/web/scrapers/sourcegraph.d.ts +2 -0
  283. package/lib/types/tools/omp/web/scrapers/spdx.d.ts +5 -0
  284. package/lib/types/tools/omp/web/scrapers/spotify.d.ts +8 -0
  285. package/lib/types/tools/omp/web/scrapers/stackoverflow.d.ts +6 -0
  286. package/lib/types/tools/omp/web/scrapers/terraform.d.ts +5 -0
  287. package/lib/types/tools/omp/web/scrapers/tldr.d.ts +7 -0
  288. package/lib/types/tools/omp/web/scrapers/twitter.d.ts +5 -0
  289. package/lib/types/tools/omp/web/scrapers/types.d.ts +90 -0
  290. package/lib/types/tools/omp/web/scrapers/utils.d.ts +26 -0
  291. package/lib/types/tools/omp/web/scrapers/vimeo.d.ts +5 -0
  292. package/lib/types/tools/omp/web/scrapers/vscode-marketplace.d.ts +5 -0
  293. package/lib/types/tools/omp/web/scrapers/w3c.d.ts +2 -0
  294. package/lib/types/tools/omp/web/scrapers/wikidata.d.ts +5 -0
  295. package/lib/types/tools/omp/web/scrapers/wikipedia.d.ts +5 -0
  296. package/lib/types/tools/omp/web/scrapers/youtube.d.ts +5 -0
  297. package/lib/types/tools/omp/web/search/providers/utils.d.ts +49 -0
  298. package/lib/types/tools/omp/web/search/types.d.ts +501 -0
  299. package/lib/types/tools/omp/web/search/utils.d.ts +4 -0
  300. package/lib/types/tools/omp/workspace-tree.d.ts +42 -0
  301. package/lib/types/tools/read/adapter/index.d.ts +49 -0
  302. package/lib/types/tools/read/adapter/internal-urls/artifact-protocol.d.ts +15 -0
  303. package/lib/types/tools/read/adapter/internal-urls/registry-helpers.d.ts +44 -0
  304. package/lib/types/tools/read/adapter/registry/agent-registry.d.ts +29 -0
  305. package/lib/types/tools/shared/auto-generated-guard.dsh.d.ts +16 -0
  306. package/lib/types/tools/shared/browser-detect.d.ts +54 -0
  307. package/lib/types/tools/shared/browser-rpc-channel.d.ts +40 -0
  308. package/lib/types/tools/shared/bun-ffi-shim.d.ts +13 -0
  309. package/lib/types/tools/shared/bun-named-shim.d.ts +42 -0
  310. package/lib/types/tools/shared/bun-shim.d.ts +138 -0
  311. package/lib/types/tools/shared/bun-sqlite-shim.d.ts +49 -0
  312. package/lib/types/tools/shared/fs-promises-shim.d.ts +15 -0
  313. package/lib/types/tools/shared/image-bridge.d.ts +98 -0
  314. package/lib/types/tools/shared/omp-prompt.d.ts +47 -0
  315. package/lib/types/tools/shared/sandbox-policy.d.ts +38 -0
  316. package/lib/types/tools/shared/session-state.d.ts +51 -0
  317. package/lib/types/tools/shared/tool-errors.d.ts +33 -0
  318. package/lib/types/tools/shared/win-path-fixes.d.ts +16 -0
  319. package/lib/types/tools/write/adapter/index.d.ts +31 -0
  320. package/lib/{types-DX_bvuus.mjs → types-PVueGi9S.mjs} +2 -2
  321. package/lib/{utils-C-dSORPa.mjs → utils-B7A3Eu4L.mjs} +2364 -2676
  322. package/lib/{utils-Cp2Mxf_U.mjs → utils-CUPhpw9A.mjs} +413 -134
  323. package/lib/{utils-CQHPEQ3W.mjs → utils-DeWqNWV8.mjs} +2 -2
  324. package/lib/{vision-guard-mBmtAHx0.mjs → vision-guard-_XwsL1DF.mjs} +14 -29
  325. package/lib/xai-oauth-CXhnz0gO.mjs +210 -0
  326. package/lib/{xiaomi-7mE345KX.mjs → xiaomi-psoUItal.mjs} +8 -37
  327. package/lib/{zai-CeNpMV3W.mjs → zai-ApJ8HBgT.mjs} +8 -71
  328. package/lib/{zip-BK7UHCwX.mjs → zip-Kd602XNe.mjs} +1 -1
  329. package/package.json +12 -12
  330. package/presets/package.json +1 -1
  331. package/presets/tool-plus-ptc/agent.cordis.yml +1 -1
  332. package/presets/tool-plus-standard/agent.cordis.yml +1 -1
  333. package/scripts/patch-pi-natives.mjs +108 -108
  334. package/lib/agent_pb-Rizyt9Zg.mjs +0 -805
  335. package/lib/anthropic-CDmj476p.mjs +0 -262
  336. package/lib/api_server_pb-CDZgLMta.mjs +0 -252
  337. package/lib/callback-server-CFJK-jvK.mjs +0 -398
  338. package/lib/codex-P1dGpX7G.mjs +0 -54
  339. package/lib/device-code-CuXTWYwY.mjs +0 -51
  340. package/lib/devin-BcQwht1W.mjs +0 -114
  341. package/lib/devin-BvMfGevz.mjs +0 -95
  342. package/lib/github-copilot-B3kQl0g0.mjs +0 -104
  343. package/lib/gitlab-duo-BriUTP8k.mjs +0 -155
  344. package/lib/gitlab-duo-workflow-wK5Ljzmc.mjs +0 -91
  345. package/lib/google-CE5tFDod.mjs +0 -30
  346. package/lib/google-antigravity-C1jgNljz.mjs +0 -198
  347. package/lib/google-oauth-shared-BLVTvokk.mjs +0 -147
  348. package/lib/grammar-D-NqNUxQ.mjs +0 -49
  349. package/lib/identity-HNO1Oe9B.mjs +0 -219
  350. package/lib/kimi-DgcUpPtK.mjs +0 -236
  351. package/lib/markit-DtGoRE6M.mjs +0 -1417
  352. package/lib/minimax-code-Y3h5li9N.mjs +0 -53
  353. package/lib/models-DRA2c_8U.mjs +0 -104660
  354. package/lib/opencode-BsVw9rCD.mjs +0 -38
  355. package/lib/to-binary-B1BEBIPC.mjs +0 -6002
  356. package/lib/wafer-BlhWLweO.mjs +0 -17
  357. package/lib/xai-oauth-5pORHUrg.mjs +0 -446
@@ -1,1678 +1,110 @@
1
1
  import { installBunShim as __installBunShim } from "./bun-shim.mjs";
2
2
  __installBunShim();
3
3
  import { n as fs_promises_shim_exports } from "./fs-promises-shim-Bx0fpxuk.mjs";
4
- import { P as $env, T as warn, _ as parseStreamingJsonThrottled, g as parseStreamingJson, h as parseJsonWithRepair } from "./src-BcD0_rQR.mjs";
5
- import { g as MissingApiKeyError, l as finalize, r as ValidationError, s as ProviderResponseError, v as AbortError } from "./error-C-f_Wnw4.mjs";
6
- import { C as kStreamingPartialJson, S as kStreamingLastParseLen, _ as kCursorExecResolved, a as normalizeSystemPrompts, b as kStreamingBlockKind, h as clearStreamingPartialJson, k as toolWireSchema, x as kStreamingEnvelopeId, y as kStreamingBlockIndex } from "./utils-Cp2Mxf_U.mjs";
7
- import { t as sanitizeText } from "./sanitize-text-CfcXzw5X.mjs";
8
- import { a as shouldBypassProxy, n as getProxyForProvider, t as connectProxiedSocket } from "./proxy-D9lm7ONA.mjs";
9
- import { t as calculateCost, y as isKimiK3ModelId } from "./models-DRA2c_8U.mjs";
10
- import "./identity-HNO1Oe9B.mjs";
11
- import { t as AssistantMessageEventStream } from "./event-stream-Dh2guZxS.mjs";
12
- import { n as isRequestDebugEnabled, t as createRequestDebugSession } from "./request-debug-HJMoJncL.mjs";
13
- import { A as isObject, B as scalarZeroValue, C as getTextEncoding, D as hasCustomJsonRepresentation, E as create, F as unsafeGet, H as ScalarType, I as unsafeIsSet, L as unsafeLocal, M as isReflectMap, N as isReflectMessage, O as isWrapper, P as unsafeClear, R as unsafeOneofCase, T as isFieldError, U as isMessage, V as protoInt64, _ as BinaryWriter, a as makeReadContext$1, c as messageDesc, d as base64Decode, f as base64Encode, g as BinaryReader, h as wktStructToReflect, i as fromBinary, j as isReflectList, k as isWrapperDesc, l as protoCamelCase, m as wktStructToLocal, n as writeField, o as readField, p as localMessageMapper, r as fileDesc, t as toBinary, u as protoSnakeCase, w as FieldError, z as unsafeSet } from "./to-binary-B1BEBIPC.mjs";
14
- import { $ as GrepUnionResultSchema, $t as PiWriteExecSuccessSchema, A as DiagnosticsSuccessSchema, An as ShellStreamStdoutSchema, At as PiBashExecErrorSchema, B as ForceBackgroundSubagentResultSchema, Bn as SubagentStopRequestResponseSchema, Bt as PiGrepExecErrorSchema, C as DeleteErrorSchema, Cn as ShellFailureSchema, Ct as McpToolCallSchema, D as DiagnosticsErrorSchema, Dn as ShellStreamSchema, Dt as McpToolResultContentItemSchema, E as DeleteSuccessSchema, En as ShellStreamExitSchema, Et as McpToolNotFoundSchema, F as ExecuteHookResponseSchema, Fn as SubagentAwaitNotFoundSchema, Ft as PiEditExecResultSchema, G as GrepContentResultSchema, Gn as WebFetchAllowlistPrecheckResultSchema, Gt as PiLsExecSuccessSchema, Hn as ToolCallSchema, Ht as PiGrepExecSuccessSchema, I as ExecuteHookResultSchema, In as SubagentAwaitResultSchema, It as PiEditExecSuccessSchema, J as GrepFileCountSchema, Jn as WriteResultSchema, Jt as PiReadExecSuccessSchema, K as GrepCountResultSchema, Kn as WriteErrorSchema, Kt as PiReadExecErrorSchema, L as FetchErrorSchema, Ln as SubagentErrorSchema, Lt as PiFindExecErrorSchema, M as ExecClientMessageSchema, Mn as SmartModeClassifierErrorSchema, Mt as PiBashExecSuccessSchema, N as ExecClientStreamCloseSchema, Nn as SmartModeClassifierResultSchema, Nt as PiEditExecErrorSchema, O as DiagnosticsRejectedSchema, On as ShellStreamStartSchema, Ot as McpToolResultSchema, P as ExecClientThrowSchema, Pn as StopRequestResponseSchema, Pt as PiEditExecRejectedSchema, Q as GrepSuccessSchema, Qt as PiWriteExecResultSchema, R as FetchResultSchema, Rn as SubagentResultSchema, Rt as PiFindExecResultSchema, S as ConversationTurnStructureSchema, Sn as ShellAllowlistPrecheckResultSchema, St as McpTextContentSchema, T as DeleteResultSchema, Tn as ShellResultSchema, Tt as McpToolErrorSchema, Un as UserMessageActionSchema, Ut as PiLsExecErrorSchema, V as GetBlobResultSchema, Vn as ThinkingMessageSchema, Vt as PiGrepExecResultSchema, W as GrepContentMatchSchema, Wn as UserMessageSchema, Wt as PiLsExecResultSchema, X as GrepFilesResultSchema, Xn as WriteShellStdinResultSchema, Xt as PiWriteExecErrorSchema, Y as GrepFileMatchSchema, Yn as WriteShellStdinErrorSchema, Yt as PiTruncationSchema, Z as GrepResultSchema, Zn as WriteSuccessSchema, Zt as PiWriteExecRejectedSchema, _ as ConversationActionSchema, _n as RequestedModelSchema, _t as McpResultSchema, a as AgentRunRequestSchema, an as ReadMcpResourceErrorSchema, at as LsDirectoryTreeNodeSchema, b as ConversationStateStructureSchema, bn as SelectedImageSchema, bt as McpStateSuccessSchema, c as AgentStoreConflictResultSchema, cn as ReadMcpResourceSuccessSchema, ct as LsRejectedSchema, d as BeforeSubmitPromptRequestResponseSchema, dn as ReadSuccessSchema, dt as McpAllowlistPrecheckResultSchema, en as PostToolUseFailureRequestResponseSchema, et as KvClientMessageSchema, f as CanvasDiagnosticsErrorSchema, fn as RecordScreenFailureSchema, ft as McpApprovedSchema, g as ComputerUseResultSchema, gn as RequestContextSuccessSchema, gt as McpRejectedSchema, h as ComputerUseErrorSchema, hn as RequestContextSchema, ht as McpImageContentSchema, i as AgentConversationTurnStructureSchema, in as ReadErrorSchema, it as ListMcpResourcesSuccessSchema, j as ExecClientControlMessageSchema, jn as ShellSuccessSchema, jt as PiBashExecResultSchema, k as DiagnosticsResultSchema, kn as ShellStreamStderrSchema, kt as ModelDetailsSchema, l as AssistantMessageSchema, ln as ReadRejectedSchema, lt as LsResultSchema, m as ClientHeartbeatSchema, mn as RequestContextResultSchema, mt as McpErrorSchema, n as AfterAgentThoughtRequestResponseSchema, nn as PreCompactRequestResponseSchema, nt as ListMcpResourcesExecResultSchema, o as AgentServerMessageSchema, on as ReadMcpResourceExecResultSchema, ot as LsDirectoryTreeNode_FileSchema, p as CanvasDiagnosticsResultSchema, pn as RecordScreenResultSchema, pt as McpArgsSchema, q as GrepErrorSchema, qn as WriteRejectedSchema, qt as PiReadExecResultSchema, r as AgentClientMessageSchema, rn as PreToolUseRequestResponseSchema, rt as ListMcpResourcesExecResult_McpResourceSchema, s as AgentStoreConflictErrorSchema, sn as ReadMcpResourceNotFoundSchema, st as LsErrorSchema, t as AfterAgentResponseRequestResponseSchema, tn as PostToolUseRequestResponseSchema, tt as ListMcpResourcesErrorSchema, u as BackgroundShellSpawnResultSchema, un as ReadResultSchema, ut as LsSuccessSchema, v as ConversationSearchErrorSchema, vn as ResumeActionSchema, vt as McpStateExecResultSchema, w as DeleteRejectedSchema, wn as ShellRejectedSchema, wt as McpToolDefinitionSchema, x as ConversationStepSchema, xn as SetBlobResultSchema, xt as McpSuccessSchema, y as ConversationSearchResultSchema, yn as SelectedContextSchema, yt as McpStateServerSchema, z as ForceBackgroundShellResultSchema, zn as SubagentStartRequestResponseSchema, zt as PiFindExecSuccessSchema } from "./agent_pb-Rizyt9Zg.mjs";
15
- import { t as deterministicUuid } from "./deterministic-id-D-yIV_eI.mjs";
4
+ import { C as warn, M as truncate, N as $env, _ as parseStreamingJson, b as debug, g as parseJsonWithRepair, v as parseStreamingJsonThrottled } from "./src-BwW51vA5.mjs";
5
+ import { _ as AbortError, c as finalize, h as MissingApiKeyError, r as ValidationError, s as ProviderResponseError } from "./error-CORgGg5a.mjs";
6
+ import { A as toolWireSchema, C as kStreamingLastParseLen, I as sanitizeSchemaForCursor, S as kStreamingEnvelopeId, b as kStreamingBlockIndex, g as clearStreamingPartialJson, o as normalizeSystemPrompts, s as normalizeToolCallId, v as kCursorExecResolved, w as kStreamingPartialJson, x as kStreamingBlockKind } from "./utils-CUPhpw9A.mjs";
7
+ import { t as sanitizeText } from "./sanitize-text-BCf5KmCf.mjs";
8
+ import { n as isRecord$1 } from "./type-guards-CttAANEx.mjs";
9
+ import { n as classifyModel, r as collapseVariantId } from "./taxonomy-DSIM99rS.mjs";
10
+ import { n as getProxyForUrl, t as connectProxiedSocket } from "./proxy-5nWqRL1f.mjs";
11
+ import { n as THINKING_EFFORTS } from "./effort-BdtQMN-_.mjs";
12
+ import { t as calculateCost } from "./models-DnXMYGcJ.mjs";
13
+ import { t as AssistantMessageEventStream } from "./event-stream-ulcDenZD.mjs";
14
+ import { n as isRequestDebugEnabled, t as createRequestDebugSession } from "./request-debug-NQN0BjHH.mjs";
15
+ import { i as fromBinary, n as decodeJsonValue, o as toBinary, r as encodeJsonValue, t as create } from "./protobuf-aab1UGVn.mjs";
16
+ import { $ as ForceBackgroundSubagentResultSchema, $n as SubagentResultSchema, $t as PiFindExecSuccessSchema, A as CursorRuleTypeGlobalSchema, An as RequestContextSuccessSchema, At as McpRejectedSchema, B as ExaFetchRequestResponseSchema, Bn as ShellResultSchema, Bt as McpToolNotFoundSchema, C as ConversationStateStructureSchema, Cn as ReadRejectedSchema, Ct as LsResultSchema, D as CreatePlanRequestResponseSchema, Dn as RecordScreenResultSchema, Dt as McpArgsSchema, E as CreatePlanErrorSchema, En as RecordScreenFailureSchema, Et as McpApprovedSchema, F as DeleteSuccessSchema, Fn as SelectedImageSchema, Ft as McpSuccessSchema, G as ExecClientMessageSchema, Gn as ShellStreamStdoutSchema, Gt as PiBashExecResultSchema, H as ExaSearchRequestResponseSchema, Hn as ShellStreamSchema, Ht as McpToolResultSchema, I as DiagnosticsErrorSchema, In as SetBlobResultSchema, It as McpTextContentSchema, J as ExecuteHookResponseSchema, Jn as SmartModeClassifierResultSchema, Jt as PiEditExecRejectedSchema, K as ExecClientStreamCloseSchema, Kn as ShellSuccessSchema, Kt as PiBashExecSuccessSchema, L as DiagnosticsRejectedSchema, Ln as ShellAllowlistPrecheckResultSchema, Lt as McpToolCallSchema, M as DeleteErrorSchema, Mn as RequestedModel_ModelParameterbytesSchema, Mt as McpStateExecResultSchema, N as DeleteRejectedSchema, Nn as ResumeActionSchema, Nt as McpStateServerSchema, O as CreatePlanResultSchema, On as RequestContextResultSchema, Ot as McpErrorSchema, P as DeleteResultSchema, Pn as SelectedContextSchema, Pt as McpStateSuccessSchema, Q as ForceBackgroundShellResultSchema, Qn as SubagentErrorSchema, Qt as PiFindExecResultSchema, R as DiagnosticsResultSchema, Rn as ShellFailureSchema, Rt as McpToolDefinitionSchema, S as ConversationSearchResultSchema, Sn as ReadMcpResourceSuccessSchema, St as LsRejectedSchema, T as ConversationTurnStructureSchema, Tn as ReadSuccessSchema, Tt as McpAllowlistPrecheckResultSchema, U as ExaSearchRequestResponse_ApprovedSchema, Un as ShellStreamStartSchema, Ut as ModelDetailsSchema, V as ExaFetchRequestResponse_ApprovedSchema, Vn as ShellStreamExitSchema, Vt as McpToolResultContentItemSchema, W as ExecClientControlMessageSchema, Wn as ShellStreamStderrSchema, Wt as PiBashExecErrorSchema, X as FetchErrorSchema, Xn as SubagentAwaitNotFoundSchema, Xt as PiEditExecSuccessSchema, Y as ExecuteHookResultSchema, Yn as StopRequestResponseSchema, Yt as PiEditExecResultSchema, Z as FetchResultSchema, Zn as SubagentAwaitResultSchema, Zt as PiFindExecErrorSchema, _ as ClientHeartbeatSchema, _n as PreToolUseRequestResponseSchema, _r as WriteShellStdinResultSchema, _t as ListMcpResourcesExecResult_McpResourceSchema, a as AgentRunRequestSchema, an as PiLsExecSuccessSchema, ar as ToolCallSchema, at as GrepCountResultSchema, b as ConversationActionSchema, bn as ReadMcpResourceExecResultSchema, bt as LsDirectoryTreeNode_FileSchema, c as AgentStoreConflictResultSchema, cn as PiReadExecSuccessSchema, cr as WebFetchAllowlistPrecheckResultSchema, ct as GrepFileMatchSchema, d as AskQuestionResultSchema, dn as PiWriteExecRejectedSchema, dr as WebSearchRequestResponseSchema, dt as GrepSuccessSchema, en as PiGrepExecErrorSchema, er as SubagentStartRequestResponseSchema, et as GetBlobResultSchema, f as AssistantMessageSchema, fn as PiWriteExecResultSchema, fr as WebSearchRequestResponse_ApprovedSchema, ft as GrepUnionResultSchema, g as CanvasDiagnosticsResultSchema, gn as PreCompactRequestResponseSchema, gr as WriteShellStdinErrorSchema, gt as ListMcpResourcesExecResultSchema, h as CanvasDiagnosticsErrorSchema, hn as PostToolUseRequestResponseSchema, hr as WriteResultSchema, ht as ListMcpResourcesErrorSchema, i as AgentConversationTurnStructureSchema, in as PiLsExecResultSchema, ir as ThinkingMessageSchema, it as GrepContentResultSchema, j as CursorRuleTypeSchema, jn as RequestedModelSchema, jt as McpResultSchema, k as CursorRuleSchema, kn as RequestContextSchema, kt as McpImageContentSchema, l as AskQuestionInteractionResponseSchema, ln as PiTruncationSchema, lr as WebFetchRequestResponseSchema, lt as GrepFilesResultSchema, m as BeforeSubmitPromptRequestResponseSchema, mn as PostToolUseFailureRequestResponseSchema, mr as WriteRejectedSchema, mt as KvClientMessageSchema, n as AfterAgentThoughtRequestResponseSchema, nn as PiGrepExecSuccessSchema, nr as SwitchModeRequestResponseSchema, o as AgentServerMessageSchema, on as PiReadExecErrorSchema, or as UserMessageActionSchema, ot as GrepErrorSchema, p as BackgroundShellSpawnResultSchema, pn as PiWriteExecSuccessSchema, pr as WriteErrorSchema, pt as InteractionResponseSchema, q as ExecClientThrowSchema, qn as SmartModeClassifierErrorSchema, qt as PiEditExecErrorSchema, r as AgentClientMessageSchema, rn as PiLsExecErrorSchema, rr as SwitchModeRequestResponse_RejectedSchema, rt as GrepContentMatchSchema, s as AgentStoreConflictErrorSchema, sn as PiReadExecResultSchema, sr as UserMessageSchema, st as GrepFileCountSchema, t as AfterAgentResponseRequestResponseSchema, tn as PiGrepExecResultSchema, tr as SubagentStopRequestResponseSchema, u as AskQuestionRejectedSchema, un as PiWriteExecErrorSchema, ur as WebFetchRequestResponse_ApprovedSchema, ut as GrepResultSchema, v as ComputerUseErrorSchema, vn as ReadErrorSchema, vr as WriteSuccessSchema, vt as ListMcpResourcesSuccessSchema, w as ConversationStepSchema, wn as ReadResultSchema, wt as LsSuccessSchema, x as ConversationSearchErrorSchema, xn as ReadMcpResourceNotFoundSchema, xt as LsErrorSchema, y as ComputerUseResultSchema, yn as ReadMcpResourceErrorSchema, yt as LsDirectoryTreeNodeSchema, z as DiagnosticsSuccessSchema, zn as ShellRejectedSchema, zt as McpToolErrorSchema } from "./cursor-proto-B8Wj8bv9.mjs";
17
+ import { t as deterministicUuid } from "./deterministic-id-CUEIMSqR.mjs";
16
18
  import * as path from "node:path";
17
19
  import { createHash } from "node:crypto";
18
20
  import http2 from "node:http2";
19
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/reflect/reflect-check.js
21
+ //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/connect-error-detail.ts
20
22
  /**
21
- * Check whether the given field value is valid for the reflect API.
22
- */
23
- function checkField(field, value) {
24
- const check = field.fieldKind == "list" ? isReflectList(value, field) : field.fieldKind == "map" ? isReflectMap(value, field) : checkSingular(field, value);
25
- if (check === true) return;
26
- let reason;
27
- switch (field.fieldKind) {
28
- case "list":
29
- reason = `expected ${formatReflectList(field)}, got ${formatVal(value)}`;
30
- break;
31
- case "map":
32
- reason = `expected ${formatReflectMap(field)}, got ${formatVal(value)}`;
33
- break;
34
- default: reason = reasonSingular(field, value, check);
35
- }
36
- return new FieldError(field, reason);
37
- }
38
- /**
39
- * Check whether the given list item is valid for the reflect API.
40
- */
41
- function checkListItem(field, index, value) {
42
- const check = checkSingular(field, value);
43
- if (check !== true) return new FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);
44
- }
45
- /**
46
- * Check whether the given map key and value are valid for the reflect API.
47
- */
48
- function checkMapEntry(field, key, value) {
49
- const checkKey = checkScalarValue(field.mapKey)(key);
50
- if (checkKey !== true) return new FieldError(field, `invalid map key: ${reasonSingular({ scalar: field.mapKey }, key, checkKey)}`);
51
- const checkVal = checkSingular(field, value);
52
- if (checkVal !== true) return new FieldError(field, `map entry ${formatVal(key)}: ${reasonSingular(field, value, checkVal)}`);
53
- }
54
- function checkSingular(field, value) {
55
- if (field.scalar !== void 0) return checkScalarValue(field.scalar)(value);
56
- if (field.enum !== void 0) {
57
- if (field.enum.open) return checkScalarValue(ScalarType.INT32)(value);
58
- return field.enum.values.some((v) => v.number === value);
59
- }
60
- return isReflectMessage(value, field.message);
61
- }
62
- /**
63
- * Return the check for values of the given scalar type.
64
- *
65
- * @private
66
- */
67
- function checkScalarValue(scalar) {
68
- switch (scalar) {
69
- case ScalarType.DOUBLE: return (value) => typeof value == "number";
70
- case ScalarType.FLOAT: return (value) => {
71
- if (typeof value != "number") return false;
72
- if (Number.isNaN(value) || !Number.isFinite(value)) return true;
73
- if (value > 34028234663852886e22 || value < -34028234663852886e22) return `${value.toFixed()} out of range`;
74
- return true;
75
- };
76
- case ScalarType.INT32:
77
- case ScalarType.SFIXED32:
78
- case ScalarType.SINT32: return (value) => {
79
- if (typeof value !== "number" || !Number.isInteger(value)) return false;
80
- if (value > 2147483647 || value < -2147483648) return `${value.toFixed()} out of range`;
81
- return true;
82
- };
83
- case ScalarType.FIXED32:
84
- case ScalarType.UINT32: return (value) => {
85
- if (typeof value !== "number" || !Number.isInteger(value)) return false;
86
- if (value > 4294967295 || value < 0) return `${value.toFixed()} out of range`;
87
- return true;
88
- };
89
- case ScalarType.BOOL: return (value) => typeof value == "boolean";
90
- case ScalarType.STRING: return (value) => {
91
- if (typeof value != "string") return false;
92
- return getTextEncoding().checkUtf8(value) || "invalid UTF8";
93
- };
94
- case ScalarType.BYTES: return (value) => value instanceof Uint8Array;
95
- case ScalarType.INT64:
96
- case ScalarType.SFIXED64:
97
- case ScalarType.SINT64: return (value) => {
98
- if (typeof value == "bigint" || typeof value == "number" || typeof value == "string" && value.length > 0) try {
99
- protoInt64.parse(value);
100
- return true;
101
- } catch (_) {
102
- return `${value} out of range`;
103
- }
104
- return false;
105
- };
106
- case ScalarType.FIXED64:
107
- case ScalarType.UINT64: return (value) => {
108
- if (typeof value == "bigint" || typeof value == "number" || typeof value == "string" && value.length > 0) try {
109
- protoInt64.uParse(value);
110
- return true;
111
- } catch (_) {
112
- return `${value} out of range`;
113
- }
114
- return false;
115
- };
116
- }
117
- }
118
- /**
119
- * Format the reason why a value is invalid for a singular field.
23
+ * Connect-protocol end-stream error formatting.
120
24
  *
121
- * @private
25
+ * A Connect end-of-stream trailer carries an error object of the shape
26
+ * code / message / details. Some backends collapse the useful part into a
27
+ * generic message (for example just "Error"), which previously surfaced
28
+ * verbatim as "Connect error invalid_argument: Error" — an unactionable
29
+ * string that hid both the failing argument and which transport produced it
30
+ * (Refs #4813). This module keeps the existing "Connect error code: message"
31
+ * prefix byte-for-byte and appends what the trailer actually contained:
32
+ * typed detail entries are summarized, and when the message is generic the
33
+ * remaining trailer fields are appended (truncated) so the server's real
34
+ * rejection is visible in logs and bug reports.
122
35
  */
123
- function reasonSingular(field, val, details) {
124
- details = typeof details == "string" ? `: ${details}` : `, got ${formatVal(val)}`;
125
- if (field.scalar !== void 0) return `expected ${scalarTypeDescription(field.scalar)}` + details;
126
- if (field.enum !== void 0) return `expected ${field.enum.toString()}` + details;
127
- return `expected ${formatReflectMessage(field.message)}` + details;
128
- }
129
- function formatVal(val) {
130
- switch (typeof val) {
131
- case "object":
132
- if (val === null) return "null";
133
- if (val instanceof Uint8Array) return `Uint8Array(${val.length})`;
134
- if (Array.isArray(val)) return `Array(${val.length})`;
135
- if (isReflectList(val)) return formatReflectList(val.field());
136
- if (isReflectMap(val)) return formatReflectMap(val.field());
137
- if (isReflectMessage(val)) return formatReflectMessage(val.desc);
138
- if (isMessage(val)) return `message ${val.$typeName}`;
139
- return "object";
140
- case "string": return val.length > 30 ? "string" : `"${val.split("\"").join("\\\"")}"`;
141
- case "boolean": return String(val);
142
- case "number": return String(val);
143
- case "bigint": return String(val) + "n";
144
- default: return typeof val;
145
- }
146
- }
147
- function formatReflectMessage(desc) {
148
- return `ReflectMessage (${desc.typeName})`;
149
- }
150
- function formatReflectList(field) {
151
- switch (field.listKind) {
152
- case "message": return `ReflectList (${field.message.toString()})`;
153
- case "enum": return `ReflectList (${field.enum.toString()})`;
154
- case "scalar": return `ReflectList (${ScalarType[field.scalar]})`;
155
- }
156
- }
157
- function formatReflectMap(field) {
158
- switch (field.mapKind) {
159
- case "message": return `ReflectMap (${ScalarType[field.mapKey]}, ${field.message.toString()})`;
160
- case "enum": return `ReflectMap (${ScalarType[field.mapKey]}, ${field.enum.toString()})`;
161
- case "scalar": return `ReflectMap (${ScalarType[field.mapKey]}, ${ScalarType[field.scalar]})`;
162
- }
163
- }
164
- function scalarTypeDescription(scalar) {
165
- switch (scalar) {
166
- case ScalarType.STRING: return "string";
167
- case ScalarType.BOOL: return "boolean";
168
- case ScalarType.INT64:
169
- case ScalarType.SINT64:
170
- case ScalarType.SFIXED64: return "bigint (int64)";
171
- case ScalarType.UINT64:
172
- case ScalarType.FIXED64: return "bigint (uint64)";
173
- case ScalarType.BYTES: return "Uint8Array";
174
- case ScalarType.DOUBLE: return "number (float64)";
175
- case ScalarType.FLOAT: return "number (float32)";
176
- case ScalarType.FIXED32:
177
- case ScalarType.UINT32: return "number (uint32)";
178
- case ScalarType.INT32:
179
- case ScalarType.SFIXED32:
180
- case ScalarType.SINT32: return "number (int32)";
181
- }
182
- }
183
- //#endregion
184
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/reflect/reflect.js
185
- /**
186
- * Create a ReflectMessage.
187
- */
188
- function reflect(messageDesc, message, check = true) {
189
- return new ReflectMessageImpl(messageDesc, message, check);
190
- }
191
- const messageSortedFields = /* @__PURE__ */ new WeakMap();
192
- var ReflectMessageImpl = class {
193
- get sortedFields() {
194
- const cached = messageSortedFields.get(this.desc);
195
- if (cached) return cached;
196
- const sortedFields = this.desc.fields.concat().sort((a, b) => a.number - b.number);
197
- messageSortedFields.set(this.desc, sortedFields);
198
- return sortedFields;
199
- }
200
- constructor(messageDesc, message, check = true) {
201
- this.lists = /* @__PURE__ */ new Map();
202
- this.maps = /* @__PURE__ */ new Map();
203
- this.check = check;
204
- this.desc = messageDesc;
205
- this.message = this[unsafeLocal] = message !== null && message !== void 0 ? message : create(messageDesc);
206
- this.fields = messageDesc.fields;
207
- this.oneofs = messageDesc.oneofs;
208
- this.members = messageDesc.members;
209
- }
210
- findNumber(number) {
211
- if (!this._fieldsByNumber) this._fieldsByNumber = new Map(this.desc.fields.map((f) => [f.number, f]));
212
- return this._fieldsByNumber.get(number);
213
- }
214
- oneofCase(oneof) {
215
- assertOwn(this.message, oneof);
216
- return unsafeOneofCase(this.message, oneof);
217
- }
218
- isSet(field) {
219
- assertOwn(this.message, field);
220
- return unsafeIsSet(this.message, field);
221
- }
222
- clear(field) {
223
- assertOwn(this.message, field);
224
- unsafeClear(this.message, field);
225
- }
226
- get(field) {
227
- assertOwn(this.message, field);
228
- const value = unsafeGet(this.message, field);
229
- switch (field.fieldKind) {
230
- case "list":
231
- let list = this.lists.get(field);
232
- if (!list || list[unsafeLocal] !== value) this.lists.set(field, list = new ReflectListImpl(field, value, this.check));
233
- return list;
234
- case "map":
235
- let map = this.maps.get(field);
236
- if (!map || map[unsafeLocal] !== value) this.maps.set(field, map = new ReflectMapImpl(field, value, this.check));
237
- return map;
238
- case "message": return messageToReflect(field, value, this.check);
239
- case "scalar": return value === void 0 ? scalarZeroValue(field.scalar, false) : longToReflect(field, value);
240
- case "enum": return value !== null && value !== void 0 ? value : field.enum.values[0].number;
241
- }
242
- }
243
- set(field, value) {
244
- assertOwn(this.message, field);
245
- if (this.check) {
246
- const err = checkField(field, value);
247
- if (err) throw err;
248
- }
249
- let local;
250
- if (field.fieldKind == "message") local = messageToLocal(field, value);
251
- else if (isReflectMap(value) || isReflectList(value)) local = value[unsafeLocal];
252
- else local = longToLocal(field, value);
253
- unsafeSet(this.message, field, local);
254
- }
255
- getUnknown() {
256
- return this.message.$unknown;
257
- }
258
- setUnknown(value) {
259
- this.message.$unknown = value;
260
- }
261
- };
262
- function assertOwn(owner, member) {
263
- if (member.parent.typeName !== owner.$typeName) throw new FieldError(member, `cannot use ${member.toString()} with message ${owner.$typeName}`, "ForeignFieldError");
264
- }
265
- var ReflectListImpl = class {
266
- field() {
267
- return this._field;
268
- }
269
- get size() {
270
- return this._arr.length;
271
- }
272
- constructor(field, unsafeInput, check) {
273
- this._field = field;
274
- this._arr = this[unsafeLocal] = unsafeInput;
275
- this.check = check;
276
- }
277
- get(index) {
278
- const item = this._arr[index];
279
- return item === void 0 ? void 0 : listItemToReflect(this._field, item, this.check);
280
- }
281
- set(index, item) {
282
- if (index < 0 || index >= this._arr.length) throw new FieldError(this._field, `list item #${index + 1}: out of range`);
283
- if (this.check) {
284
- const err = checkListItem(this._field, index, item);
285
- if (err) throw err;
286
- }
287
- this._arr[index] = listItemToLocal(this._field, item);
288
- }
289
- add(item) {
290
- if (this.check) {
291
- const err = checkListItem(this._field, this._arr.length, item);
292
- if (err) throw err;
293
- }
294
- this._arr.push(listItemToLocal(this._field, item));
295
- }
296
- clear() {
297
- this._arr.splice(0, this._arr.length);
298
- }
299
- [Symbol.iterator]() {
300
- return this.values();
301
- }
302
- keys() {
303
- return this._arr.keys();
304
- }
305
- *values() {
306
- for (const item of this._arr) yield listItemToReflect(this._field, item, this.check);
307
- }
308
- *entries() {
309
- for (let i = 0; i < this._arr.length; i++) yield [i, listItemToReflect(this._field, this._arr[i], this.check)];
310
- }
311
- };
312
- var ReflectMapImpl = class {
313
- constructor(field, unsafeInput, check = true) {
314
- this.obj = this[unsafeLocal] = unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : {};
315
- this.check = check;
316
- this._field = field;
317
- }
318
- field() {
319
- return this._field;
320
- }
321
- set(key, value) {
322
- if (this.check) {
323
- const err = checkMapEntry(this._field, key, value);
324
- if (err) throw err;
325
- }
326
- this.obj[mapKeyToLocal(key)] = mapValueToLocal(this._field, value);
327
- return this;
328
- }
329
- delete(key) {
330
- const k = mapKeyToLocal(key);
331
- const has = Object.prototype.hasOwnProperty.call(this.obj, k);
332
- if (has) delete this.obj[k];
333
- return has;
334
- }
335
- clear() {
336
- for (const key of Object.keys(this.obj)) delete this.obj[key];
337
- }
338
- get(key) {
339
- let val = this.obj[mapKeyToLocal(key)];
340
- if (val !== void 0) val = mapValueToReflect(this._field, val, this.check);
341
- return val;
342
- }
343
- has(key) {
344
- return Object.prototype.hasOwnProperty.call(this.obj, mapKeyToLocal(key));
345
- }
346
- *keys() {
347
- for (const objKey of Object.keys(this.obj)) yield mapKeyToReflect(objKey, this._field.mapKey);
348
- }
349
- *entries() {
350
- for (const objEntry of Object.entries(this.obj)) yield [mapKeyToReflect(objEntry[0], this._field.mapKey), mapValueToReflect(this._field, objEntry[1], this.check)];
351
- }
352
- [Symbol.iterator]() {
353
- return this.entries();
354
- }
355
- get size() {
356
- return Object.keys(this.obj).length;
357
- }
358
- *values() {
359
- for (const val of Object.values(this.obj)) yield mapValueToReflect(this._field, val, this.check);
360
- }
361
- forEach(callbackfn, thisArg) {
362
- for (const mapEntry of this.entries()) callbackfn.call(thisArg, mapEntry[1], mapEntry[0], this);
363
- }
364
- };
365
- function messageToLocal(field, value) {
366
- if (!isReflectMessage(value)) return value;
367
- if (isWrapper(value.message) && !field.oneof && field.fieldKind == "message") return value.message.value;
368
- if (value.desc.typeName == "google.protobuf.Struct" && field.parent.typeName != "google.protobuf.Value") return wktStructToLocal(value.message);
369
- return value.message;
370
- }
371
- function messageToReflect(field, value, check) {
372
- if (value !== void 0) {
373
- if (isWrapperDesc(field.message) && !field.oneof && field.fieldKind == "message") value = {
374
- $typeName: field.message.typeName,
375
- value: longToReflect(field.message.fields[0], value)
376
- };
377
- else if (field.message.typeName == "google.protobuf.Struct" && field.parent.typeName != "google.protobuf.Value" && isObject(value)) value = wktStructToReflect(value);
378
- }
379
- return new ReflectMessageImpl(field.message, value, check);
380
- }
381
- function listItemToLocal(field, value) {
382
- if (field.listKind == "message") return messageToLocal(field, value);
383
- return longToLocal(field, value);
384
- }
385
- function listItemToReflect(field, value, check) {
386
- if (field.listKind == "message") return messageToReflect(field, value, check);
387
- return longToReflect(field, value);
388
- }
389
- function mapValueToLocal(field, value) {
390
- if (field.mapKind == "message") return messageToLocal(field, value);
391
- return longToLocal(field, value);
392
- }
393
- function mapValueToReflect(field, value, check) {
394
- if (field.mapKind == "message") return messageToReflect(field, value, check);
395
- return value;
396
- }
397
- function mapKeyToLocal(key) {
398
- return typeof key == "string" || typeof key == "number" ? key : String(key);
399
- }
400
- /**
401
- * Converts a map key (any scalar value except float, double, or bytes) from its
402
- * representation in a message (string or number, the only possible object key
403
- * types) to the closest possible type in ECMAScript.
404
- */
405
- function mapKeyToReflect(key, type) {
406
- switch (type) {
407
- case ScalarType.STRING: return key;
408
- case ScalarType.INT32:
409
- case ScalarType.FIXED32:
410
- case ScalarType.UINT32:
411
- case ScalarType.SFIXED32:
412
- case ScalarType.SINT32: {
413
- const n = Number.parseInt(key);
414
- if (Number.isFinite(n)) return n;
415
- break;
416
- }
417
- case ScalarType.BOOL:
418
- switch (key) {
419
- case "true": return true;
420
- case "false": return false;
421
- }
422
- break;
423
- case ScalarType.UINT64:
424
- case ScalarType.FIXED64:
425
- try {
426
- return protoInt64.uParse(key);
427
- } catch (_a) {}
428
- break;
429
- default: try {
430
- return protoInt64.parse(key);
431
- } catch (_b) {}
432
- }
433
- return key;
434
- }
435
- function longToReflect(field, value) {
436
- switch (field.scalar) {
437
- case ScalarType.INT64:
438
- case ScalarType.SFIXED64:
439
- case ScalarType.SINT64:
440
- if ("longAsString" in field && field.longAsString && typeof value == "string") value = protoInt64.parse(value);
441
- break;
442
- case ScalarType.FIXED64:
443
- case ScalarType.UINT64: if ("longAsString" in field && field.longAsString && typeof value == "string") value = protoInt64.uParse(value);
444
- }
445
- return value;
446
- }
447
- function longToLocal(field, value) {
448
- switch (field.scalar) {
449
- case ScalarType.INT64:
450
- case ScalarType.SFIXED64:
451
- case ScalarType.SINT64:
452
- if ("longAsString" in field && field.longAsString) value = String(value);
453
- else if (typeof value == "string" || typeof value == "number") value = protoInt64.parse(value);
454
- break;
455
- case ScalarType.FIXED64:
456
- case ScalarType.UINT64: if ("longAsString" in field && field.longAsString) value = String(value);
457
- else if (typeof value == "string" || typeof value == "number") value = protoInt64.uParse(value);
458
- }
459
- return value;
460
- }
461
- /**
462
- * Describes the message google.protobuf.Any.
463
- * Use `create(AnySchema)` to create a new message.
464
- */
465
- const AnySchema = /*@__PURE__*/ messageDesc(/* @__PURE__ */ fileDesc("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"), 0);
466
- //#endregion
467
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/wkt/any.js
468
- function anyPack(schema, message, into) {
469
- let ret = false;
470
- if (!into) {
471
- into = create(AnySchema);
472
- ret = true;
473
- }
474
- into.value = toBinary(schema, message);
475
- into.typeUrl = typeNameToUrl(message.$typeName);
476
- return ret ? into : void 0;
477
- }
478
- function anyIs(any, descOrTypeName) {
479
- if (any.typeUrl === "") return false;
480
- return (typeof descOrTypeName == "string" ? descOrTypeName : descOrTypeName.typeName) === typeUrlToName(any.typeUrl);
481
- }
482
- function anyUnpack(any, registryOrMessageDesc) {
483
- if (any.typeUrl === "") return;
484
- const desc = registryOrMessageDesc.kind == "message" ? registryOrMessageDesc : registryOrMessageDesc.getMessage(typeUrlToName(any.typeUrl));
485
- if (!desc || !anyIs(any, desc)) return;
486
- return fromBinary(desc, any.value);
487
- }
488
- function typeNameToUrl(name) {
489
- return `type.googleapis.com/${name}`;
490
- }
491
- function typeUrlToName(url) {
492
- const slash = url.lastIndexOf("/");
493
- const name = slash >= 0 ? url.substring(slash + 1) : url;
494
- if (!name.length) throw new Error(`invalid type url: ${url}`);
495
- return name;
496
- }
497
- //#endregion
498
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/wkt/gen/google/protobuf/struct_pb.js
499
- /**
500
- * Describes the file google/protobuf/struct.proto.
501
- */
502
- const file_google_protobuf_struct = /*@__PURE__*/ fileDesc("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");
503
- /**
504
- * Describes the message google.protobuf.Struct.
505
- * Use `create(StructSchema)` to create a new message.
506
- */
507
- const StructSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_struct, 0);
508
- /**
509
- * Describes the message google.protobuf.Value.
510
- * Use `create(ValueSchema)` to create a new message.
511
- */
512
- const ValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_struct, 1);
513
- /**
514
- * Describes the message google.protobuf.ListValue.
515
- * Use `create(ListValueSchema)` to create a new message.
516
- */
517
- const ListValueSchema = /*@__PURE__*/ messageDesc(file_google_protobuf_struct, 2);
518
- /**
519
- * `NullValue` is a singleton enumeration to represent the null value for the
520
- * `Value` type union.
521
- *
522
- * The JSON representation for `NullValue` is JSON `null`.
523
- *
524
- * @generated from enum google.protobuf.NullValue
525
- */
526
- var NullValue;
527
- (function(NullValue) {
528
- /**
529
- * Null value.
530
- *
531
- * @generated from enum value: NULL_VALUE = 0;
532
- */
533
- NullValue[NullValue["NULL_VALUE"] = 0] = "NULL_VALUE";
534
- })(NullValue || (NullValue = {}));
535
- //#endregion
536
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/extensions.js
537
- /**
538
- * Retrieve an extension value from a message.
539
- *
540
- * The function never returns undefined. Use hasExtension() to check whether an
541
- * extension is set. If the extension is not set, this function returns the
542
- * default value (if one was specified in the protobuf source), or the zero value
543
- * (for example `0` for numeric types, `[]` for repeated extension fields, and
544
- * an empty message instance for message fields).
545
- *
546
- * Extensions are stored as unknown fields on a message. To mutate an extension
547
- * value, make sure to store the new value with setExtension() after mutating.
548
- *
549
- * If the extension does not extend the given message, an error is raised.
550
- */
551
- function getExtension(message, extension, options) {
552
- assertExtendee(extension, message);
553
- const ufs = filterUnknownFields(message.$unknown, extension);
554
- const [container, field, get] = createExtensionContainer(extension);
555
- const ctx = makeReadContext$1(options);
556
- for (const uf of ufs) readField(container, new BinaryReader(uf.data), field, uf.wireType, ctx);
557
- return get();
558
- }
559
- /**
560
- * Set an extension value on a message. If the message already has a value for
561
- * this extension, the value is replaced.
562
- *
563
- * If the extension does not extend the given message, an error is raised.
564
- */
565
- function setExtension(message, extension, value) {
566
- var _a;
567
- assertExtendee(extension, message);
568
- const ufs = ((_a = message.$unknown) !== null && _a !== void 0 ? _a : []).filter((uf) => uf.no !== extension.number);
569
- const [container, field] = createExtensionContainer(extension, value);
570
- const writer = new BinaryWriter();
571
- writeField(writer, { writeUnknownFields: true }, container, field);
572
- const reader = new BinaryReader(writer.finish());
573
- while (reader.pos < reader.len) {
574
- const [no, wireType] = reader.tag();
575
- const data = reader.skip(wireType, no);
576
- ufs.push({
577
- no,
578
- wireType,
579
- data
580
- });
581
- }
582
- message.$unknown = ufs;
583
- }
584
- function filterUnknownFields(unknownFields, extension) {
585
- if (unknownFields === void 0) return [];
586
- if (extension.fieldKind === "enum" || extension.fieldKind === "scalar") {
587
- for (let i = unknownFields.length - 1; i >= 0; --i) if (unknownFields[i].no == extension.number) return [unknownFields[i]];
588
- return [];
589
- }
590
- return unknownFields.filter((uf) => uf.no === extension.number);
591
- }
592
- /**
593
- * @private
594
- */
595
- function createExtensionContainer(extension, value) {
596
- const localName = extension.typeName;
597
- const field = Object.assign(Object.assign({}, extension), {
598
- kind: "field",
599
- parent: extension.extendee,
600
- localName
601
- });
602
- const desc = Object.assign(Object.assign({}, extension.extendee), {
603
- fields: [field],
604
- members: [field],
605
- oneofs: []
606
- });
607
- const container = create(desc, value !== void 0 ? { [localName]: value } : void 0);
608
- return [
609
- reflect(desc, container),
610
- field,
611
- () => {
612
- const value = container[localName];
613
- if (value === void 0) {
614
- const desc = extension.message;
615
- if (isWrapperDesc(desc)) return scalarZeroValue(desc.fields[0].scalar, desc.fields[0].longAsString);
616
- return create(desc);
617
- }
618
- return value;
619
- }
620
- ];
621
- }
622
- function assertExtendee(extension, message) {
623
- if (extension.extendee.typeName != message.$typeName) throw new Error(`extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);
624
- }
625
- //#endregion
626
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/wkt/json.js
627
- /**
628
- * Minimum google.protobuf.Timestamp in milliseconds (inclusive).
629
- * Only enforced in ProtoJSON.
630
- *
631
- * @private
632
- */
633
- const timestampMsMin = /*@__PURE__*/ Date.parse("0001-01-01T00:00:00Z");
634
- /**
635
- * Maximum google.protobuf.Timestamp in milliseconds (inclusive).
636
- * Only enforced in ProtoJSON.
637
- *
638
- * @private
639
- */
640
- const timestampMsMax = /*@__PURE__*/ Date.parse("9999-12-31T23:59:59Z");
641
- //#endregion
642
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/to-json.js
643
- const LEGACY_REQUIRED = 3;
644
- const IMPLICIT$1 = 2;
645
- const jsonWriteDefaults = {
646
- alwaysEmitImplicit: false,
647
- enumAsInteger: false,
648
- useProtoFieldName: false
649
- };
650
- function makeWriteOptions(options) {
651
- return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;
652
- }
653
- /**
654
- * Serialize the message to a JSON value, a JavaScript value that can be
655
- * passed to JSON.stringify().
656
- */
657
- function toJson(schema, message, options) {
658
- return compiledWriter(schema)(makeWriteOptions(options), message);
659
- }
660
- const compiledWriters = /* @__PURE__ */ new WeakMap();
661
- /**
662
- * Return the compiled encoder for a message, compiling it on first use.
663
- */
664
- function compiledWriter(desc) {
665
- let compiled = compiledWriters.get(desc);
666
- if (compiled === void 0) compiled = compileMessage$1(desc);
667
- return compiled;
668
- }
669
- function compileMessage$1(desc) {
670
- const typeName = desc.typeName;
671
- const writeWkt = compileWkt$1(desc);
672
- if (writeWkt !== void 0) {
673
- const foreignField = desc.fields[0];
674
- const compiledWriter = (opts, message) => {
675
- if (message.$typeName !== typeName && foreignField !== void 0) throw new FieldError(foreignField, `cannot use ${foreignField} with message ${message.$typeName}`, "ForeignFieldError");
676
- return writeWkt(opts, message);
677
- };
678
- compiledWriters.set(desc, compiledWriter);
679
- return compiledWriter;
680
- }
681
- const sortedFields = desc.fields.concat().sort((a, b) => a.number - b.number);
682
- const foreignField = sortedFields[0];
683
- const fieldWriters = [];
684
- const compiledWriter = (opts, message) => {
685
- if (message.$typeName !== typeName && foreignField !== void 0) throw new FieldError(foreignField, `cannot use ${foreignField} with message ${message.$typeName}`, "ForeignFieldError");
686
- const json = {};
687
- for (let i = 0; i < fieldWriters.length; i++) fieldWriters[i](opts, message, json);
688
- if (opts.registry) writeExtensions(json, opts, opts.registry, message, desc);
689
- return json;
690
- };
691
- compiledWriters.set(desc, compiledWriter);
692
- for (const field of sortedFields) fieldWriters.push(compileField(field));
693
- return compiledWriter;
694
- }
695
- /**
696
- * Compile an encoder for a well-known type with a custom JSON representation,
697
- * or return undefined for other messages.
698
- */
699
- function compileWkt$1(desc) {
700
- if (!desc.typeName.startsWith("google.protobuf.")) return;
701
- switch (desc.typeName) {
702
- case "google.protobuf.Any": return (opts, message) => anyToJson(message, opts);
703
- case "google.protobuf.Timestamp": return (opts, message) => timestampToJson(message);
704
- case "google.protobuf.Duration": return (opts, message) => durationToJson(message);
705
- case "google.protobuf.FieldMask": return (opts, message) => fieldMaskToJson(message);
706
- case "google.protobuf.Struct": return (opts, message) => structToJson(message);
707
- case "google.protobuf.Value": return (opts, message) => valueToJson(message);
708
- case "google.protobuf.ListValue": return (opts, message) => listValueToJson(message);
709
- default:
710
- if (isWrapperDesc(desc)) {
711
- const valueField = desc.fields[0];
712
- const localName = valueField.localName;
713
- const zero = scalarZeroValue(valueField.scalar, false);
714
- const writeScalar = compileScalarValue(valueField);
715
- return (opts, message) => {
716
- const value = message[localName];
717
- return writeScalar(opts, value === void 0 ? zero : value);
718
- };
719
- }
720
- return;
721
- }
722
- }
723
- function compileField(field) {
724
- switch (field.fieldKind) {
725
- case "scalar":
726
- case "enum":
727
- case "message": return compileSingularField(field);
728
- case "list":
729
- case "map": {
730
- const writeValue = field.fieldKind == "list" ? compileListValue(field) : compileMapValue(field);
731
- const protoName = field.name;
732
- const jsonKey = field.jsonName;
733
- const localName = field.localName;
734
- return (opts, message, json) => {
735
- const value = writeValue(opts, message[localName]);
736
- if (value !== void 0) json[opts.useProtoFieldName ? protoName : jsonKey] = value;
737
- };
738
- }
739
- }
740
- }
741
- /**
742
- * Compile an encoder for a singular field: the presence check, and the
743
- * value encoder.
744
- */
745
- function compileSingularField(field) {
746
- const writeValue = compileSingularValue(field);
747
- const protoName = field.name;
748
- const jsonKey = field.jsonName;
749
- const localName = field.localName;
750
- if (field.oneof) {
751
- const oneofLocalName = field.oneof.localName;
752
- return (opts, message, json) => {
753
- const oneof = message[oneofLocalName];
754
- if (oneof.case === localName) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, oneof.value);
755
- };
756
- }
757
- if (field.presence != IMPLICIT$1) {
758
- const requiredError = field.presence == LEGACY_REQUIRED ? `cannot encode ${field} to JSON: required field not set` : void 0;
759
- return (opts, message, json) => {
760
- const value = message[localName];
761
- if (value !== void 0 && Object.prototype.hasOwnProperty.call(message, localName)) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
762
- else if (requiredError !== void 0) throw new Error(requiredError);
763
- };
764
- }
765
- if (field.fieldKind == "enum") {
766
- const zero = field.enum.values[0].number;
767
- return (opts, message, json) => {
768
- const value = message[localName];
769
- if (value !== zero || opts.alwaysEmitImplicit) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
770
- };
771
- }
772
- switch (field.scalar) {
773
- case ScalarType.BOOL: return (opts, message, json) => {
774
- const value = message[localName];
775
- if (value !== false || opts.alwaysEmitImplicit) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
776
- };
777
- case ScalarType.STRING: return (opts, message, json) => {
778
- const value = message[localName];
779
- if (value !== "" || opts.alwaysEmitImplicit) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
780
- };
781
- case ScalarType.BYTES: return (opts, message, json) => {
782
- const value = message[localName];
783
- if (!(value instanceof Uint8Array) || value.byteLength > 0 || opts.alwaysEmitImplicit) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
784
- };
785
- case ScalarType.DOUBLE:
786
- case ScalarType.FLOAT: return (opts, message, json) => {
787
- const value = message[localName];
788
- if (!Object.is(value, 0) || opts.alwaysEmitImplicit) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
789
- };
790
- default: return (opts, message, json) => {
791
- const value = message[localName];
792
- if (value != 0 || opts.alwaysEmitImplicit) json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
793
- };
794
- }
795
- }
796
- /**
797
- * Compile an encoder for the value of a field of any kind. Used for
798
- * extension values.
799
- */
800
- function compileFieldValue(field) {
801
- switch (field.fieldKind) {
802
- case "scalar":
803
- case "enum":
804
- case "message": return compileSingularValue(field);
805
- case "list": return compileListValue(field);
806
- case "map": return compileMapValue(field);
807
- }
808
- }
809
- /**
810
- * Compile an encoder for the value of a singular field.
811
- */
812
- function compileSingularValue(field) {
813
- switch (field.fieldKind) {
814
- case "scalar": return compileScalarValue(field);
815
- case "enum": return compileEnumValue(field);
816
- case "message": return compileMessageValue(field);
817
- }
818
- }
819
- /**
820
- * Compile an encoder for the value of a message field.
821
- */
822
- function compileMessageValue(field) {
823
- const { toMessage } = localMessageMapper(field);
824
- const writeMessage = compiledWriter(field.message);
825
- return (opts, value) => writeMessage(opts, toMessage(value));
826
- }
827
- /**
828
- * Compile an encoder for a list field value. Returns undefined for an empty
829
- * list, unless alwaysEmitImplicit is enabled.
830
- */
831
- function compileListValue(field) {
832
- const writeItem = compileListItemValue(field);
833
- return (opts, value) => {
834
- const items = value;
835
- if (items.length == 0 && !opts.alwaysEmitImplicit) return;
836
- const jsonArray = [];
837
- for (let i = 0; i < items.length; i++) jsonArray.push(writeItem(opts, items[i]));
838
- return jsonArray;
839
- };
840
- }
841
- function compileListItemValue(field) {
842
- switch (field.listKind) {
843
- case "scalar": return compileScalarValue(field);
844
- case "enum": return compileEnumValue(field);
845
- case "message": return compileMessageValue(field);
846
- }
847
- }
848
- /**
849
- * Compile an encoder for a map field value. Returns undefined for an empty
850
- * map, unless alwaysEmitImplicit is enabled. Map keys are stored as object
851
- * keys and are used as JSON keys as-is.
852
- */
853
- function compileMapValue(field) {
854
- const writeMapValue = compileMapEntryValue(field);
855
- return (opts, value) => {
856
- const record = value;
857
- const keys = Object.keys(record);
858
- if (keys.length == 0 && !opts.alwaysEmitImplicit) return;
859
- const jsonObject = {};
860
- for (let i = 0; i < keys.length; i++) {
861
- const key = keys[i];
862
- jsonObject[key] = writeMapValue(opts, record[key]);
863
- }
864
- return jsonObject;
865
- };
866
- }
867
- function compileMapEntryValue(field) {
868
- switch (field.mapKind) {
869
- case "scalar": return compileScalarValue(field);
870
- case "enum": return compileEnumValue(field);
871
- case "message": return compileMessageValue(field);
872
- }
873
- }
874
- /**
875
- * Compile an encoder for an enum value.
876
- */
877
- function compileEnumValue(field) {
878
- const desc = field.enum;
879
- if (desc.typeName == "google.protobuf.NullValue") return (opts, value) => {
880
- if (typeof value != "number") throw errorEnumValue(desc, value);
881
- return null;
882
- };
883
- return (opts, value) => {
884
- var _a, _b;
885
- if (typeof value != "number") throw errorEnumValue(desc, value);
886
- if (opts.enumAsInteger) return value;
887
- return (_b = (_a = desc.value[value]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : value;
888
- };
889
- }
890
- function errorEnumValue(desc, value) {
891
- return /* @__PURE__ */ new Error(`cannot encode ${desc} to JSON: expected number, got ${formatVal(value)}`);
892
- }
893
- /**
894
- * Compile an encoder for a scalar value. Errors report the original field
895
- * descriptor, which may be a list or map field for items of those fields.
896
- */
897
- function compileScalarValue(field) {
898
- switch (field.scalar) {
899
- case ScalarType.INT32:
900
- case ScalarType.SFIXED32:
901
- case ScalarType.SINT32:
902
- case ScalarType.FIXED32:
903
- case ScalarType.UINT32: return (opts, value) => {
904
- if (typeof value != "number") throw errorScalarValue(field, value);
905
- return value;
906
- };
907
- case ScalarType.FLOAT:
908
- case ScalarType.DOUBLE: return (opts, value) => {
909
- if (typeof value != "number") throw errorScalarValue(field, value);
910
- if (Number.isNaN(value)) return "NaN";
911
- if (value === Number.POSITIVE_INFINITY) return "Infinity";
912
- if (value === Number.NEGATIVE_INFINITY) return "-Infinity";
913
- return value;
914
- };
915
- case ScalarType.STRING: return (opts, value) => {
916
- if (typeof value != "string") throw errorScalarValue(field, value);
917
- return value;
918
- };
919
- case ScalarType.BOOL: return (opts, value) => {
920
- if (typeof value != "boolean") throw errorScalarValue(field, value);
921
- return value;
922
- };
923
- case ScalarType.UINT64:
924
- case ScalarType.FIXED64:
925
- case ScalarType.INT64:
926
- case ScalarType.SFIXED64:
927
- case ScalarType.SINT64: return (opts, value) => {
928
- if (typeof value == "bigint" || typeof value == "string" || typeof value == "number" && Number.isInteger(value)) return value.toString();
929
- throw errorScalarValue(field, value);
930
- };
931
- case ScalarType.BYTES: return (opts, value) => {
932
- if (value instanceof Uint8Array) return base64Encode(value);
933
- throw errorScalarValue(field, value);
934
- };
935
- }
936
- }
937
- function errorScalarValue(field, value) {
938
- var _a;
939
- return /* @__PURE__ */ new Error(`cannot encode ${field} to JSON: ${(_a = checkField(field, value)) === null || _a === void 0 ? void 0 : _a.message}`);
940
- }
941
- /**
942
- * Write extensions for unknown fields that are found in the registry.
943
- */
944
- function writeExtensions(json, opts, registry, message, desc) {
945
- const unknown = message.$unknown;
946
- if (unknown === void 0) return;
947
- const tagSeen = /* @__PURE__ */ new Set();
948
- for (let i = 0; i < unknown.length; i++) {
949
- const { no } = unknown[i];
950
- if (!tagSeen.has(no)) {
951
- tagSeen.add(no);
952
- const extension = registry.getExtensionFor(desc, no);
953
- if (!extension) continue;
954
- const [container, field] = createExtensionContainer(extension, getExtension(message, extension));
955
- const local = container[unsafeLocal];
956
- const jsonValue = compileFieldValue(field)(opts, local[field.localName]);
957
- if (jsonValue !== void 0) json[extension.jsonName] = jsonValue;
958
- }
959
- }
960
- }
961
- function anyToJson(val, opts) {
962
- if (val.typeUrl === "") return {};
963
- const { registry } = opts;
964
- let message;
965
- let desc;
966
- if (registry) {
967
- message = anyUnpack(val, registry);
968
- if (message) desc = registry.getMessage(message.$typeName);
969
- }
970
- if (!desc || !message) throw new Error(`cannot encode message ${val.$typeName} to JSON: "${val.typeUrl}" is not in the type registry`);
971
- const json = hasCustomJsonRepresentation(desc) ? { value: compiledWriter(desc)(opts, message) } : compiledWriter(desc)(opts, message);
972
- json["@type"] = val.typeUrl;
973
- return json;
974
- }
975
- function durationToJson(val) {
976
- const seconds = Number(val.seconds);
977
- const nanos = val.nanos;
978
- if (seconds > 315576e6 || seconds < -315576e6) throw new Error(`cannot encode message ${val.$typeName} to JSON: value out of range`);
979
- if (seconds > 0 && nanos < 0 || seconds < 0 && nanos > 0) throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos sign must match seconds sign`);
980
- let text = val.seconds.toString();
981
- if (nanos !== 0) {
982
- let nanosStr = Math.abs(nanos).toString();
983
- nanosStr = "0".repeat(9 - nanosStr.length) + nanosStr;
984
- if (nanosStr.substring(3) === "000000") nanosStr = nanosStr.substring(0, 3);
985
- else if (nanosStr.substring(6) === "000") nanosStr = nanosStr.substring(0, 6);
986
- text += "." + nanosStr;
987
- if (nanos < 0 && seconds == 0) text = "-" + text;
988
- }
989
- return text + "s";
990
- }
991
- function fieldMaskToJson(val) {
992
- return val.paths.map((p) => {
993
- if (protoSnakeCase(protoCamelCase(p)) !== p) throw new Error(`cannot encode message ${val.$typeName} to JSON: lowerCamelCase of path name "${p}" is irreversible`);
994
- return protoCamelCase(p);
995
- }).join(",");
996
- }
997
- function structToJson(val) {
998
- const json = {};
999
- const keys = Object.keys(val.fields);
1000
- for (let i = 0; i < keys.length; i++) {
1001
- const key = keys[i];
1002
- json[key] = valueToJson(val.fields[key]);
1003
- }
1004
- return json;
1005
- }
1006
- function valueToJson(val) {
1007
- switch (val.kind.case) {
1008
- case "nullValue": return null;
1009
- case "numberValue":
1010
- if (!Number.isFinite(val.kind.value)) throw new Error(`${val.$typeName} cannot be NaN or Infinity`);
1011
- return val.kind.value;
1012
- case "boolValue": return val.kind.value;
1013
- case "stringValue": return val.kind.value;
1014
- case "structValue": return structToJson(val.kind.value);
1015
- case "listValue": return listValueToJson(val.kind.value);
1016
- default: throw new Error(`${val.$typeName} must have a value`);
1017
- }
1018
- }
1019
- function listValueToJson(val) {
1020
- return val.values.map(valueToJson);
1021
- }
1022
- function timestampToJson(val) {
1023
- const ms = Number(val.seconds) * 1e3;
1024
- if (ms < timestampMsMin || ms > timestampMsMax) throw new Error(`cannot encode message ${val.$typeName} to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
1025
- if (val.nanos < 0) throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be negative`);
1026
- if (val.nanos > 999999999) throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be greater than 99999999`);
1027
- let z = "Z";
1028
- if (val.nanos > 0) {
1029
- const nanosStr = (val.nanos + 1e9).toString().substring(1);
1030
- if (nanosStr.substring(3) === "000000") z = "." + nanosStr.substring(0, 3) + "Z";
1031
- else if (nanosStr.substring(6) === "000") z = "." + nanosStr.substring(0, 6) + "Z";
1032
- else z = "." + nanosStr + "Z";
1033
- }
1034
- return new Date(ms).toISOString().replace(".000Z", z);
1035
- }
1036
- //#endregion
1037
- //#region node_modules/.pnpm/@bufbuild+protobuf@2.14.0/node_modules/@bufbuild/protobuf/dist/esm/from-json.js
1038
- const IMPLICIT = 2;
1039
- function makeReadContext(options) {
1040
- return Object.assign(Object.assign({
1041
- ignoreUnknownFields: false,
1042
- recursionLimit: 100
1043
- }, options), { depth: 0 });
1044
- }
1045
- /**
1046
- * Parse a message from a JSON value.
1047
- *
1048
- * Duplicate keys are rejected, but a value parsed by JSON.parse has already
1049
- * dropped duplicates (the last one wins). Use `fromJsonString` for strict
1050
- * duplicate-key checking.
1051
- */
1052
- function fromJson(schema, json, options) {
1053
- const message = create(schema);
1054
- readMessage(schema, message, json, options);
1055
- return message;
36
+ /** Messages that carry no diagnostic content on their own. */
37
+ const GENERIC_CONNECT_ERROR_MESSAGES = /* @__PURE__ */ new Set([
38
+ "",
39
+ "error",
40
+ "unknown",
41
+ "unknown error",
42
+ "internal",
43
+ "internal error"
44
+ ]);
45
+ /** Upper bound for appended trailer context so errors stay log-line sized. */
46
+ const MAX_EXTRA_DETAIL_CHARS = 400;
47
+ function isRecord(value) {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1056
49
  }
1057
- /**
1058
- * Run the compiled decoder for the message, wrapping FieldErrors with the
1059
- * standard error message.
1060
- */
1061
- function readMessage(schema, message, json, options) {
50
+ function safeJson(value) {
1062
51
  try {
1063
- compiledReader(schema)(message, json, makeReadContext(options));
1064
- } catch (e) {
1065
- if (isFieldError(e)) throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, { cause: e });
1066
- throw e;
1067
- }
1068
- }
1069
- const compiledReaders = /* @__PURE__ */ new WeakMap();
1070
- /**
1071
- * Return the compiled decoder for a message, compiling it on first use.
1072
- */
1073
- function compiledReader(desc) {
1074
- let compiled = compiledReaders.get(desc);
1075
- if (compiled === void 0) compiled = compileMessage(desc);
1076
- return compiled;
1077
- }
1078
- function compileMessage(desc) {
1079
- const descString = String(desc);
1080
- const readWkt = compileWkt(desc);
1081
- if (readWkt !== void 0) {
1082
- const compiled = (message, json, ctx) => {
1083
- if (++ctx.depth > ctx.recursionLimit) throw new Error(`cannot decode ${descString} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
1084
- readWkt(message, json, ctx);
1085
- ctx.depth--;
1086
- };
1087
- compiledReaders.set(desc, compiled);
1088
- return compiled;
1089
- }
1090
- const typeName = desc.typeName;
1091
- const fieldsByJsonKey = /* @__PURE__ */ new Map();
1092
- const compiled = (message, json, ctx) => {
1093
- var _a;
1094
- if (++ctx.depth > ctx.recursionLimit) throw new Error(`cannot decode ${descString} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
1095
- if (json == null || Array.isArray(json) || typeof json != "object") throw new Error(`cannot decode ${descString} from JSON: ${formatVal(json)}`);
1096
- const oneofSeen = /* @__PURE__ */ new Map();
1097
- const fieldSeen = /* @__PURE__ */ new Set();
1098
- const jsonKeys = Object.keys(json);
1099
- for (let i = 0; i < jsonKeys.length; i++) {
1100
- const jsonKey = jsonKeys[i];
1101
- const jsonValue = json[jsonKey];
1102
- const entry = fieldsByJsonKey.get(jsonKey);
1103
- if (entry !== void 0) {
1104
- const field = entry.field;
1105
- if (fieldSeen.has(field)) throw new FieldError(field, "set multiple times");
1106
- fieldSeen.add(field);
1107
- if (entry.oneofScalarNullSkip && jsonValue === null) continue;
1108
- if (entry.oneof) {
1109
- const seen = oneofSeen.get(entry.oneof);
1110
- if (seen !== void 0) throw new FieldError(entry.oneof, `oneof set multiple times by ${seen.name} and ${field.name}`);
1111
- oneofSeen.set(entry.oneof, field);
1112
- }
1113
- entry.read(message, jsonValue, ctx);
1114
- } else {
1115
- const extension = jsonKey.startsWith("[") && jsonKey.endsWith("]") ? (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1)) : void 0;
1116
- if ((extension === null || extension === void 0 ? void 0 : extension.extendee.typeName) == typeName) {
1117
- const [container, field, get] = createExtensionContainer(extension);
1118
- compileFieldReader(field)(container[unsafeLocal], jsonValue, ctx);
1119
- setExtension(message, extension, get());
1120
- }
1121
- if (extension === void 0 && !ctx.ignoreUnknownFields) throw new Error(`cannot decode ${descString} from JSON: key "${jsonKey}" is unknown`);
1122
- }
1123
- }
1124
- ctx.depth--;
1125
- };
1126
- compiledReaders.set(desc, compiled);
1127
- for (const field of desc.fields) {
1128
- const entry = {
1129
- read: compileFieldReader(field),
1130
- field,
1131
- oneof: field.oneof,
1132
- oneofScalarNullSkip: field.oneof !== void 0 && field.fieldKind == "scalar"
1133
- };
1134
- fieldsByJsonKey.set(field.name, entry).set(field.jsonName, entry);
1135
- }
1136
- return compiled;
1137
- }
1138
- /**
1139
- * Compile a decoder for a well-known type with a custom JSON representation,
1140
- * or return undefined for other messages. The recursion limit is enforced by
1141
- * the caller.
1142
- */
1143
- function compileWkt(desc) {
1144
- if (!desc.typeName.startsWith("google.protobuf.")) return;
1145
- switch (desc.typeName) {
1146
- case "google.protobuf.Any": return (message, json, ctx) => anyFromJson(message, json, ctx);
1147
- case "google.protobuf.Timestamp": return (message, json) => timestampFromJson(message, json);
1148
- case "google.protobuf.Duration": return (message, json) => durationFromJson(message, json);
1149
- case "google.protobuf.FieldMask": return (message, json) => fieldMaskFromJson(message, json);
1150
- case "google.protobuf.Struct": return (message, json, ctx) => structFromJson(message, json, ctx);
1151
- case "google.protobuf.Value": return (message, json, ctx) => valueFromJson(message, json, ctx);
1152
- case "google.protobuf.ListValue": return (message, json, ctx) => listValueFromJson(message, json, ctx);
1153
- default:
1154
- if (isWrapperDesc(desc)) {
1155
- const valueField = desc.fields[0];
1156
- const localName = valueField.localName;
1157
- const scalar = valueField.scalar;
1158
- const longAsString = valueField.longAsString;
1159
- const readScalar = compileScalarConverter(valueField);
1160
- return (message, json) => {
1161
- if (json === null) message[localName] = scalarZeroValue(scalar, longAsString);
1162
- else message[localName] = readScalar(json);
1163
- };
1164
- }
1165
- return;
1166
- }
1167
- }
1168
- function compileFieldReader(field) {
1169
- switch (field.fieldKind) {
1170
- case "scalar": return compileScalarFieldReader(field);
1171
- case "enum": return compileEnumFieldReader(field);
1172
- case "message": return compileMessageFieldReader(field);
1173
- case "list": return compileListFieldReader(field);
1174
- case "map": return compileMapFieldReader(field);
1175
- }
1176
- }
1177
- function compileScalarFieldReader(field) {
1178
- const readScalar = compileScalarConverter(field);
1179
- const localName = field.localName;
1180
- if (field.oneof) {
1181
- const oneofLocalName = field.oneof.localName;
1182
- return (message, json) => {
1183
- message[oneofLocalName] = {
1184
- case: localName,
1185
- value: readScalar(json)
1186
- };
1187
- };
1188
- }
1189
- const clear = compileClear(field);
1190
- return (message, json) => {
1191
- if (json === null) clear(message);
1192
- else message[localName] = readScalar(json);
1193
- };
1194
- }
1195
- /**
1196
- * Compile a function that resets the field to unset, mirroring the clear
1197
- * operation of the reflect API for fields that are not part of a oneof.
1198
- */
1199
- function compileClear(field) {
1200
- const localName = field.localName;
1201
- if (field.presence != IMPLICIT) return (message) => {
1202
- delete message[localName];
1203
- };
1204
- if (field.fieldKind == "enum") {
1205
- const zero = field.enum.values[0].number;
1206
- return (message) => {
1207
- message[localName] = zero;
1208
- };
1209
- }
1210
- const scalar = field.scalar;
1211
- const longAsString = field.longAsString;
1212
- return (message) => {
1213
- message[localName] = scalarZeroValue(scalar, longAsString);
1214
- };
1215
- }
1216
- function compileEnumFieldReader(field) {
1217
- const readEnumValue = compileEnumConverter(field.enum);
1218
- const checkEnum = compileEnumCheck(field.enum);
1219
- const localName = field.localName;
1220
- const nullResets = field.enum.typeName != "google.protobuf.NullValue";
1221
- if (field.oneof) {
1222
- const oneofLocalName = field.oneof.localName;
1223
- return (message, json, ctx) => {
1224
- if (json === null && nullResets) {
1225
- if (message[oneofLocalName].case === localName) message[oneofLocalName] = { case: void 0 };
1226
- return;
1227
- }
1228
- const value = readEnumValue(json, ctx.ignoreUnknownFields);
1229
- if (value === tokenIgnoredUnknownEnum) return;
1230
- const check = checkEnum(value);
1231
- if (check !== true) throw new FieldError(field, reasonSingular(field, value, check));
1232
- message[oneofLocalName] = {
1233
- case: localName,
1234
- value
1235
- };
1236
- };
1237
- }
1238
- const clear = compileClear(field);
1239
- return (message, json, ctx) => {
1240
- if (json === null && nullResets) {
1241
- clear(message);
1242
- return;
1243
- }
1244
- const value = readEnumValue(json, ctx.ignoreUnknownFields);
1245
- if (value === tokenIgnoredUnknownEnum) return;
1246
- const check = checkEnum(value);
1247
- if (check !== true) throw new FieldError(field, reasonSingular(field, value, check));
1248
- message[localName] = value;
1249
- };
1250
- }
1251
- function compileMessageFieldReader(field) {
1252
- const localName = field.localName;
1253
- const { toMessage, toLocal } = localMessageMapper(field);
1254
- const readChild = compiledReader(field.message);
1255
- const nullResets = field.message.typeName != "google.protobuf.Value";
1256
- if (field.oneof) {
1257
- const oneofLocalName = field.oneof.localName;
1258
- return (message, json, ctx) => {
1259
- const oneof = message[oneofLocalName];
1260
- if (json === null && nullResets) {
1261
- if (oneof.case === localName) message[oneofLocalName] = { case: void 0 };
1262
- return;
1263
- }
1264
- const child = toMessage(oneof.case === localName ? oneof.value : void 0);
1265
- readChild(child, json, ctx);
1266
- message[oneofLocalName] = {
1267
- case: localName,
1268
- value: toLocal(child)
1269
- };
1270
- };
52
+ return (typeof value === "string" ? value : JSON.stringify(value)) || void 0;
53
+ } catch {
54
+ return;
1271
55
  }
1272
- return (message, json, ctx) => {
1273
- if (json === null && nullResets) {
1274
- delete message[localName];
1275
- return;
1276
- }
1277
- const child = toMessage(message[localName]);
1278
- readChild(child, json, ctx);
1279
- message[localName] = toLocal(child);
1280
- };
1281
- }
1282
- function compileListFieldReader(field) {
1283
- const localName = field.localName;
1284
- const readItem = compileListItemReader(field);
1285
- return (message, json, ctx) => {
1286
- if (json === null) return;
1287
- if (!Array.isArray(json)) throw new FieldError(field, "expected Array, got " + formatVal(json));
1288
- const items = message[localName];
1289
- for (let i = 0; i < json.length; i++) {
1290
- const value = readItem(json[i], ctx, items.length);
1291
- if (value !== tokenIgnoredUnknownEnum) items.push(value);
1292
- }
1293
- };
1294
56
  }
1295
57
  /**
1296
- * Compile a decoder for a list item. The index is only used in errors, and
1297
- * accounts for previously merged items.
58
+ * Summarizes Connect error detail entries (objects with type / value / debug
59
+ * fields per the Connect JSON error model). Returns undefined when nothing
60
+ * usable is present.
1298
61
  */
1299
- function compileListItemReader(field) {
1300
- switch (field.listKind) {
1301
- case "scalar": {
1302
- const parseScalar = compileScalarParse(field);
1303
- const checkValue = checkScalarValue(field.scalar);
1304
- const toLocal = compileScalarToLocal(field);
1305
- return (json, ctx, index) => {
1306
- if (json === null) throw new FieldError(field, "list item must not be null");
1307
- const value = parseScalar(json);
1308
- const check = checkValue(value);
1309
- if (check !== true) throw new FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);
1310
- return toLocal(value);
1311
- };
1312
- }
1313
- case "enum": {
1314
- const readEnumValue = compileEnumConverter(field.enum);
1315
- const checkEnum = compileEnumCheck(field.enum);
1316
- const nullResets = field.enum.typeName != "google.protobuf.NullValue";
1317
- return (json, ctx, index) => {
1318
- if (json === null && nullResets) throw new FieldError(field, "list item must not be null");
1319
- const value = readEnumValue(json, ctx.ignoreUnknownFields);
1320
- if (value === tokenIgnoredUnknownEnum) return value;
1321
- const check = checkEnum(value);
1322
- if (check !== true) throw new FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);
1323
- return value;
1324
- };
1325
- }
1326
- case "message": {
1327
- const { toMessage, toLocal } = localMessageMapper(field);
1328
- const readChild = compiledReader(field.message);
1329
- const nullResets = field.message.typeName != "google.protobuf.Value";
1330
- return (json, ctx) => {
1331
- if (json === null && nullResets) throw new FieldError(field, "list item must not be null");
1332
- const child = toMessage(void 0);
1333
- readChild(child, json, ctx);
1334
- return toLocal(child);
1335
- };
1336
- }
62
+ function summarizeConnectErrorDetails(details) {
63
+ if (!Array.isArray(details) || details.length === 0) return void 0;
64
+ const parts = [];
65
+ for (const entry of details) {
66
+ if (!isRecord(entry)) continue;
67
+ const type = typeof entry.type === "string" && entry.type ? entry.type : void 0;
68
+ const debug = entry.debug !== void 0 ? safeJson(entry.debug) : void 0;
69
+ const value = entry.value !== void 0 ? safeJson(entry.value) : void 0;
70
+ const diagnostic = debug ?? value;
71
+ if (type && diagnostic) parts.push(`${type}: ${diagnostic}`);
72
+ else if (type) parts.push(type);
73
+ else if (diagnostic) parts.push(diagnostic);
1337
74
  }
75
+ if (parts.length === 0) return void 0;
76
+ return truncate(parts.join("; "), MAX_EXTRA_DETAIL_CHARS);
1338
77
  }
1339
- function compileMapFieldReader(field) {
1340
- const localName = field.localName;
1341
- const mapKey = field.mapKey;
1342
- const parseMapKey = compileMapKeyParse(mapKey);
1343
- const checkMapKey = checkScalarValue(mapKey);
1344
- let parseValue;
1345
- let checkValue;
1346
- let toLocalValue = (value) => value;
1347
- let nullResets = true;
1348
- switch (field.mapKind) {
1349
- case "scalar":
1350
- parseValue = compileScalarParse(field);
1351
- checkValue = checkScalarValue(field.scalar);
1352
- toLocalValue = compileScalarToLocal(field);
1353
- break;
1354
- case "enum": {
1355
- const readEnumValue = compileEnumConverter(field.enum);
1356
- parseValue = (json, ctx) => readEnumValue(json, ctx.ignoreUnknownFields);
1357
- checkValue = compileEnumCheck(field.enum);
1358
- nullResets = field.enum.typeName != "google.protobuf.NullValue";
1359
- break;
1360
- }
1361
- case "message": {
1362
- const { toMessage, toLocal } = localMessageMapper(field);
1363
- const readChild = compiledReader(field.message);
1364
- nullResets = field.message.typeName != "google.protobuf.Value";
1365
- parseValue = (json, ctx) => {
1366
- const child = toMessage(void 0);
1367
- readChild(child, json, ctx);
1368
- return toLocal(child);
1369
- };
1370
- break;
1371
- }
1372
- }
1373
- return (message, json, ctx) => {
1374
- if (json === null) return;
1375
- if (typeof json != "object" || Array.isArray(json)) throw new FieldError(field, "expected object, got " + formatVal(json));
1376
- const record = message[localName];
1377
- const seen = /* @__PURE__ */ new Set();
1378
- const jsonMapKeys = Object.keys(json);
1379
- for (let i = 0; i < jsonMapKeys.length; i++) {
1380
- const jsonMapKey = jsonMapKeys[i];
1381
- const jsonMapValue = json[jsonMapKey];
1382
- const key = parseMapKey(jsonMapKey);
1383
- if (seen.has(key)) throw new FieldError(field, `duplicate map key "${jsonMapKey}"`);
1384
- seen.add(key);
1385
- if (jsonMapValue === null && nullResets) throw new FieldError(field, "map value must not be null");
1386
- const value = parseValue(jsonMapValue, ctx);
1387
- if (value === tokenIgnoredUnknownEnum) continue;
1388
- const checkKey = checkMapKey(key);
1389
- if (checkKey !== true) throw new FieldError(field, `invalid map key: ${reasonSingular({ scalar: mapKey }, key, checkKey)}`);
1390
- if (checkValue !== void 0) {
1391
- const check = checkValue(value);
1392
- if (check !== true) throw new FieldError(field, `map entry ${formatVal(key)}: ${reasonSingular(field, value, check)}`);
1393
- }
1394
- record[key] = toLocalValue(value);
1395
- }
1396
- };
1397
- }
1398
- const tokenIgnoredUnknownEnum = Symbol();
1399
78
  /**
1400
- * Compile a converter from a JSON value to an enum value. JSON null returns
1401
- * the enum's first value. With ignoreUnknownFields false, unknown string
1402
- * values raise an error; with true, they return tokenIgnoredUnknownEnum.
1403
- * The value is not checked against the enum's values, see compileEnumCheck.
79
+ * Formats a Connect end-stream error object into a diagnosable message.
80
+ * The "Connect error code: message" prefix is preserved exactly; detail
81
+ * entries are appended when present, and when the message itself is generic
82
+ * the remaining trailer fields are inlined so the error names what the
83
+ * server actually sent instead of a bare "Error".
1404
84
  */
1405
- function compileEnumConverter(desc) {
1406
- const zero = desc.values[0].number;
1407
- const values = desc.values;
1408
- return (json, ignoreUnknownFields) => {
1409
- if (json === null) return zero;
1410
- switch (typeof json) {
1411
- case "number":
1412
- if (Number.isInteger(json)) return json;
1413
- break;
1414
- case "string": {
1415
- const value = values.find((ev) => ev.name === json);
1416
- if (value !== void 0) return value.number;
1417
- if (ignoreUnknownFields) return tokenIgnoredUnknownEnum;
1418
- break;
1419
- }
85
+ function formatConnectEndStreamError(error) {
86
+ const record = isRecord(error) ? error : {};
87
+ const code = typeof record.code === "string" && record.code ? record.code : "unknown";
88
+ const message = typeof record.message === "string" ? record.message : "";
89
+ const detail = summarizeConnectErrorDetails(record.details);
90
+ const parts = [`Connect error ${code}: ${message || "Unknown error"}`];
91
+ if (detail) parts.push(`[details: ${detail}]`);
92
+ else if (GENERIC_CONNECT_ERROR_MESSAGES.has(message.trim().toLowerCase())) {
93
+ const extras = {};
94
+ for (const [key, value] of Object.entries(record)) {
95
+ if (key === "code" || key === "message") continue;
96
+ extras[key] = value;
1420
97
  }
1421
- throw new Error(`cannot decode ${desc} from JSON: ${formatVal(json)}`);
1422
- };
1423
- }
1424
- /**
1425
- * Compile the check that the reflect API performs for enum values: open
1426
- * enums accept any int32 value, closed enums accept only declared values.
1427
- */
1428
- function compileEnumCheck(desc) {
1429
- if (desc.open) return checkScalarValue(ScalarType.INT32);
1430
- const values = desc.values;
1431
- return (value) => values.some((v) => v.number === value);
1432
- }
1433
- /**
1434
- * Compile a converter from a JSON value to the local representation of a
1435
- * scalar, fusing JSON parsing, the validation of the reflect API, and the
1436
- * conversion to the local 64-bit integer representation.
1437
- */
1438
- function compileScalarConverter(field) {
1439
- const parseScalar = compileScalarParse(field);
1440
- const checkValue = checkScalarValue(field.scalar);
1441
- const toLocal = compileScalarToLocal(field);
1442
- return (json) => {
1443
- const value = parseScalar(json);
1444
- const check = checkValue(value);
1445
- if (check !== true) throw new FieldError(field, reasonSingular(field, value, check));
1446
- return toLocal(value);
1447
- };
1448
- }
1449
- /**
1450
- * Compile the JSON-specific parsing step for a scalar value: the special
1451
- * string values of float and double, string-encoded numbers, and base64
1452
- * bytes. Returns the input unchanged if the JSON value cannot be converted;
1453
- * the validation step raises an error for it.
1454
- */
1455
- function compileScalarParse(field) {
1456
- switch (field.scalar) {
1457
- case ScalarType.DOUBLE:
1458
- case ScalarType.FLOAT: return (json) => {
1459
- if (json === "NaN") return NaN;
1460
- if (json === "Infinity") return Number.POSITIVE_INFINITY;
1461
- if (json === "-Infinity") return Number.NEGATIVE_INFINITY;
1462
- if (typeof json == "number") {
1463
- if (Number.isNaN(json)) throw new FieldError(field, "unexpected NaN number");
1464
- if (!Number.isFinite(json)) throw new FieldError(field, "unexpected infinite number");
1465
- return json;
1466
- }
1467
- if (typeof json == "string") {
1468
- if (json === "") return json;
1469
- if (json.trim().length !== json.length) return json;
1470
- const float = Number(json);
1471
- if (!Number.isFinite(float)) return json;
1472
- return float;
1473
- }
1474
- return json;
1475
- };
1476
- case ScalarType.INT32:
1477
- case ScalarType.FIXED32:
1478
- case ScalarType.SFIXED32:
1479
- case ScalarType.SINT32:
1480
- case ScalarType.UINT32: return int32FromJson;
1481
- case ScalarType.BYTES: return (json) => {
1482
- if (typeof json == "string") {
1483
- if (json === "") return /* @__PURE__ */ new Uint8Array(0);
1484
- try {
1485
- return base64Decode(json);
1486
- } catch (e) {
1487
- const message = e instanceof Error ? e.message : String(e);
1488
- throw new FieldError(field, message);
1489
- }
1490
- }
1491
- return json;
1492
- };
1493
- default: return (json) => json;
1494
- }
1495
- }
1496
- /**
1497
- * Compile the conversion of a validated scalar value to its local
1498
- * representation: 64-bit integers become bigint, or string with the
1499
- * longAsString option.
1500
- */
1501
- function compileScalarToLocal(field) {
1502
- const longAsString = field.fieldKind !== "map" && field.longAsString;
1503
- switch (field.scalar) {
1504
- case ScalarType.INT64:
1505
- case ScalarType.SFIXED64:
1506
- case ScalarType.SINT64:
1507
- if (longAsString) return (value) => String(value);
1508
- return (value) => typeof value == "string" || typeof value == "number" ? protoInt64.parse(value) : value;
1509
- case ScalarType.FIXED64:
1510
- case ScalarType.UINT64:
1511
- if (longAsString) return (value) => String(value);
1512
- return (value) => typeof value == "string" || typeof value == "number" ? protoInt64.uParse(value) : value;
1513
- default: return (value) => value;
1514
- }
1515
- }
1516
- /**
1517
- * Return a parser from a JSON value to a map key for the given key type.
1518
- * Canonicalizes 64-bit integers given as string, so that "01" and "1" are
1519
- * one key, and duplicates can raise an error.
1520
- * The parser returns the input if the JSON value cannot be converted.
1521
- */
1522
- function compileMapKeyParse(type) {
1523
- switch (type) {
1524
- case ScalarType.BOOL: return (jsonString) => {
1525
- switch (jsonString) {
1526
- case "true": return true;
1527
- case "false": return false;
1528
- }
1529
- return jsonString;
1530
- };
1531
- case ScalarType.INT32:
1532
- case ScalarType.FIXED32:
1533
- case ScalarType.UINT32:
1534
- case ScalarType.SFIXED32:
1535
- case ScalarType.SINT32: return int32FromJson;
1536
- case ScalarType.INT64:
1537
- case ScalarType.SINT64:
1538
- case ScalarType.SFIXED64:
1539
- case ScalarType.UINT64:
1540
- case ScalarType.FIXED64: return (jsonString) => /^-?0+$/.test(jsonString) ? "0" : jsonString.replace(/^(-?)0+(?=\d)/, "$1");
1541
- default: return (jsonString) => jsonString;
1542
- }
1543
- }
1544
- /**
1545
- * Try to parse a JSON value to a 32-bit integer for the reflect API.
1546
- *
1547
- * Returns the input if the JSON value cannot be converted.
1548
- */
1549
- function int32FromJson(json) {
1550
- if (typeof json == "string") {
1551
- if (json === "") return json;
1552
- if (json.trim().length !== json.length) return json;
1553
- const num = Number(json);
1554
- if (Number.isNaN(num)) return json;
1555
- return num;
1556
- }
1557
- return json;
1558
- }
1559
- function anyFromJson(any, json, ctx) {
1560
- var _a;
1561
- if (json === null || Array.isArray(json) || typeof json != "object") throw new Error(`cannot decode message ${any.$typeName} from JSON: expected object but got ${formatVal(json)}`);
1562
- if (Object.keys(json).length == 0) return;
1563
- const typeUrl = json["@type"];
1564
- if (typeof typeUrl != "string" || typeUrl == "") throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is empty`);
1565
- const typeName = typeUrl.includes("/") ? typeUrl.substring(typeUrl.lastIndexOf("/") + 1) : typeUrl;
1566
- if (!typeName.length) throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is invalid`);
1567
- const desc = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
1568
- if (!desc) throw new Error(`cannot decode message ${any.$typeName} from JSON: ${typeUrl} is not in the type registry`);
1569
- const message = create(desc);
1570
- if (hasCustomJsonRepresentation(desc) && Object.prototype.hasOwnProperty.call(json, "value")) compiledReader(desc)(message, json.value, ctx);
1571
- else {
1572
- const copy = Object.assign({}, json);
1573
- delete copy["@type"];
1574
- compiledReader(desc)(message, copy, ctx);
1575
- }
1576
- anyPack(desc, message, any);
1577
- }
1578
- function timestampFromJson(timestamp, json) {
1579
- if (typeof json !== "string") throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: ${formatVal(json)}`);
1580
- const matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);
1581
- if (!matches) throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
1582
- const ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z"));
1583
- if (Number.isNaN(ms)) throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
1584
- if (ms < timestampMsMin || ms > timestampMsMax) throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
1585
- timestamp.seconds = protoInt64.parse(ms / 1e3);
1586
- timestamp.nanos = 0;
1587
- if (matches[7]) timestamp.nanos = parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1e9;
1588
- }
1589
- function durationFromJson(duration, json) {
1590
- if (typeof json !== "string") throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${formatVal(json)}`);
1591
- const match = json.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);
1592
- if (match === null) throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${formatVal(json)}`);
1593
- const longSeconds = Number(match[1]);
1594
- if (longSeconds > 315576e6 || longSeconds < -315576e6) throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${formatVal(json)}`);
1595
- duration.seconds = protoInt64.parse(longSeconds);
1596
- if (typeof match[2] !== "string") return;
1597
- const nanosStr = match[2] + "0".repeat(9 - match[2].length);
1598
- duration.nanos = parseInt(nanosStr);
1599
- if (longSeconds < 0 || Object.is(longSeconds, -0)) duration.nanos = -duration.nanos;
1600
- }
1601
- function fieldMaskFromJson(fieldMask, json) {
1602
- if (typeof json !== "string") throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: ${formatVal(json)}`);
1603
- if (json === "") return;
1604
- fieldMask.paths = json.split(",").map((path) => {
1605
- if (path.includes("_")) throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);
1606
- return protoSnakeCase(path);
1607
- });
1608
- }
1609
- function structFromJson(struct, json, ctx) {
1610
- if (typeof json != "object" || json == null || Array.isArray(json)) throw new Error(`cannot decode message ${struct.$typeName} from JSON ${formatVal(json)}`);
1611
- const keys = Object.keys(json);
1612
- for (let i = 0; i < keys.length; i++) {
1613
- const key = keys[i];
1614
- const parsedValue = create(ValueSchema);
1615
- valueFromJson(parsedValue, json[key], ctx);
1616
- struct.fields[key] = parsedValue;
1617
- }
1618
- }
1619
- function valueFromJson(value, json, ctx) {
1620
- if (++ctx.depth > ctx.recursionLimit) throw new Error(`cannot decode ${value.$typeName} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
1621
- switch (typeof json) {
1622
- case "number":
1623
- value.kind = {
1624
- case: "numberValue",
1625
- value: json
1626
- };
1627
- break;
1628
- case "string":
1629
- value.kind = {
1630
- case: "stringValue",
1631
- value: json
1632
- };
1633
- break;
1634
- case "boolean":
1635
- value.kind = {
1636
- case: "boolValue",
1637
- value: json
1638
- };
1639
- break;
1640
- case "object":
1641
- if (json === null) value.kind = {
1642
- case: "nullValue",
1643
- value: NullValue.NULL_VALUE
1644
- };
1645
- else if (Array.isArray(json)) {
1646
- const listValue = create(ListValueSchema);
1647
- listValueFromJson(listValue, json, ctx);
1648
- value.kind = {
1649
- case: "listValue",
1650
- value: listValue
1651
- };
1652
- } else {
1653
- const struct = create(StructSchema);
1654
- structFromJson(struct, json, ctx);
1655
- value.kind = {
1656
- case: "structValue",
1657
- value: struct
1658
- };
1659
- }
1660
- break;
1661
- default: throw new Error(`cannot decode message ${value.$typeName} from JSON ${formatVal(json)}`);
1662
- }
1663
- ctx.depth--;
1664
- return value;
1665
- }
1666
- function listValueFromJson(listValue, json, ctx) {
1667
- if (!Array.isArray(json)) throw new Error(`cannot decode message ${listValue.$typeName} from JSON ${formatVal(json)}`);
1668
- for (let i = 0; i < json.length; i++) {
1669
- const value = create(ValueSchema);
1670
- valueFromJson(value, json[i], ctx);
1671
- listValue.values.push(value);
98
+ const raw = Object.keys(extras).length > 0 ? safeJson(extras) : void 0;
99
+ if (raw && raw !== "{}") parts.push(`[trailer: ${truncate(raw, MAX_EXTRA_DETAIL_CHARS)}]`);
1672
100
  }
101
+ return parts.join(" ");
1673
102
  }
1674
103
  //#endregion
1675
- //#region node_modules/.pnpm/@oh-my-pi+pi-ai@17.3.5/node_modules/@oh-my-pi/pi-ai/src/providers/cursor-pi-args.ts
104
+ //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/cursor-external-tool-handoff.md
105
+ var cursor_external_tool_handoff_default = "Tool call received and handed off to the external client for execution. Do not retry or call it again; end the turn. The result will be provided in the next request.\n";
106
+ //#endregion
107
+ //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/cursor-pi-args.ts
1676
108
  /**
1677
109
  * Translate a Pi frame's args into the local tool kwargs that run it.
1678
110
  *
@@ -1684,7 +116,7 @@ function listValueFromJson(listValue, json, ctx) {
1684
116
  *
1685
117
  * Kept apart from `cursor/exec-modern.ts` on purpose: these are pure
1686
118
  * string/path functions with no protobuf coupling, while that module pulls in
1687
- * `@bufbuild/protobuf` and the generated `agent_pb` graph. The legacy shim is
119
+ * the generated cursor protobuf graph. The legacy shim is
1688
120
  * compiled into the bundled virtual module registry, so importing it from a
1689
121
  * nested path would drag the whole exec implementation in with it — and
1690
122
  * `./providers/*` is a single-segment wildcard export that cannot serve a
@@ -1715,8 +147,9 @@ function piReadPath(readPath, offset, limit) {
1715
147
  const start = offset !== void 0 ? Math.max(1, Math.floor(offset)) : void 0;
1716
148
  const count = limit !== void 0 ? Math.floor(limit) : void 0;
1717
149
  if (start === void 0 && count === void 0) return readPath;
1718
- if (start === void 0) return `${readPath}:raw:1+${count}`;
1719
- return count === void 0 ? `${readPath}:raw:${start}-` : `${readPath}:raw:${start}+${count}`;
150
+ const base = readPath.split(":").some((chunk) => chunk.toLowerCase() === "raw") ? readPath : `${readPath}:raw`;
151
+ if (start === void 0) return `${base}:1+${count}`;
152
+ return count === void 0 ? `${base}:${start}-` : `${base}:${start}+${count}`;
1720
153
  }
1721
154
  const READ_RANGE_CHUNK_RE = /^L?(\d+)(?:(\.\.|[-+])L?(\d+)?)?$/i;
1722
155
  function isReadRangeList(value) {
@@ -1746,6 +179,39 @@ function piReadPathHasRange(readPath) {
1746
179
  return preceding !== void 0 && isReadRangeList(preceding);
1747
180
  }
1748
181
  /**
182
+ * Force a Cursor exec read onto `read`'s verbatim `:raw` selector.
183
+ *
184
+ * Native `editToolCall` (StrReplace) materializes via `readArgs` then
185
+ * `writeArgs`. The server treats the read result as file bytes and writes
186
+ * them back. A hashline-formatted native read (`[path#TAG]` + `LINE:`
187
+ * prefixes) poisons that cycle: the write would persist the markup.
188
+ * `:raw` is the existing selector that drops both. A path that already
189
+ * carries `raw` is left alone; a range-only selector gets `raw` inserted
190
+ * so the range still applies without the gutter.
191
+ */
192
+ function cursorRawReadPath(readPath) {
193
+ const chunks = readPath.split(":");
194
+ if (chunks.some((chunk) => chunk.toLowerCase() === "raw")) return readPath;
195
+ if (piReadPathHasRange(readPath)) {
196
+ const last = chunks.pop();
197
+ return `${chunks.join(":")}:raw:${last}`;
198
+ }
199
+ return `${readPath}:raw`;
200
+ }
201
+ /**
202
+ * Path the edit-owned materialization read should execute.
203
+ *
204
+ * Range is composed first (`piReadPath` already uses `:raw` for a range),
205
+ * then a whole-file path is forced onto `:raw`. The caller must drop
206
+ * `offset`/`limit` after this so the bridge's `piReadPath` cannot append a
207
+ * second `:raw` onto the already-composed selector.
208
+ */
209
+ function cursorEditOwnedReadPath(readPath, offset, limit) {
210
+ const ranged = piReadPath(readPath, offset, limit);
211
+ if (ranged === null) return null;
212
+ return cursorRawReadPath(ranged);
213
+ }
214
+ /**
1749
215
  * The same range as {@link piReadPath}, rendered for a transcript block rather
1750
216
  * than for execution.
1751
217
  *
@@ -1844,7 +310,7 @@ function omitUndefinedArgs(args) {
1844
310
  return out;
1845
311
  }
1846
312
  //#endregion
1847
- //#region node_modules/.pnpm/@oh-my-pi+pi-ai@17.3.5/node_modules/@oh-my-pi/pi-ai/src/providers/cursor/exec-modern.ts
313
+ //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/cursor/exec-modern.ts
1848
314
  /**
1849
315
  * Proto builders for the modern Cursor CLI exec frames (`ExecServerMessage`
1850
316
  * 27-31, 36-38, 40-55).
@@ -2236,7 +702,178 @@ function buildNeutralHookResult(request) {
2236
702
  break;
2237
703
  default: return null;
2238
704
  }
2239
- return create(ExecuteHookResultSchema, { response });
705
+ return create(ExecuteHookResultSchema, { response });
706
+ }
707
+ //#endregion
708
+ //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/cursor/interaction-query.ts
709
+ const NOT_IMPLEMENTED_SUFFIX$1 = "not implemented by this client";
710
+ function frameConnectMessage$1(data, flags = 0) {
711
+ const frame = Buffer.alloc(5 + data.length);
712
+ frame[0] = flags;
713
+ frame.writeUInt32BE(data.length, 1);
714
+ frame.set(data, 5);
715
+ return frame;
716
+ }
717
+ function isProtoUnknownField(value) {
718
+ if (!value || typeof value !== "object") return false;
719
+ if (!("no" in value) || !("wireType" in value) || !("data" in value)) return false;
720
+ return typeof value.no === "number" && typeof value.wireType === "number" && value.data instanceof Uint8Array;
721
+ }
722
+ function protoUnknownFields$1(message) {
723
+ if (!("$unknown" in message) || !Array.isArray(message.$unknown)) return [];
724
+ return message.$unknown.filter(isProtoUnknownField);
725
+ }
726
+ function attachUnknownApprovedField(response, fieldNo) {
727
+ const bag = response;
728
+ const field = {
729
+ no: fieldNo,
730
+ wireType: 2,
731
+ data: new Uint8Array([
732
+ 2,
733
+ 10,
734
+ 0
735
+ ])
736
+ };
737
+ const existing = bag.$unknown;
738
+ if (Array.isArray(existing)) {
739
+ existing.push(field);
740
+ return;
741
+ }
742
+ bag.$unknown = [field];
743
+ }
744
+ function log$1(type, subtype, data) {
745
+ if (!$env.DEBUG_CURSOR) return;
746
+ const dataStr = ($env.DEBUG_CURSOR === "2" || $env.DEBUG_CURSOR === "verbose") && data ? ` ${JSON.stringify(data)?.slice(0, 500)}` : "";
747
+ console.error(`[CURSOR] ${type}${subtype ? `: ${subtype}` : ""}${dataStr}`);
748
+ }
749
+ function sendInteractionResponse(h2Request, queryId, result) {
750
+ const response = create(InteractionResponseSchema, {
751
+ id: queryId,
752
+ result
753
+ });
754
+ const clientMessage = create(AgentClientMessageSchema, { message: {
755
+ case: "interactionResponse",
756
+ value: response
757
+ } });
758
+ h2Request.write(frameConnectMessage$1(toBinary(AgentClientMessageSchema, clientMessage)));
759
+ log$1("interactionResponse", result.case, { id: queryId });
760
+ }
761
+ function sendUnknownApprovedInteractionResponse(h2Request, queryId, fieldNo) {
762
+ const response = create(InteractionResponseSchema, { id: queryId });
763
+ attachUnknownApprovedField(response, fieldNo);
764
+ const clientMessage = create(AgentClientMessageSchema, { message: {
765
+ case: "interactionResponse",
766
+ value: response
767
+ } });
768
+ h2Request.write(frameConnectMessage$1(toBinary(AgentClientMessageSchema, clientMessage)));
769
+ log$1("interactionResponse", "unknownApproved", {
770
+ id: queryId,
771
+ field: fieldNo
772
+ });
773
+ }
774
+ /**
775
+ * Answer a Cursor `interaction_query` so the Run RPC can continue.
776
+ *
777
+ * Hosted web search / Exa / unnamed permission gates (field 9 = WebFetch on
778
+ * current Cursor builds) block the turn until the client writes an
779
+ * `interaction_response`. Dropping the frame leaves the HTTP/2 stream alive
780
+ * on heartbeats that are not semantic progress; the lazy idle watchdog then
781
+ * aborts with "Provider stream stalled while waiting for the next event".
782
+ *
783
+ * Unsupported interactive queries are rejected so the server is not stranded.
784
+ * VM setup is left unanswered rather than reporting a fake success.
785
+ */
786
+ function handleInteractionQuery(query, h2Request) {
787
+ const queryCase = query.query.case;
788
+ log$1("interactionQuery", queryCase, query.query.value);
789
+ if (!queryCase) {
790
+ const unknown = protoUnknownFields$1(query).find((field) => field.wireType === 2 && field.no >= 2);
791
+ if (unknown) {
792
+ log$1("warn", "unknownInteractionQueryApproved", {
793
+ id: query.id,
794
+ field: unknown.no
795
+ });
796
+ sendUnknownApprovedInteractionResponse(h2Request, query.id, unknown.no);
797
+ return;
798
+ }
799
+ log$1("warn", "unknownInteractionQuery", { id: query.id });
800
+ return;
801
+ }
802
+ switch (queryCase) {
803
+ case "webSearchRequestQuery":
804
+ sendInteractionResponse(h2Request, query.id, {
805
+ case: "webSearchRequestResponse",
806
+ value: create(WebSearchRequestResponseSchema, { result: {
807
+ case: "approved",
808
+ value: create(WebSearchRequestResponse_ApprovedSchema, {})
809
+ } })
810
+ });
811
+ return;
812
+ case "exaSearchRequestQuery":
813
+ sendInteractionResponse(h2Request, query.id, {
814
+ case: "exaSearchRequestResponse",
815
+ value: create(ExaSearchRequestResponseSchema, { result: {
816
+ case: "approved",
817
+ value: create(ExaSearchRequestResponse_ApprovedSchema, {})
818
+ } })
819
+ });
820
+ return;
821
+ case "exaFetchRequestQuery":
822
+ sendInteractionResponse(h2Request, query.id, {
823
+ case: "exaFetchRequestResponse",
824
+ value: create(ExaFetchRequestResponseSchema, { result: {
825
+ case: "approved",
826
+ value: create(ExaFetchRequestResponse_ApprovedSchema, {})
827
+ } })
828
+ });
829
+ return;
830
+ case "webFetchRequestQuery":
831
+ sendInteractionResponse(h2Request, query.id, {
832
+ case: "webFetchRequestResponse",
833
+ value: create(WebFetchRequestResponseSchema, { result: {
834
+ case: "approved",
835
+ value: create(WebFetchRequestResponse_ApprovedSchema, {})
836
+ } })
837
+ });
838
+ return;
839
+ case "askQuestionInteractionQuery":
840
+ sendInteractionResponse(h2Request, query.id, {
841
+ case: "askQuestionInteractionResponse",
842
+ value: create(AskQuestionInteractionResponseSchema, { result: create(AskQuestionResultSchema, { result: {
843
+ case: "rejected",
844
+ value: create(AskQuestionRejectedSchema, { reason: `Interactive questions are ${NOT_IMPLEMENTED_SUFFIX$1}` })
845
+ } }) })
846
+ });
847
+ return;
848
+ case "switchModeRequestQuery":
849
+ sendInteractionResponse(h2Request, query.id, {
850
+ case: "switchModeRequestResponse",
851
+ value: create(SwitchModeRequestResponseSchema, { result: {
852
+ case: "rejected",
853
+ value: create(SwitchModeRequestResponse_RejectedSchema, { reason: `Mode switches are ${NOT_IMPLEMENTED_SUFFIX$1}` })
854
+ } })
855
+ });
856
+ return;
857
+ case "createPlanRequestQuery":
858
+ sendInteractionResponse(h2Request, query.id, {
859
+ case: "createPlanRequestResponse",
860
+ value: create(CreatePlanRequestResponseSchema, { result: create(CreatePlanResultSchema, { result: {
861
+ case: "error",
862
+ value: create(CreatePlanErrorSchema, { error: `Plan files are ${NOT_IMPLEMENTED_SUFFIX$1}` })
863
+ } }) })
864
+ });
865
+ return;
866
+ case "setupVmEnvironmentArgs":
867
+ log$1("warn", "unhandledInteractionQuery", {
868
+ queryCase,
869
+ id: query.id
870
+ });
871
+ return;
872
+ default: log$1("warn", "unhandledInteractionQuery", {
873
+ queryCase,
874
+ id: query.id
875
+ });
876
+ }
2240
877
  }
2241
878
  const CURSOR_CLIENT_VERSION = "cli-2026.07.23-e383d2b";
2242
879
  /**
@@ -2299,6 +936,8 @@ const CURSOR_PROXY_TUNNEL_TIMEOUT_MS = 3e4;
2299
936
  const NOT_IMPLEMENTED_SUFFIX = "not implemented by this client";
2300
937
  /** Bare gRPC `resource_exhausted` end-streams (also inside a Connect error message). */
2301
938
  const RESOURCE_EXHAUSTED_PATTERN = /resource.?exhausted/i;
939
+ /** Model-resolution failures that can safely retry the exact discovery id before any server output. */
940
+ const CURSOR_MODEL_NOT_FOUND_PATTERN = /^(?:Connect error not_found:|gRPC error 5:)/i;
2302
941
  const NOT_IMPLEMENTED = `Not implemented by this client`;
2303
942
  const conversationStateCache = /* @__PURE__ */ new Map();
2304
943
  const conversationBlobStores = /* @__PURE__ */ new Map();
@@ -2306,13 +945,15 @@ const warnedCursorKimiK3ReplayMessages = /* @__PURE__ */ new Set();
2306
945
  /**
2307
946
  * Base conversation id → rotated wire id (#8345). Cursor's backend can pin a
2308
947
  * per-conversation rejection (bare `resource_exhausted`, zero tokens) to one
2309
- * conversationId forever; the session is then unusable until /fork mints a
2310
- * new id. On the first such failure the id is rotated once and the cached
2311
- * state migrates, so the retry loop's next attempt starts a fresh
2312
- * conversation — the same recovery /fork performs. Keyed by the base id the
2313
- * caller derived, so a failed rotation is never repeated.
948
+ * conversationId forever. On such a failure the id is rotated and the next
949
+ * attempt rebuilds a fresh conversation from `context` (no cached-state
950
+ * migration). A failed rotation is not repeated, so real account exhaustion
951
+ * is not hidden. After the rotated id completes a turn, a later poison of
952
+ * that id is allowed to rotate again.
2314
953
  */
2315
954
  const rotatedConversationIds = /* @__PURE__ */ new Map();
955
+ const successfulRotatedConversationIds = /* @__PURE__ */ new Set();
956
+ const freshRotatedConversationIds = /* @__PURE__ */ new Set();
2316
957
  const CONNECT_END_STREAM_FLAG = 2;
2317
958
  async function appendCursorDebugLog(entry) {
2318
959
  const logPath = $env.DEBUG_CURSOR_LOG;
@@ -2341,14 +982,17 @@ function frameConnectMessage(data, flags = 0) {
2341
982
  frame.set(data, 5);
2342
983
  return frame;
2343
984
  }
985
+ var ConnectEndStreamError = class extends ProviderResponseError {
986
+ diagnosticMessage;
987
+ constructor(classificationMessage, diagnosticMessage) {
988
+ super(classificationMessage, { kind: "envelope" });
989
+ this.diagnosticMessage = diagnosticMessage;
990
+ }
991
+ };
2344
992
  function parseConnectEndStream(data) {
2345
993
  try {
2346
994
  const error = JSON.parse(new TextDecoder().decode(data))?.error;
2347
- if (error) {
2348
- const code = typeof error.code === "string" ? error.code : "unknown";
2349
- const message = typeof error.message === "string" ? error.message : "Unknown error";
2350
- return new ProviderResponseError(`Connect error ${code}: ${message}`, { kind: "envelope" });
2351
- }
995
+ if (error) return new ConnectEndStreamError(`Connect error ${typeof error.code === "string" ? error.code : "unknown"}: ${typeof error.message === "string" ? error.message : "Unknown error"}`, formatConnectEndStreamError(error));
2352
996
  return null;
2353
997
  } catch {
2354
998
  return new ProviderResponseError("Failed to parse Connect end stream", { kind: "envelope" });
@@ -2456,10 +1100,10 @@ function omitTypeName(record) {
2456
1100
  const { $typeName: _, ...rest } = record;
2457
1101
  return rest;
2458
1102
  }
2459
- const streamCursor = (model, context, options) => {
1103
+ function streamCursorWithWireMode(model, context, options, wireMode, timing) {
2460
1104
  const stream = new AssistantMessageEventStream();
2461
1105
  (async () => {
2462
- const startTime = performance.now();
1106
+ const startTime = timing?.startTime ?? performance.now();
2463
1107
  let firstTokenTime;
2464
1108
  const output = {
2465
1109
  role: "assistant",
@@ -2482,7 +1126,7 @@ const streamCursor = (model, context, options) => {
2482
1126
  }
2483
1127
  },
2484
1128
  stopReason: "stop",
2485
- timestamp: Date.now()
1129
+ timestamp: timing?.timestamp ?? Date.now()
2486
1130
  };
2487
1131
  const inFlightDispatches = /* @__PURE__ */ new Set();
2488
1132
  let abortSettled;
@@ -2490,7 +1134,7 @@ const streamCursor = (model, context, options) => {
2490
1134
  const signal = options?.signal;
2491
1135
  while (inFlightDispatches.size > 0) {
2492
1136
  if (signal?.aborted) return;
2493
- const settled = Promise.all([...inFlightDispatches]);
1137
+ const settled = Promise.all(inFlightDispatches);
2494
1138
  if (!signal) {
2495
1139
  await settled;
2496
1140
  continue;
@@ -2507,6 +1151,7 @@ const streamCursor = (model, context, options) => {
2507
1151
  let h2Settled = false;
2508
1152
  let sawTurnEnded = false;
2509
1153
  let endStreamError = null;
1154
+ let sawProgressOrSideEffect = false;
2510
1155
  let openBlockState;
2511
1156
  const settleH2 = (error) => {
2512
1157
  if (h2Settled) return;
@@ -2528,21 +1173,27 @@ const streamCursor = (model, context, options) => {
2528
1173
  let baseConversationId;
2529
1174
  let conversationId;
2530
1175
  let usageState;
1176
+ let serializedFallbackWireModelId;
2531
1177
  try {
2532
1178
  const apiKey = options?.apiKey;
2533
1179
  if (!apiKey) throw new MissingApiKeyError(void 0, "Cursor API key (access token) is required");
2534
1180
  baseConversationId = options?.conversationId ?? options?.sessionId ?? crypto.randomUUID();
2535
1181
  conversationId = rotatedConversationIds.get(baseConversationId) ?? baseConversationId;
1182
+ const rotatedFresh = freshRotatedConversationIds.has(conversationId);
2536
1183
  const blobStore = conversationBlobStores.get(conversationId) ?? /* @__PURE__ */ new Map();
2537
1184
  conversationBlobStores.set(conversationId, blobStore);
2538
- const cachedState = conversationStateCache.get(conversationId);
2539
- const { requestBytes, conversationState } = buildGrpcRequest(model, context, options, {
1185
+ const cachedState = rotatedFresh ? void 0 : conversationStateCache.get(conversationId);
1186
+ const builtRequest = await buildGrpcRequestForWireMode(model, context, options, {
2540
1187
  conversationId,
2541
1188
  blobStore,
2542
- conversationState: cachedState
2543
- });
1189
+ conversationState: cachedState,
1190
+ rotatedFresh
1191
+ }, wireMode);
1192
+ const { requestBytes, conversationState } = builtRequest;
1193
+ serializedFallbackWireModelId = builtRequest.fallbackWireModelId;
2544
1194
  conversationStateCache.set(conversationId, conversationState);
2545
- const requestContextTools = buildMcpToolDefinitions(context.tools);
1195
+ const requestContextTools = buildMcpToolDefinitions(context.tools, model.requiresCursorToolSchemaProjection === true);
1196
+ const requestContextRules = buildCursorRequestContextRules(context.systemPrompt);
2546
1197
  const baseUrl = model.baseUrl || "https://api2.cursor.sh";
2547
1198
  const requestPath = "/agent.v1.AgentService/Run";
2548
1199
  const requestHeaders = {
@@ -2565,7 +1216,7 @@ const streamCursor = (model, context, options) => {
2565
1216
  headers: requestHeaders,
2566
1217
  bodyBase64: Buffer.from(requestBytes).toString("base64")
2567
1218
  }) : void 0;
2568
- const proxyUrl = shouldBypassProxy(new URL(baseUrl)) ? void 0 : getProxyForProvider(model.provider);
1219
+ const proxyUrl = getProxyForUrl(model.provider, new URL(baseUrl));
2569
1220
  if (proxyUrl) {
2570
1221
  const tlsSocket = await connectProxiedSocket(proxyUrl, baseUrl, {
2571
1222
  signal: options?.signal,
@@ -2643,8 +1294,10 @@ const streamCursor = (model, context, options) => {
2643
1294
  }
2644
1295
  try {
2645
1296
  const serverMessage = fromBinary(AgentServerMessageSchema, messageBytes);
2646
- const isTurnEnded = serverMessage.message.case === "interactionUpdate" && serverMessage.message.value.message?.case === "turnEnded";
2647
- const dispatch = handleServerMessage(serverMessage, output, stream, state, blobStore, h2Request, options?.execHandlers, options?.onToolResult, usageState, requestContextTools, onConversationCheckpoint).catch((error) => {
1297
+ const interactionCase = (serverMessage.message.case === "interactionUpdate" ? serverMessage.message.value : void 0)?.message?.case;
1298
+ if (interactionCase !== "heartbeat") sawProgressOrSideEffect = true;
1299
+ const isTurnEnded = interactionCase === "turnEnded";
1300
+ const dispatch = handleServerMessage(serverMessage, output, stream, state, blobStore, h2Request, options?.execHandlers, options?.onToolResult, usageState, requestContextTools, requestContextRules, onConversationCheckpoint, options?.externalToolExecutor).catch((error) => {
2648
1301
  log("error", "handleServerMessage", { error: String(error) });
2649
1302
  });
2650
1303
  inFlightDispatches.add(dispatch);
@@ -2688,11 +1341,15 @@ const streamCursor = (model, context, options) => {
2688
1341
  h2Request.write(frameConnectMessage(requestBytes));
2689
1342
  heartbeatTimer = setInterval(sendHeartbeat, 5e3);
2690
1343
  await h2Completion.promise;
1344
+ if (conversationId && baseConversationId && conversationId !== baseConversationId) {
1345
+ successfulRotatedConversationIds.add(conversationId);
1346
+ freshRotatedConversationIds.delete(conversationId);
1347
+ }
2691
1348
  await drainInFlightDispatches();
2692
1349
  endCurrentTextBlock(output, stream, state);
2693
1350
  endCurrentThinkingBlock(output, stream, state);
2694
1351
  flushOpenToolCalls(output, stream, state);
2695
- calculateCost(model, output.usage);
1352
+ calculateCost(model, output.usage, output.timestamp);
2696
1353
  output.duration = performance.now() - startTime;
2697
1354
  if (firstTokenTime) output.ttft = firstTokenTime - startTime;
2698
1355
  stream.push({
@@ -2702,6 +1359,30 @@ const streamCursor = (model, context, options) => {
2702
1359
  });
2703
1360
  stream.end();
2704
1361
  } catch (error) {
1362
+ if ((wireMode === "normalized" && !sawProgressOrSideEffect && !options?.signal?.aborted && error instanceof Error && CURSOR_MODEL_NOT_FOUND_PATTERN.test(error.message) ? serializedFallbackWireModelId : void 0) !== void 0) {
1363
+ if (heartbeatTimer) {
1364
+ clearInterval(heartbeatTimer);
1365
+ heartbeatTimer = null;
1366
+ }
1367
+ h2Request?.close();
1368
+ h2Client?.close();
1369
+ const fallbackStream = streamCursorWithWireMode(model, context, options, "discovered", {
1370
+ startTime,
1371
+ timestamp: output.timestamp
1372
+ });
1373
+ stream.forwardLocalWorkFrom(fallbackStream);
1374
+ try {
1375
+ for await (const event of fallbackStream) {
1376
+ if (event.type === "start") continue;
1377
+ stream.push(event);
1378
+ }
1379
+ const fallbackResult = await fallbackStream.result();
1380
+ if (!stream.resultSettled) stream.end(fallbackResult);
1381
+ } finally {
1382
+ stream.forwardLocalWorkFrom(void 0);
1383
+ }
1384
+ return;
1385
+ }
2705
1386
  await drainInFlightDispatches();
2706
1387
  if (openBlockState) {
2707
1388
  endCurrentTextBlock(output, stream, openBlockState);
@@ -2712,18 +1393,26 @@ const streamCursor = (model, context, options) => {
2712
1393
  api: model.api,
2713
1394
  signal: options?.signal
2714
1395
  });
2715
- if (conversationId !== void 0 && baseConversationId !== void 0 && usageState !== void 0 && !usageState.sawTokenDelta && RESOURCE_EXHAUSTED_PATTERN.test(result.message) && !rotatedConversationIds.has(baseConversationId)) {
1396
+ const currentRotated = baseConversationId === void 0 ? void 0 : rotatedConversationIds.get(baseConversationId);
1397
+ const canRotate = currentRotated === void 0 || successfulRotatedConversationIds.has(currentRotated);
1398
+ if (conversationId !== void 0 && baseConversationId !== void 0 && usageState !== void 0 && !usageState.sawTokenDelta && RESOURCE_EXHAUSTED_PATTERN.test(result.message) && canRotate) {
2716
1399
  const rotated = crypto.randomUUID();
1400
+ if (currentRotated) successfulRotatedConversationIds.delete(currentRotated);
2717
1401
  rotatedConversationIds.set(baseConversationId, rotated);
2718
- const state = conversationStateCache.get(conversationId);
2719
- if (state) conversationStateCache.set(rotated, state);
2720
- const blobs = conversationBlobStores.get(conversationId);
2721
- if (blobs) conversationBlobStores.set(rotated, blobs);
1402
+ freshRotatedConversationIds.add(rotated);
1403
+ debug("cursor conversation rotated", {
1404
+ base: baseConversationId,
1405
+ from: conversationId,
1406
+ to: rotated
1407
+ });
2722
1408
  }
2723
1409
  output.stopReason = result.stopReason;
2724
1410
  output.errorStatus = result.status;
2725
1411
  output.errorId = result.id;
2726
- output.errorMessage = result.message;
1412
+ if (error instanceof ConnectEndStreamError) {
1413
+ output.errorClassificationMessage = result.message;
1414
+ output.errorMessage = error.diagnosticMessage;
1415
+ } else output.errorMessage = result.message;
2727
1416
  output.duration = performance.now() - startTime;
2728
1417
  if (firstTokenTime) output.ttft = firstTokenTime - startTime;
2729
1418
  stream.push({
@@ -2743,19 +1432,57 @@ const streamCursor = (model, context, options) => {
2743
1432
  }
2744
1433
  })();
2745
1434
  return stream;
2746
- };
1435
+ }
1436
+ /** Streams a Cursor Agent turn, retrying a discovered effort id when its normalized wire id is unavailable. */
1437
+ const streamCursor = (model, context, options) => streamCursorWithWireMode(model, context, options, "normalized");
2747
1438
  function markCursorExecResolved(block) {
2748
1439
  block[kCursorExecResolved] = true;
2749
1440
  }
2750
1441
  /** Exported for tests: drives one Cursor server message through the stream (exec waits mark the stream busy). */
2751
- async function handleServerMessage(msg, output, stream, state, blobStore, h2Request, execHandlers, onToolResult, usageState, requestContextTools, onConversationCheckpoint) {
1442
+ async function handleServerMessage(msg, output, stream, state, blobStore, h2Request, execHandlers, onToolResult, usageState, requestContextTools, requestContextRules = [], onConversationCheckpoint, externalToolExecutor = false) {
2752
1443
  const msgCase = msg.message.case;
2753
1444
  log("serverMessage", msgCase, msg.message.value);
2754
1445
  if (msgCase === "interactionUpdate") processInteractionUpdate(msg.message.value, output, stream, state, usageState);
2755
1446
  else if (msgCase === "kvServerMessage") handleKvServerMessage(msg.message.value, blobStore, h2Request);
2756
- else if (msgCase === "execServerMessage") await stream.trackLocalWork(handleExecServerMessage(msg.message.value, h2Request, execHandlers, onToolResult, requestContextTools, output, stream, state));
1447
+ else if (msgCase === "execServerMessage") await stream.trackLocalWork(handleExecServerMessage(msg.message.value, h2Request, execHandlers, onToolResult, requestContextTools, requestContextRules, output, stream, state, externalToolExecutor));
1448
+ else if (msgCase === "interactionQuery") handleInteractionQuery(msg.message.value, h2Request);
2757
1449
  else if (msgCase === "conversationCheckpointUpdate") handleConversationCheckpointUpdate(msg.message.value, output, usageState, onConversationCheckpoint);
2758
1450
  }
1451
+ function selectHostedFetchCall(toolCall) {
1452
+ const oneof = toolCall?.tool;
1453
+ if (oneof?.case === "fetchToolCall" || oneof?.case === "webFetchToolCall") return oneof.value;
1454
+ }
1455
+ function hostedFetchUnknown(toolCall) {
1456
+ if (!toolCall) return false;
1457
+ return protoUnknownFields(toolCall).some((field) => field.no === 37) || protoUnknownFields(toolCall.tool ?? {}).some((field) => field.no === 37);
1458
+ }
1459
+ function extractHttpUrlFromUnknown(message) {
1460
+ for (const field of protoUnknownFields(message)) {
1461
+ const match = new TextDecoder().decode(field.data).match(/https?:\/\/[^\x00-\x1f]+/);
1462
+ if (match) return match[0];
1463
+ }
1464
+ const nested = message.tool;
1465
+ return nested ? extractHttpUrlFromUnknown(nested) : void 0;
1466
+ }
1467
+ function describeHostedFetchResult(call) {
1468
+ const result = call?.result?.result;
1469
+ if (result?.case === "success") return {
1470
+ text: result.value?.content || result.value?.url || "Fetched",
1471
+ isError: false
1472
+ };
1473
+ if (result?.case === "error") return {
1474
+ text: result.value?.error || "Fetch failed",
1475
+ isError: true
1476
+ };
1477
+ return {
1478
+ text: "Fetch completed",
1479
+ isError: false
1480
+ };
1481
+ }
1482
+ function protoUnknownFields(message) {
1483
+ const raw = message.$unknown;
1484
+ return Array.isArray(raw) ? raw : [];
1485
+ }
2759
1486
  function handleKvServerMessage(kvMsg, blobStore, h2Request) {
2760
1487
  const kvCase = kvMsg.message.case;
2761
1488
  if (kvCase === "getBlobArgs") {
@@ -3019,7 +1746,7 @@ function sendShellStreamExitFromResult(h2Request, execMsg, execResult, sendBuffe
3019
1746
  default: return;
3020
1747
  }
3021
1748
  }
3022
- async function handleExecServerMessage(execMsg, h2Request, execHandlers, onToolResult, requestContextTools, output, stream, state) {
1749
+ async function handleExecServerMessage(execMsg, h2Request, execHandlers, onToolResult, requestContextTools, requestContextRules, output, stream, state, externalToolExecutor) {
3023
1750
  const execCase = execMsg.message.case;
3024
1751
  log("exec", "dispatch", {
3025
1752
  execCase,
@@ -3028,7 +1755,7 @@ async function handleExecServerMessage(execMsg, h2Request, execHandlers, onToolR
3028
1755
  });
3029
1756
  if (execCase === "requestContextArgs") {
3030
1757
  const requestContext = create(RequestContextSchema, {
3031
- rules: [],
1758
+ rules: requestContextRules,
3032
1759
  repositoryInfo: [],
3033
1760
  tools: requestContextTools,
3034
1761
  gitRepos: [],
@@ -3056,8 +1783,16 @@ async function handleExecServerMessage(execMsg, h2Request, execHandlers, onToolR
3056
1783
  case "readArgs": {
3057
1784
  const args = execMsg.message.value;
3058
1785
  if (!args.toolCallId) args.toolCallId = crypto.randomUUID();
3059
- synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "read", { path: piReadDisplayPath(args.path, args.offset, args.limit) });
3060
- const { execResult } = await resolveExecHandler(args, execHandlers?.read?.bind(execHandlers), onToolResult, (toolResult) => buildReadResultFromToolResult(args.path, toolResult, args.offset !== void 0 || args.limit !== void 0 || piReadPathHasRange(args.path)), (reason) => buildReadRejectedResult(args.path, reason), (error) => buildReadErrorResult(args.path, error), {
1786
+ const editOwned = isEditOwnedToolCallId(state, output, args.toolCallId);
1787
+ const composed = editOwned ? cursorEditOwnedReadPath(args.path, args.offset, args.limit) : args.path;
1788
+ const handlerArgs = editOwned ? composed === null ? args : {
1789
+ ...args,
1790
+ path: composed,
1791
+ offset: void 0,
1792
+ limit: void 0
1793
+ } : args;
1794
+ if (!editOwned) synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "read", { path: piReadDisplayPath(args.path, args.offset, args.limit) });
1795
+ const { execResult } = await resolveExecHandler(handlerArgs, execHandlers?.read?.bind(execHandlers), editOwned ? void 0 : onToolResult, (toolResult) => buildReadResultFromToolResult(args.path, toolResult, args.offset !== void 0 || args.limit !== void 0 || piReadPathHasRange(args.path)), (reason) => buildReadRejectedResult(args.path, reason), (error) => buildReadErrorResult(args.path, error), editOwned ? null : {
3061
1796
  toolCallId: args.toolCallId,
3062
1797
  toolName: "read"
3063
1798
  });
@@ -3100,20 +1835,26 @@ async function handleExecServerMessage(execMsg, h2Request, execHandlers, onToolR
3100
1835
  case "writeArgs": {
3101
1836
  const args = execMsg.message.value;
3102
1837
  if (!args.toolCallId) args.toolCallId = crypto.randomUUID();
1838
+ const editOwned = isEditOwnedToolCallId(state, output, args.toolCallId);
3103
1839
  const content = args.fileText ?? new TextDecoder().decode(args.fileBytes ?? /* @__PURE__ */ new Uint8Array());
3104
- synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "write", {
1840
+ if (!editOwned) synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "write", {
3105
1841
  path: args.path,
3106
1842
  content
3107
1843
  });
3108
- const { execResult } = await resolveExecHandler(args, execHandlers?.write?.bind(execHandlers), onToolResult, (toolResult) => buildWriteResultFromToolResult({
1844
+ const write = execHandlers?.write?.bind(execHandlers);
1845
+ const { execResult } = await resolveExecHandler(args, write ? async (writeArgs) => {
1846
+ const result = await write(writeArgs);
1847
+ return editOwned ? remapExecHandlerToolName(result, "edit") : result;
1848
+ } : void 0, onToolResult, (toolResult) => buildWriteResultFromToolResult({
3109
1849
  path: args.path,
3110
1850
  fileText: args.fileText,
3111
1851
  fileBytes: args.fileBytes,
3112
1852
  returnFileContentAfterWrite: args.returnFileContentAfterWrite
3113
1853
  }, toolResult), (reason) => buildWriteRejectedResult(args.path, reason), (error) => buildWriteErrorResult(args.path, error), {
3114
1854
  toolCallId: args.toolCallId,
3115
- toolName: "write"
1855
+ toolName: editOwned ? "edit" : "write"
3116
1856
  });
1857
+ if (editOwned) markEditToolCallPaired(state, args.toolCallId);
3117
1858
  sendExecClientMessage(h2Request, execMsg, "writeResult", execResult);
3118
1859
  return;
3119
1860
  }
@@ -3226,7 +1967,7 @@ async function handleExecServerMessage(execMsg, h2Request, execHandlers, onToolR
3226
1967
  state.resolvedMcpToolCallIds.add(mcpCall.toolCallId);
3227
1968
  }
3228
1969
  }
3229
- const { execResult } = await resolveExecHandler(mcpCall, execHandlers?.mcp?.bind(execHandlers), onToolResult, (toolResult) => buildMcpResultFromToolResult(mcpCall, toolResult), (_reason) => buildMcpToolNotFoundResult(mcpCall), (error) => buildMcpErrorResult(error), execHandlers?.mcp ? {
1970
+ const { execResult } = await resolveExecHandler(mcpCall, execHandlers?.mcp?.bind(execHandlers), onToolResult, (toolResult) => buildMcpResultFromToolResult(mcpCall, toolResult), (_reason) => externalToolExecutor && !execHandlers?.mcp ? buildMcpExternalHandoffResult() : buildMcpToolNotFoundResult(mcpCall), (error) => buildMcpErrorResult(error), execHandlers?.mcp ? {
3230
1971
  toolCallId: mcpCall.toolCallId,
3231
1972
  toolName: mcpCall.toolName
3232
1973
  } : null);
@@ -3717,7 +2458,7 @@ async function resolveExecHandler(args, handler, onToolResult, buildFromToolResu
3717
2458
  }
3718
2459
  /**
3719
2460
  * Derive the transcript state of an exec result the SDK handler returned in the
3720
- * TResult-only form, which carries no `toolResult` to copy it from.
2461
+ * R-only form, which carries no `toolResult` to copy it from.
3721
2462
  *
3722
2463
  * Every exec result in `agent.proto` is a `oneof result` whose success variant
3723
2464
  * is named `success` — the rest (`error`, `rejected`, `file_not_found`,
@@ -4203,9 +2944,11 @@ function parseToolArgsJson(text) {
4203
2944
  }
4204
2945
  function decodeMcpArgValue(value) {
4205
2946
  try {
4206
- const parsedValue = fromBinary(ValueSchema, value);
4207
- const jsonValue = toJson(ValueSchema, parsedValue);
4208
- if (typeof jsonValue === "string") return parseToolArgsJson(jsonValue);
2947
+ const jsonValue = decodeJsonValue(value);
2948
+ if (typeof jsonValue === "string") {
2949
+ const first = jsonValue.trimStart()[0];
2950
+ return first === "{" || first === "[" || first === "\"" ? parseToolArgsJson(jsonValue) : jsonValue;
2951
+ }
4209
2952
  return jsonValue;
4210
2953
  } catch {}
4211
2954
  return parseToolArgsJson(new TextDecoder().decode(value));
@@ -4271,6 +3014,141 @@ function selectMcpCall(toolCall) {
4271
3014
  return toolCall?.mcpToolCall;
4272
3015
  }
4273
3016
  /**
3017
+ * Same oneof-first selector as MCP: a wire-decoded `ToolCall` exposes
3018
+ * `editToolCall` only as `{ case: "editToolCall", value }`.
3019
+ */
3020
+ function selectEditCall(toolCall) {
3021
+ const oneof = toolCall?.tool;
3022
+ if (oneof?.case === "editToolCall") return oneof.value;
3023
+ return toolCall?.editToolCall;
3024
+ }
3025
+ function selectEditStreamDelta(update) {
3026
+ const oneof = update.toolCallDelta?.delta;
3027
+ if (oneof?.case === "editToolCallDelta") return oneof.value?.streamContentDelta;
3028
+ return update.toolCallDelta?.editToolCallDelta?.streamContentDelta;
3029
+ }
3030
+ function rememberEditOwnedToolCall(state, toolCall, envelopeId) {
3031
+ if (!state.editOwnedToolCallIds) state.editOwnedToolCallIds = /* @__PURE__ */ new Set();
3032
+ const ids = state.editOwnedToolCallIds;
3033
+ if (envelopeId) ids.add(envelopeId);
3034
+ if (toolCall?.toolCallId) ids.add(toolCall.toolCallId);
3035
+ }
3036
+ function isEditOwnedToolCallId(state, output, toolCallId) {
3037
+ if (state.editOwnedToolCallIds?.has(toolCallId)) return true;
3038
+ return output.content.some((block) => block.type === "toolCall" && block.id === toolCallId && block.name === "edit");
3039
+ }
3040
+ function stringToolArg(args, key) {
3041
+ const value = args?.[key];
3042
+ return typeof value === "string" ? value : void 0;
3043
+ }
3044
+ function markEditToolCallPaired(state, toolCallId) {
3045
+ if (!state.pairedEditToolCallIds) state.pairedEditToolCallIds = /* @__PURE__ */ new Set();
3046
+ state.pairedEditToolCallIds.add(toolCallId);
3047
+ }
3048
+ /**
3049
+ * `EditToolCall.result` is an `EditResult` message whose own oneof is also
3050
+ * named `result`. The discriminator is `result.result.case`, same nesting as
3051
+ * `describeConnectScmResult` / the todo extractors.
3052
+ */
3053
+ function describeEditResult(toolCall) {
3054
+ const oneof = selectEditCall(toolCall)?.result?.result;
3055
+ const variant = oneof?.case;
3056
+ const value = oneof?.value;
3057
+ if (variant === "success") return {
3058
+ text: value?.message || value?.path || "Edited",
3059
+ isError: false
3060
+ };
3061
+ if (variant === "error") return {
3062
+ text: value?.modelVisibleError || value?.error || "Edit failed",
3063
+ isError: true
3064
+ };
3065
+ if (variant === "rejected") return {
3066
+ text: value?.reason || "Edit rejected",
3067
+ isError: true
3068
+ };
3069
+ if (variant === "fileNotFound") return {
3070
+ text: value?.path ? `File not found: ${value.path}` : "File not found",
3071
+ isError: true
3072
+ };
3073
+ if (variant === "readPermissionDenied") return {
3074
+ text: value?.path ? `Read permission denied: ${value.path}` : "Read permission denied",
3075
+ isError: true
3076
+ };
3077
+ if (variant === "writePermissionDenied") return {
3078
+ text: value?.error || (value?.path ? `Write permission denied: ${value.path}` : "Write permission denied"),
3079
+ isError: true
3080
+ };
3081
+ return {
3082
+ text: "Edit reported no result",
3083
+ isError: true
3084
+ };
3085
+ }
3086
+ function remapExecHandlerToolName(result, toolName) {
3087
+ if (isToolResultMessage(result)) return {
3088
+ ...result,
3089
+ toolName
3090
+ };
3091
+ if (result && typeof result === "object" && "toolResult" in result) {
3092
+ const record = result;
3093
+ if (record.toolResult && record.result !== void 0) return {
3094
+ result: record.result,
3095
+ toolResult: {
3096
+ ...record.toolResult,
3097
+ toolName
3098
+ }
3099
+ };
3100
+ if (record.toolResult) return {
3101
+ ...record.toolResult,
3102
+ toolName
3103
+ };
3104
+ }
3105
+ return result;
3106
+ }
3107
+ /**
3108
+ * Open (or refresh) the single `edit` transcript block for a native StrReplace
3109
+ * `editToolCall`. Materialization reads/writes reuse this id and must not
3110
+ * synthesize their own blocks.
3111
+ */
3112
+ function openOrUpdateEditBlock(output, stream, state, toolCall, envelopeId) {
3113
+ const edit = selectEditCall(toolCall);
3114
+ if (!edit && toolCall?.tool?.case !== "editToolCall") return void 0;
3115
+ rememberEditOwnedToolCall(state, toolCall, envelopeId);
3116
+ const id = toolCall?.toolCallId || envelopeId;
3117
+ if (!id) return void 0;
3118
+ const nextArgs = omitUndefinedArgs({
3119
+ path: edit?.args?.path,
3120
+ stream_content: edit?.args?.streamContent
3121
+ });
3122
+ const existing = output.content.find((block) => block.type === "toolCall" && block.id === id);
3123
+ if (existing) {
3124
+ existing.arguments = {
3125
+ ...existing.arguments,
3126
+ ...nextArgs
3127
+ };
3128
+ return existing;
3129
+ }
3130
+ endCurrentTextBlock(output, stream, state);
3131
+ endCurrentThinkingBlock(output, stream, state);
3132
+ const block = {
3133
+ type: "toolCall",
3134
+ id,
3135
+ name: "edit",
3136
+ arguments: nextArgs,
3137
+ [kStreamingBlockIndex]: output.content.length,
3138
+ [kStreamingBlockKind]: "cursor-edit",
3139
+ [kStreamingEnvelopeId]: envelopeId || void 0,
3140
+ [kCursorExecResolved]: true
3141
+ };
3142
+ output.content.push(block);
3143
+ retainStreamedCall(state, block, envelopeId);
3144
+ stream.push({
3145
+ type: "toolcall_start",
3146
+ contentIndex: output.content.length - 1,
3147
+ partial: output
3148
+ });
3149
+ return block;
3150
+ }
3151
+ /**
4274
3152
  * The streamed `ToolCall` variants whose block the exec channel owns.
4275
3153
  *
4276
3154
  * Each of these is announced on the interaction stream AND dispatched as its
@@ -4348,17 +3226,19 @@ function flushOpenToolCalls(output, stream, state) {
4348
3226
  clearStreamingPartialJson(block);
4349
3227
  }
4350
3228
  const kind = block[kStreamingBlockKind];
4351
- if (kind === "connect-scm" || kind === "todo") state.onToolResult?.({
4352
- role: "toolResult",
4353
- toolCallId: block.id,
4354
- toolName: block.name,
4355
- content: [{
4356
- type: "text",
4357
- text: "The connection to Cursor closed before this call completed."
4358
- }],
4359
- isError: true,
4360
- timestamp: Date.now()
4361
- });
3229
+ if (kind === "connect-scm" || kind === "todo" || kind === "cursor-edit") {
3230
+ if (!(kind === "cursor-edit" && state.pairedEditToolCallIds?.has(block.id))) state.onToolResult?.({
3231
+ role: "toolResult",
3232
+ toolCallId: block.id,
3233
+ toolName: block.name,
3234
+ content: [{
3235
+ type: "text",
3236
+ text: "The connection to Cursor closed before this call completed."
3237
+ }],
3238
+ isError: true,
3239
+ timestamp: Date.now()
3240
+ });
3241
+ }
4362
3242
  stream.push({
4363
3243
  type: "toolcall_end",
4364
3244
  contentIndex: idx,
@@ -4579,6 +3459,19 @@ function buildMcpResultFromToolResult(_mcpCall, toolResult) {
4579
3459
  })
4580
3460
  } });
4581
3461
  }
3462
+ const MCP_EXTERNAL_HANDOFF_MESSAGE = cursor_external_tool_handoff_default.trim();
3463
+ function buildMcpExternalHandoffResult() {
3464
+ return create(McpResultSchema, { result: {
3465
+ case: "success",
3466
+ value: create(McpSuccessSchema, {
3467
+ content: [create(McpToolResultContentItemSchema, { content: {
3468
+ case: "text",
3469
+ value: create(McpTextContentSchema, { text: MCP_EXTERNAL_HANDOFF_MESSAGE })
3470
+ } })],
3471
+ isError: false
3472
+ })
3473
+ } });
3474
+ }
4582
3475
  function buildMcpToolNotFoundResult(mcpCall) {
4583
3476
  return create(McpResultSchema, { result: {
4584
3477
  case: "toolNotFound",
@@ -4611,7 +3504,7 @@ function buildMcpErrorResult(error) {
4611
3504
  * - otherwise → completion wins.
4612
3505
  */
4613
3506
  function mergeCursorMcpToolCallArgs(streamed, completion) {
4614
- const merged = { ...streamed ?? {} };
3507
+ const merged = { ...streamed };
4615
3508
  if (!completion) return merged;
4616
3509
  for (const [key, completionValue] of Object.entries(completion)) {
4617
3510
  const streamedValue = merged[key];
@@ -4819,9 +3712,8 @@ function processInteractionUpdate(update, output, stream, state, usageState) {
4819
3712
  type: "toolCall",
4820
3713
  id,
4821
3714
  name: args.toolName || args.name || "",
4822
- arguments: {},
3715
+ arguments: decodeMcpArgsMap(args.args) ?? {},
4823
3716
  [kStreamingBlockIndex]: output.content.length,
4824
- [kStreamingPartialJson]: "",
4825
3717
  [kStreamingBlockKind]: "mcp",
4826
3718
  [kStreamingEnvelopeId]: update.message.value.callId || void 0
4827
3719
  };
@@ -4854,10 +3746,55 @@ function processInteractionUpdate(update, output, stream, state, usageState) {
4854
3746
  contentIndex: output.content.length - 1,
4855
3747
  partial: output
4856
3748
  });
3749
+ return;
3750
+ }
3751
+ const fetchCall = selectHostedFetchCall(toolCall);
3752
+ if (fetchCall || hostedFetchUnknown(toolCall)) {
3753
+ const url = fetchCall?.args?.url || extractHttpUrlFromUnknown(toolCall);
3754
+ const block = {
3755
+ type: "toolCall",
3756
+ id: fetchCall?.args?.toolCallId || update.message.value.callId || crypto.randomUUID(),
3757
+ name: "web_fetch",
3758
+ arguments: url ? { url } : {},
3759
+ [kStreamingBlockIndex]: output.content.length,
3760
+ [kStreamingBlockKind]: "web-fetch",
3761
+ [kStreamingEnvelopeId]: update.message.value.callId || void 0,
3762
+ [kCursorExecResolved]: true
3763
+ };
3764
+ output.content.push(block);
3765
+ retainStreamedCall(state, block, update.message.value.callId);
3766
+ stream.push({
3767
+ type: "toolcall_start",
3768
+ contentIndex: output.content.length - 1,
3769
+ partial: output
3770
+ });
3771
+ return;
4857
3772
  }
3773
+ openOrUpdateEditBlock(output, stream, state, toolCall, update.message.value.callId);
4858
3774
  }
4859
3775
  } else if (updateCase === "toolCallDelta" || updateCase === "partialToolCall") {
4860
- const target = resolveStreamedCall(state, update.message.value.callId);
3776
+ const value = update.message.value;
3777
+ if (updateCase === "partialToolCall" && value.toolCall) openOrUpdateEditBlock(output, stream, state, value.toolCall, value.callId);
3778
+ const editDelta = selectEditStreamDelta(value);
3779
+ if (editDelta) {
3780
+ const target = resolveStreamedCall(state, value.callId);
3781
+ if (target?.[kStreamingBlockKind] === "cursor-edit") {
3782
+ const current = stringToolArg(target.arguments, "stream_content") ?? "";
3783
+ target.arguments = {
3784
+ ...target.arguments,
3785
+ stream_content: current + editDelta
3786
+ };
3787
+ const idx = output.content.indexOf(target);
3788
+ stream.push({
3789
+ type: "toolcall_delta",
3790
+ contentIndex: idx,
3791
+ delta: editDelta,
3792
+ partial: output
3793
+ });
3794
+ return;
3795
+ }
3796
+ }
3797
+ const target = resolveStreamedCall(state, value.callId);
4861
3798
  if (target?.[kStreamingBlockKind] === "mcp") {
4862
3799
  const snapshot = update.message.value.argsTextDelta || "";
4863
3800
  const current = target[kStreamingPartialJson] ?? "";
@@ -4884,7 +3821,7 @@ function processInteractionUpdate(update, output, stream, state, usageState) {
4884
3821
  const toolCall = update.message.value.toolCall;
4885
3822
  if (settled[kStreamingBlockKind] === "mcp") {
4886
3823
  const partial = settled[kStreamingPartialJson];
4887
- if (partial !== void 0) settled.arguments = parseStreamingJson(partial);
3824
+ if (partial) settled.arguments = parseStreamingJson(partial);
4888
3825
  const decodedArgs = decodeMcpArgsMap(selectMcpCall(toolCall)?.args?.args);
4889
3826
  settled.arguments = mergeCursorMcpToolCallArgs(settled.arguments, decodedArgs);
4890
3827
  } else if (settled[kStreamingBlockKind] === "connect-scm") {
@@ -4906,6 +3843,22 @@ function processInteractionUpdate(update, output, stream, state, usageState) {
4906
3843
  isError,
4907
3844
  timestamp: Date.now()
4908
3845
  });
3846
+ } else if (settled[kStreamingBlockKind] === "web-fetch") {
3847
+ const fetchCall = selectHostedFetchCall(toolCall);
3848
+ const url = fetchCall?.args?.url || extractHttpUrlFromUnknown(toolCall ?? {});
3849
+ if (url) settled.arguments = { url };
3850
+ const { text, isError } = describeHostedFetchResult(fetchCall);
3851
+ state.onToolResult?.({
3852
+ role: "toolResult",
3853
+ toolCallId: settled.id,
3854
+ toolName: "web_fetch",
3855
+ content: [{
3856
+ type: "text",
3857
+ text
3858
+ }],
3859
+ isError,
3860
+ timestamp: Date.now()
3861
+ });
4909
3862
  } else if (settled[kStreamingBlockKind] === "todo") {
4910
3863
  const snapshot = toolCall ? extractTodoSnapshot(toolCall) : null;
4911
3864
  const error = toolCall ? extractTodoError(toolCall) : null;
@@ -4922,6 +3875,27 @@ function processInteractionUpdate(update, output, stream, state, usageState) {
4922
3875
  log("error", "onTodoSnapshot", { error: hostError });
4923
3876
  }
4924
3877
  state.onToolResult?.(persisted ?? buildTodoToolResult(settled.id, snapshot, hostError ?? error));
3878
+ } else if (settled[kStreamingBlockKind] === "cursor-edit") {
3879
+ const edit = selectEditCall(toolCall);
3880
+ if (edit?.args) settled.arguments = omitUndefinedArgs({
3881
+ ...settled.arguments,
3882
+ path: edit.args.path ?? stringToolArg(settled.arguments, "path"),
3883
+ stream_content: edit.args.streamContent ?? stringToolArg(settled.arguments, "stream_content")
3884
+ });
3885
+ if (!state.pairedEditToolCallIds?.has(settled.id)) {
3886
+ const { text, isError } = describeEditResult(toolCall);
3887
+ state.onToolResult?.({
3888
+ role: "toolResult",
3889
+ toolCallId: settled.id,
3890
+ toolName: "edit",
3891
+ content: [{
3892
+ type: "text",
3893
+ text
3894
+ }],
3895
+ isError,
3896
+ timestamp: Date.now()
3897
+ });
3898
+ }
4925
3899
  }
4926
3900
  const idx = output.content.indexOf(settled);
4927
3901
  clearStreamingPartialJson(settled);
@@ -4935,7 +3909,7 @@ function processInteractionUpdate(update, output, stream, state, usageState) {
4935
3909
  }
4936
3910
  } else if (updateCase === "turnEnded") {
4937
3911
  output.stopReason = "stop";
4938
- if (isKimiK3ModelId(output.model) && !output.content.some((item) => item.type === "thinking" && item.thinking.length > 0)) warn("Cursor kimi-k3 turn completed without thinking blocks; persisted history will replay this turn without reasoning", {
3912
+ if (classifyModel("cursor", output.model).family === "k3" && !output.content.some((item) => item.type === "thinking" && item.thinking.length > 0)) warn("Cursor kimi-k3 turn completed without thinking blocks; persisted history will replay this turn without reasoning", {
4939
3913
  model: output.model,
4940
3914
  messageTimestamp: output.timestamp
4941
3915
  });
@@ -4962,6 +3936,23 @@ function storeCursorBlob(blobStore, data) {
4962
3936
  return blobId;
4963
3937
  }
4964
3938
  /**
3939
+ * Cursor AgentService reconstructs the model prompt from `requestContext.rules`,
3940
+ * not from the client-supplied `rootPromptMessagesJson` system blobs. Map each
3941
+ * OMP system-prompt entry to a global CursorRule so always-apply rules survive
3942
+ * that reconstruction.
3943
+ */
3944
+ function buildCursorRequestContextRules(systemPrompt) {
3945
+ return normalizeSystemPrompts(systemPrompt).map((content, index) => create(CursorRuleSchema, {
3946
+ fullPath: `/omp/system-prompt/${index}.mdc`,
3947
+ content,
3948
+ source: 2,
3949
+ type: create(CursorRuleTypeSchema, { type: {
3950
+ case: "global",
3951
+ value: create(CursorRuleTypeGlobalSchema, {})
3952
+ } })
3953
+ }));
3954
+ }
3955
+ /**
4965
3956
  * Local tools Cursor already drives natively over the exec channel, so
4966
3957
  * advertising them again as MCP tools would give the model two ways to call the
4967
3958
  * same thing.
@@ -4981,18 +3972,28 @@ const CURSOR_NATIVE_TOOL_NAMES = /* @__PURE__ */ new Set([
4981
3972
  "grep",
4982
3973
  "todo"
4983
3974
  ]);
4984
- function buildMcpToolDefinitions(tools) {
3975
+ function isJsonValue(value) {
3976
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
3977
+ if (typeof value === "number") return Number.isFinite(value);
3978
+ if (Array.isArray(value)) return value.every(isJsonValue);
3979
+ if (!isRecord$1(value)) return false;
3980
+ for (const key in value) if (!isJsonValue(value[key])) return false;
3981
+ return true;
3982
+ }
3983
+ function buildMcpToolDefinitions(tools, requiresCursorToolSchemaProjection = false) {
4985
3984
  if (!tools || tools.length === 0) return [];
4986
3985
  const advertisedTools = tools.filter((tool) => !CURSOR_NATIVE_TOOL_NAMES.has(tool.name));
4987
3986
  if (advertisedTools.length === 0) return [];
4988
3987
  const writeTool = tools.find((tool) => tool.name === "write");
4989
3988
  return (writeTool ? [...advertisedTools, writeTool] : advertisedTools).map((tool) => {
4990
- const jsonSchema = toolWireSchema(tool);
4991
- const inputSchema = toBinary(ValueSchema, fromJson(ValueSchema, jsonSchema && typeof jsonSchema === "object" ? jsonSchema : {
3989
+ const wireSchema = toolWireSchema(tool);
3990
+ const jsonSchema = requiresCursorToolSchemaProjection ? sanitizeSchemaForCursor(wireSchema) : wireSchema;
3991
+ const schemaValue = jsonSchema !== null && !Array.isArray(jsonSchema) && isJsonValue(jsonSchema) ? jsonSchema : {
4992
3992
  type: "object",
4993
3993
  properties: {},
4994
3994
  required: []
4995
- }));
3995
+ };
3996
+ const inputSchema = encodeJsonValue(schemaValue);
4996
3997
  return create(McpToolDefinitionSchema, {
4997
3998
  name: tool.name,
4998
3999
  description: tool.description || "",
@@ -5050,7 +4051,7 @@ function cursorUserContentKey(content) {
5050
4051
  return hash.digest("hex");
5051
4052
  }
5052
4053
  function canReplayCursorThinking(msg, targetModelId) {
5053
- return targetModelId !== void 0 && isKimiK3ModelId(targetModelId) && msg.api === "cursor-agent" && msg.provider === "cursor" && msg.model === targetModelId;
4054
+ return targetModelId !== void 0 && classifyModel("cursor", targetModelId).family === "k3" && msg.api === "cursor-agent" && msg.provider === "cursor" && msg.model === targetModelId;
5054
4055
  }
5055
4056
  function buildCursorAssistantContent(msg, targetModelId) {
5056
4057
  const content = [];
@@ -5069,14 +4070,14 @@ function buildCursorAssistantContent(msg, targetModelId) {
5069
4070
  });
5070
4071
  } else if (item.type === "toolCall") content.push({
5071
4072
  type: "tool-call",
5072
- toolCallId: item.id,
4073
+ toolCallId: normalizeToolCallId(item.id),
5073
4074
  toolName: item.name,
5074
- args: item.arguments
4075
+ args: normalizeCursorMcpArguments(item.arguments)
5075
4076
  });
5076
4077
  return content;
5077
4078
  }
5078
4079
  function assertCursorKimiK3HistoryReplayable(messages, activeUserMessageIndex, targetModelId) {
5079
- if (!targetModelId || !isKimiK3ModelId(targetModelId)) return;
4080
+ if (!targetModelId || classifyModel("cursor", targetModelId).family !== "k3") return;
5080
4081
  const historyEnd = activeUserMessageIndex >= 0 ? activeUserMessageIndex : messages.length;
5081
4082
  const missingThinkingTurns = [];
5082
4083
  const newlyWarnedKeys = [];
@@ -5142,8 +4143,27 @@ function buildCursorSystemPromptJsons(systemPrompt) {
5142
4143
  content
5143
4144
  }));
5144
4145
  }
4146
+ function collectCursorToolHistory(messages, historyEnd) {
4147
+ const toolResults = /* @__PURE__ */ new Map();
4148
+ const pairedToolCallIds = /* @__PURE__ */ new Set();
4149
+ for (let index = 0; index < historyEnd; index++) {
4150
+ const message = messages[index];
4151
+ if (message.role === "toolResult") toolResults.set(message.toolCallId, message);
4152
+ else if (message.role === "assistant") {
4153
+ for (const item of message.content) if (item.type === "toolCall") pairedToolCallIds.add(item.id);
4154
+ }
4155
+ }
4156
+ return {
4157
+ toolResults,
4158
+ pairedToolCallIds
4159
+ };
4160
+ }
4161
+ function cursorOrphanToolResultText(result) {
4162
+ return `${result.isError ? "[Tool Error]" : "[Tool Result]"}\n${toolResultToText(result) || "(empty result)"}`;
4163
+ }
5145
4164
  function buildRootPromptMessagesJson(messages, systemPromptIds, blobStore, activeUserMessageIndex = findLastUserMessageIndex(messages), targetModelId) {
5146
4165
  assertCursorKimiK3HistoryReplayable(messages, activeUserMessageIndex, targetModelId);
4166
+ const { pairedToolCallIds } = collectCursorToolHistory(messages, activeUserMessageIndex >= 0 ? activeUserMessageIndex : messages.length);
5147
4167
  const entries = [...systemPromptIds];
5148
4168
  const pushJson = (obj) => {
5149
4169
  const bytes = new TextEncoder().encode(JSON.stringify(obj));
@@ -5166,41 +4186,67 @@ function buildRootPromptMessagesJson(messages, systemPromptIds, blobStore, activ
5166
4186
  role: "assistant",
5167
4187
  content
5168
4188
  });
5169
- } else if (msg.role === "toolResult") pushJson({
5170
- role: "tool",
5171
- id: msg.toolCallId,
5172
- content: [{
5173
- type: "tool-result",
5174
- toolName: msg.toolName,
5175
- toolCallId: msg.toolCallId,
5176
- result: toolResultToText(msg),
5177
- ...msg.isError ? { isError: true } : {}
5178
- }]
5179
- });
4189
+ } else if (msg.role === "toolResult") {
4190
+ if (!pairedToolCallIds.has(msg.toolCallId)) {
4191
+ pushJson({
4192
+ role: "assistant",
4193
+ content: [{
4194
+ type: "text",
4195
+ text: cursorOrphanToolResultText(msg)
4196
+ }]
4197
+ });
4198
+ continue;
4199
+ }
4200
+ const toolCallId = normalizeToolCallId(msg.toolCallId);
4201
+ pushJson({
4202
+ role: "tool",
4203
+ id: toolCallId,
4204
+ content: [{
4205
+ type: "tool-result",
4206
+ toolName: msg.toolName,
4207
+ toolCallId,
4208
+ result: toolResultToText(msg),
4209
+ ...msg.isError ? { isError: true } : {}
4210
+ }]
4211
+ });
4212
+ }
5180
4213
  }
5181
4214
  return entries;
5182
4215
  }
5183
- function isPlainRecord(value) {
5184
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
5185
- const prototype = Object.getPrototypeOf(value);
5186
- return prototype === Object.prototype || prototype === null;
4216
+ function normalizeCursorMcpArgument(value, seen) {
4217
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4218
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
4219
+ if (typeof value !== "object") return void 0;
4220
+ if (seen.has(value)) return void 0;
4221
+ seen.add(value);
4222
+ try {
4223
+ if (Array.isArray(value)) return value.map((item) => normalizeCursorMcpArgument(item, seen) ?? null);
4224
+ if (!isRecord$1(value)) return void 0;
4225
+ const normalized = Object.create(null);
4226
+ for (const key in value) {
4227
+ if (!Object.hasOwn(value, key)) continue;
4228
+ const normalizedItem = normalizeCursorMcpArgument(value[key], seen);
4229
+ if (normalizedItem !== void 0) normalized[key] = normalizedItem;
4230
+ }
4231
+ return normalized;
4232
+ } finally {
4233
+ seen.delete(value);
4234
+ }
5187
4235
  }
5188
- function isJsonValue(value) {
5189
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
5190
- if (typeof value === "number") return Number.isFinite(value);
5191
- if (Array.isArray(value)) return value.every(isJsonValue);
5192
- if (!isPlainRecord(value)) return false;
5193
- for (const key in value) if (!isJsonValue(value[key])) return false;
5194
- return true;
4236
+ function normalizeCursorMcpArguments(args) {
4237
+ const normalized = Object.create(null);
4238
+ const seen = /* @__PURE__ */ new Set();
4239
+ for (const name in args) {
4240
+ if (!Object.hasOwn(args, name)) continue;
4241
+ const normalizedValue = normalizeCursorMcpArgument(args[name], seen);
4242
+ if (normalizedValue !== void 0) normalized[name] = normalizedValue;
4243
+ }
4244
+ return normalized;
5195
4245
  }
5196
4246
  function encodeCursorMcpArguments(toolCall) {
5197
- const encoded = {};
5198
- for (const name in toolCall.arguments) {
5199
- const value = toolCall.arguments[name];
5200
- if (value === void 0) continue;
5201
- if (!isJsonValue(value)) throw new ValidationError(`Cursor tool argument ${toolCall.name}.${name} is not JSON-serializable`);
5202
- encoded[name] = toBinary(ValueSchema, fromJson(ValueSchema, value));
5203
- }
4247
+ const encoded = Object.create(null);
4248
+ const normalized = normalizeCursorMcpArguments(toolCall.arguments);
4249
+ for (const name in normalized) encoded[name] = encodeJsonValue(normalized[name]);
5204
4250
  return encoded;
5205
4251
  }
5206
4252
  function createCursorMcpResult(result) {
@@ -5223,11 +4269,12 @@ function createCursorMcpResult(result) {
5223
4269
  } });
5224
4270
  }
5225
4271
  function createCursorToolCallStep(toolCall, result) {
4272
+ const toolCallId = normalizeToolCallId(toolCall.id);
5226
4273
  const mcpCall = create(McpToolCallSchema, {
5227
4274
  args: create(McpArgsSchema, {
5228
4275
  name: toolCall.name,
5229
4276
  args: encodeCursorMcpArguments(toolCall),
5230
- toolCallId: toolCall.id,
4277
+ toolCallId,
5231
4278
  providerIdentifier: "pi-agent",
5232
4279
  toolName: toolCall.name
5233
4280
  }),
@@ -5240,7 +4287,7 @@ function createCursorToolCallStep(toolCall, result) {
5240
4287
  case: "mcpToolCall",
5241
4288
  value: mcpCall
5242
4289
  },
5243
- toolCallId: toolCall.id
4290
+ toolCallId
5244
4291
  })
5245
4292
  } });
5246
4293
  }
@@ -5254,16 +4301,7 @@ function createCursorToolCallStep(toolCall, result) {
5254
4301
  */
5255
4302
  function buildConversationTurns(messages, blobStore, activeUserMessageIndex = findLastUserMessageIndex(messages), targetModelId) {
5256
4303
  const turns = [];
5257
- const historyEnd = activeUserMessageIndex >= 0 ? activeUserMessageIndex : messages.length;
5258
- const toolResults = /* @__PURE__ */ new Map();
5259
- const pairedToolCallIds = /* @__PURE__ */ new Set();
5260
- for (let index = 0; index < historyEnd; index++) {
5261
- const message = messages[index];
5262
- if (message.role === "toolResult") toolResults.set(message.toolCallId, message);
5263
- else if (message.role === "assistant") {
5264
- for (const item of message.content) if (item.type === "toolCall") pairedToolCallIds.add(item.id);
5265
- }
5266
- }
4304
+ const { toolResults, pairedToolCallIds } = collectCursorToolHistory(messages, activeUserMessageIndex >= 0 ? activeUserMessageIndex : messages.length);
5267
4305
  let i = 0;
5268
4306
  while (i < messages.length) {
5269
4307
  const msg = messages[i];
@@ -5302,15 +4340,11 @@ function buildConversationTurns(messages, blobStore, activeUserMessageIndex = fi
5302
4340
  stepBlobIds.push(storeCursorBlob(blobStore, toBinary(ConversationStepSchema, step)));
5303
4341
  }
5304
4342
  else if (stepMsg.role === "toolResult" && !pairedToolCallIds.has(stepMsg.toolCallId)) {
5305
- const text = toolResultToText(stepMsg);
5306
- if (text) {
5307
- const prefix = stepMsg.isError ? "[Tool Error]" : "[Tool Result]";
5308
- const step = create(ConversationStepSchema, { message: {
5309
- case: "assistantMessage",
5310
- value: create(AssistantMessageSchema, { text: `${prefix}\n${text}` })
5311
- } });
5312
- stepBlobIds.push(storeCursorBlob(blobStore, toBinary(ConversationStepSchema, step)));
5313
- }
4343
+ const step = create(ConversationStepSchema, { message: {
4344
+ case: "assistantMessage",
4345
+ value: create(AssistantMessageSchema, { text: cursorOrphanToolResultText(stepMsg) })
4346
+ } });
4347
+ stepBlobIds.push(storeCursorBlob(blobStore, toBinary(ConversationStepSchema, step)));
5314
4348
  }
5315
4349
  i++;
5316
4350
  }
@@ -5344,12 +4378,72 @@ function extractImages(content) {
5344
4378
  }
5345
4379
  }));
5346
4380
  }
5347
- function buildGrpcRequest(model, context, options, state) {
4381
+ /**
4382
+ * Resolve the Cursor Run wire model id and its parameter list.
4383
+ *
4384
+ * Cursor's `GetUsableModels` lists reasoning models as per-effort sibling
4385
+ * slugs (`gpt-5.4-mini-low`, `gpt-5.6-sol-high`), and OMP copies those ids 1:1.
4386
+ * The Run endpoint rejects a sibling slug as the wire `model_id` with
4387
+ * `resource_exhausted` (errorId 528384); the official `cursor-agent` splits the
4388
+ * slug into its base model id plus a `reasoning` effort parameter. Mirror that
4389
+ * for OpenAI-family ids: split the tier with the compiled catalog policy
4390
+ * (`collapseVariantId`, KDL suffix/lane rules) and emit
4391
+ * `{ id: "reasoning", value: <effort> }`. The off tier (`-none`) is a sibling
4392
+ * slug too, so it normalizes to the bare (lane-preserving) base with no
4393
+ * reasoning parameter instead of going out raw.
4394
+ *
4395
+ * Non-OpenAI ids pass through unchanged — Cursor-native ids (`composer-*`,
4396
+ * `cursor-grok-*`, `default`) carry no effort suffix, and Claude/other siblings
4397
+ * need additional parameters (`thinking`, `context`) whose per-model values are
4398
+ * not exposed by the decoded `GetUsableModels` schema, so guessing them would
4399
+ * re-trigger 528384.
4400
+ */
4401
+ function resolveCursorWireModel(model, requestModelId, wireMode = "normalized") {
4402
+ const wireModelId = requestModelId ?? model.requestModelId ?? model.id;
4403
+ if (wireMode === "discovered") return {
4404
+ modelId: wireModelId,
4405
+ parameters: []
4406
+ };
4407
+ const collapsed = collapseVariantId("cursor", wireModelId);
4408
+ const effort = collapsed.effort;
4409
+ const base = effort !== void 0 ? collapsed.logicalId : void 0;
4410
+ if (effort !== void 0 && base && classifyModel("cursor", base).class === "openai") {
4411
+ if (effort === "off") return {
4412
+ modelId: base,
4413
+ parameters: []
4414
+ };
4415
+ if (THINKING_EFFORTS.includes(effort)) return {
4416
+ modelId: base,
4417
+ parameters: [create(RequestedModel_ModelParameterbytesSchema, {
4418
+ id: "reasoning",
4419
+ value: collapsed.effort
4420
+ })]
4421
+ };
4422
+ }
4423
+ if (wireModelId === "composer-2.5") return {
4424
+ modelId: wireModelId,
4425
+ parameters: [create(RequestedModel_ModelParameterbytesSchema, {
4426
+ id: "fast",
4427
+ value: "false"
4428
+ })]
4429
+ };
4430
+ return {
4431
+ modelId: wireModelId,
4432
+ parameters: []
4433
+ };
4434
+ }
4435
+ async function buildGrpcRequestForWireMode(model, context, options, state, wireMode) {
5348
4436
  const blobStore = state.blobStore;
5349
4437
  const systemPromptIds = buildCursorSystemPromptJsons(context.systemPrompt).map((json) => storeCursorBlob(blobStore, new TextEncoder().encode(json)));
5350
- const activeUserMessageIndex = context.messages.length - 1;
4438
+ const lastUserMessageIndex = findLastUserMessageIndex(context.messages);
4439
+ let activeUserMessageIndex = context.messages.length - 1;
5351
4440
  const activeMessage = context.messages[activeUserMessageIndex];
5352
- const activeUserMessage = activeMessage?.role === "user" || activeMessage?.role === "developer" ? activeMessage : void 0;
4441
+ let activeUserMessage = activeMessage?.role === "user" || activeMessage?.role === "developer" ? activeMessage : void 0;
4442
+ if (state.rotatedFresh && !activeUserMessage && lastUserMessageIndex >= 0) {
4443
+ activeUserMessageIndex = lastUserMessageIndex;
4444
+ const lastUser = context.messages[lastUserMessageIndex];
4445
+ if (lastUser.role === "user" || lastUser.role === "developer") activeUserMessage = lastUser;
4446
+ }
5353
4447
  let userContent;
5354
4448
  let userText = "";
5355
4449
  let hasUserImages = false;
@@ -5391,7 +4485,7 @@ function buildGrpcRequest(model, context, options, state) {
5391
4485
  rootPromptMessagesJson,
5392
4486
  turns
5393
4487
  });
5394
- const wireModelId = model.requestModelId ?? model.id;
4488
+ const { modelId: wireModelId, parameters: wireParameters } = resolveCursorWireModel(model, options?.wireModelId, wireMode);
5395
4489
  const cursorMaxMode = model.cursorMaxMode === true;
5396
4490
  const modelDetails = create(ModelDetailsSchema, {
5397
4491
  modelId: wireModelId,
@@ -5401,17 +4495,25 @@ function buildGrpcRequest(model, context, options, state) {
5401
4495
  });
5402
4496
  const requestedModel = create(RequestedModelSchema, {
5403
4497
  modelId: wireModelId,
5404
- maxMode: cursorMaxMode
4498
+ maxMode: cursorMaxMode,
4499
+ parameters: wireParameters
5405
4500
  });
5406
- const runRequest = create(AgentRunRequestSchema, {
4501
+ let runRequest = create(AgentRunRequestSchema, {
5407
4502
  conversationState,
5408
4503
  action,
5409
4504
  modelDetails,
5410
4505
  requestedModel,
5411
4506
  conversationId: state.conversationId
5412
4507
  });
5413
- options?.onPayload?.(runRequest, model);
5414
4508
  if (options?.customSystemPrompt) runRequest.customSystemPrompt = options.customSystemPrompt;
4509
+ const replacementRequest = await options?.onPayload?.(runRequest, model);
4510
+ if (replacementRequest !== void 0) runRequest = replacementRequest;
4511
+ const discoveredWireModelId = options?.wireModelId ?? model.requestModelId ?? model.id;
4512
+ const serializedParameters = runRequest.requestedModel?.parameters;
4513
+ const fallbackWireModelId = wireMode === "normalized" && wireParameters.length > 0 && wireModelId !== discoveredWireModelId && runRequest.requestedModel?.modelId === wireModelId && runRequest.modelDetails?.modelId === wireModelId && serializedParameters?.length === wireParameters.length && serializedParameters.every((parameter, index) => {
4514
+ const expected = wireParameters[index];
4515
+ return expected !== void 0 && parameter.id === expected.id && parameter.value === expected.value;
4516
+ }) ? discoveredWireModelId : void 0;
5415
4517
  const clientMessage = create(AgentClientMessageSchema, { message: {
5416
4518
  case: "runRequest",
5417
4519
  value: runRequest
@@ -5428,7 +4530,8 @@ function buildGrpcRequest(model, context, options, state) {
5428
4530
  return {
5429
4531
  requestBytes,
5430
4532
  blobStore,
5431
- conversationState
4533
+ conversationState,
4534
+ fallbackWireModelId
5432
4535
  };
5433
4536
  }
5434
4537
  function hasImages(content) {