@mangostudio/cli-darwin-arm64 0.1.0 → 0.1.1-canary.00a342c

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 (1844) hide show
  1. package/cursor-sidecar/node_modules/@bufbuild/protobuf/README.md +43 -0
  2. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/binary-encoding.d.ts +422 -0
  3. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/binary-encoding.js +444 -0
  4. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/binary-format.d.ts +113 -0
  5. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/binary-format.js +15 -0
  6. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/codegen-info.d.ts +33 -0
  7. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/codegen-info.js +69 -0
  8. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/create-descriptor-set.d.ts +36 -0
  9. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/create-descriptor-set.js +910 -0
  10. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/create-registry-from-desc.d.ts +15 -0
  11. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/create-registry-from-desc.js +264 -0
  12. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/create-registry.d.ts +9 -0
  13. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/create-registry.js +94 -0
  14. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/descriptor-set.d.ts +672 -0
  15. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/descriptor-set.js +15 -0
  16. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/enum.d.ts +35 -0
  17. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/enum.js +15 -0
  18. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/extension-accessor.d.ts +35 -0
  19. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/extension-accessor.js +114 -0
  20. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/extension.d.ts +24 -0
  21. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/extension.js +15 -0
  22. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/field-list.d.ts +27 -0
  23. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/field-list.js +15 -0
  24. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/field.d.ts +314 -0
  25. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/field.js +15 -0
  26. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/any_pb.d.ts +157 -0
  27. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/any_pb.js +273 -0
  28. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/api_pb.d.ts +256 -0
  29. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/api_pb.js +316 -0
  30. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/compiler/plugin_pb.d.ts +271 -0
  31. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/compiler/plugin_pb.js +219 -0
  32. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/descriptor_pb.d.ts +2277 -0
  33. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/descriptor_pb.js +2077 -0
  34. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/duration_pb.d.ts +100 -0
  35. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/duration_pb.js +169 -0
  36. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/empty_pb.d.ts +28 -0
  37. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/empty_pb.js +52 -0
  38. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/field_mask_pb.d.ts +227 -0
  39. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/field_mask_pb.js +311 -0
  40. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/source_context_pb.d.ts +29 -0
  41. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/source_context_pb.js +55 -0
  42. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/struct_pb.d.ts +158 -0
  43. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/struct_pb.js +240 -0
  44. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/timestamp_pb.d.ts +132 -0
  45. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/timestamp_pb.js +213 -0
  46. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/type_pb.d.ts +437 -0
  47. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/type_pb.js +562 -0
  48. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/wrappers_pb.d.ts +267 -0
  49. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/protobuf/wrappers_pb.js +569 -0
  50. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/varint.d.ts +70 -0
  51. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/google/varint.js +323 -0
  52. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/index.d.ts +42 -0
  53. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/index.js +84 -0
  54. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/is-message.d.ts +22 -0
  55. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/is-message.js +52 -0
  56. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/json-format.d.ts +111 -0
  57. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/json-format.js +15 -0
  58. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/message-type.d.ts +51 -0
  59. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/message-type.js +15 -0
  60. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/message.d.ts +131 -0
  61. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/message.js +129 -0
  62. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/package.json +1 -0
  63. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/assert.d.ts +16 -0
  64. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/assert.js +59 -0
  65. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/binary-format.d.ts +7 -0
  66. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/binary-format.js +431 -0
  67. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/enum.d.ts +27 -0
  68. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/enum.js +94 -0
  69. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/extensions.d.ts +34 -0
  70. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/extensions.js +86 -0
  71. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/feature-set.d.ts +19 -0
  72. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/feature-set.js +120 -0
  73. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field-list.d.ts +18 -0
  74. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field-list.js +76 -0
  75. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field-normalize.d.ts +9 -0
  76. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field-normalize.js +69 -0
  77. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field-wrapper.d.ts +25 -0
  78. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field-wrapper.js +57 -0
  79. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field.d.ts +16 -0
  80. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/field.js +45 -0
  81. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/json-format.d.ts +2 -0
  82. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/json-format.js +626 -0
  83. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/message-type.d.ts +18 -0
  84. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/message-type.js +50 -0
  85. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/names.d.ts +43 -0
  86. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/names.js +278 -0
  87. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/options-map.d.ts +7 -0
  88. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/options-map.js +15 -0
  89. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/proto-runtime.d.ts +53 -0
  90. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/proto-runtime.js +41 -0
  91. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/reflect.d.ts +9 -0
  92. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/reflect.js +79 -0
  93. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/reify-wkt.d.ts +102 -0
  94. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/reify-wkt.js +172 -0
  95. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/scalars.d.ts +18 -0
  96. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/scalars.js +105 -0
  97. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/text-format.d.ts +4 -0
  98. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/text-format.js +189 -0
  99. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/util-common.d.ts +2 -0
  100. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/util-common.js +237 -0
  101. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/util.d.ts +38 -0
  102. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/private/util.js +15 -0
  103. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-base64.d.ts +18 -0
  104. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-base64.js +128 -0
  105. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-delimited.d.ts +54 -0
  106. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-delimited.js +155 -0
  107. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-double.d.ts +5 -0
  108. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-double.js +29 -0
  109. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-int64.d.ts +95 -0
  110. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto-int64.js +116 -0
  111. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto2.d.ts +4 -0
  112. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto2.js +53 -0
  113. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto3.d.ts +4 -0
  114. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/proto3.js +56 -0
  115. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/scalar.d.ts +53 -0
  116. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/scalar.js +81 -0
  117. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/service-type.d.ts +96 -0
  118. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/service-type.js +53 -0
  119. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/to-plain-message.d.ts +12 -0
  120. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/to-plain-message.js +72 -0
  121. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/type-registry.d.ts +57 -0
  122. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/cjs/type-registry.js +15 -0
  123. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/binary-encoding.d.ts +422 -0
  124. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/binary-encoding.js +439 -0
  125. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/binary-format.d.ts +113 -0
  126. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/binary-format.js +14 -0
  127. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/codegen-info.d.ts +33 -0
  128. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/codegen-info.js +67 -0
  129. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/create-descriptor-set.d.ts +36 -0
  130. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/create-descriptor-set.js +906 -0
  131. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/create-registry-from-desc.d.ts +15 -0
  132. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/create-registry-from-desc.js +261 -0
  133. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/create-registry.d.ts +9 -0
  134. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/create-registry.js +90 -0
  135. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/descriptor-set.d.ts +672 -0
  136. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/descriptor-set.js +14 -0
  137. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/enum.d.ts +35 -0
  138. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/enum.js +14 -0
  139. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/extension-accessor.d.ts +35 -0
  140. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/extension-accessor.js +107 -0
  141. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/extension.d.ts +24 -0
  142. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/extension.js +14 -0
  143. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/field-list.d.ts +27 -0
  144. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/field-list.js +14 -0
  145. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/field.d.ts +314 -0
  146. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/field.js +14 -0
  147. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/any_pb.d.ts +157 -0
  148. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/any_pb.js +269 -0
  149. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/api_pb.d.ts +256 -0
  150. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/api_pb.js +310 -0
  151. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/compiler/plugin_pb.d.ts +271 -0
  152. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/compiler/plugin_pb.js +212 -0
  153. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/descriptor_pb.d.ts +2277 -0
  154. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/descriptor_pb.js +2041 -0
  155. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/duration_pb.d.ts +100 -0
  156. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/duration_pb.js +165 -0
  157. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/empty_pb.d.ts +28 -0
  158. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/empty_pb.js +48 -0
  159. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/field_mask_pb.d.ts +227 -0
  160. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/field_mask_pb.js +307 -0
  161. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/source_context_pb.d.ts +29 -0
  162. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/source_context_pb.js +51 -0
  163. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/struct_pb.d.ts +158 -0
  164. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/struct_pb.js +234 -0
  165. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/timestamp_pb.d.ts +132 -0
  166. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/timestamp_pb.js +209 -0
  167. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/type_pb.d.ts +437 -0
  168. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/type_pb.js +554 -0
  169. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/wrappers_pb.d.ts +267 -0
  170. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/protobuf/wrappers_pb.js +557 -0
  171. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/varint.d.ts +70 -0
  172. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/google/varint.js +313 -0
  173. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/index.d.ts +42 -0
  174. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/index.js +43 -0
  175. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/is-message.d.ts +22 -0
  176. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/is-message.js +48 -0
  177. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/json-format.d.ts +111 -0
  178. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/json-format.js +14 -0
  179. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/message-type.d.ts +51 -0
  180. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/message-type.js +14 -0
  181. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/message.d.ts +131 -0
  182. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/message.js +125 -0
  183. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/assert.d.ts +16 -0
  184. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/assert.js +52 -0
  185. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/binary-format.d.ts +7 -0
  186. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/binary-format.js +427 -0
  187. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/enum.d.ts +27 -0
  188. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/enum.js +87 -0
  189. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/extensions.d.ts +34 -0
  190. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/extensions.js +81 -0
  191. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/feature-set.d.ts +19 -0
  192. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/feature-set.js +116 -0
  193. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field-list.d.ts +18 -0
  194. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field-list.js +72 -0
  195. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field-normalize.d.ts +9 -0
  196. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field-normalize.js +65 -0
  197. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field-wrapper.d.ts +25 -0
  198. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field-wrapper.js +53 -0
  199. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field.d.ts +16 -0
  200. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/field.js +41 -0
  201. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/json-format.d.ts +2 -0
  202. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/json-format.js +623 -0
  203. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/message-type.d.ts +18 -0
  204. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/message-type.js +46 -0
  205. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/names.d.ts +43 -0
  206. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/names.js +269 -0
  207. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/options-map.d.ts +7 -0
  208. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/options-map.js +14 -0
  209. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/proto-runtime.d.ts +53 -0
  210. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/proto-runtime.js +37 -0
  211. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/reflect.d.ts +9 -0
  212. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/reflect.js +74 -0
  213. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/reify-wkt.d.ts +102 -0
  214. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/reify-wkt.js +168 -0
  215. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/scalars.d.ts +18 -0
  216. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/scalars.js +99 -0
  217. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/text-format.d.ts +4 -0
  218. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/text-format.js +184 -0
  219. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/util-common.d.ts +2 -0
  220. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/util-common.js +234 -0
  221. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/util.d.ts +38 -0
  222. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/private/util.js +14 -0
  223. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-base64.d.ts +18 -0
  224. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-base64.js +125 -0
  225. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-delimited.d.ts +54 -0
  226. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-delimited.js +152 -0
  227. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-double.d.ts +5 -0
  228. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-double.js +26 -0
  229. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-int64.d.ts +95 -0
  230. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js +113 -0
  231. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto2.d.ts +4 -0
  232. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto2.js +50 -0
  233. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto3.d.ts +4 -0
  234. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/proto3.js +53 -0
  235. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/scalar.d.ts +53 -0
  236. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/scalar.js +78 -0
  237. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/service-type.d.ts +96 -0
  238. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/service-type.js +50 -0
  239. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/to-plain-message.d.ts +12 -0
  240. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/to-plain-message.js +70 -0
  241. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/type-registry.d.ts +57 -0
  242. package/cursor-sidecar/node_modules/@bufbuild/protobuf/dist/esm/type-registry.js +14 -0
  243. package/cursor-sidecar/node_modules/@bufbuild/protobuf/package.json +34 -0
  244. package/cursor-sidecar/node_modules/@connectrpc/connect/README.md +62 -0
  245. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/any-client.d.ts +22 -0
  246. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/any-client.js +34 -0
  247. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/call-options.d.ts +34 -0
  248. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/call-options.js +15 -0
  249. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/callback-client.d.ts +31 -0
  250. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/callback-client.js +116 -0
  251. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/code.d.ts +75 -0
  252. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/code.js +92 -0
  253. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/connect-error.d.ts +90 -0
  254. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/connect-error.js +134 -0
  255. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/context-values.d.ts +34 -0
  256. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/context-values.js +41 -0
  257. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/cors.d.ts +45 -0
  258. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/cors.js +82 -0
  259. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/http-headers.d.ts +36 -0
  260. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/http-headers.js +68 -0
  261. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/implementation.d.ts +165 -0
  262. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/implementation.js +79 -0
  263. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/index.d.ts +22 -0
  264. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/index.js +47 -0
  265. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/interceptor.d.ts +155 -0
  266. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/interceptor.js +27 -0
  267. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/method-type.d.ts +43 -0
  268. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/method-type.js +15 -0
  269. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/package.json +1 -0
  270. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/promise-client.d.ts +49 -0
  271. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/promise-client.js +147 -0
  272. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/async-iterable.d.ts +527 -0
  273. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/async-iterable.js +959 -0
  274. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/compression.d.ts +48 -0
  275. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/compression.js +75 -0
  276. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/content-type-matcher.d.ts +16 -0
  277. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/content-type-matcher.js +43 -0
  278. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/create-method-url.d.ts +17 -0
  279. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/create-method-url.js +36 -0
  280. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/envelope.d.ts +59 -0
  281. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/envelope.js +152 -0
  282. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/index.d.ts +24 -0
  283. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/index.js +93 -0
  284. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/invoke-implementation.d.ts +21 -0
  285. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/invoke-implementation.js +250 -0
  286. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/limit-io.d.ts +24 -0
  287. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/limit-io.js +80 -0
  288. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/normalize.d.ts +12 -0
  289. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/normalize.js +56 -0
  290. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/protocol-handler-factory.d.ts +18 -0
  291. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/protocol-handler-factory.js +15 -0
  292. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/run-call.d.ts +45 -0
  293. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/run-call.js +119 -0
  294. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/serialization.d.ts +104 -0
  295. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/serialization.js +148 -0
  296. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/signals.d.ts +36 -0
  297. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/signals.js +100 -0
  298. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/transport-options.d.ts +98 -0
  299. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/transport-options.js +15 -0
  300. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal-fetch.d.ts +35 -0
  301. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal-fetch.js +150 -0
  302. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal-handler-client.d.ts +7 -0
  303. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal-handler-client.js +90 -0
  304. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal-handler.d.ts +155 -0
  305. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal-handler.js +131 -0
  306. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal.d.ts +102 -0
  307. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol/universal.js +78 -0
  308. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/code-string.d.ts +16 -0
  309. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/code-string.js +52 -0
  310. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/content-type.d.ts +40 -0
  311. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/content-type.js +71 -0
  312. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/end-stream.d.ts +44 -0
  313. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/end-stream.js +132 -0
  314. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/error-json.d.ts +36 -0
  315. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/error-json.js +163 -0
  316. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/get-request.d.ts +7 -0
  317. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/get-request.js +68 -0
  318. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/handler-factory.d.ts +6 -0
  319. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/handler-factory.js +281 -0
  320. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/headers.d.ts +12 -0
  321. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/headers.js +28 -0
  322. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/http-status.d.ts +15 -0
  323. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/http-status.js +90 -0
  324. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/index.d.ts +16 -0
  325. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/index.js +81 -0
  326. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/parse-timeout.d.ts +13 -0
  327. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/parse-timeout.js +44 -0
  328. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/query-params.d.ts +8 -0
  329. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/query-params.js +24 -0
  330. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/request-header.d.ts +19 -0
  331. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/request-header.js +70 -0
  332. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/trailer-mux.d.ts +19 -0
  333. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/trailer-mux.js +53 -0
  334. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/transport.d.ts +6 -0
  335. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/transport.js +214 -0
  336. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/validate-response.d.ts +30 -0
  337. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/validate-response.js +72 -0
  338. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/version.d.ts +20 -0
  339. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-connect/version.js +58 -0
  340. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/content-type.d.ts +16 -0
  341. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/content-type.js +38 -0
  342. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/gen/status_pb.d.ts +89 -0
  343. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/gen/status_pb.js +120 -0
  344. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/handler-factory.d.ts +6 -0
  345. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/handler-factory.js +122 -0
  346. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/headers.d.ts +12 -0
  347. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/headers.js +28 -0
  348. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/http-status.d.ts +8 -0
  349. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/http-status.js +46 -0
  350. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/index.d.ts +10 -0
  351. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/index.js +61 -0
  352. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/parse-timeout.d.ts +13 -0
  353. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/parse-timeout.js +53 -0
  354. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/request-header.d.ts +13 -0
  355. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/request-header.js +56 -0
  356. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/trailer-status.d.ts +28 -0
  357. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/trailer-status.js +104 -0
  358. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/transport.d.ts +6 -0
  359. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/transport.js +185 -0
  360. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/validate-response.d.ts +33 -0
  361. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/validate-response.js +75 -0
  362. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/validate-trailer.d.ts +13 -0
  363. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc/validate-trailer.js +44 -0
  364. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/content-type.d.ts +19 -0
  365. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/content-type.js +41 -0
  366. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/handler-factory.d.ts +6 -0
  367. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/handler-factory.js +128 -0
  368. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/headers.d.ts +20 -0
  369. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/headers.js +44 -0
  370. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/index.d.ts +8 -0
  371. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/index.js +61 -0
  372. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/request-header.d.ts +13 -0
  373. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/request-header.js +59 -0
  374. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/trailer.d.ts +27 -0
  375. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/trailer.js +71 -0
  376. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/transport.d.ts +6 -0
  377. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/transport.js +238 -0
  378. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/validate-response.d.ts +34 -0
  379. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/protocol-grpc-web/validate-response.js +73 -0
  380. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/router-transport.d.ts +13 -0
  381. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/router-transport.js +32 -0
  382. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/router.d.ts +88 -0
  383. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/router.js +83 -0
  384. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/transport.d.ts +20 -0
  385. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/cjs/transport.js +15 -0
  386. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/any-client.d.ts +22 -0
  387. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/any-client.js +31 -0
  388. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/call-options.d.ts +34 -0
  389. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/call-options.js +14 -0
  390. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/callback-client.d.ts +31 -0
  391. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/callback-client.js +113 -0
  392. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/code.d.ts +75 -0
  393. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/code.js +89 -0
  394. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/connect-error.d.ts +90 -0
  395. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/connect-error.js +130 -0
  396. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/context-values.d.ts +34 -0
  397. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/context-values.js +37 -0
  398. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/cors.d.ts +45 -0
  399. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/cors.js +79 -0
  400. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/http-headers.d.ts +36 -0
  401. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/http-headers.js +63 -0
  402. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/implementation.d.ts +165 -0
  403. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/implementation.js +75 -0
  404. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/index.d.ts +22 -0
  405. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/index.js +27 -0
  406. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/interceptor.d.ts +155 -0
  407. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/interceptor.js +24 -0
  408. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/method-type.d.ts +43 -0
  409. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/method-type.js +14 -0
  410. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/promise-client.d.ts +49 -0
  411. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/promise-client.js +139 -0
  412. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.d.ts +527 -0
  413. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js +937 -0
  414. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/compression.d.ts +48 -0
  415. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/compression.js +71 -0
  416. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/content-type-matcher.d.ts +16 -0
  417. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/content-type-matcher.js +40 -0
  418. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/create-method-url.d.ts +17 -0
  419. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/create-method-url.js +33 -0
  420. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/envelope.d.ts +59 -0
  421. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/envelope.js +145 -0
  422. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/index.d.ts +24 -0
  423. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/index.js +32 -0
  424. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/invoke-implementation.d.ts +21 -0
  425. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/invoke-implementation.js +246 -0
  426. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.d.ts +24 -0
  427. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.js +75 -0
  428. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/normalize.d.ts +12 -0
  429. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/normalize.js +53 -0
  430. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/protocol-handler-factory.d.ts +18 -0
  431. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/protocol-handler-factory.js +14 -0
  432. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/run-call.d.ts +45 -0
  433. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/run-call.js +115 -0
  434. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/serialization.d.ts +104 -0
  435. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/serialization.js +140 -0
  436. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/signals.d.ts +36 -0
  437. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/signals.js +95 -0
  438. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/transport-options.d.ts +98 -0
  439. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/transport-options.js +14 -0
  440. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal-fetch.d.ts +35 -0
  441. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal-fetch.js +142 -0
  442. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal-handler-client.d.ts +7 -0
  443. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal-handler-client.js +87 -0
  444. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal-handler.d.ts +155 -0
  445. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal-handler.js +125 -0
  446. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal.d.ts +102 -0
  447. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol/universal.js +74 -0
  448. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.d.ts +16 -0
  449. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.js +48 -0
  450. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/content-type.d.ts +40 -0
  451. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/content-type.js +66 -0
  452. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/end-stream.d.ts +44 -0
  453. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/end-stream.js +126 -0
  454. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/error-json.d.ts +36 -0
  455. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/error-json.js +157 -0
  456. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/get-request.d.ts +7 -0
  457. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/get-request.js +65 -0
  458. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/handler-factory.d.ts +6 -0
  459. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/handler-factory.js +278 -0
  460. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/headers.d.ts +12 -0
  461. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/headers.js +25 -0
  462. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/http-status.d.ts +15 -0
  463. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/http-status.js +86 -0
  464. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/index.d.ts +16 -0
  465. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/index.js +33 -0
  466. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/parse-timeout.d.ts +13 -0
  467. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/parse-timeout.js +41 -0
  468. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/query-params.d.ts +8 -0
  469. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/query-params.js +21 -0
  470. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/request-header.d.ts +19 -0
  471. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/request-header.js +66 -0
  472. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/trailer-mux.d.ts +19 -0
  473. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/trailer-mux.js +49 -0
  474. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/transport.d.ts +6 -0
  475. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/transport.js +211 -0
  476. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/validate-response.d.ts +30 -0
  477. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/validate-response.js +68 -0
  478. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/version.d.ts +20 -0
  479. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-connect/version.js +53 -0
  480. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/content-type.d.ts +16 -0
  481. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/content-type.js +34 -0
  482. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/gen/status_pb.d.ts +89 -0
  483. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/gen/status_pb.js +116 -0
  484. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/handler-factory.d.ts +6 -0
  485. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/handler-factory.js +119 -0
  486. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/headers.d.ts +12 -0
  487. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/headers.js +25 -0
  488. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/http-status.d.ts +8 -0
  489. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/http-status.js +43 -0
  490. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/index.d.ts +10 -0
  491. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/index.js +28 -0
  492. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/parse-timeout.d.ts +13 -0
  493. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/parse-timeout.js +50 -0
  494. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/request-header.d.ts +13 -0
  495. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/request-header.js +52 -0
  496. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/trailer-status.d.ts +28 -0
  497. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/trailer-status.js +99 -0
  498. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/transport.d.ts +6 -0
  499. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/transport.js +182 -0
  500. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/validate-response.d.ts +33 -0
  501. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/validate-response.js +71 -0
  502. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/validate-trailer.d.ts +13 -0
  503. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc/validate-trailer.js +41 -0
  504. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/content-type.d.ts +19 -0
  505. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/content-type.js +37 -0
  506. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/handler-factory.d.ts +6 -0
  507. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/handler-factory.js +125 -0
  508. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/headers.d.ts +20 -0
  509. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/headers.js +33 -0
  510. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/index.d.ts +8 -0
  511. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/index.js +26 -0
  512. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/request-header.d.ts +13 -0
  513. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/request-header.js +55 -0
  514. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/trailer.d.ts +27 -0
  515. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/trailer.js +65 -0
  516. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/transport.d.ts +6 -0
  517. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/transport.js +235 -0
  518. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/validate-response.d.ts +34 -0
  519. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/protocol-grpc-web/validate-response.js +69 -0
  520. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/router-transport.d.ts +13 -0
  521. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/router-transport.js +29 -0
  522. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/router.d.ts +88 -0
  523. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/router.js +80 -0
  524. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/transport.d.ts +20 -0
  525. package/cursor-sidecar/node_modules/@connectrpc/connect/dist/esm/transport.js +14 -0
  526. package/cursor-sidecar/node_modules/@connectrpc/connect/package.json +75 -0
  527. package/cursor-sidecar/node_modules/@connectrpc/connect/protocol-connect.js +16 -0
  528. package/cursor-sidecar/node_modules/@connectrpc/connect/protocol-grpc-web.js +16 -0
  529. package/cursor-sidecar/node_modules/@connectrpc/connect/protocol-grpc.js +16 -0
  530. package/cursor-sidecar/node_modules/@connectrpc/connect/protocol.js +16 -0
  531. package/cursor-sidecar/node_modules/@connectrpc/connect-node/README.md +141 -0
  532. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/compression.d.ts +15 -0
  533. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/compression.js +89 -0
  534. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/connect-node-adapter.d.ts +42 -0
  535. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/connect-node-adapter.js +61 -0
  536. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/connect-transport.d.ts +100 -0
  537. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/connect-transport.js +25 -0
  538. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/grpc-transport.d.ts +96 -0
  539. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/grpc-transport.js +25 -0
  540. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/grpc-web-transport.d.ts +96 -0
  541. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/grpc-web-transport.js +25 -0
  542. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/http2-session-manager.d.ts +146 -0
  543. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/http2-session-manager.js +536 -0
  544. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/index.d.ts +15 -0
  545. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/index.js +36 -0
  546. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-error.d.ts +45 -0
  547. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-error.js +154 -0
  548. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-headers-polyfill.d.ts +1 -0
  549. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-headers-polyfill.js +29 -0
  550. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-transport-options.d.ts +89 -0
  551. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-transport-options.js +58 -0
  552. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-client.d.ts +54 -0
  553. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-client.js +326 -0
  554. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-handler.d.ts +41 -0
  555. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-handler.js +234 -0
  556. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-header.d.ts +19 -0
  557. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-header.js +97 -0
  558. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/cjs/package.json +1 -0
  559. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/compression.d.ts +15 -0
  560. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/compression.js +86 -0
  561. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/connect-node-adapter.d.ts +42 -0
  562. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/connect-node-adapter.js +58 -0
  563. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/connect-transport.d.ts +100 -0
  564. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/connect-transport.js +22 -0
  565. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/grpc-transport.d.ts +96 -0
  566. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/grpc-transport.js +22 -0
  567. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/grpc-web-transport.d.ts +96 -0
  568. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/grpc-web-transport.js +22 -0
  569. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/http2-session-manager.d.ts +146 -0
  570. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/http2-session-manager.js +532 -0
  571. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/index.d.ts +15 -0
  572. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/index.js +23 -0
  573. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-error.d.ts +45 -0
  574. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-error.js +147 -0
  575. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-headers-polyfill.d.ts +1 -0
  576. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-headers-polyfill.js +27 -0
  577. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-transport-options.d.ts +89 -0
  578. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-transport-options.js +58 -0
  579. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-universal-client.d.ts +54 -0
  580. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-universal-client.js +324 -0
  581. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-universal-handler.d.ts +41 -0
  582. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-universal-handler.js +230 -0
  583. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-universal-header.d.ts +19 -0
  584. package/cursor-sidecar/node_modules/@connectrpc/connect-node/dist/esm/node-universal-header.js +93 -0
  585. package/cursor-sidecar/node_modules/@connectrpc/connect-node/package.json +46 -0
  586. package/cursor-sidecar/node_modules/@connectrpc/connect-web/README.md +54 -0
  587. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/assert-fetch-api.d.ts +4 -0
  588. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/assert-fetch-api.js +27 -0
  589. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/connect-transport.d.ts +68 -0
  590. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/connect-transport.js +200 -0
  591. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/grpc-web-transport.d.ts +69 -0
  592. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/grpc-web-transport.js +247 -0
  593. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/index.d.ts +4 -0
  594. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/index.js +20 -0
  595. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/cjs/package.json +1 -0
  596. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/assert-fetch-api.d.ts +4 -0
  597. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/assert-fetch-api.js +24 -0
  598. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/connect-transport.d.ts +68 -0
  599. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/connect-transport.js +197 -0
  600. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/grpc-web-transport.d.ts +69 -0
  601. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/grpc-web-transport.js +244 -0
  602. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/index.d.ts +4 -0
  603. package/cursor-sidecar/node_modules/@connectrpc/connect-web/dist/esm/index.js +15 -0
  604. package/cursor-sidecar/node_modules/@connectrpc/connect-web/package.json +58 -0
  605. package/cursor-sidecar/node_modules/@cursor/sdk/LICENSE.md +3 -0
  606. package/cursor-sidecar/node_modules/@cursor/sdk/README.md +5 -0
  607. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/162.js +1 -0
  608. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/174.js +1 -0
  609. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/18.js +1 -0
  610. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/181.js +1 -0
  611. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/19.js +1 -0
  612. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/250.js +2 -0
  613. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/250.js.LICENSE.txt +1 -0
  614. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/284.js +1 -0
  615. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/295.js +1 -0
  616. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/343.js +1 -0
  617. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/400.js +1 -0
  618. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/642.js +1 -0
  619. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/656.js +1 -0
  620. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/690.js +1 -0
  621. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/730.js +1 -0
  622. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/731.js +1 -0
  623. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/745.js +8 -0
  624. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/745.js.LICENSE.txt +30 -0
  625. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/796.js +1 -0
  626. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/831.js +1 -0
  627. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/856.js +1 -0
  628. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/914.js +1 -0
  629. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/986.js +1 -0
  630. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/996.js +1 -0
  631. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/options.d.ts +242 -0
  632. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/options.d.ts.map +1 -0
  633. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/run-event-notifier-api.d.ts +120 -0
  634. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/run-event-notifier-api.d.ts.map +1 -0
  635. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/run-store-public-types.d.ts +183 -0
  636. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/run-store-public-types.d.ts.map +1 -0
  637. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/local-agent-record-conversion.d.ts +7 -0
  638. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/local-agent-record-conversion.d.ts.map +1 -0
  639. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/local-agent-store.d.ts +292 -0
  640. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/local-agent-store.d.ts.map +1 -0
  641. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/sdk-state-root.d.ts +6 -0
  642. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/sdk-state-root.d.ts.map +1 -0
  643. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/sqlite-local-agent-store.d.ts +30 -0
  644. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/store/sqlite-local-agent-store.d.ts.map +1 -0
  645. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/usage-types.d.ts +21 -0
  646. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent/usage-types.d.ts.map +1 -0
  647. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent.d.ts +172 -0
  648. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/agent.d.ts.map +1 -0
  649. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/analytics.d.ts +16 -0
  650. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/analytics.d.ts.map +1 -0
  651. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/artifacts.d.ts +6 -0
  652. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/artifacts.d.ts.map +1 -0
  653. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-agent.d.ts +47 -0
  654. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-agent.d.ts.map +1 -0
  655. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-api-client.d.ts +200 -0
  656. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-api-client.d.ts.map +1 -0
  657. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-executor.d.ts +14 -0
  658. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-executor.d.ts.map +1 -0
  659. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-mcp-utils.d.ts +4 -0
  660. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/cloud-mcp-utils.d.ts.map +1 -0
  661. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/core-adapter.d.ts +2 -0
  662. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/core-adapter.d.ts.map +1 -0
  663. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/custom-tools.d.ts +29 -0
  664. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/custom-tools.d.ts.map +1 -0
  665. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/errors.d.ts +145 -0
  666. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/errors.d.ts.map +1 -0
  667. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/executor-common.d.ts +20 -0
  668. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/executor-common.d.ts.map +1 -0
  669. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/executor-types.d.ts +67 -0
  670. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/executor-types.d.ts.map +1 -0
  671. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/index.d.ts +18 -0
  672. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/index.d.ts.map +1 -0
  673. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/index.js +1 -0
  674. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/local-executor.d.ts +21 -0
  675. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/local-executor.d.ts.map +1 -0
  676. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/local-model-validation.d.ts +6 -0
  677. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/local-model-validation.d.ts.map +1 -0
  678. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/messages.d.ts +118 -0
  679. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/messages.d.ts.map +1 -0
  680. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/options.d.ts +242 -0
  681. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/options.d.ts.map +1 -0
  682. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/package.json +3 -0
  683. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/platform.d.ts +73 -0
  684. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/platform.d.ts.map +1 -0
  685. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/prefetched-blobs.d.ts +13 -0
  686. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/prefetched-blobs.d.ts.map +1 -0
  687. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/public-api.d.ts +18 -0
  688. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/public-api.d.ts.map +1 -0
  689. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-event-notifier-api.d.ts +120 -0
  690. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-event-notifier-api.d.ts.map +1 -0
  691. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-event-tailer.d.ts +33 -0
  692. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-event-tailer.d.ts.map +1 -0
  693. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-interaction-accumulator.d.ts +37 -0
  694. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-interaction-accumulator.d.ts.map +1 -0
  695. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-store-public-types.d.ts +183 -0
  696. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run-store-public-types.d.ts.map +1 -0
  697. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run.d.ts +51 -0
  698. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/run.d.ts.map +1 -0
  699. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/safe-connect-transport.d.ts +9 -0
  700. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/safe-connect-transport.d.ts.map +1 -0
  701. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/safe-node-http-client.d.ts +11 -0
  702. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/safe-node-http-client.d.ts.map +1 -0
  703. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sdk-config.d.ts +25 -0
  704. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sdk-config.d.ts.map +1 -0
  705. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sdk-statsig.d.ts +14 -0
  706. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sdk-statsig.d.ts.map +1 -0
  707. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sqlite.d.ts +8 -0
  708. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sqlite.d.ts.map +1 -0
  709. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/sqlite.js +1 -0
  710. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/index.d.ts +7 -0
  711. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/index.d.ts.map +1 -0
  712. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/jsonl-local-agent-store.d.ts +34 -0
  713. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/jsonl-local-agent-store.d.ts.map +1 -0
  714. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/local-agent-record-conversion.d.ts +7 -0
  715. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/local-agent-record-conversion.d.ts.map +1 -0
  716. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/local-agent-store.d.ts +292 -0
  717. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/local-agent-store.d.ts.map +1 -0
  718. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/open-default-local-agent-store.d.ts +4 -0
  719. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/open-default-local-agent-store.d.ts.map +1 -0
  720. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sdk-local-defaults.d.ts +15 -0
  721. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sdk-local-defaults.d.ts.map +1 -0
  722. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sdk-state-root.d.ts +6 -0
  723. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sdk-state-root.d.ts.map +1 -0
  724. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sqlite-local-agent-store.d.ts +30 -0
  725. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sqlite-local-agent-store.d.ts.map +1 -0
  726. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sqlite-storage-unavailable.d.ts +6 -0
  727. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/store/sqlite-storage-unavailable.d.ts.map +1 -0
  728. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/stubs.d.ts +105 -0
  729. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/stubs.d.ts.map +1 -0
  730. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/subagent-conversion.d.ts +22 -0
  731. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/subagent-conversion.d.ts.map +1 -0
  732. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/tool-call-utils.d.ts +7 -0
  733. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/tool-call-utils.d.ts.map +1 -0
  734. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/transport.d.ts +47 -0
  735. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/transport.d.ts.map +1 -0
  736. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/types/conversation-types.d.ts +12062 -0
  737. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/types/conversation-types.d.ts.map +1 -0
  738. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/types/delta-types.d.ts +2 -0
  739. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/types/delta-types.d.ts.map +1 -0
  740. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/types/tool-call-types.d.ts +2 -0
  741. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/types/tool-call-types.d.ts.map +1 -0
  742. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/usage-types.d.ts +21 -0
  743. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/usage-types.d.ts.map +1 -0
  744. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/utils/conversation-utils.d.ts +3 -0
  745. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/utils/conversation-utils.d.ts.map +1 -0
  746. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/utils/logger.d.ts +12 -0
  747. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/utils/logger.d.ts.map +1 -0
  748. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/utils/message-schemas.d.ts +2 -0
  749. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/utils/message-schemas.d.ts.map +1 -0
  750. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/vendor/cursor-sdk-shared/core-adapter.d.ts +3 -0
  751. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/vendor/cursor-sdk-shared/core-adapter.test.d.ts +1 -0
  752. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/vendor/cursor-sdk-shared/delta-types.d.ts +19196 -0
  753. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/vendor/cursor-sdk-shared/index.d.ts +4 -0
  754. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/vendor/cursor-sdk-shared/message-schemas.d.ts +105 -0
  755. package/cursor-sidecar/node_modules/@cursor/sdk/dist/cjs/vendor/cursor-sdk-shared/tool-call-types.d.ts +7894 -0
  756. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/162.js +1 -0
  757. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/18.js +1 -0
  758. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/181.js +1 -0
  759. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/19.js +1 -0
  760. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/250.js +2 -0
  761. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/250.js.LICENSE.txt +1 -0
  762. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/284.js +1 -0
  763. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/295.js +1 -0
  764. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/343.js +1 -0
  765. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/357.js +1 -0
  766. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/400.js +1 -0
  767. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/642.js +1 -0
  768. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/656.js +1 -0
  769. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/690.js +1 -0
  770. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/730.js +1 -0
  771. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/731.js +1 -0
  772. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/745.js +8 -0
  773. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/745.js.LICENSE.txt +30 -0
  774. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/831.js +1 -0
  775. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/856.js +1 -0
  776. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/914.js +1 -0
  777. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/986.js +1 -0
  778. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/988.js +1 -0
  779. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/996.js +1 -0
  780. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/options.d.ts +242 -0
  781. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/options.d.ts.map +1 -0
  782. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/run-event-notifier-api.d.ts +120 -0
  783. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/run-event-notifier-api.d.ts.map +1 -0
  784. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/run-store-public-types.d.ts +183 -0
  785. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/run-store-public-types.d.ts.map +1 -0
  786. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/local-agent-record-conversion.d.ts +7 -0
  787. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/local-agent-record-conversion.d.ts.map +1 -0
  788. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/local-agent-store.d.ts +292 -0
  789. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/local-agent-store.d.ts.map +1 -0
  790. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/sdk-state-root.d.ts +6 -0
  791. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/sdk-state-root.d.ts.map +1 -0
  792. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/sqlite-local-agent-store.d.ts +30 -0
  793. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/store/sqlite-local-agent-store.d.ts.map +1 -0
  794. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/usage-types.d.ts +21 -0
  795. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent/usage-types.d.ts.map +1 -0
  796. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent.d.ts +172 -0
  797. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/agent.d.ts.map +1 -0
  798. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/analytics.d.ts +16 -0
  799. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/analytics.d.ts.map +1 -0
  800. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/artifacts.d.ts +6 -0
  801. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/artifacts.d.ts.map +1 -0
  802. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-agent.d.ts +47 -0
  803. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-agent.d.ts.map +1 -0
  804. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-api-client.d.ts +200 -0
  805. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-api-client.d.ts.map +1 -0
  806. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-executor.d.ts +14 -0
  807. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-executor.d.ts.map +1 -0
  808. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-mcp-utils.d.ts +4 -0
  809. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/cloud-mcp-utils.d.ts.map +1 -0
  810. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/core-adapter.d.ts +2 -0
  811. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/core-adapter.d.ts.map +1 -0
  812. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/custom-tools.d.ts +29 -0
  813. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/custom-tools.d.ts.map +1 -0
  814. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/errors.d.ts +145 -0
  815. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/errors.d.ts.map +1 -0
  816. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/executor-common.d.ts +20 -0
  817. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/executor-common.d.ts.map +1 -0
  818. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/executor-types.d.ts +67 -0
  819. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/executor-types.d.ts.map +1 -0
  820. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/index.d.ts +18 -0
  821. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/index.d.ts.map +1 -0
  822. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/index.js +1 -0
  823. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/local-executor.d.ts +21 -0
  824. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/local-executor.d.ts.map +1 -0
  825. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/local-model-validation.d.ts +6 -0
  826. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/local-model-validation.d.ts.map +1 -0
  827. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/messages.d.ts +118 -0
  828. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/messages.d.ts.map +1 -0
  829. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/options.d.ts +242 -0
  830. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/options.d.ts.map +1 -0
  831. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/platform.d.ts +73 -0
  832. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/platform.d.ts.map +1 -0
  833. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/prefetched-blobs.d.ts +13 -0
  834. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/prefetched-blobs.d.ts.map +1 -0
  835. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/public-api.d.ts +18 -0
  836. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/public-api.d.ts.map +1 -0
  837. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-event-notifier-api.d.ts +120 -0
  838. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-event-notifier-api.d.ts.map +1 -0
  839. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-event-tailer.d.ts +33 -0
  840. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-event-tailer.d.ts.map +1 -0
  841. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-interaction-accumulator.d.ts +37 -0
  842. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-interaction-accumulator.d.ts.map +1 -0
  843. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-store-public-types.d.ts +183 -0
  844. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run-store-public-types.d.ts.map +1 -0
  845. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run.d.ts +51 -0
  846. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/run.d.ts.map +1 -0
  847. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/safe-connect-transport.d.ts +9 -0
  848. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/safe-connect-transport.d.ts.map +1 -0
  849. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/safe-node-http-client.d.ts +11 -0
  850. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/safe-node-http-client.d.ts.map +1 -0
  851. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sdk-config.d.ts +25 -0
  852. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sdk-config.d.ts.map +1 -0
  853. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sdk-statsig.d.ts +14 -0
  854. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sdk-statsig.d.ts.map +1 -0
  855. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sqlite.d.ts +8 -0
  856. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sqlite.d.ts.map +1 -0
  857. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/sqlite.js +1 -0
  858. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/index.d.ts +7 -0
  859. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/index.d.ts.map +1 -0
  860. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/jsonl-local-agent-store.d.ts +34 -0
  861. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/jsonl-local-agent-store.d.ts.map +1 -0
  862. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/local-agent-record-conversion.d.ts +7 -0
  863. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/local-agent-record-conversion.d.ts.map +1 -0
  864. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/local-agent-store.d.ts +292 -0
  865. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/local-agent-store.d.ts.map +1 -0
  866. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/open-default-local-agent-store.d.ts +4 -0
  867. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/open-default-local-agent-store.d.ts.map +1 -0
  868. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sdk-local-defaults.d.ts +15 -0
  869. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sdk-local-defaults.d.ts.map +1 -0
  870. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sdk-state-root.d.ts +6 -0
  871. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sdk-state-root.d.ts.map +1 -0
  872. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sqlite-local-agent-store.d.ts +30 -0
  873. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sqlite-local-agent-store.d.ts.map +1 -0
  874. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sqlite-storage-unavailable.d.ts +6 -0
  875. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/store/sqlite-storage-unavailable.d.ts.map +1 -0
  876. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/stubs.d.ts +105 -0
  877. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/stubs.d.ts.map +1 -0
  878. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/subagent-conversion.d.ts +22 -0
  879. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/subagent-conversion.d.ts.map +1 -0
  880. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/tool-call-utils.d.ts +7 -0
  881. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/tool-call-utils.d.ts.map +1 -0
  882. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/transport.d.ts +47 -0
  883. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/transport.d.ts.map +1 -0
  884. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/types/conversation-types.d.ts +12062 -0
  885. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/types/conversation-types.d.ts.map +1 -0
  886. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/types/delta-types.d.ts +2 -0
  887. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/types/delta-types.d.ts.map +1 -0
  888. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/types/tool-call-types.d.ts +2 -0
  889. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/types/tool-call-types.d.ts.map +1 -0
  890. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/usage-types.d.ts +21 -0
  891. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/usage-types.d.ts.map +1 -0
  892. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/utils/conversation-utils.d.ts +3 -0
  893. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/utils/conversation-utils.d.ts.map +1 -0
  894. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/utils/logger.d.ts +12 -0
  895. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/utils/logger.d.ts.map +1 -0
  896. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/utils/message-schemas.d.ts +2 -0
  897. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/utils/message-schemas.d.ts.map +1 -0
  898. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/vendor/cursor-sdk-shared/core-adapter.d.ts +3 -0
  899. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/vendor/cursor-sdk-shared/core-adapter.test.d.ts +1 -0
  900. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/vendor/cursor-sdk-shared/delta-types.d.ts +19196 -0
  901. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/vendor/cursor-sdk-shared/index.d.ts +4 -0
  902. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/vendor/cursor-sdk-shared/message-schemas.d.ts +105 -0
  903. package/cursor-sidecar/node_modules/@cursor/sdk/dist/esm/vendor/cursor-sdk-shared/tool-call-types.d.ts +7894 -0
  904. package/cursor-sidecar/node_modules/@cursor/sdk/package.json +119 -0
  905. package/cursor-sidecar/node_modules/@cursor/sdk-darwin-arm64/README.md +5 -0
  906. package/cursor-sidecar/node_modules/@cursor/sdk-darwin-arm64/bin/cursorsandbox +0 -0
  907. package/cursor-sidecar/node_modules/@cursor/sdk-darwin-arm64/bin/rg +0 -0
  908. package/cursor-sidecar/node_modules/@cursor/sdk-darwin-arm64/package.json +28 -0
  909. package/cursor-sidecar/node_modules/@fastify/busboy/LICENSE +19 -0
  910. package/cursor-sidecar/node_modules/@fastify/busboy/README.md +271 -0
  911. package/cursor-sidecar/node_modules/@fastify/busboy/deps/dicer/LICENSE +19 -0
  912. package/cursor-sidecar/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js +213 -0
  913. package/cursor-sidecar/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js +100 -0
  914. package/cursor-sidecar/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js +13 -0
  915. package/cursor-sidecar/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts +164 -0
  916. package/cursor-sidecar/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js +228 -0
  917. package/cursor-sidecar/node_modules/@fastify/busboy/lib/main.d.ts +196 -0
  918. package/cursor-sidecar/node_modules/@fastify/busboy/lib/main.js +85 -0
  919. package/cursor-sidecar/node_modules/@fastify/busboy/lib/types/multipart.js +306 -0
  920. package/cursor-sidecar/node_modules/@fastify/busboy/lib/types/urlencoded.js +190 -0
  921. package/cursor-sidecar/node_modules/@fastify/busboy/lib/utils/Decoder.js +54 -0
  922. package/cursor-sidecar/node_modules/@fastify/busboy/lib/utils/basename.js +14 -0
  923. package/cursor-sidecar/node_modules/@fastify/busboy/lib/utils/decodeText.js +114 -0
  924. package/cursor-sidecar/node_modules/@fastify/busboy/lib/utils/getLimit.js +16 -0
  925. package/cursor-sidecar/node_modules/@fastify/busboy/lib/utils/parseParams.js +196 -0
  926. package/cursor-sidecar/node_modules/@fastify/busboy/package.json +86 -0
  927. package/cursor-sidecar/node_modules/@statsig/client-core/package.json +15 -0
  928. package/cursor-sidecar/node_modules/@statsig/client-core/src/$_StatsigGlobal.d.ts +19 -0
  929. package/cursor-sidecar/node_modules/@statsig/client-core/src/$_StatsigGlobal.js +41 -0
  930. package/cursor-sidecar/node_modules/@statsig/client-core/src/CacheKey.d.ts +4 -0
  931. package/cursor-sidecar/node_modules/@statsig/client-core/src/CacheKey.js +28 -0
  932. package/cursor-sidecar/node_modules/@statsig/client-core/src/ClientInterfaces.d.ts +62 -0
  933. package/cursor-sidecar/node_modules/@statsig/client-core/src/ClientInterfaces.js +2 -0
  934. package/cursor-sidecar/node_modules/@statsig/client-core/src/DataAdapterCore.d.ts +29 -0
  935. package/cursor-sidecar/node_modules/@statsig/client-core/src/DataAdapterCore.js +216 -0
  936. package/cursor-sidecar/node_modules/@statsig/client-core/src/Diagnostics.d.ts +67 -0
  937. package/cursor-sidecar/node_modules/@statsig/client-core/src/Diagnostics.js +100 -0
  938. package/cursor-sidecar/node_modules/@statsig/client-core/src/DnsTxtQuery.d.ts +2 -0
  939. package/cursor-sidecar/node_modules/@statsig/client-core/src/DnsTxtQuery.js +63 -0
  940. package/cursor-sidecar/node_modules/@statsig/client-core/src/DownloadConfigSpecsResponse.d.ts +61 -0
  941. package/cursor-sidecar/node_modules/@statsig/client-core/src/DownloadConfigSpecsResponse.js +2 -0
  942. package/cursor-sidecar/node_modules/@statsig/client-core/src/ErrorBoundary.d.ts +17 -0
  943. package/cursor-sidecar/node_modules/@statsig/client-core/src/ErrorBoundary.js +197 -0
  944. package/cursor-sidecar/node_modules/@statsig/client-core/src/EvaluationOptions.d.ts +30 -0
  945. package/cursor-sidecar/node_modules/@statsig/client-core/src/EvaluationOptions.js +2 -0
  946. package/cursor-sidecar/node_modules/@statsig/client-core/src/EvaluationTypes.d.ts +49 -0
  947. package/cursor-sidecar/node_modules/@statsig/client-core/src/EvaluationTypes.js +2 -0
  948. package/cursor-sidecar/node_modules/@statsig/client-core/src/EvaluationTypesV2.d.ts +30 -0
  949. package/cursor-sidecar/node_modules/@statsig/client-core/src/EvaluationTypesV2.js +2 -0
  950. package/cursor-sidecar/node_modules/@statsig/client-core/src/EventBatch.d.ts +8 -0
  951. package/cursor-sidecar/node_modules/@statsig/client-core/src/EventBatch.js +14 -0
  952. package/cursor-sidecar/node_modules/@statsig/client-core/src/EventLogger.d.ts +48 -0
  953. package/cursor-sidecar/node_modules/@statsig/client-core/src/EventLogger.js +349 -0
  954. package/cursor-sidecar/node_modules/@statsig/client-core/src/EventRetryConstants.d.ts +7 -0
  955. package/cursor-sidecar/node_modules/@statsig/client-core/src/EventRetryConstants.js +12 -0
  956. package/cursor-sidecar/node_modules/@statsig/client-core/src/Hashing.d.ts +3 -0
  957. package/cursor-sidecar/node_modules/@statsig/client-core/src/Hashing.js +35 -0
  958. package/cursor-sidecar/node_modules/@statsig/client-core/src/InitializeResponse.d.ts +66 -0
  959. package/cursor-sidecar/node_modules/@statsig/client-core/src/InitializeResponse.js +2 -0
  960. package/cursor-sidecar/node_modules/@statsig/client-core/src/Log.d.ts +15 -0
  961. package/cursor-sidecar/node_modules/@statsig/client-core/src/Log.js +44 -0
  962. package/cursor-sidecar/node_modules/@statsig/client-core/src/MemoKey.d.ts +11 -0
  963. package/cursor-sidecar/node_modules/@statsig/client-core/src/MemoKey.js +37 -0
  964. package/cursor-sidecar/node_modules/@statsig/client-core/src/NetworkConfig.d.ts +26 -0
  965. package/cursor-sidecar/node_modules/@statsig/client-core/src/NetworkConfig.js +23 -0
  966. package/cursor-sidecar/node_modules/@statsig/client-core/src/NetworkCore.d.ts +55 -0
  967. package/cursor-sidecar/node_modules/@statsig/client-core/src/NetworkCore.js +371 -0
  968. package/cursor-sidecar/node_modules/@statsig/client-core/src/NetworkFallbackResolver.d.ts +21 -0
  969. package/cursor-sidecar/node_modules/@statsig/client-core/src/NetworkFallbackResolver.js +198 -0
  970. package/cursor-sidecar/node_modules/@statsig/client-core/src/OverrideAdapter.d.ts +16 -0
  971. package/cursor-sidecar/node_modules/@statsig/client-core/src/OverrideAdapter.js +2 -0
  972. package/cursor-sidecar/node_modules/@statsig/client-core/src/ParamStoreTypes.d.ts +65 -0
  973. package/cursor-sidecar/node_modules/@statsig/client-core/src/ParamStoreTypes.js +2 -0
  974. package/cursor-sidecar/node_modules/@statsig/client-core/src/SDKFlags.d.ts +4 -0
  975. package/cursor-sidecar/node_modules/@statsig/client-core/src/SDKFlags.js +13 -0
  976. package/cursor-sidecar/node_modules/@statsig/client-core/src/SDKType.d.ts +8 -0
  977. package/cursor-sidecar/node_modules/@statsig/client-core/src/SDKType.js +19 -0
  978. package/cursor-sidecar/node_modules/@statsig/client-core/src/SafeJs.d.ts +8 -0
  979. package/cursor-sidecar/node_modules/@statsig/client-core/src/SafeJs.js +68 -0
  980. package/cursor-sidecar/node_modules/@statsig/client-core/src/SessionID.d.ts +20 -0
  981. package/cursor-sidecar/node_modules/@statsig/client-core/src/SessionID.js +106 -0
  982. package/cursor-sidecar/node_modules/@statsig/client-core/src/SizeOf.d.ts +1 -0
  983. package/cursor-sidecar/node_modules/@statsig/client-core/src/SizeOf.js +26 -0
  984. package/cursor-sidecar/node_modules/@statsig/client-core/src/StableID.d.ts +9 -0
  985. package/cursor-sidecar/node_modules/@statsig/client-core/src/StableID.js +90 -0
  986. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigClientBase.d.ts +74 -0
  987. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigClientBase.js +207 -0
  988. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigClientEventEmitter.d.ts +100 -0
  989. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigClientEventEmitter.js +6 -0
  990. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigDataAdapter.d.ts +131 -0
  991. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigDataAdapter.js +4 -0
  992. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigEvent.d.ts +28 -0
  993. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigEvent.js +98 -0
  994. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigMetadata.d.ts +18 -0
  995. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigMetadata.js +14 -0
  996. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigOptionsCommon.d.ts +180 -0
  997. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigOptionsCommon.js +16 -0
  998. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigPlugin.d.ts +5 -0
  999. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigPlugin.js +2 -0
  1000. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigTypeFactories.d.ts +8 -0
  1001. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigTypeFactories.js +57 -0
  1002. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigTypes.d.ts +43 -0
  1003. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigTypes.js +2 -0
  1004. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigUpdateDetails.d.ts +14 -0
  1005. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigUpdateDetails.js +17 -0
  1006. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigUser.d.ts +24 -0
  1007. package/cursor-sidecar/node_modules/@statsig/client-core/src/StatsigUser.js +25 -0
  1008. package/cursor-sidecar/node_modules/@statsig/client-core/src/StorageProvider.d.ts +17 -0
  1009. package/cursor-sidecar/node_modules/@statsig/client-core/src/StorageProvider.js +90 -0
  1010. package/cursor-sidecar/node_modules/@statsig/client-core/src/TypedJsonParse.d.ts +8 -0
  1011. package/cursor-sidecar/node_modules/@statsig/client-core/src/TypedJsonParse.js +27 -0
  1012. package/cursor-sidecar/node_modules/@statsig/client-core/src/TypingUtils.d.ts +7 -0
  1013. package/cursor-sidecar/node_modules/@statsig/client-core/src/TypingUtils.js +12 -0
  1014. package/cursor-sidecar/node_modules/@statsig/client-core/src/UUID.d.ts +1 -0
  1015. package/cursor-sidecar/node_modules/@statsig/client-core/src/UUID.js +28 -0
  1016. package/cursor-sidecar/node_modules/@statsig/client-core/src/UrlConfiguration.d.ts +12 -0
  1017. package/cursor-sidecar/node_modules/@statsig/client-core/src/UrlConfiguration.js +41 -0
  1018. package/cursor-sidecar/node_modules/@statsig/client-core/src/VisibilityObserving.d.ts +9 -0
  1019. package/cursor-sidecar/node_modules/@statsig/client-core/src/VisibilityObserving.js +39 -0
  1020. package/cursor-sidecar/node_modules/@statsig/client-core/src/__tests__/MockOverrideAdapter.d.ts +16 -0
  1021. package/cursor-sidecar/node_modules/@statsig/client-core/src/__tests__/MockOverrideAdapter.js +21 -0
  1022. package/cursor-sidecar/node_modules/@statsig/client-core/src/index.d.ts +47 -0
  1023. package/cursor-sidecar/node_modules/@statsig/client-core/src/index.js +70 -0
  1024. package/cursor-sidecar/node_modules/@statsig/js-client/LICENSE +14 -0
  1025. package/cursor-sidecar/node_modules/@statsig/js-client/README.md +49 -0
  1026. package/cursor-sidecar/node_modules/@statsig/js-client/build/statsig-js-client+session-replay+web-analytics.min.js +2 -0
  1027. package/cursor-sidecar/node_modules/@statsig/js-client/build/statsig-js-client+session-replay.min.js +1 -0
  1028. package/cursor-sidecar/node_modules/@statsig/js-client/build/statsig-js-client+web-analytics.min.js +2 -0
  1029. package/cursor-sidecar/node_modules/@statsig/js-client/build/statsig-js-client.min.js +1 -0
  1030. package/cursor-sidecar/node_modules/@statsig/js-client/package.json +18 -0
  1031. package/cursor-sidecar/node_modules/@statsig/js-client/src/EvaluationResponseDeltas.d.ts +10 -0
  1032. package/cursor-sidecar/node_modules/@statsig/js-client/src/EvaluationResponseDeltas.js +49 -0
  1033. package/cursor-sidecar/node_modules/@statsig/js-client/src/EvaluationStore.d.ts +29 -0
  1034. package/cursor-sidecar/node_modules/@statsig/js-client/src/EvaluationStore.js +175 -0
  1035. package/cursor-sidecar/node_modules/@statsig/js-client/src/InitializeContainer.d.ts +9 -0
  1036. package/cursor-sidecar/node_modules/@statsig/js-client/src/InitializeContainer.js +2 -0
  1037. package/cursor-sidecar/node_modules/@statsig/js-client/src/Network.d.ts +9 -0
  1038. package/cursor-sidecar/node_modules/@statsig/js-client/src/Network.js +74 -0
  1039. package/cursor-sidecar/node_modules/@statsig/js-client/src/ParamStoreGetterFactory.d.ts +3 -0
  1040. package/cursor-sidecar/node_modules/@statsig/js-client/src/ParamStoreGetterFactory.js +74 -0
  1041. package/cursor-sidecar/node_modules/@statsig/js-client/src/StatsigClient.d.ts +244 -0
  1042. package/cursor-sidecar/node_modules/@statsig/js-client/src/StatsigClient.js +418 -0
  1043. package/cursor-sidecar/node_modules/@statsig/js-client/src/StatsigEvaluationsDataAdapter.d.ts +15 -0
  1044. package/cursor-sidecar/node_modules/@statsig/js-client/src/StatsigEvaluationsDataAdapter.js +65 -0
  1045. package/cursor-sidecar/node_modules/@statsig/js-client/src/StatsigOptions.d.ts +42 -0
  1046. package/cursor-sidecar/node_modules/@statsig/js-client/src/StatsigOptions.js +2 -0
  1047. package/cursor-sidecar/node_modules/@statsig/js-client/src/V1InitializeContainer.d.ts +13 -0
  1048. package/cursor-sidecar/node_modules/@statsig/js-client/src/V1InitializeContainer.js +35 -0
  1049. package/cursor-sidecar/node_modules/@statsig/js-client/src/V2InitializeContainer.d.ts +13 -0
  1050. package/cursor-sidecar/node_modules/@statsig/js-client/src/V2InitializeContainer.js +82 -0
  1051. package/cursor-sidecar/node_modules/@statsig/js-client/src/index.d.ts +9 -0
  1052. package/cursor-sidecar/node_modules/@statsig/js-client/src/index.js +25 -0
  1053. package/cursor-sidecar/node_modules/undici/LICENSE +21 -0
  1054. package/cursor-sidecar/node_modules/undici/README.md +443 -0
  1055. package/cursor-sidecar/node_modules/undici/docs/api/Agent.md +80 -0
  1056. package/cursor-sidecar/node_modules/undici/docs/api/BalancedPool.md +99 -0
  1057. package/cursor-sidecar/node_modules/undici/docs/api/CacheStorage.md +30 -0
  1058. package/cursor-sidecar/node_modules/undici/docs/api/Client.md +273 -0
  1059. package/cursor-sidecar/node_modules/undici/docs/api/Connector.md +115 -0
  1060. package/cursor-sidecar/node_modules/undici/docs/api/ContentType.md +57 -0
  1061. package/cursor-sidecar/node_modules/undici/docs/api/Cookies.md +101 -0
  1062. package/cursor-sidecar/node_modules/undici/docs/api/DiagnosticsChannel.md +204 -0
  1063. package/cursor-sidecar/node_modules/undici/docs/api/DispatchInterceptor.md +60 -0
  1064. package/cursor-sidecar/node_modules/undici/docs/api/Dispatcher.md +887 -0
  1065. package/cursor-sidecar/node_modules/undici/docs/api/Errors.md +47 -0
  1066. package/cursor-sidecar/node_modules/undici/docs/api/Fetch.md +27 -0
  1067. package/cursor-sidecar/node_modules/undici/docs/api/MockAgent.md +540 -0
  1068. package/cursor-sidecar/node_modules/undici/docs/api/MockClient.md +77 -0
  1069. package/cursor-sidecar/node_modules/undici/docs/api/MockErrors.md +12 -0
  1070. package/cursor-sidecar/node_modules/undici/docs/api/MockPool.md +547 -0
  1071. package/cursor-sidecar/node_modules/undici/docs/api/Pool.md +84 -0
  1072. package/cursor-sidecar/node_modules/undici/docs/api/PoolStats.md +35 -0
  1073. package/cursor-sidecar/node_modules/undici/docs/api/ProxyAgent.md +126 -0
  1074. package/cursor-sidecar/node_modules/undici/docs/api/RetryHandler.md +108 -0
  1075. package/cursor-sidecar/node_modules/undici/docs/api/WebSocket.md +43 -0
  1076. package/cursor-sidecar/node_modules/undici/docs/api/api-lifecycle.md +62 -0
  1077. package/cursor-sidecar/node_modules/undici/docs/assets/lifecycle-diagram.png +0 -0
  1078. package/cursor-sidecar/node_modules/undici/docs/best-practices/client-certificate.md +64 -0
  1079. package/cursor-sidecar/node_modules/undici/docs/best-practices/mocking-request.md +136 -0
  1080. package/cursor-sidecar/node_modules/undici/docs/best-practices/proxy.md +127 -0
  1081. package/cursor-sidecar/node_modules/undici/docs/best-practices/writing-tests.md +20 -0
  1082. package/cursor-sidecar/node_modules/undici/index-fetch.js +15 -0
  1083. package/cursor-sidecar/node_modules/undici/index.d.ts +3 -0
  1084. package/cursor-sidecar/node_modules/undici/index.js +167 -0
  1085. package/cursor-sidecar/node_modules/undici/lib/agent.js +148 -0
  1086. package/cursor-sidecar/node_modules/undici/lib/api/abort-signal.js +54 -0
  1087. package/cursor-sidecar/node_modules/undici/lib/api/api-connect.js +104 -0
  1088. package/cursor-sidecar/node_modules/undici/lib/api/api-pipeline.js +249 -0
  1089. package/cursor-sidecar/node_modules/undici/lib/api/api-request.js +180 -0
  1090. package/cursor-sidecar/node_modules/undici/lib/api/api-stream.js +220 -0
  1091. package/cursor-sidecar/node_modules/undici/lib/api/api-upgrade.js +105 -0
  1092. package/cursor-sidecar/node_modules/undici/lib/api/index.js +7 -0
  1093. package/cursor-sidecar/node_modules/undici/lib/api/readable.js +322 -0
  1094. package/cursor-sidecar/node_modules/undici/lib/api/util.js +46 -0
  1095. package/cursor-sidecar/node_modules/undici/lib/balanced-pool.js +190 -0
  1096. package/cursor-sidecar/node_modules/undici/lib/cache/cache.js +838 -0
  1097. package/cursor-sidecar/node_modules/undici/lib/cache/cachestorage.js +144 -0
  1098. package/cursor-sidecar/node_modules/undici/lib/cache/symbols.js +5 -0
  1099. package/cursor-sidecar/node_modules/undici/lib/cache/util.js +49 -0
  1100. package/cursor-sidecar/node_modules/undici/lib/client.js +2283 -0
  1101. package/cursor-sidecar/node_modules/undici/lib/compat/dispatcher-weakref.js +48 -0
  1102. package/cursor-sidecar/node_modules/undici/lib/cookies/constants.js +12 -0
  1103. package/cursor-sidecar/node_modules/undici/lib/cookies/index.js +183 -0
  1104. package/cursor-sidecar/node_modules/undici/lib/cookies/parse.js +317 -0
  1105. package/cursor-sidecar/node_modules/undici/lib/cookies/util.js +274 -0
  1106. package/cursor-sidecar/node_modules/undici/lib/core/connect.js +189 -0
  1107. package/cursor-sidecar/node_modules/undici/lib/core/constants.js +118 -0
  1108. package/cursor-sidecar/node_modules/undici/lib/core/errors.js +230 -0
  1109. package/cursor-sidecar/node_modules/undici/lib/core/request.js +499 -0
  1110. package/cursor-sidecar/node_modules/undici/lib/core/symbols.js +63 -0
  1111. package/cursor-sidecar/node_modules/undici/lib/core/util.js +522 -0
  1112. package/cursor-sidecar/node_modules/undici/lib/dispatcher-base.js +192 -0
  1113. package/cursor-sidecar/node_modules/undici/lib/dispatcher.js +19 -0
  1114. package/cursor-sidecar/node_modules/undici/lib/fetch/LICENSE +21 -0
  1115. package/cursor-sidecar/node_modules/undici/lib/fetch/body.js +613 -0
  1116. package/cursor-sidecar/node_modules/undici/lib/fetch/constants.js +151 -0
  1117. package/cursor-sidecar/node_modules/undici/lib/fetch/dataURL.js +627 -0
  1118. package/cursor-sidecar/node_modules/undici/lib/fetch/file.js +344 -0
  1119. package/cursor-sidecar/node_modules/undici/lib/fetch/formdata.js +265 -0
  1120. package/cursor-sidecar/node_modules/undici/lib/fetch/global.js +40 -0
  1121. package/cursor-sidecar/node_modules/undici/lib/fetch/headers.js +593 -0
  1122. package/cursor-sidecar/node_modules/undici/lib/fetch/index.js +2148 -0
  1123. package/cursor-sidecar/node_modules/undici/lib/fetch/request.js +946 -0
  1124. package/cursor-sidecar/node_modules/undici/lib/fetch/response.js +571 -0
  1125. package/cursor-sidecar/node_modules/undici/lib/fetch/symbols.js +10 -0
  1126. package/cursor-sidecar/node_modules/undici/lib/fetch/util.js +1144 -0
  1127. package/cursor-sidecar/node_modules/undici/lib/fetch/webidl.js +646 -0
  1128. package/cursor-sidecar/node_modules/undici/lib/fileapi/encoding.js +290 -0
  1129. package/cursor-sidecar/node_modules/undici/lib/fileapi/filereader.js +344 -0
  1130. package/cursor-sidecar/node_modules/undici/lib/fileapi/progressevent.js +78 -0
  1131. package/cursor-sidecar/node_modules/undici/lib/fileapi/symbols.js +10 -0
  1132. package/cursor-sidecar/node_modules/undici/lib/fileapi/util.js +392 -0
  1133. package/cursor-sidecar/node_modules/undici/lib/global.js +32 -0
  1134. package/cursor-sidecar/node_modules/undici/lib/handler/DecoratorHandler.js +35 -0
  1135. package/cursor-sidecar/node_modules/undici/lib/handler/RedirectHandler.js +221 -0
  1136. package/cursor-sidecar/node_modules/undici/lib/handler/RetryHandler.js +336 -0
  1137. package/cursor-sidecar/node_modules/undici/lib/interceptor/redirectInterceptor.js +21 -0
  1138. package/cursor-sidecar/node_modules/undici/lib/llhttp/constants.d.ts +199 -0
  1139. package/cursor-sidecar/node_modules/undici/lib/llhttp/constants.js +278 -0
  1140. package/cursor-sidecar/node_modules/undici/lib/llhttp/constants.js.map +1 -0
  1141. package/cursor-sidecar/node_modules/undici/lib/llhttp/llhttp-wasm.js +1 -0
  1142. package/cursor-sidecar/node_modules/undici/lib/llhttp/llhttp.wasm +0 -0
  1143. package/cursor-sidecar/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js +1 -0
  1144. package/cursor-sidecar/node_modules/undici/lib/llhttp/llhttp_simd.wasm +0 -0
  1145. package/cursor-sidecar/node_modules/undici/lib/llhttp/utils.d.ts +4 -0
  1146. package/cursor-sidecar/node_modules/undici/lib/llhttp/utils.js +15 -0
  1147. package/cursor-sidecar/node_modules/undici/lib/llhttp/utils.js.map +1 -0
  1148. package/cursor-sidecar/node_modules/undici/lib/llhttp/wasm_build_env.txt +32 -0
  1149. package/cursor-sidecar/node_modules/undici/lib/mock/mock-agent.js +171 -0
  1150. package/cursor-sidecar/node_modules/undici/lib/mock/mock-client.js +59 -0
  1151. package/cursor-sidecar/node_modules/undici/lib/mock/mock-errors.js +17 -0
  1152. package/cursor-sidecar/node_modules/undici/lib/mock/mock-interceptor.js +206 -0
  1153. package/cursor-sidecar/node_modules/undici/lib/mock/mock-pool.js +59 -0
  1154. package/cursor-sidecar/node_modules/undici/lib/mock/mock-symbols.js +23 -0
  1155. package/cursor-sidecar/node_modules/undici/lib/mock/mock-utils.js +351 -0
  1156. package/cursor-sidecar/node_modules/undici/lib/mock/pending-interceptors-formatter.js +40 -0
  1157. package/cursor-sidecar/node_modules/undici/lib/mock/pluralizer.js +29 -0
  1158. package/cursor-sidecar/node_modules/undici/lib/node/fixed-queue.js +117 -0
  1159. package/cursor-sidecar/node_modules/undici/lib/pool-base.js +194 -0
  1160. package/cursor-sidecar/node_modules/undici/lib/pool-stats.js +34 -0
  1161. package/cursor-sidecar/node_modules/undici/lib/pool.js +108 -0
  1162. package/cursor-sidecar/node_modules/undici/lib/proxy-agent.js +189 -0
  1163. package/cursor-sidecar/node_modules/undici/lib/timers.js +97 -0
  1164. package/cursor-sidecar/node_modules/undici/lib/websocket/connection.js +291 -0
  1165. package/cursor-sidecar/node_modules/undici/lib/websocket/constants.js +51 -0
  1166. package/cursor-sidecar/node_modules/undici/lib/websocket/events.js +303 -0
  1167. package/cursor-sidecar/node_modules/undici/lib/websocket/frame.js +73 -0
  1168. package/cursor-sidecar/node_modules/undici/lib/websocket/receiver.js +344 -0
  1169. package/cursor-sidecar/node_modules/undici/lib/websocket/symbols.js +12 -0
  1170. package/cursor-sidecar/node_modules/undici/lib/websocket/util.js +200 -0
  1171. package/cursor-sidecar/node_modules/undici/lib/websocket/websocket.js +641 -0
  1172. package/cursor-sidecar/node_modules/undici/package.json +167 -0
  1173. package/cursor-sidecar/node_modules/undici/types/README.md +6 -0
  1174. package/cursor-sidecar/node_modules/undici/types/agent.d.ts +31 -0
  1175. package/cursor-sidecar/node_modules/undici/types/api.d.ts +43 -0
  1176. package/cursor-sidecar/node_modules/undici/types/balanced-pool.d.ts +18 -0
  1177. package/cursor-sidecar/node_modules/undici/types/cache.d.ts +36 -0
  1178. package/cursor-sidecar/node_modules/undici/types/client.d.ts +97 -0
  1179. package/cursor-sidecar/node_modules/undici/types/connector.d.ts +34 -0
  1180. package/cursor-sidecar/node_modules/undici/types/content-type.d.ts +21 -0
  1181. package/cursor-sidecar/node_modules/undici/types/cookies.d.ts +28 -0
  1182. package/cursor-sidecar/node_modules/undici/types/diagnostics-channel.d.ts +67 -0
  1183. package/cursor-sidecar/node_modules/undici/types/dispatcher.d.ts +241 -0
  1184. package/cursor-sidecar/node_modules/undici/types/errors.d.ts +128 -0
  1185. package/cursor-sidecar/node_modules/undici/types/fetch.d.ts +209 -0
  1186. package/cursor-sidecar/node_modules/undici/types/file.d.ts +39 -0
  1187. package/cursor-sidecar/node_modules/undici/types/filereader.d.ts +54 -0
  1188. package/cursor-sidecar/node_modules/undici/types/formdata.d.ts +108 -0
  1189. package/cursor-sidecar/node_modules/undici/types/global-dispatcher.d.ts +9 -0
  1190. package/cursor-sidecar/node_modules/undici/types/global-origin.d.ts +7 -0
  1191. package/cursor-sidecar/node_modules/undici/types/handlers.d.ts +9 -0
  1192. package/cursor-sidecar/node_modules/undici/types/header.d.ts +4 -0
  1193. package/cursor-sidecar/node_modules/undici/types/index.d.ts +65 -0
  1194. package/cursor-sidecar/node_modules/undici/types/interceptors.d.ts +5 -0
  1195. package/cursor-sidecar/node_modules/undici/types/mock-agent.d.ts +50 -0
  1196. package/cursor-sidecar/node_modules/undici/types/mock-client.d.ts +25 -0
  1197. package/cursor-sidecar/node_modules/undici/types/mock-errors.d.ts +12 -0
  1198. package/cursor-sidecar/node_modules/undici/types/mock-interceptor.d.ts +93 -0
  1199. package/cursor-sidecar/node_modules/undici/types/mock-pool.d.ts +25 -0
  1200. package/cursor-sidecar/node_modules/undici/types/patch.d.ts +71 -0
  1201. package/cursor-sidecar/node_modules/undici/types/pool-stats.d.ts +19 -0
  1202. package/cursor-sidecar/node_modules/undici/types/pool.d.ts +28 -0
  1203. package/cursor-sidecar/node_modules/undici/types/proxy-agent.d.ts +30 -0
  1204. package/cursor-sidecar/node_modules/undici/types/readable.d.ts +61 -0
  1205. package/cursor-sidecar/node_modules/undici/types/retry-handler.d.ts +116 -0
  1206. package/cursor-sidecar/node_modules/undici/types/webidl.d.ts +220 -0
  1207. package/cursor-sidecar/node_modules/undici/types/websocket.d.ts +131 -0
  1208. package/cursor-sidecar/node_modules/zod/LICENSE +21 -0
  1209. package/cursor-sidecar/node_modules/zod/README.md +208 -0
  1210. package/cursor-sidecar/node_modules/zod/index.cjs +33 -0
  1211. package/cursor-sidecar/node_modules/zod/index.d.cts +4 -0
  1212. package/cursor-sidecar/node_modules/zod/index.d.ts +4 -0
  1213. package/cursor-sidecar/node_modules/zod/index.js +4 -0
  1214. package/cursor-sidecar/node_modules/zod/package.json +118 -0
  1215. package/cursor-sidecar/node_modules/zod/src/index.ts +4 -0
  1216. package/cursor-sidecar/node_modules/zod/src/v3/ZodError.ts +330 -0
  1217. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/datetime.ts +58 -0
  1218. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +80 -0
  1219. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/index.ts +59 -0
  1220. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/ipv4.ts +57 -0
  1221. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/object.ts +69 -0
  1222. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/primitives.ts +162 -0
  1223. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/realworld.ts +63 -0
  1224. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/string.ts +55 -0
  1225. package/cursor-sidecar/node_modules/zod/src/v3/benchmarks/union.ts +80 -0
  1226. package/cursor-sidecar/node_modules/zod/src/v3/errors.ts +13 -0
  1227. package/cursor-sidecar/node_modules/zod/src/v3/external.ts +6 -0
  1228. package/cursor-sidecar/node_modules/zod/src/v3/helpers/enumUtil.ts +17 -0
  1229. package/cursor-sidecar/node_modules/zod/src/v3/helpers/errorUtil.ts +8 -0
  1230. package/cursor-sidecar/node_modules/zod/src/v3/helpers/parseUtil.ts +176 -0
  1231. package/cursor-sidecar/node_modules/zod/src/v3/helpers/partialUtil.ts +34 -0
  1232. package/cursor-sidecar/node_modules/zod/src/v3/helpers/typeAliases.ts +2 -0
  1233. package/cursor-sidecar/node_modules/zod/src/v3/helpers/util.ts +224 -0
  1234. package/cursor-sidecar/node_modules/zod/src/v3/index.ts +4 -0
  1235. package/cursor-sidecar/node_modules/zod/src/v3/locales/en.ts +124 -0
  1236. package/cursor-sidecar/node_modules/zod/src/v3/standard-schema.ts +113 -0
  1237. package/cursor-sidecar/node_modules/zod/src/v3/tests/Mocker.ts +54 -0
  1238. package/cursor-sidecar/node_modules/zod/src/v3/tests/all-errors.test.ts +157 -0
  1239. package/cursor-sidecar/node_modules/zod/src/v3/tests/anyunknown.test.ts +28 -0
  1240. package/cursor-sidecar/node_modules/zod/src/v3/tests/array.test.ts +71 -0
  1241. package/cursor-sidecar/node_modules/zod/src/v3/tests/async-parsing.test.ts +388 -0
  1242. package/cursor-sidecar/node_modules/zod/src/v3/tests/async-refinements.test.ts +46 -0
  1243. package/cursor-sidecar/node_modules/zod/src/v3/tests/base.test.ts +29 -0
  1244. package/cursor-sidecar/node_modules/zod/src/v3/tests/bigint.test.ts +55 -0
  1245. package/cursor-sidecar/node_modules/zod/src/v3/tests/branded.test.ts +53 -0
  1246. package/cursor-sidecar/node_modules/zod/src/v3/tests/catch.test.ts +220 -0
  1247. package/cursor-sidecar/node_modules/zod/src/v3/tests/coerce.test.ts +133 -0
  1248. package/cursor-sidecar/node_modules/zod/src/v3/tests/complex.test.ts +56 -0
  1249. package/cursor-sidecar/node_modules/zod/src/v3/tests/custom.test.ts +31 -0
  1250. package/cursor-sidecar/node_modules/zod/src/v3/tests/date.test.ts +32 -0
  1251. package/cursor-sidecar/node_modules/zod/src/v3/tests/deepmasking.test.ts +186 -0
  1252. package/cursor-sidecar/node_modules/zod/src/v3/tests/default.test.ts +112 -0
  1253. package/cursor-sidecar/node_modules/zod/src/v3/tests/description.test.ts +33 -0
  1254. package/cursor-sidecar/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +315 -0
  1255. package/cursor-sidecar/node_modules/zod/src/v3/tests/enum.test.ts +80 -0
  1256. package/cursor-sidecar/node_modules/zod/src/v3/tests/error.test.ts +551 -0
  1257. package/cursor-sidecar/node_modules/zod/src/v3/tests/firstparty.test.ts +87 -0
  1258. package/cursor-sidecar/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +21 -0
  1259. package/cursor-sidecar/node_modules/zod/src/v3/tests/function.test.ts +257 -0
  1260. package/cursor-sidecar/node_modules/zod/src/v3/tests/generics.test.ts +48 -0
  1261. package/cursor-sidecar/node_modules/zod/src/v3/tests/instanceof.test.ts +37 -0
  1262. package/cursor-sidecar/node_modules/zod/src/v3/tests/intersection.test.ts +110 -0
  1263. package/cursor-sidecar/node_modules/zod/src/v3/tests/language-server.source.ts +76 -0
  1264. package/cursor-sidecar/node_modules/zod/src/v3/tests/language-server.test.ts +207 -0
  1265. package/cursor-sidecar/node_modules/zod/src/v3/tests/literal.test.ts +36 -0
  1266. package/cursor-sidecar/node_modules/zod/src/v3/tests/map.test.ts +110 -0
  1267. package/cursor-sidecar/node_modules/zod/src/v3/tests/masking.test.ts +4 -0
  1268. package/cursor-sidecar/node_modules/zod/src/v3/tests/mocker.test.ts +19 -0
  1269. package/cursor-sidecar/node_modules/zod/src/v3/tests/nan.test.ts +21 -0
  1270. package/cursor-sidecar/node_modules/zod/src/v3/tests/nativeEnum.test.ts +87 -0
  1271. package/cursor-sidecar/node_modules/zod/src/v3/tests/nullable.test.ts +42 -0
  1272. package/cursor-sidecar/node_modules/zod/src/v3/tests/number.test.ts +176 -0
  1273. package/cursor-sidecar/node_modules/zod/src/v3/tests/object-augmentation.test.ts +29 -0
  1274. package/cursor-sidecar/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +29 -0
  1275. package/cursor-sidecar/node_modules/zod/src/v3/tests/object.test.ts +434 -0
  1276. package/cursor-sidecar/node_modules/zod/src/v3/tests/optional.test.ts +42 -0
  1277. package/cursor-sidecar/node_modules/zod/src/v3/tests/parseUtil.test.ts +23 -0
  1278. package/cursor-sidecar/node_modules/zod/src/v3/tests/parser.test.ts +41 -0
  1279. package/cursor-sidecar/node_modules/zod/src/v3/tests/partials.test.ts +243 -0
  1280. package/cursor-sidecar/node_modules/zod/src/v3/tests/pickomit.test.ts +111 -0
  1281. package/cursor-sidecar/node_modules/zod/src/v3/tests/pipeline.test.ts +29 -0
  1282. package/cursor-sidecar/node_modules/zod/src/v3/tests/preprocess.test.ts +186 -0
  1283. package/cursor-sidecar/node_modules/zod/src/v3/tests/primitive.test.ts +440 -0
  1284. package/cursor-sidecar/node_modules/zod/src/v3/tests/promise.test.ts +90 -0
  1285. package/cursor-sidecar/node_modules/zod/src/v3/tests/readonly.test.ts +194 -0
  1286. package/cursor-sidecar/node_modules/zod/src/v3/tests/record.test.ts +171 -0
  1287. package/cursor-sidecar/node_modules/zod/src/v3/tests/recursive.test.ts +197 -0
  1288. package/cursor-sidecar/node_modules/zod/src/v3/tests/refine.test.ts +313 -0
  1289. package/cursor-sidecar/node_modules/zod/src/v3/tests/safeparse.test.ts +27 -0
  1290. package/cursor-sidecar/node_modules/zod/src/v3/tests/set.test.ts +142 -0
  1291. package/cursor-sidecar/node_modules/zod/src/v3/tests/standard-schema.test.ts +83 -0
  1292. package/cursor-sidecar/node_modules/zod/src/v3/tests/string.test.ts +916 -0
  1293. package/cursor-sidecar/node_modules/zod/src/v3/tests/transformer.test.ts +233 -0
  1294. package/cursor-sidecar/node_modules/zod/src/v3/tests/tuple.test.ts +90 -0
  1295. package/cursor-sidecar/node_modules/zod/src/v3/tests/unions.test.ts +57 -0
  1296. package/cursor-sidecar/node_modules/zod/src/v3/tests/validations.test.ts +133 -0
  1297. package/cursor-sidecar/node_modules/zod/src/v3/tests/void.test.ts +15 -0
  1298. package/cursor-sidecar/node_modules/zod/src/v3/types.ts +5136 -0
  1299. package/cursor-sidecar/node_modules/zod/src/v4/classic/checks.ts +30 -0
  1300. package/cursor-sidecar/node_modules/zod/src/v4/classic/coerce.ts +27 -0
  1301. package/cursor-sidecar/node_modules/zod/src/v4/classic/compat.ts +66 -0
  1302. package/cursor-sidecar/node_modules/zod/src/v4/classic/errors.ts +75 -0
  1303. package/cursor-sidecar/node_modules/zod/src/v4/classic/external.ts +50 -0
  1304. package/cursor-sidecar/node_modules/zod/src/v4/classic/index.ts +5 -0
  1305. package/cursor-sidecar/node_modules/zod/src/v4/classic/iso.ts +90 -0
  1306. package/cursor-sidecar/node_modules/zod/src/v4/classic/parse.ts +33 -0
  1307. package/cursor-sidecar/node_modules/zod/src/v4/classic/schemas.ts +2054 -0
  1308. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +26 -0
  1309. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/array.test.ts +264 -0
  1310. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/assignability.test.ts +210 -0
  1311. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +381 -0
  1312. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +68 -0
  1313. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/base.test.ts +7 -0
  1314. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/bigint.test.ts +54 -0
  1315. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/brand.test.ts +63 -0
  1316. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/catch.test.ts +252 -0
  1317. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +20 -0
  1318. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/coerce.test.ts +160 -0
  1319. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/continuability.test.ts +352 -0
  1320. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/custom.test.ts +40 -0
  1321. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/date.test.ts +31 -0
  1322. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/datetime.test.ts +296 -0
  1323. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/default.test.ts +313 -0
  1324. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/description.test.ts +32 -0
  1325. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +619 -0
  1326. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/enum.test.ts +285 -0
  1327. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +527 -0
  1328. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/error.test.ts +711 -0
  1329. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/file.test.ts +91 -0
  1330. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +175 -0
  1331. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/function.test.ts +268 -0
  1332. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/generics.test.ts +72 -0
  1333. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/index.test.ts +829 -0
  1334. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +34 -0
  1335. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/intersection.test.ts +171 -0
  1336. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/json.test.ts +108 -0
  1337. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/lazy.test.ts +227 -0
  1338. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/literal.test.ts +92 -0
  1339. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/map.test.ts +196 -0
  1340. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/nan.test.ts +21 -0
  1341. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +168 -0
  1342. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +86 -0
  1343. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/nullable.test.ts +22 -0
  1344. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/number.test.ts +247 -0
  1345. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/object.test.ts +563 -0
  1346. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/optional.test.ts +123 -0
  1347. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/partial.test.ts +147 -0
  1348. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +127 -0
  1349. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/pipe.test.ts +81 -0
  1350. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/prefault.test.ts +37 -0
  1351. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +298 -0
  1352. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/primitive.test.ts +175 -0
  1353. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/promise.test.ts +81 -0
  1354. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +23 -0
  1355. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/readonly.test.ts +252 -0
  1356. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/record.test.ts +342 -0
  1357. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +356 -0
  1358. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/refine.test.ts +532 -0
  1359. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/registries.test.ts +204 -0
  1360. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/set.test.ts +179 -0
  1361. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +57 -0
  1362. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +109 -0
  1363. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/string.test.ts +881 -0
  1364. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +66 -0
  1365. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +758 -0
  1366. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +2314 -0
  1367. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/transform.test.ts +250 -0
  1368. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/tuple.test.ts +163 -0
  1369. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/union.test.ts +94 -0
  1370. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/validations.test.ts +283 -0
  1371. package/cursor-sidecar/node_modules/zod/src/v4/classic/tests/void.test.ts +12 -0
  1372. package/cursor-sidecar/node_modules/zod/src/v4/core/api.ts +1594 -0
  1373. package/cursor-sidecar/node_modules/zod/src/v4/core/checks.ts +1283 -0
  1374. package/cursor-sidecar/node_modules/zod/src/v4/core/config.ts +15 -0
  1375. package/cursor-sidecar/node_modules/zod/src/v4/core/core.ts +134 -0
  1376. package/cursor-sidecar/node_modules/zod/src/v4/core/doc.ts +44 -0
  1377. package/cursor-sidecar/node_modules/zod/src/v4/core/errors.ts +424 -0
  1378. package/cursor-sidecar/node_modules/zod/src/v4/core/function.ts +176 -0
  1379. package/cursor-sidecar/node_modules/zod/src/v4/core/index.ts +15 -0
  1380. package/cursor-sidecar/node_modules/zod/src/v4/core/json-schema.ts +143 -0
  1381. package/cursor-sidecar/node_modules/zod/src/v4/core/parse.ts +94 -0
  1382. package/cursor-sidecar/node_modules/zod/src/v4/core/regexes.ts +135 -0
  1383. package/cursor-sidecar/node_modules/zod/src/v4/core/registries.ts +96 -0
  1384. package/cursor-sidecar/node_modules/zod/src/v4/core/schemas.ts +3842 -0
  1385. package/cursor-sidecar/node_modules/zod/src/v4/core/standard-schema.ts +64 -0
  1386. package/cursor-sidecar/node_modules/zod/src/v4/core/tests/index.test.ts +46 -0
  1387. package/cursor-sidecar/node_modules/zod/src/v4/core/tests/locales/be.test.ts +124 -0
  1388. package/cursor-sidecar/node_modules/zod/src/v4/core/tests/locales/en.test.ts +22 -0
  1389. package/cursor-sidecar/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +128 -0
  1390. package/cursor-sidecar/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +69 -0
  1391. package/cursor-sidecar/node_modules/zod/src/v4/core/to-json-schema.ts +977 -0
  1392. package/cursor-sidecar/node_modules/zod/src/v4/core/util.ts +775 -0
  1393. package/cursor-sidecar/node_modules/zod/src/v4/core/versions.ts +5 -0
  1394. package/cursor-sidecar/node_modules/zod/src/v4/core/zsf.ts +323 -0
  1395. package/cursor-sidecar/node_modules/zod/src/v4/index.ts +4 -0
  1396. package/cursor-sidecar/node_modules/zod/src/v4/locales/ar.ts +125 -0
  1397. package/cursor-sidecar/node_modules/zod/src/v4/locales/az.ts +121 -0
  1398. package/cursor-sidecar/node_modules/zod/src/v4/locales/be.ts +184 -0
  1399. package/cursor-sidecar/node_modules/zod/src/v4/locales/ca.ts +127 -0
  1400. package/cursor-sidecar/node_modules/zod/src/v4/locales/cs.ts +142 -0
  1401. package/cursor-sidecar/node_modules/zod/src/v4/locales/de.ts +124 -0
  1402. package/cursor-sidecar/node_modules/zod/src/v4/locales/en.ts +127 -0
  1403. package/cursor-sidecar/node_modules/zod/src/v4/locales/eo.ts +125 -0
  1404. package/cursor-sidecar/node_modules/zod/src/v4/locales/es.ts +125 -0
  1405. package/cursor-sidecar/node_modules/zod/src/v4/locales/fa.ts +134 -0
  1406. package/cursor-sidecar/node_modules/zod/src/v4/locales/fi.ts +131 -0
  1407. package/cursor-sidecar/node_modules/zod/src/v4/locales/fr-CA.ts +126 -0
  1408. package/cursor-sidecar/node_modules/zod/src/v4/locales/fr.ts +124 -0
  1409. package/cursor-sidecar/node_modules/zod/src/v4/locales/he.ts +125 -0
  1410. package/cursor-sidecar/node_modules/zod/src/v4/locales/hu.ts +126 -0
  1411. package/cursor-sidecar/node_modules/zod/src/v4/locales/id.ts +125 -0
  1412. package/cursor-sidecar/node_modules/zod/src/v4/locales/index.ts +39 -0
  1413. package/cursor-sidecar/node_modules/zod/src/v4/locales/it.ts +125 -0
  1414. package/cursor-sidecar/node_modules/zod/src/v4/locales/ja.ts +122 -0
  1415. package/cursor-sidecar/node_modules/zod/src/v4/locales/kh.ts +126 -0
  1416. package/cursor-sidecar/node_modules/zod/src/v4/locales/ko.ts +131 -0
  1417. package/cursor-sidecar/node_modules/zod/src/v4/locales/mk.ts +127 -0
  1418. package/cursor-sidecar/node_modules/zod/src/v4/locales/ms.ts +124 -0
  1419. package/cursor-sidecar/node_modules/zod/src/v4/locales/nl.ts +126 -0
  1420. package/cursor-sidecar/node_modules/zod/src/v4/locales/no.ts +124 -0
  1421. package/cursor-sidecar/node_modules/zod/src/v4/locales/ota.ts +125 -0
  1422. package/cursor-sidecar/node_modules/zod/src/v4/locales/pl.ts +126 -0
  1423. package/cursor-sidecar/node_modules/zod/src/v4/locales/ps.ts +133 -0
  1424. package/cursor-sidecar/node_modules/zod/src/v4/locales/pt.ts +123 -0
  1425. package/cursor-sidecar/node_modules/zod/src/v4/locales/ru.ts +184 -0
  1426. package/cursor-sidecar/node_modules/zod/src/v4/locales/sl.ts +126 -0
  1427. package/cursor-sidecar/node_modules/zod/src/v4/locales/sv.ts +127 -0
  1428. package/cursor-sidecar/node_modules/zod/src/v4/locales/ta.ts +125 -0
  1429. package/cursor-sidecar/node_modules/zod/src/v4/locales/th.ts +126 -0
  1430. package/cursor-sidecar/node_modules/zod/src/v4/locales/tr.ts +121 -0
  1431. package/cursor-sidecar/node_modules/zod/src/v4/locales/ua.ts +126 -0
  1432. package/cursor-sidecar/node_modules/zod/src/v4/locales/ur.ts +126 -0
  1433. package/cursor-sidecar/node_modules/zod/src/v4/locales/vi.ts +125 -0
  1434. package/cursor-sidecar/node_modules/zod/src/v4/locales/zh-CN.ts +123 -0
  1435. package/cursor-sidecar/node_modules/zod/src/v4/locales/zh-TW.ts +125 -0
  1436. package/cursor-sidecar/node_modules/zod/src/v4/mini/checks.ts +32 -0
  1437. package/cursor-sidecar/node_modules/zod/src/v4/mini/coerce.ts +22 -0
  1438. package/cursor-sidecar/node_modules/zod/src/v4/mini/external.ts +40 -0
  1439. package/cursor-sidecar/node_modules/zod/src/v4/mini/index.ts +3 -0
  1440. package/cursor-sidecar/node_modules/zod/src/v4/mini/iso.ts +62 -0
  1441. package/cursor-sidecar/node_modules/zod/src/v4/mini/parse.ts +1 -0
  1442. package/cursor-sidecar/node_modules/zod/src/v4/mini/schemas.ts +1579 -0
  1443. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/assignability.test.ts +129 -0
  1444. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/brand.test.ts +51 -0
  1445. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/checks.test.ts +144 -0
  1446. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/computed.test.ts +36 -0
  1447. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/error.test.ts +22 -0
  1448. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/functions.test.ts +43 -0
  1449. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/index.test.ts +871 -0
  1450. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/number.test.ts +95 -0
  1451. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/object.test.ts +185 -0
  1452. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +43 -0
  1453. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +275 -0
  1454. package/cursor-sidecar/node_modules/zod/src/v4/mini/tests/string.test.ts +299 -0
  1455. package/cursor-sidecar/node_modules/zod/src/v4-mini/index.ts +1 -0
  1456. package/cursor-sidecar/node_modules/zod/v3/ZodError.cjs +138 -0
  1457. package/cursor-sidecar/node_modules/zod/v3/ZodError.d.cts +164 -0
  1458. package/cursor-sidecar/node_modules/zod/v3/ZodError.d.ts +164 -0
  1459. package/cursor-sidecar/node_modules/zod/v3/ZodError.js +133 -0
  1460. package/cursor-sidecar/node_modules/zod/v3/errors.cjs +17 -0
  1461. package/cursor-sidecar/node_modules/zod/v3/errors.d.cts +5 -0
  1462. package/cursor-sidecar/node_modules/zod/v3/errors.d.ts +5 -0
  1463. package/cursor-sidecar/node_modules/zod/v3/errors.js +9 -0
  1464. package/cursor-sidecar/node_modules/zod/v3/external.cjs +22 -0
  1465. package/cursor-sidecar/node_modules/zod/v3/external.d.cts +6 -0
  1466. package/cursor-sidecar/node_modules/zod/v3/external.d.ts +6 -0
  1467. package/cursor-sidecar/node_modules/zod/v3/external.js +6 -0
  1468. package/cursor-sidecar/node_modules/zod/v3/helpers/enumUtil.cjs +2 -0
  1469. package/cursor-sidecar/node_modules/zod/v3/helpers/enumUtil.d.cts +8 -0
  1470. package/cursor-sidecar/node_modules/zod/v3/helpers/enumUtil.d.ts +8 -0
  1471. package/cursor-sidecar/node_modules/zod/v3/helpers/enumUtil.js +1 -0
  1472. package/cursor-sidecar/node_modules/zod/v3/helpers/errorUtil.cjs +9 -0
  1473. package/cursor-sidecar/node_modules/zod/v3/helpers/errorUtil.d.cts +9 -0
  1474. package/cursor-sidecar/node_modules/zod/v3/helpers/errorUtil.d.ts +9 -0
  1475. package/cursor-sidecar/node_modules/zod/v3/helpers/errorUtil.js +6 -0
  1476. package/cursor-sidecar/node_modules/zod/v3/helpers/parseUtil.cjs +124 -0
  1477. package/cursor-sidecar/node_modules/zod/v3/helpers/parseUtil.d.cts +78 -0
  1478. package/cursor-sidecar/node_modules/zod/v3/helpers/parseUtil.d.ts +78 -0
  1479. package/cursor-sidecar/node_modules/zod/v3/helpers/parseUtil.js +109 -0
  1480. package/cursor-sidecar/node_modules/zod/v3/helpers/partialUtil.cjs +2 -0
  1481. package/cursor-sidecar/node_modules/zod/v3/helpers/partialUtil.d.cts +8 -0
  1482. package/cursor-sidecar/node_modules/zod/v3/helpers/partialUtil.d.ts +8 -0
  1483. package/cursor-sidecar/node_modules/zod/v3/helpers/partialUtil.js +1 -0
  1484. package/cursor-sidecar/node_modules/zod/v3/helpers/typeAliases.cjs +2 -0
  1485. package/cursor-sidecar/node_modules/zod/v3/helpers/typeAliases.d.cts +2 -0
  1486. package/cursor-sidecar/node_modules/zod/v3/helpers/typeAliases.d.ts +2 -0
  1487. package/cursor-sidecar/node_modules/zod/v3/helpers/typeAliases.js +1 -0
  1488. package/cursor-sidecar/node_modules/zod/v3/helpers/util.cjs +137 -0
  1489. package/cursor-sidecar/node_modules/zod/v3/helpers/util.d.cts +85 -0
  1490. package/cursor-sidecar/node_modules/zod/v3/helpers/util.d.ts +85 -0
  1491. package/cursor-sidecar/node_modules/zod/v3/helpers/util.js +133 -0
  1492. package/cursor-sidecar/node_modules/zod/v3/index.cjs +33 -0
  1493. package/cursor-sidecar/node_modules/zod/v3/index.d.cts +4 -0
  1494. package/cursor-sidecar/node_modules/zod/v3/index.d.ts +4 -0
  1495. package/cursor-sidecar/node_modules/zod/v3/index.js +4 -0
  1496. package/cursor-sidecar/node_modules/zod/v3/locales/en.cjs +111 -0
  1497. package/cursor-sidecar/node_modules/zod/v3/locales/en.d.cts +3 -0
  1498. package/cursor-sidecar/node_modules/zod/v3/locales/en.d.ts +3 -0
  1499. package/cursor-sidecar/node_modules/zod/v3/locales/en.js +109 -0
  1500. package/cursor-sidecar/node_modules/zod/v3/standard-schema.cjs +2 -0
  1501. package/cursor-sidecar/node_modules/zod/v3/standard-schema.d.cts +102 -0
  1502. package/cursor-sidecar/node_modules/zod/v3/standard-schema.d.ts +102 -0
  1503. package/cursor-sidecar/node_modules/zod/v3/standard-schema.js +1 -0
  1504. package/cursor-sidecar/node_modules/zod/v3/types.cjs +3775 -0
  1505. package/cursor-sidecar/node_modules/zod/v3/types.d.cts +1031 -0
  1506. package/cursor-sidecar/node_modules/zod/v3/types.d.ts +1031 -0
  1507. package/cursor-sidecar/node_modules/zod/v3/types.js +3693 -0
  1508. package/cursor-sidecar/node_modules/zod/v4/classic/checks.cjs +32 -0
  1509. package/cursor-sidecar/node_modules/zod/v4/classic/checks.d.cts +1 -0
  1510. package/cursor-sidecar/node_modules/zod/v4/classic/checks.d.ts +1 -0
  1511. package/cursor-sidecar/node_modules/zod/v4/classic/checks.js +1 -0
  1512. package/cursor-sidecar/node_modules/zod/v4/classic/coerce.cjs +47 -0
  1513. package/cursor-sidecar/node_modules/zod/v4/classic/coerce.d.cts +17 -0
  1514. package/cursor-sidecar/node_modules/zod/v4/classic/coerce.d.ts +17 -0
  1515. package/cursor-sidecar/node_modules/zod/v4/classic/coerce.js +17 -0
  1516. package/cursor-sidecar/node_modules/zod/v4/classic/compat.cjs +57 -0
  1517. package/cursor-sidecar/node_modules/zod/v4/classic/compat.d.cts +46 -0
  1518. package/cursor-sidecar/node_modules/zod/v4/classic/compat.d.ts +46 -0
  1519. package/cursor-sidecar/node_modules/zod/v4/classic/compat.js +27 -0
  1520. package/cursor-sidecar/node_modules/zod/v4/classic/errors.cjs +67 -0
  1521. package/cursor-sidecar/node_modules/zod/v4/classic/errors.d.cts +30 -0
  1522. package/cursor-sidecar/node_modules/zod/v4/classic/errors.d.ts +30 -0
  1523. package/cursor-sidecar/node_modules/zod/v4/classic/errors.js +41 -0
  1524. package/cursor-sidecar/node_modules/zod/v4/classic/external.cjs +70 -0
  1525. package/cursor-sidecar/node_modules/zod/v4/classic/external.d.cts +13 -0
  1526. package/cursor-sidecar/node_modules/zod/v4/classic/external.d.ts +13 -0
  1527. package/cursor-sidecar/node_modules/zod/v4/classic/external.js +18 -0
  1528. package/cursor-sidecar/node_modules/zod/v4/classic/index.cjs +33 -0
  1529. package/cursor-sidecar/node_modules/zod/v4/classic/index.d.cts +4 -0
  1530. package/cursor-sidecar/node_modules/zod/v4/classic/index.d.ts +4 -0
  1531. package/cursor-sidecar/node_modules/zod/v4/classic/index.js +4 -0
  1532. package/cursor-sidecar/node_modules/zod/v4/classic/iso.cjs +60 -0
  1533. package/cursor-sidecar/node_modules/zod/v4/classic/iso.d.cts +22 -0
  1534. package/cursor-sidecar/node_modules/zod/v4/classic/iso.d.ts +22 -0
  1535. package/cursor-sidecar/node_modules/zod/v4/classic/iso.js +30 -0
  1536. package/cursor-sidecar/node_modules/zod/v4/classic/parse.cjs +32 -0
  1537. package/cursor-sidecar/node_modules/zod/v4/classic/parse.d.cts +23 -0
  1538. package/cursor-sidecar/node_modules/zod/v4/classic/parse.d.ts +23 -0
  1539. package/cursor-sidecar/node_modules/zod/v4/classic/parse.js +6 -0
  1540. package/cursor-sidecar/node_modules/zod/v4/classic/schemas.cjs +1109 -0
  1541. package/cursor-sidecar/node_modules/zod/v4/classic/schemas.d.cts +630 -0
  1542. package/cursor-sidecar/node_modules/zod/v4/classic/schemas.d.ts +630 -0
  1543. package/cursor-sidecar/node_modules/zod/v4/classic/schemas.js +1006 -0
  1544. package/cursor-sidecar/node_modules/zod/v4/core/api.cjs +1039 -0
  1545. package/cursor-sidecar/node_modules/zod/v4/core/api.d.cts +284 -0
  1546. package/cursor-sidecar/node_modules/zod/v4/core/api.d.ts +284 -0
  1547. package/cursor-sidecar/node_modules/zod/v4/core/api.js +906 -0
  1548. package/cursor-sidecar/node_modules/zod/v4/core/checks.cjs +591 -0
  1549. package/cursor-sidecar/node_modules/zod/v4/core/checks.d.cts +278 -0
  1550. package/cursor-sidecar/node_modules/zod/v4/core/checks.d.ts +278 -0
  1551. package/cursor-sidecar/node_modules/zod/v4/core/checks.js +565 -0
  1552. package/cursor-sidecar/node_modules/zod/v4/core/core.cjs +67 -0
  1553. package/cursor-sidecar/node_modules/zod/v4/core/core.d.cts +49 -0
  1554. package/cursor-sidecar/node_modules/zod/v4/core/core.d.ts +49 -0
  1555. package/cursor-sidecar/node_modules/zod/v4/core/core.js +61 -0
  1556. package/cursor-sidecar/node_modules/zod/v4/core/doc.cjs +39 -0
  1557. package/cursor-sidecar/node_modules/zod/v4/core/doc.d.cts +14 -0
  1558. package/cursor-sidecar/node_modules/zod/v4/core/doc.d.ts +14 -0
  1559. package/cursor-sidecar/node_modules/zod/v4/core/doc.js +35 -0
  1560. package/cursor-sidecar/node_modules/zod/v4/core/errors.cjs +226 -0
  1561. package/cursor-sidecar/node_modules/zod/v4/core/errors.d.cts +208 -0
  1562. package/cursor-sidecar/node_modules/zod/v4/core/errors.d.ts +208 -0
  1563. package/cursor-sidecar/node_modules/zod/v4/core/errors.js +195 -0
  1564. package/cursor-sidecar/node_modules/zod/v4/core/function.cjs +102 -0
  1565. package/cursor-sidecar/node_modules/zod/v4/core/function.d.cts +52 -0
  1566. package/cursor-sidecar/node_modules/zod/v4/core/function.d.ts +52 -0
  1567. package/cursor-sidecar/node_modules/zod/v4/core/function.js +75 -0
  1568. package/cursor-sidecar/node_modules/zod/v4/core/index.cjs +44 -0
  1569. package/cursor-sidecar/node_modules/zod/v4/core/index.d.cts +15 -0
  1570. package/cursor-sidecar/node_modules/zod/v4/core/index.d.ts +15 -0
  1571. package/cursor-sidecar/node_modules/zod/v4/core/index.js +15 -0
  1572. package/cursor-sidecar/node_modules/zod/v4/core/json-schema.cjs +2 -0
  1573. package/cursor-sidecar/node_modules/zod/v4/core/json-schema.d.cts +87 -0
  1574. package/cursor-sidecar/node_modules/zod/v4/core/json-schema.d.ts +87 -0
  1575. package/cursor-sidecar/node_modules/zod/v4/core/json-schema.js +1 -0
  1576. package/cursor-sidecar/node_modules/zod/v4/core/parse.cjs +87 -0
  1577. package/cursor-sidecar/node_modules/zod/v4/core/parse.d.cts +25 -0
  1578. package/cursor-sidecar/node_modules/zod/v4/core/parse.d.ts +25 -0
  1579. package/cursor-sidecar/node_modules/zod/v4/core/parse.js +57 -0
  1580. package/cursor-sidecar/node_modules/zod/v4/core/regexes.cjs +103 -0
  1581. package/cursor-sidecar/node_modules/zod/v4/core/regexes.d.cts +62 -0
  1582. package/cursor-sidecar/node_modules/zod/v4/core/regexes.d.ts +62 -0
  1583. package/cursor-sidecar/node_modules/zod/v4/core/regexes.js +95 -0
  1584. package/cursor-sidecar/node_modules/zod/v4/core/registries.cjs +56 -0
  1585. package/cursor-sidecar/node_modules/zod/v4/core/registries.d.cts +35 -0
  1586. package/cursor-sidecar/node_modules/zod/v4/core/registries.d.ts +35 -0
  1587. package/cursor-sidecar/node_modules/zod/v4/core/registries.js +51 -0
  1588. package/cursor-sidecar/node_modules/zod/v4/core/schemas.cjs +1748 -0
  1589. package/cursor-sidecar/node_modules/zod/v4/core/schemas.d.cts +1041 -0
  1590. package/cursor-sidecar/node_modules/zod/v4/core/schemas.d.ts +1041 -0
  1591. package/cursor-sidecar/node_modules/zod/v4/core/schemas.js +1717 -0
  1592. package/cursor-sidecar/node_modules/zod/v4/core/standard-schema.cjs +2 -0
  1593. package/cursor-sidecar/node_modules/zod/v4/core/standard-schema.d.cts +55 -0
  1594. package/cursor-sidecar/node_modules/zod/v4/core/standard-schema.d.ts +55 -0
  1595. package/cursor-sidecar/node_modules/zod/v4/core/standard-schema.js +1 -0
  1596. package/cursor-sidecar/node_modules/zod/v4/core/to-json-schema.cjs +854 -0
  1597. package/cursor-sidecar/node_modules/zod/v4/core/to-json-schema.d.cts +88 -0
  1598. package/cursor-sidecar/node_modules/zod/v4/core/to-json-schema.d.ts +88 -0
  1599. package/cursor-sidecar/node_modules/zod/v4/core/to-json-schema.js +849 -0
  1600. package/cursor-sidecar/node_modules/zod/v4/core/util.cjs +539 -0
  1601. package/cursor-sidecar/node_modules/zod/v4/core/util.d.cts +183 -0
  1602. package/cursor-sidecar/node_modules/zod/v4/core/util.d.ts +183 -0
  1603. package/cursor-sidecar/node_modules/zod/v4/core/util.js +493 -0
  1604. package/cursor-sidecar/node_modules/zod/v4/core/versions.cjs +8 -0
  1605. package/cursor-sidecar/node_modules/zod/v4/core/versions.d.cts +5 -0
  1606. package/cursor-sidecar/node_modules/zod/v4/core/versions.d.ts +5 -0
  1607. package/cursor-sidecar/node_modules/zod/v4/core/versions.js +5 -0
  1608. package/cursor-sidecar/node_modules/zod/v4/index.cjs +22 -0
  1609. package/cursor-sidecar/node_modules/zod/v4/index.d.cts +3 -0
  1610. package/cursor-sidecar/node_modules/zod/v4/index.d.ts +3 -0
  1611. package/cursor-sidecar/node_modules/zod/v4/index.js +3 -0
  1612. package/cursor-sidecar/node_modules/zod/v4/locales/ar.cjs +142 -0
  1613. package/cursor-sidecar/node_modules/zod/v4/locales/ar.d.cts +4 -0
  1614. package/cursor-sidecar/node_modules/zod/v4/locales/ar.d.ts +4 -0
  1615. package/cursor-sidecar/node_modules/zod/v4/locales/ar.js +116 -0
  1616. package/cursor-sidecar/node_modules/zod/v4/locales/az.cjs +141 -0
  1617. package/cursor-sidecar/node_modules/zod/v4/locales/az.d.cts +4 -0
  1618. package/cursor-sidecar/node_modules/zod/v4/locales/az.d.ts +4 -0
  1619. package/cursor-sidecar/node_modules/zod/v4/locales/az.js +115 -0
  1620. package/cursor-sidecar/node_modules/zod/v4/locales/be.cjs +190 -0
  1621. package/cursor-sidecar/node_modules/zod/v4/locales/be.d.cts +4 -0
  1622. package/cursor-sidecar/node_modules/zod/v4/locales/be.d.ts +4 -0
  1623. package/cursor-sidecar/node_modules/zod/v4/locales/be.js +164 -0
  1624. package/cursor-sidecar/node_modules/zod/v4/locales/ca.cjs +144 -0
  1625. package/cursor-sidecar/node_modules/zod/v4/locales/ca.d.cts +4 -0
  1626. package/cursor-sidecar/node_modules/zod/v4/locales/ca.d.ts +4 -0
  1627. package/cursor-sidecar/node_modules/zod/v4/locales/ca.js +118 -0
  1628. package/cursor-sidecar/node_modules/zod/v4/locales/cs.cjs +161 -0
  1629. package/cursor-sidecar/node_modules/zod/v4/locales/cs.d.cts +4 -0
  1630. package/cursor-sidecar/node_modules/zod/v4/locales/cs.d.ts +4 -0
  1631. package/cursor-sidecar/node_modules/zod/v4/locales/cs.js +135 -0
  1632. package/cursor-sidecar/node_modules/zod/v4/locales/de.cjs +142 -0
  1633. package/cursor-sidecar/node_modules/zod/v4/locales/de.d.cts +4 -0
  1634. package/cursor-sidecar/node_modules/zod/v4/locales/de.d.ts +4 -0
  1635. package/cursor-sidecar/node_modules/zod/v4/locales/de.js +116 -0
  1636. package/cursor-sidecar/node_modules/zod/v4/locales/en.cjs +145 -0
  1637. package/cursor-sidecar/node_modules/zod/v4/locales/en.d.cts +5 -0
  1638. package/cursor-sidecar/node_modules/zod/v4/locales/en.d.ts +5 -0
  1639. package/cursor-sidecar/node_modules/zod/v4/locales/en.js +117 -0
  1640. package/cursor-sidecar/node_modules/zod/v4/locales/eo.cjs +144 -0
  1641. package/cursor-sidecar/node_modules/zod/v4/locales/eo.d.cts +5 -0
  1642. package/cursor-sidecar/node_modules/zod/v4/locales/eo.d.ts +5 -0
  1643. package/cursor-sidecar/node_modules/zod/v4/locales/eo.js +116 -0
  1644. package/cursor-sidecar/node_modules/zod/v4/locales/es.cjs +143 -0
  1645. package/cursor-sidecar/node_modules/zod/v4/locales/es.d.cts +4 -0
  1646. package/cursor-sidecar/node_modules/zod/v4/locales/es.d.ts +4 -0
  1647. package/cursor-sidecar/node_modules/zod/v4/locales/es.js +117 -0
  1648. package/cursor-sidecar/node_modules/zod/v4/locales/fa.cjs +148 -0
  1649. package/cursor-sidecar/node_modules/zod/v4/locales/fa.d.cts +4 -0
  1650. package/cursor-sidecar/node_modules/zod/v4/locales/fa.d.ts +4 -0
  1651. package/cursor-sidecar/node_modules/zod/v4/locales/fa.js +122 -0
  1652. package/cursor-sidecar/node_modules/zod/v4/locales/fi.cjs +148 -0
  1653. package/cursor-sidecar/node_modules/zod/v4/locales/fi.d.cts +4 -0
  1654. package/cursor-sidecar/node_modules/zod/v4/locales/fi.d.ts +4 -0
  1655. package/cursor-sidecar/node_modules/zod/v4/locales/fi.js +122 -0
  1656. package/cursor-sidecar/node_modules/zod/v4/locales/fr-CA.cjs +143 -0
  1657. package/cursor-sidecar/node_modules/zod/v4/locales/fr-CA.d.cts +4 -0
  1658. package/cursor-sidecar/node_modules/zod/v4/locales/fr-CA.d.ts +4 -0
  1659. package/cursor-sidecar/node_modules/zod/v4/locales/fr-CA.js +117 -0
  1660. package/cursor-sidecar/node_modules/zod/v4/locales/fr.cjs +142 -0
  1661. package/cursor-sidecar/node_modules/zod/v4/locales/fr.d.cts +4 -0
  1662. package/cursor-sidecar/node_modules/zod/v4/locales/fr.d.ts +4 -0
  1663. package/cursor-sidecar/node_modules/zod/v4/locales/fr.js +116 -0
  1664. package/cursor-sidecar/node_modules/zod/v4/locales/he.cjs +143 -0
  1665. package/cursor-sidecar/node_modules/zod/v4/locales/he.d.cts +4 -0
  1666. package/cursor-sidecar/node_modules/zod/v4/locales/he.d.ts +4 -0
  1667. package/cursor-sidecar/node_modules/zod/v4/locales/he.js +117 -0
  1668. package/cursor-sidecar/node_modules/zod/v4/locales/hu.cjs +143 -0
  1669. package/cursor-sidecar/node_modules/zod/v4/locales/hu.d.cts +4 -0
  1670. package/cursor-sidecar/node_modules/zod/v4/locales/hu.d.ts +4 -0
  1671. package/cursor-sidecar/node_modules/zod/v4/locales/hu.js +117 -0
  1672. package/cursor-sidecar/node_modules/zod/v4/locales/id.cjs +142 -0
  1673. package/cursor-sidecar/node_modules/zod/v4/locales/id.d.cts +4 -0
  1674. package/cursor-sidecar/node_modules/zod/v4/locales/id.d.ts +4 -0
  1675. package/cursor-sidecar/node_modules/zod/v4/locales/id.js +116 -0
  1676. package/cursor-sidecar/node_modules/zod/v4/locales/index.cjs +84 -0
  1677. package/cursor-sidecar/node_modules/zod/v4/locales/index.d.cts +39 -0
  1678. package/cursor-sidecar/node_modules/zod/v4/locales/index.d.ts +39 -0
  1679. package/cursor-sidecar/node_modules/zod/v4/locales/index.js +39 -0
  1680. package/cursor-sidecar/node_modules/zod/v4/locales/it.cjs +143 -0
  1681. package/cursor-sidecar/node_modules/zod/v4/locales/it.d.cts +4 -0
  1682. package/cursor-sidecar/node_modules/zod/v4/locales/it.d.ts +4 -0
  1683. package/cursor-sidecar/node_modules/zod/v4/locales/it.js +117 -0
  1684. package/cursor-sidecar/node_modules/zod/v4/locales/ja.cjs +141 -0
  1685. package/cursor-sidecar/node_modules/zod/v4/locales/ja.d.cts +4 -0
  1686. package/cursor-sidecar/node_modules/zod/v4/locales/ja.d.ts +4 -0
  1687. package/cursor-sidecar/node_modules/zod/v4/locales/ja.js +115 -0
  1688. package/cursor-sidecar/node_modules/zod/v4/locales/kh.cjs +143 -0
  1689. package/cursor-sidecar/node_modules/zod/v4/locales/kh.d.cts +4 -0
  1690. package/cursor-sidecar/node_modules/zod/v4/locales/kh.d.ts +4 -0
  1691. package/cursor-sidecar/node_modules/zod/v4/locales/kh.js +117 -0
  1692. package/cursor-sidecar/node_modules/zod/v4/locales/ko.cjs +147 -0
  1693. package/cursor-sidecar/node_modules/zod/v4/locales/ko.d.cts +4 -0
  1694. package/cursor-sidecar/node_modules/zod/v4/locales/ko.d.ts +4 -0
  1695. package/cursor-sidecar/node_modules/zod/v4/locales/ko.js +121 -0
  1696. package/cursor-sidecar/node_modules/zod/v4/locales/mk.cjs +144 -0
  1697. package/cursor-sidecar/node_modules/zod/v4/locales/mk.d.cts +4 -0
  1698. package/cursor-sidecar/node_modules/zod/v4/locales/mk.d.ts +4 -0
  1699. package/cursor-sidecar/node_modules/zod/v4/locales/mk.js +118 -0
  1700. package/cursor-sidecar/node_modules/zod/v4/locales/ms.cjs +142 -0
  1701. package/cursor-sidecar/node_modules/zod/v4/locales/ms.d.cts +4 -0
  1702. package/cursor-sidecar/node_modules/zod/v4/locales/ms.d.ts +4 -0
  1703. package/cursor-sidecar/node_modules/zod/v4/locales/ms.js +116 -0
  1704. package/cursor-sidecar/node_modules/zod/v4/locales/nl.cjs +143 -0
  1705. package/cursor-sidecar/node_modules/zod/v4/locales/nl.d.cts +4 -0
  1706. package/cursor-sidecar/node_modules/zod/v4/locales/nl.d.ts +4 -0
  1707. package/cursor-sidecar/node_modules/zod/v4/locales/nl.js +117 -0
  1708. package/cursor-sidecar/node_modules/zod/v4/locales/no.cjs +142 -0
  1709. package/cursor-sidecar/node_modules/zod/v4/locales/no.d.cts +4 -0
  1710. package/cursor-sidecar/node_modules/zod/v4/locales/no.d.ts +4 -0
  1711. package/cursor-sidecar/node_modules/zod/v4/locales/no.js +116 -0
  1712. package/cursor-sidecar/node_modules/zod/v4/locales/ota.cjs +143 -0
  1713. package/cursor-sidecar/node_modules/zod/v4/locales/ota.d.cts +4 -0
  1714. package/cursor-sidecar/node_modules/zod/v4/locales/ota.d.ts +4 -0
  1715. package/cursor-sidecar/node_modules/zod/v4/locales/ota.js +117 -0
  1716. package/cursor-sidecar/node_modules/zod/v4/locales/pl.cjs +143 -0
  1717. package/cursor-sidecar/node_modules/zod/v4/locales/pl.d.cts +4 -0
  1718. package/cursor-sidecar/node_modules/zod/v4/locales/pl.d.ts +4 -0
  1719. package/cursor-sidecar/node_modules/zod/v4/locales/pl.js +117 -0
  1720. package/cursor-sidecar/node_modules/zod/v4/locales/ps.cjs +148 -0
  1721. package/cursor-sidecar/node_modules/zod/v4/locales/ps.d.cts +4 -0
  1722. package/cursor-sidecar/node_modules/zod/v4/locales/ps.d.ts +4 -0
  1723. package/cursor-sidecar/node_modules/zod/v4/locales/ps.js +122 -0
  1724. package/cursor-sidecar/node_modules/zod/v4/locales/pt.cjs +142 -0
  1725. package/cursor-sidecar/node_modules/zod/v4/locales/pt.d.cts +4 -0
  1726. package/cursor-sidecar/node_modules/zod/v4/locales/pt.d.ts +4 -0
  1727. package/cursor-sidecar/node_modules/zod/v4/locales/pt.js +116 -0
  1728. package/cursor-sidecar/node_modules/zod/v4/locales/ru.cjs +190 -0
  1729. package/cursor-sidecar/node_modules/zod/v4/locales/ru.d.cts +4 -0
  1730. package/cursor-sidecar/node_modules/zod/v4/locales/ru.d.ts +4 -0
  1731. package/cursor-sidecar/node_modules/zod/v4/locales/ru.js +164 -0
  1732. package/cursor-sidecar/node_modules/zod/v4/locales/sl.cjs +143 -0
  1733. package/cursor-sidecar/node_modules/zod/v4/locales/sl.d.cts +4 -0
  1734. package/cursor-sidecar/node_modules/zod/v4/locales/sl.d.ts +4 -0
  1735. package/cursor-sidecar/node_modules/zod/v4/locales/sl.js +117 -0
  1736. package/cursor-sidecar/node_modules/zod/v4/locales/sv.cjs +144 -0
  1737. package/cursor-sidecar/node_modules/zod/v4/locales/sv.d.cts +4 -0
  1738. package/cursor-sidecar/node_modules/zod/v4/locales/sv.d.ts +4 -0
  1739. package/cursor-sidecar/node_modules/zod/v4/locales/sv.js +118 -0
  1740. package/cursor-sidecar/node_modules/zod/v4/locales/ta.cjs +143 -0
  1741. package/cursor-sidecar/node_modules/zod/v4/locales/ta.d.cts +4 -0
  1742. package/cursor-sidecar/node_modules/zod/v4/locales/ta.d.ts +4 -0
  1743. package/cursor-sidecar/node_modules/zod/v4/locales/ta.js +117 -0
  1744. package/cursor-sidecar/node_modules/zod/v4/locales/th.cjs +143 -0
  1745. package/cursor-sidecar/node_modules/zod/v4/locales/th.d.cts +4 -0
  1746. package/cursor-sidecar/node_modules/zod/v4/locales/th.d.ts +4 -0
  1747. package/cursor-sidecar/node_modules/zod/v4/locales/th.js +117 -0
  1748. package/cursor-sidecar/node_modules/zod/v4/locales/tr.cjs +143 -0
  1749. package/cursor-sidecar/node_modules/zod/v4/locales/tr.d.cts +5 -0
  1750. package/cursor-sidecar/node_modules/zod/v4/locales/tr.d.ts +5 -0
  1751. package/cursor-sidecar/node_modules/zod/v4/locales/tr.js +115 -0
  1752. package/cursor-sidecar/node_modules/zod/v4/locales/ua.cjs +143 -0
  1753. package/cursor-sidecar/node_modules/zod/v4/locales/ua.d.cts +4 -0
  1754. package/cursor-sidecar/node_modules/zod/v4/locales/ua.d.ts +4 -0
  1755. package/cursor-sidecar/node_modules/zod/v4/locales/ua.js +117 -0
  1756. package/cursor-sidecar/node_modules/zod/v4/locales/ur.cjs +143 -0
  1757. package/cursor-sidecar/node_modules/zod/v4/locales/ur.d.cts +4 -0
  1758. package/cursor-sidecar/node_modules/zod/v4/locales/ur.d.ts +4 -0
  1759. package/cursor-sidecar/node_modules/zod/v4/locales/ur.js +117 -0
  1760. package/cursor-sidecar/node_modules/zod/v4/locales/vi.cjs +142 -0
  1761. package/cursor-sidecar/node_modules/zod/v4/locales/vi.d.cts +4 -0
  1762. package/cursor-sidecar/node_modules/zod/v4/locales/vi.d.ts +4 -0
  1763. package/cursor-sidecar/node_modules/zod/v4/locales/vi.js +116 -0
  1764. package/cursor-sidecar/node_modules/zod/v4/locales/zh-CN.cjs +142 -0
  1765. package/cursor-sidecar/node_modules/zod/v4/locales/zh-CN.d.cts +4 -0
  1766. package/cursor-sidecar/node_modules/zod/v4/locales/zh-CN.d.ts +4 -0
  1767. package/cursor-sidecar/node_modules/zod/v4/locales/zh-CN.js +116 -0
  1768. package/cursor-sidecar/node_modules/zod/v4/locales/zh-TW.cjs +143 -0
  1769. package/cursor-sidecar/node_modules/zod/v4/locales/zh-TW.d.cts +4 -0
  1770. package/cursor-sidecar/node_modules/zod/v4/locales/zh-TW.d.ts +4 -0
  1771. package/cursor-sidecar/node_modules/zod/v4/locales/zh-TW.js +117 -0
  1772. package/cursor-sidecar/node_modules/zod/v4/mini/checks.cjs +34 -0
  1773. package/cursor-sidecar/node_modules/zod/v4/mini/checks.d.cts +1 -0
  1774. package/cursor-sidecar/node_modules/zod/v4/mini/checks.d.ts +1 -0
  1775. package/cursor-sidecar/node_modules/zod/v4/mini/checks.js +1 -0
  1776. package/cursor-sidecar/node_modules/zod/v4/mini/coerce.cjs +47 -0
  1777. package/cursor-sidecar/node_modules/zod/v4/mini/coerce.d.cts +7 -0
  1778. package/cursor-sidecar/node_modules/zod/v4/mini/coerce.d.ts +7 -0
  1779. package/cursor-sidecar/node_modules/zod/v4/mini/coerce.js +17 -0
  1780. package/cursor-sidecar/node_modules/zod/v4/mini/external.cjs +62 -0
  1781. package/cursor-sidecar/node_modules/zod/v4/mini/external.d.cts +11 -0
  1782. package/cursor-sidecar/node_modules/zod/v4/mini/external.d.ts +11 -0
  1783. package/cursor-sidecar/node_modules/zod/v4/mini/external.js +13 -0
  1784. package/cursor-sidecar/node_modules/zod/v4/mini/index.cjs +32 -0
  1785. package/cursor-sidecar/node_modules/zod/v4/mini/index.d.cts +3 -0
  1786. package/cursor-sidecar/node_modules/zod/v4/mini/index.d.ts +3 -0
  1787. package/cursor-sidecar/node_modules/zod/v4/mini/index.js +3 -0
  1788. package/cursor-sidecar/node_modules/zod/v4/mini/iso.cjs +60 -0
  1789. package/cursor-sidecar/node_modules/zod/v4/mini/iso.d.cts +22 -0
  1790. package/cursor-sidecar/node_modules/zod/v4/mini/iso.d.ts +22 -0
  1791. package/cursor-sidecar/node_modules/zod/v4/mini/iso.js +30 -0
  1792. package/cursor-sidecar/node_modules/zod/v4/mini/parse.cjs +8 -0
  1793. package/cursor-sidecar/node_modules/zod/v4/mini/parse.d.cts +1 -0
  1794. package/cursor-sidecar/node_modules/zod/v4/mini/parse.d.ts +1 -0
  1795. package/cursor-sidecar/node_modules/zod/v4/mini/parse.js +1 -0
  1796. package/cursor-sidecar/node_modules/zod/v4/mini/schemas.cjs +839 -0
  1797. package/cursor-sidecar/node_modules/zod/v4/mini/schemas.d.cts +356 -0
  1798. package/cursor-sidecar/node_modules/zod/v4/mini/schemas.d.ts +356 -0
  1799. package/cursor-sidecar/node_modules/zod/v4/mini/schemas.js +732 -0
  1800. package/cursor-sidecar/node_modules/zod/v4-mini/index.cjs +17 -0
  1801. package/cursor-sidecar/node_modules/zod/v4-mini/index.d.cts +1 -0
  1802. package/cursor-sidecar/node_modules/zod/v4-mini/index.d.ts +1 -0
  1803. package/cursor-sidecar/node_modules/zod/v4-mini/index.js +1 -0
  1804. package/cursor-sidecar/run-agent.mjs +282 -0
  1805. package/cursor-sidecar/sidecar-runtime.mjs +145 -0
  1806. package/mangostudio +0 -0
  1807. package/package.json +2 -2
  1808. package/public/assets/MarkdownContentRenderer-BR_xaZT1.js +0 -4
  1809. package/public/assets/bash-DKfk-jqG.js +0 -1
  1810. package/public/assets/c-6LDlXRu0.js +0 -1
  1811. package/public/assets/cpp-u2b-vpJ9.js +0 -1
  1812. package/public/assets/csharp-Ceix8dHH.js +0 -1
  1813. package/public/assets/css-Dc0OpoBJ.js +0 -1
  1814. package/public/assets/go-PnJdfxiR.js +0 -1
  1815. package/public/assets/html-UIM7GmnP.js +0 -1
  1816. package/public/assets/index-BFmJdqP5.css +0 -2
  1817. package/public/assets/index-BVWRnZBA.js +0 -90
  1818. package/public/assets/java-B8S38LsY.js +0 -1
  1819. package/public/assets/javascript-okWskhVA.js +0 -1
  1820. package/public/assets/json-BjaDPSOc.js +0 -1
  1821. package/public/assets/jsx-DjqxE-UL.js +0 -1
  1822. package/public/assets/logo-Cb9ic_TX.webp +0 -0
  1823. package/public/assets/markdown-YiYqiPes.js +0 -1
  1824. package/public/assets/markdown-parser-B0W8Yv4o.js +0 -64
  1825. package/public/assets/php-D9TzMTdN.js +0 -1
  1826. package/public/assets/powershell-Dvslkh7q.js +0 -1
  1827. package/public/assets/python-DaRRuALo.js +0 -1
  1828. package/public/assets/rolldown-runtime-BYbx6iT9.js +0 -1
  1829. package/public/assets/ruby-DjRoLTaK.js +0 -1
  1830. package/public/assets/rust-CR5Dd4HD.js +0 -1
  1831. package/public/assets/shellscript-Cd3e2TuR.js +0 -1
  1832. package/public/assets/shiki-qzSzbvts.js +0 -2
  1833. package/public/assets/sql-D3oCX4qf.js +0 -1
  1834. package/public/assets/swift-CJSMoxIm.js +0 -1
  1835. package/public/assets/syntax-core-BoMshe5A.js +0 -152
  1836. package/public/assets/syntax-themes-Dq65SZkH.js +0 -1
  1837. package/public/assets/tsx-DcRFScAN.js +0 -1
  1838. package/public/assets/typescript-ButPIGrc.js +0 -1
  1839. package/public/assets/ui-BEql6gkw.js +0 -9
  1840. package/public/assets/vendor-TU_R2f75.js +0 -11
  1841. package/public/assets/vendor-deps-C4ULb-aw.js +0 -4
  1842. package/public/assets/xml-Lpki4g8-.js +0 -1
  1843. package/public/assets/yaml-sdi5CfWK.js +0 -1
  1844. package/public/index.html +0 -46
@@ -0,0 +1 @@
1
+ export const __webpack_esm_id__=357;export const __webpack_esm_ids__=[357];export const __webpack_esm_modules__={"./src/agent/core-adapter.ts"(e,t,r){r.d(t,{k:()=>i});var n=r("../proto/dist/generated/agent/v1/agent_pb.js"),o=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),s=r("../proto/dist/generated/agent/v1/subagents_pb.js");function i(e,t){var r,n,o,s,i,c,l,u,d;switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:null!==(s=null===(r=e.message.value.userMessage)||void 0===r?void 0:r.text)&&void 0!==s?s:""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":return{type:"summary-completed"};case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:null!==(i=null===(o=null===(n=e.message.value.event.value)||void 0===n?void 0:n.toJson)||void 0===o?void 0:o.call(n))&&void 0!==i?i:e.message.value.event.value}:{}};case"toolCallStarted":return a("tool-call-started",e.message.value);case"partialToolCall":return a("partial-tool-call",e.message.value);case"toolCallCompleted":return a("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value,r=void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens;return Object.assign({type:"turn-ended"},r&&{usage:Object.assign({inputTokens:Number(null!==(c=t.inputTokens)&&void 0!==c?c:BigInt(0)),outputTokens:Number(null!==(l=t.outputTokens)&&void 0!==l?l:BigInt(0)),cacheReadTokens:Number(null!==(u=t.cacheReadTokens)&&void 0!==u?u:BigInt(0)),cacheWriteTokens:Number(null!==(d=t.cacheWriteTokens)&&void 0!==d?d:BigInt(0))},t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)})})}case"toolCallDelta":return null;case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"promptSuggestion":case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case void 0:return null;default:return e.message,null}}function a(e,t){const r=function(e){if(!(null==e?void 0:e.tool))return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"shell",args:Object.assign(Object.assign({command:t.command},t.workingDirectory?{workingDirectory:t.workingDirectory}:{}),t.timeout?{timeout:t.timeout}:{})},r?{result:h(r)}:{}):null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"delete",args:{path:t.path}},r?{result:m(r)}:{}):null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"glob",args:Object.assign({globPattern:t.globPattern},t.targetDirectory?{targetDirectory:t.targetDirectory}:{})},r?{result:f(r)}:{}):null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"grep",args:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({pattern:t.pattern},t.path?{path:t.path}:{}),t.glob?{glob:t.glob}:{}),t.outputMode?{outputMode:t.outputMode}:{}),t.contextBefore?{contextBefore:t.contextBefore}:{}),t.contextAfter?{contextAfter:t.contextAfter}:{}),t.context?{context:t.context}:{}),t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{}),t.type?{type:t.type}:{}),t.headLimit?{headLimit:t.headLimit}:{}),void 0!==t.offset?{offset:t.offset}:{}),t.multiline?{multiline:t.multiline}:{}),t.sort?{sort:t.sort}:{}),t.sortAscending?{sortAscending:t.sortAscending}:{})},r?{result:g(r)}:{}):null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"read",args:{path:t.path}},r?{result:y(r)}:{}):null}case"editToolCall":{const{args:t,result:r}=e.tool.value;if(!t)return null;const n={path:t.path};return Object.assign({type:"edit",args:n},r?{result:w(r)}:{})}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"ls",args:Object.assign({path:t.path},t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{})},r?{result:b(r)}:{}):null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"readLints",args:{paths:t.paths}},r?{result:S(r)}:{}):null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"mcp",args:Object.assign(Object.assign(Object.assign({},t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{}),t.toolName?{toolName:t.toolName}:{}),t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{})},r?{result:E(r)}:{}):null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"generateImage",args:Object.assign({description:t.description},t.filePath?{filePath:t.filePath}:{})},r?{result:_(r)}:{}):null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"recordScreen",args:{mode:C(t.mode)}},r?{result:P(r)}:{}):null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"semSearch",args:Object.assign(Object.assign({query:t.query},t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{}),t.explanation?{explanation:t.explanation}:{})},r?{result:x(r)}:{}):null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"createPlan",args:{plan:t.plan}},r?{result:R(r)}:{}):null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:I(e.status)})))}},r?{result:T(r)}:{}):null}case"fetchToolCall":case"switchModeToolCall":case"computerUseToolCall":case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"task",args:c(t)},r?{result:d(r)}:{}):null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updatePrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"piReadToolCall":case"piBashToolCall":case"piEditToolCall":case"piWriteToolCall":case"piGrepToolCall":case"piFindToolCall":case"piLsToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function c(e){var t,r;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({description:null!==(t=e.description)&&void 0!==t?t:"",prompt:null!==(r=e.prompt)&&void 0!==r?r:""},e.subagentType?{subagentType:l(e.subagentType)}:{}),e.model?{model:e.model}:{}),e.resume?{resume:e.resume}:{}),e.agentId?{agentId:e.agentId}:{}),e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{}),void 0!==e.mode?{mode:u(e.mode)}:{}),e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{})}function l(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function u(e){switch(e){case s.FL.AGENT:return"agent";case s.FL.PLAN:return"plan";default:return"unspecified"}}function d(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>{var t,r;return null!==(r=null===(t=e.toJson)||void 0===t?void 0:t.call(e))&&void 0!==r?r:e}))}:{}),t.agentId?{agentId:t.agentId}:{}),{isBackground:null!==(r=t.isBackground)&&void 0!==r&&r}),void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{}),t.resultSuffix?{resultSuffix:t.resultSuffix}:{}),{backgroundReason:p(t.backgroundReason)}),t.transcriptPath?{transcriptPath:t.transcriptPath}:{})}}case"error":return{status:"error",error:{message:null!==(n=e.result.value.error)&&void 0!==n?n:"Task failed"}};default:return}}function p(e){switch(e){case n.qL.AGENT_REQUEST:return"agentRequest";case n.qL.USER_REQUEST:return"userRequest";case n.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function h(e){var t,r,n,o,s,i,a,c;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:null!==(r=t.exitCode)&&void 0!==r?r:0,signal:null!==(n=t.signal)&&void 0!==n?n:"",stdout:null!==(o=t.stdout)&&void 0!==o?o:"",stderr:null!==(s=t.stderr)&&void 0!==s?s:"",executionTime:null!==(i=t.executionTime)&&void 0!==i?i:0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:null!==(a=e.result.value.reason)&&void 0!==a?a:"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:null!==(c=e.result.value.error)&&void 0!==c?c:"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function m(e){var t,r,n,o,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(null!==(r=e.result.value.fileSize)&&void 0!==r?r:0)}}:{status:"error",error:{message:null!==(s=null!==(o=null!==(n=e.result.value.error)&&void 0!==n?n:e.result.value.reason)&&void 0!==o?o:e.result.value.clientVisibleError)&&void 0!==s?s:e.result.case,path:e.result.value.path}}}function f(e){var t,r,n,o,s,i,a;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{files:null!==(r=e.result.value.files)&&void 0!==r?r:[],totalFiles:null!==(n=e.result.value.totalFiles)&&void 0!==n?n:0,clientTruncated:null!==(o=e.result.value.clientTruncated)&&void 0!==o&&o,ripgrepTruncated:null!==(s=e.result.value.ripgrepTruncated)&&void 0!==s&&s}}:{status:"error",error:{message:null!==(a=null!==(i=e.result.value.error)&&void 0!==i?i:e.result.value.reason)&&void 0!==a?a:e.result.case}}}function g(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=v(n);return{status:"success",value:Object.assign(Object.assign({},Object.keys(r).length>0?{workspaceResults:r}:{}),t.activeEditorResult?{activeEditorResult:v(t.activeEditorResult)}:{})}}return{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}}function v(e){var t,r,n,o,s,i,a,c,l;if(null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"content":return{type:"content",output:{matches:null!==(o=null===(r=e.result.value.matches)||void 0===r?void 0:r.map((e=>Object.assign(Object.assign(Object.assign(Object.assign({file:e.file},void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{}),{line:e.line}),e.beforeContext?{beforeContext:e.beforeContext}:{}),e.afterContext?{afterContext:e.afterContext}:{}))))&&void 0!==o?o:[],totalMatches:null!==(s=e.result.value.totalMatches)&&void 0!==s?s:0}};case"files":return{type:"files",output:{files:null!==(i=e.result.value.files)&&void 0!==i?i:[],count:null!==(a=e.result.value.count)&&void 0!==a?a:0}};case"count":return{type:"count",output:{counts:null!==(c=null===(n=e.result.value.counts)||void 0===n?void 0:n.map((e=>({file:e.file,count:e.count}))))&&void 0!==c?c:[],total:null!==(l=e.result.value.total)&&void 0!==l?l:0}};default:return}}function y(e){var t,r,n,o,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:null!==(r=e.result.value.totalLines)&&void 0!==r?r:0,fileSize:Number(null!==(n=e.result.value.fileSize)&&void 0!==n?n:0)}}:{status:"error",error:{message:null!==(s=null!==(o=e.result.value.error)&&void 0!==o?o:e.result.value.reason)&&void 0!==s?s:e.result.case,path:e.result.value.path}}}function w(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:Object.assign(Object.assign(Object.assign({},void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{}),void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{}),e.result.value.diffString?{diffString:e.result.value.diffString}:{})}:{status:"error",error:{message:null!==(n=null!==(r=e.result.value.error)&&void 0!==r?r:e.result.value.reason)&&void 0!==n?n:e.result.case,path:e.result.value.path}}}function b(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:k(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function k(e){var t,r,n,o,s,i,a,c;if(e)return{absPath:null!==(n=e.absPath)&&void 0!==n?n:"",childrenDirs:null!==(o=null===(t=e.childrenDirs)||void 0===t?void 0:t.map(k))&&void 0!==o?o:[],childrenFiles:null!==(s=null===(r=e.childrenFiles)||void 0===r?void 0:r.map((e=>({name:e.name}))))&&void 0!==s?s:[],childrenWereProcessed:null!==(i=e.childrenWereProcessed)&&void 0!==i&&i,fullSubtreeExtensionCounts:null!==(a=e.fullSubtreeExtensionCounts)&&void 0!==a?a:{},numFiles:null!==(c=e.numFiles)&&void 0!==c?c:0}}function S(e){var t,r,n,o,s,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:null!==(n=null===(r=e.result.value.fileDiagnostics)||void 0===r?void 0:r.map((e=>{var t,r,n;return{path:e.path,diagnostics:null!==(r=null===(t=e.diagnostics)||void 0===t?void 0:t.map((e=>Object.assign(Object.assign({severity:A(e.severity)},e.range?{range:Object.assign(Object.assign({},e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{}),e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{})}:{}),{message:e.message,source:e.source,code:e.code}))))&&void 0!==r?r:[],diagnosticsCount:null!==(n=e.diagnosticsCount)&&void 0!==n?n:0}})))&&void 0!==n?n:[],totalFiles:null!==(o=e.result.value.totalFiles)&&void 0!==o?o:0,totalDiagnostics:null!==(s=e.result.value.totalDiagnostics)&&void 0!==s?s:0}}:{status:"error",error:{message:null!==(i=e.result.value.error)&&void 0!==i?i:e.result.case}}}function E(e){var t,r,n,o,s,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{content:null!==(n=null===(r=e.result.value.content)||void 0===r?void 0:r.map((e=>{var t,r;const n={};return"text"===(null===(t=e.content)||void 0===t?void 0:t.case)?n.text={text:e.content.value.text}:"image"===(null===(r=e.content)||void 0===r?void 0:r.case)&&(n.image=Object.assign({data:e.content.value.data},e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{})),n})))&&void 0!==n?n:[],isError:null!==(o=e.result.value.isError)&&void 0!==o&&o}}:{status:"error",error:{message:null!==(i=null!==(s=e.result.value.error)&&void 0!==s?s:e.result.value.reason)&&void 0!==i?i:e.result.case}}}function x(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{results:null!==(r=e.result.value.results)&&void 0!==r?r:""}}:{status:"error",error:{message:null!==(n=e.result.value.error)&&void 0!==n?n:e.result.case}}}function _(e){var t,r,n;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{filePath:null!==(r=e.result.value.filePath)&&void 0!==r?r:""}}:{status:"error",error:{message:null!==(n=e.result.value.error)&&void 0!==n?n:e.result.case}}}function C(e){switch(e){case o.$u.START_RECORDING:return"START_RECORDING";case o.$u.SAVE_RECORDING:return"SAVE_RECORDING";case o.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function P(e){var t,r,n,o,s;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:null!==(r=e.result.value.wasPriorRecordingCancelled)&&void 0!==r&&r}};case"saveSuccess":return{status:"success",value:{path:null!==(n=e.result.value.path)&&void 0!==n?n:"",recordingDurationMs:Number(null!==(o=e.result.value.recordingDurationMs)&&void 0!==o?o:0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:null!==(s=e.result.value.error)&&void 0!==s?s:"Unknown error"}};default:return}}function R(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function T(e){var t,r,n,o,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{todos:null!==(n=null===(r=e.result.value.todos)||void 0===r?void 0:r.map((e=>({content:e.content,status:I(e.status)}))))&&void 0!==n?n:[],totalCount:null!==(o=e.result.value.totalCount)&&void 0!==o?o:0}}:{status:"error",error:{message:null!==(s=e.result.value.error)&&void 0!==s?s:e.result.case}}}function I(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function A(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}},"./src/agent/custom-tools.ts"(e,t,r){r.d(t,{Hc:()=>c,Sh:()=>u,VJ:()=>l,ll:()=>d});var n=r("node:buffer?4cd4"),o=r("../agent-exec/dist/index.js"),s=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),i=r("@bufbuild/protobuf");const a={type:"object",properties:{},additionalProperties:!0};function c(e){return void 0===e?[]:Object.entries(e).map((([e,t])=>{var r,n;return{clientKey:o.iK,providerIdentifier:o.iK,toolName:e,name:`${o.iK}-${e}`,description:null!==(r=t.description)&&void 0!==r?r:"",inputSchema:null!==(n=t.inputSchema)&&void 0!==n?n:a,source:"internal"}}))}function l(e){return void 0!==e&&Object.keys(e).length>0}function u(e){return e.providerIdentifier===o.iK}function d(e){return{execute(t,r,n){return a=this,c=void 0,u=function*(){const t=r.toolName||function(e){const t=`${o.iK}-`;return e.startsWith(t)?e.slice(t.length):e}(r.name),n=e[t];if(void 0===n)return new s.iz({result:{case:"error",value:new s.Nh({error:`Unknown custom tool: ${t}`})}});try{return function(e){var t;const r=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:h(e)?e:void 0};var t}(e),n=void 0!==r.structuredContent?i.Struct.fromJson(r.structuredContent):void 0;return new s.iz({result:{case:"success",value:new s.QW({content:r.content.map(p),isError:null!==(t=r.isError)&&void 0!==t&&t,structuredContent:n})}})}(yield n.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(r),{toolCallId:r.toolCallId||void 0}))}catch(e){return new s.iz({result:{case:"error",value:new s.Nh({error:e instanceof Error?e.message:String(e)})}})}},new((l=void 0)||(l=Promise))((function(e,t){function r(e){try{o(u.next(e))}catch(e){t(e)}}function n(e){try{o(u.throw(e))}catch(e){t(e)}}function o(t){var o;t.done?e(t.value):(o=t.value,o instanceof l?o:new l((function(e){e(o)}))).then(r,n)}o((u=u.apply(a,c||[])).next())}));var a,c,l,u}}}function p(e){var t;return"text"===e.type?new s._Z({content:{case:"text",value:new s.zN({text:e.text})}}):new s._Z({content:{case:"image",value:new s.do({data:n.Buffer.from(e.data,"base64"),mimeType:null!==(t=e.mimeType)&&void 0!==t?t:""})}})}function h(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}},"./src/agent/local-executor.ts"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{createLocalExecutor:()=>J});var o=r("node:buffer?4cd4"),s=r("node:crypto?8af2"),i=r("node:fs"),a=r("node:os"),c=r("node:path"),l=r("../agent-client/dist/index.js"),u=r("../agent-core/dist/index.js"),d=r("../agent-exec/dist/index.js"),p=r("../agent-kv/dist/index.js"),h=r("../context/dist/index.js"),m=r("../context-rpc/dist/index.js"),f=r("../cursor-sdk-local-runtime/dist/index.js"),g=r("../local-exec/dist/index.js"),v=r("../proto/dist/generated/agent/v1/agent_pb.js"),y=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),w=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),b=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),k=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),S=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),E=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),x=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js"),_=r("../shell-exec/dist/index.js"),C=r("../utils/dist/index.js"),P=r("@connectrpc/connect"),R=r("./src/agent/core-adapter.ts"),T=r("./src/agent/custom-tools.ts"),I=r("./src/agent/errors.ts"),A=r("./src/agent/executor-common.ts"),j=r("./src/agent/sdk-statsig.ts"),O=r("./src/agent/utils/logger.ts"),D=e([f]),M=D.then?(await D)():D;f=M[0];var N=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};function $(e,t){if(!(0,T.VJ)(t))return;const r=e.resources.base;if(!(r instanceof g.Dv))throw new I.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(d.Yi),s=(0,T.ll)(t);e.resources.base.register(d.Yi,{execute(e,t,r){return N(this,void 0,void 0,(function*(){if((0,T.Sh)(t)){const o=yield(0,g._5)(e,t,Object.assign(Object.assign({},n),{toolDef:{source:"internal"}}));return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}))}})}const L={warn(){},error(){}},F={log(){}};class U{requestApproval(e){return N(this,void 0,void 0,(function*(){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${B(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}))}}function B(e){switch(e.type){case g.S5.Shell:return"this shell command";case g.S5.Mcp:return"this MCP tool call";case g.S5.Write:return"this file edit";case g.S5.Delete:return"this file deletion";default:return"this operation"}}function H(e,t={}){return Object.assign({type:e},t)}function z(e){try{const t=(0,i.statSync)(e);return t.isFile()&&("win32"===process.platform||!!(73&t.mode))}catch(e){return!1}}function W(e){const t=`${process.platform}-${process.arch}`,r=[`@cursor/sdk-${t}`,`@cursor/february-${t}`];if(!process.argv[1])return;let n=(0,c.dirname)((0,c.resolve)(process.argv[1]));const o=(0,c.parse)(n).root;for(;n!==o;){for(const t of r){const r=(0,c.join)(n,"node_modules",t,"bin",e);if(z(r))return r}n=(0,c.dirname)(n)}}function q(){const e=W("win32"===process.platform?"cursorsandbox.exe":"cursorsandbox");e&&(0,_.St)({sandboxBinaryPath:e})}function G(e){return N(this,void 0,void 0,(function*(){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===(null==n?void 0:n.enabled))return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=V(r)?r:!0===(null==n?void 0:n.enabled)?H("workspace_readwrite",{networkPolicy:(0,_.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(q(),!(0,_.K3)(void 0,{ctx:e.initializationCtx}))throw new I.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=yield(0,_.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}))}function V(e){return void 0!==e&&"insecure_none"!==e.type}function J(e,t){return N(this,void 0,void 0,(function*(){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,n=(0,h.q6)().with(h._O,F);(0,f.Ob)(r.settingSources),/:\/\/(localhost|127\.0\.0\.1)/.test(A.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),r.apiKey&&(yield Promise.all([(0,A.ly)(r.apiKey),(0,A.mU)(r.apiKey)]));const i=r.workingDirectory||process.cwd(),u=(0,C.Rv)((0,a.homedir)(),i);let w;const b="win32"===process.platform?"rg.exe":"rg",k=process.env.CURSOR_RIPGREP_PATH;w=k&&(0,c.isAbsolute)(k)?k:W(b),w||(w=(0,_.Qd)()),w&&(0,_.J)(w);let E,I=(0,f.GG)(),D=!1;if(r.apiKey)try{E=(0,A.KU)(r.apiKey);const e=(0,P.createClient)(x.I,E),t=yield(0,j.c)(r.apiKey);D=t.checkFeatureGate("hooks_stdin_transport");const n={getDefaultNetworkAllowlist:()=>N(this,void 0,void 0,(function*(){return t.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})}))};I=new g.w(new g.zM(e),n,{isMcpAccessNetworkAllowlistEnabled:()=>t.checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:e=>t.checkFeatureGate("mcp_settings_overhaul",e)})}catch(e){O.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const M=r.apiKey?yield(0,_.tv)(`${(0,a.homedir)()}/.cursor/sandbox.json`,(0,a.homedir)()):void 0,B=void 0!==r.apiKey?yield G({cwd:i,perUserSandboxPolicy:M,sandboxOptions:r.sandboxOptions,initializationCtx:n}):void 0,H=null==B?void 0:B.defaultSandboxPolicy,z=null==B?void 0:B.defaultSandboxPolicySources,q=V(H),J=yield(0,f.Oh)({workingDirectory:i,projectDir:u,teamSettingsService:I,initializationCtx:n,dashboardTransport:E,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:H,defaultSandboxPolicySources:z,approvalMode:q?"allowlist":void 0,pendingDecisionProvider:q||!0===r.autoReview?new U:void 0,getNetworkAllowlistInfo:q?()=>(0,g.mA)(I,(0,a.homedir)(),i):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:D});let Z,X;return{run:(e,t,n)=>N(this,void 0,void 0,(function*(){return(0,f.ni)(L,(()=>N(this,void 0,void 0,(function*(){var a,c,u,g;const w=(0,h.VI)((0,h.q6)().withName("sdk.run").with(h._O,F)),[b,k]=w.ctx.withCancel(),E=null!==(a=t.sessionId)&&void 0!==a?a:(0,s.randomUUID)(),x=t.mcpServersOverride,_=(0,T.Hc)(t.customTools);let C;C=yield J.createSessionRuntime({sessionId:E,mcpServersOverride:x,extraMcpTools:_});const I=new Map;try{const a=C.resources.wrapped;$(C,t.customTools);const h=null!==(c=t.blobStore)&&void 0!==c?c:new p.ve;let w=null!==(u=t.initialState)&&void 0!==u?u:new v.Y9({});const T=void 0!==t.model?new v.G4({modelId:t.model.id,parameters:(null!==(g=t.model.params)&&void 0!==g?g:[]).map((e=>new v.SR({id:e.id,value:e.value})))}):void 0,j=Array.isArray(e.images)?e.images.map((e=>{const t=(0,s.randomUUID)(),r=new Uint8Array(o.Buffer.from(e.data,"base64")),n=(0,A.v8)(r);return new S.d(Object.assign(Object.assign({uuid:t},n?{mimeType:n}:{}),{dataOrBlobId:{case:"data",value:r}}))})):[],D=j.length>0?new S.xv({selectedImages:j}):void 0,M=K(t.mode),L=new v.QF({action:{case:"userMessageAction",value:new v.Vt({userMessage:new v.RG(Object.assign({text:e.text,selectedContext:D},void 0!==M?{mode:M}:{}))})}}),F={sendUpdate:(e,t)=>N(this,void 0,void 0,(function*(){const e=(0,R.k)(t,E);null!==e&&(yield n.sendUpdate(e))})),query:(e,t)=>N(this,void 0,void 0,(function*(){return Y(t)}))};if(Z!==t.apiKey||!X){yield Promise.all([(0,A.ly)(t.apiKey),(0,A.mU)(t.apiKey)]);const e=(0,A.KU)(t.apiKey),r=(0,P.createClient)(y.N,e),n=(0,m.ht)(r,{injectTraceHeaders:!0});X=new l.PW(n),Z=t.apiKey}const U=(0,A.Vh)(X,(()=>{const e=(0,A.KU)(t.apiKey),r=(0,P.createClient)(y.N,e),n=(0,m.ht)(r,{injectTraceHeaders:!0}),o=new l.PW(n);return X=o,Z=t.apiKey,o})),B=new f.O({agentClient:U,getResources:e=>N(this,[e],void 0,(function*({agentId:e}){let r=I.get(e);return r||(r=yield J.createSessionRuntime({sessionId:e,mcpServersOverride:x,extraMcpTools:_}),$(r,t.customTools),r.resources.base.register(d.Zn,H),I.set(e,r)),r.resources.wrapped})),mcpTools:_,workspacePath:i,parentConversationId:E,onSessionReleased:e=>{const t=I.get(e);t&&(t.dispose(),I.delete(e))}}),H=(0,d.hv)(B);C.resources.base.register(d.Zn,H);const z=J.services.hooksRuntime,W=z?(0,f.vW)({workspaceRuntime:z,sessionState:C.state,metadata:C.metadata}):void 0,q=new f.xK({workspacePath:i,conversationId:E,blobStore:h}),G=(0,f.Bq)(b,L,Object.assign(Object.assign({agentClient:U,interactionListener:F,resources:a,blobStore:h,initialState:w,conversationId:E,mcpTools:_,runOptions:{generationUUID:t.requestId,requestedModel:T,enableAgentRetries:!1!==r.enableAgentRetries}},t.preFetchedBlobs&&t.preFetchedBlobs.length>0?{preFetchedBlobs:t.preFetchedBlobs}:{}),{hooks:W,onCheckpoint(e){return N(this,void 0,void 0,(function*(){var r;w=e,q.writeFromState(b,e),yield null===(r=t.onCheckpoint)||void 0===r?void 0:r.call(t,e)}))}})),V=G.done.finally((()=>N(this,void 0,void 0,(function*(){try{yield B.awaitBackgroundWorkers()}finally{yield q.waitForPendingWrites().catch((()=>{}));for(const e of I.values())try{yield e.dispose()}catch(e){O.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}I.clear(),yield C.dispose()}})))).catch((e=>{throw e}));return{abort(){G.abort(),k()},done:V}}catch(e){for(const e of I.values())try{yield e.dispose()}catch(e){}throw I.clear(),yield C.dispose(),e}}))))})),reload(){return N(this,void 0,void 0,(function*(){yield J.reload()}))},dispose(){return N(this,void 0,void 0,(function*(){yield J.dispose()}))}}}))}function K(e){switch(e){case"agent":return v.xy.AGENT;case"plan":return v.xy.PLAN;default:return}}function Y(e){var t;switch(e.query.case){case"webSearchRequestQuery":return u.x1.webSearchApproved(e.id);case"webFetchRequestQuery":return u.x1.webFetchApproved(e.id);case"switchModeRequestQuery":return u.x1.switchModeApproved(e.id);case"askQuestionInteractionQuery":return u.x1.askQuestion(e.id,new w.tz({result:{case:"rejected",value:new w.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return u.x1.createPlan(e.id,new b.bK({result:{case:"success",value:new b.Jo},planUri:""}));case"setupVmEnvironmentArgs":return u.x1.setupVmEnvironment(e.id,new E.r$({result:{case:"success",value:new E.JH}}));case"replaceEnvArgs":return u.x1.replaceEnv(e.id,new k.dV({result:{case:"failure",value:new k.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return u.x1.prManagement(e.id,(0,u.p_)());case"mcpAuthRequestQuery":return u.x1.mcpAuthRejected(e.id,"MCP authentication is not supported in local SDK runs");case"generateImageRequestQuery":return u.x1.generateImageApproved(e.id,null===(t=e.query.value.args)||void 0===t?void 0:t.description);case void 0:throw new I.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new I.j1("Unhandled interaction query type",{isRetryable:!1})}}n()}catch(Z){n(Z)}}))},"./src/agent/sdk-statsig.ts"(e,t,r){r.d(t,{c:()=>l});var n=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),o=r("./src/agent/executor-common.ts"),s=r("./src/agent/utils/logger.ts"),i=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const a={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},c=new Map;function l(e){let t=c.get(e);return t||(t=function(e){return i(this,void 0,void 0,(function*(){try{const t=yield function(e){return i(this,void 0,void 0,(function*(){const t=yield(0,o.dC)(e,o.EV);if(!t)return;const r=o.EV.endsWith("/")?o.EV.slice(0,-1):o.EV,n=yield fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,o.tF)(),"x-ghost-mode":(0,o.U)(e)},body:JSON.stringify({})});if(!n.ok)return void s.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const i=yield n.json();return"string"==typeof i.config&&i.config.length>0?i.config:void 0}))}(e);if(!t)return a;const r=new n.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const t=JSON.parse(e);if(t.user)return Object.assign(Object.assign({},t.user),{custom:Object.assign(Object.assign({},t.user.custom),{clientType:"sdk",clientVersion:(0,o.tF)()})})}catch(e){s.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,o.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch(e){return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch(e){return n}}}}catch(e){return s.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),a}}))}(e),c.set(e,t),t.then((r=>{r===a&&c.get(e)===t&&c.delete(e)}),(()=>{c.get(e)===t&&c.delete(e)}))),t}},"../agent-client/dist/index.js"(e,t,r){r.d(t,{PW:()=>me});var n=r("../context/dist/index.js"),o=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class s{checkpointStream;checkpointHandler;ctx;constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,n.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{o(e)}}}var i=r("../agent-exec/dist/index.js"),a=(r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),r("../proto/dist/generated/aiserver/v1/utils_pb.js"));const c=e=>String(e).replace(/[\r\n]/g,"");var l=r("../agent-core/dist/index.js"),u=r("../agent-kv/dist/index.js"),d=r("../proto/dist/generated/agent/v1/agent_pb.js"),p=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),h=r("../proto/dist/generated/agent/v1/exec_pb.js"),m=r("../proto/dist/generated/agent/v1/mcp_pb.js"),f=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),g=r("../utils/dist/index.js"),v=r("@bufbuild/protobuf"),y=r("@connectrpc/connect"),w=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=a4b9a5e69295313832387f25b708426bcf53041a2f50bc7b95_d0a2f6c9e28298af3d10922a7e4db69f/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js");class b extends Error{cause;requestId;displayInfo;constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo}get name(){return this.kind}}class k extends b{get kind(){return"RetriableError"}}class S extends b{action;constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class E extends b{get kind(){return"NonRetriableError"}}class x extends b{get kind(){return"CancelledError"}}const _=new Set([a.yM.NOT_LOGGED_IN,a.yM.AGENT_REQUIRES_LOGIN,a.yM.AUTH_TOKEN_NOT_FOUND,a.yM.AUTH_TOKEN_EXPIRED,a.yM.INVALID_AUTH_ID,a.yM.UNAUTHORIZED,a.yM.GITHUB_NO_USER_CREDENTIALS,a.yM.GITHUB_USER_NO_ACCESS]),C=new Set([a.yM.FREE_USER_USAGE_LIMIT,a.yM.FREE_USER_RATE_LIMIT_EXCEEDED,a.yM.PRO_USER_ONLY,a.yM.PRO_USER_USAGE_LIMIT,a.yM.PRO_USER_RATE_LIMIT_EXCEEDED,a.yM.RATE_LIMITED,a.yM.RATE_LIMITED_CHANGEABLE,a.yM.GENERIC_RATE_LIMIT_EXCEEDED]),P=new Set([a.yM.USAGE_PRICING_REQUIRED,a.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),R=new Set([a.yM.BAD_API_KEY,a.yM.BAD_USER_API_KEY,a.yM.OUTDATED_CLIENT]),T=new Set([a.yM.USER_ABORTED_REQUEST,a.yM.DEBOUNCED]),I=new Set([a.yM.CUSTOM_MESSAGE]),A=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted"];function j(e,t={}){const{requestId:r}=t;if(e instanceof b)return e;if(function(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}(e))return function(e,t){var r,n,o,s,i,c,l;const u=function(e){var t,r;const n=e.findDetails(a.vj);if(n.length>0)return n[0];try{const n=null===(r=null===(t=e.cause)||void 0===t?void 0:t.findDetails)||void 0===r?void 0:r.call(t,a.vj);return null==n?void 0:n[0]}catch(e){return}}(e),d={cause:e,requestId:t,displayInfo:{title:null===(r=null==u?void 0:u.details)||void 0===r?void 0:r.title,detail:null===(n=null==u?void 0:u.details)||void 0===n?void 0:n.detail,isRetryable:null===(o=null==u?void 0:u.details)||void 0===o?void 0:o.isRetryable,connectCode:e.code,errorCode:null==u?void 0:u.error,errorDetails:u}};if(e.code===y.Code.Canceled||e.code===y.Code.Aborted)return D(e)?new k(e.message,d):new x(e.message,d);if(void 0!==(null==u?void 0:u.error)){const t=u.error;if(T.has(t))return new x(O(e,u),d);const r=null===(i=null===(s=u.details)||void 0===s?void 0:s.analyticsMetadata)||void 0===i?void 0:i.actionRequired;if(void 0!==r&&""!==r)return new S(O(e,u),r,d);if(_.has(t))return new S(O(e,u),"login",d);if(C.has(t))return new S(O(e,u),"upgrade",d);if(P.has(t))return new S(O(e,u),"payment",d);if(R.has(t))return new S(O(e,u),"config",d);if(I.has(t)&&!0!==(null===(c=u.details)||void 0===c?void 0:c.isRetryable))return new E(O(e,u),d);if(!1===(null===(l=u.details)||void 0===l?void 0:l.isRetryable))return new E(O(e,u),d)}return e.code===y.Code.Unauthenticated?new S(e.message,"login",d):new k(e.message,d)}(e,r);if(e instanceof Error){if("AbortError"===e.name)return new x(e.message,{cause:e,requestId:r});if(D(e))return new k(e.message,{cause:e,requestId:r})}const n=e instanceof Error?e.message:String(e);return new k(n,{cause:e instanceof Error?e:void 0,requestId:r})}function O(e,t){if(null==t?void 0:t.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}function D(e){let t=e;for(;t instanceof Error;){const e=`${t.name}: ${t.message}`;if(A.some((t=>e.includes(t))))return!0;const r=t.code;if("string"==typeof r&&A.some((e=>r.includes(e))))return!0;t=t.cause}return!1}function M(e){return e.cause instanceof Error?D(e.cause):A.some((t=>e.message.includes(t)))}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class L extends Error{constructor(e){super(e),this.name="LostConnection"}}class F{serverStream;clientStream;controlledExecManager;constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{N(t,(0,n.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if(t instanceof p.Nv){this.controlledExecManager.handleControlMessage(t);continue}const o=(async()=>{var r;const o={stack:[],error:void 0,hasError:!1};try{let s,i;if(t.spanContext){const o=t.spanContext;s=(0,n.V5)({traceId:o.traceId,spanId:o.spanId,traceFlags:null!==(r=o.traceFlags)&&void 0!==r?r:1},"exec.handle",e),i=(0,n.fU)(s)}else s=e;N(o,i?new n.r2(s,i):void 0,!1);const a=this.controlledExecManager.handle(s,t);for await(const e of a)await this.clientStream.write(e)}catch(e){o.error=e,o.hasError=!0}finally{$(o)}})();r.push(o)}await Promise.all(r)}catch(e){if(e instanceof y.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new L(e.message);if(e instanceof y.ConnectError&&e.code===y.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new L(e.message)}else{if(e instanceof g.W2)throw new L(e.message);if(e instanceof y.ConnectError&&e.code===y.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new L(e.message)}}}}catch(e){t.error=e,t.hasError=!0}finally{$(t)}}}var U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,n.h)("ClientInteractionController");class H{interactionStream;interactionListener;queryResponseStream;constructor(e,t,r){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,n.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let o,s=Promise.resolve();for await(const t of this.interactionStream)"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):"interactionUpdate"===t.case&&(s=s.then((()=>this.handleInteractionUpdate(e,t.value))).catch((t=>{B.error(e,"Error handling interaction update",t),null!=o||(o=t)})));if(await s,void 0!==o)throw o}catch(e){t.error=e,t.hasError=!0}finally{U(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){this.interactionListener.query(e,t).then((e=>this.queryResponseStream.write(e))).catch((t=>{B.error(e,"Error handling interaction query",t)}))}}var z=r("../metrics/dist/index.js");const W=(0,n.h)("@anysphere/agent-client:stall-detector"),q=(0,z.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type"]}),G=(0,z.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type"]}),V=(0,z.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall"}),J=(0,z.Pu)("agent_client.stream.total",{description:"Total number of streams monitored"});class K{handlers=new Map;track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){var e;const t=Date.now(),r={};for(const[n,o]of this.handlers)r[n]={state:o.state,durationMs:(null!==(e=o.endedAt)&&void 0!==e?e:t)-o.startedAt,error:o.error};return r}}class Y{timer;advisoryTimer;heartbeatOnlyTimer;lastActivityTime=Date.now();lastMeaningfulActivityTime=Date.now();hasLogged=!1;hasLoggedAdvisory=!1;hasLoggedHeartbeatOnly=!1;hasEverStalled=!1;lastClientSentHeartbeatAt;lastServerSentHeartbeatAt;streamEndedAt;abortedAt;disposedAt;onCtxSignalAbort;lastActivity;lastInboundMessage;lastOutboundMessage;activityHistory=[];thresholdMs;advisoryThresholdMs;heartbeatOnlyThresholdMs;onStall;onStallCallback;handlerTracker;constructor(e,t,r){var n;this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=null!==(n=t.heartbeatOnlyThresholdMs)&&void 0!==n?n:3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker),this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),J.increment(this.ctx,1),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog("[NAL client stall detector] Stream aborted while stall detector active","aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}ctx;trackActivity(e,t){var r;const n={type:e,messageType:t};this.lastActivity=n,"inbound_message"===e?this.lastInboundMessage=n:"outbound_write"===e&&(this.lastOutboundMessage=n);const o=this.activityHistory.at(-1);(null==o?void 0:o.type)===e&&o.messageType===t?o.repeat=(null!==(r=o.repeat)&&void 0!==r?r:1)+1:(this.activityHistory.push(n),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=Date.now(),r&&(this.lastMeaningfulActivityTime=Date.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=Date.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=Date.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=Date.now()}startTimer(){if(this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{const t=this.thresholdMs-(Date.now()-this.lastActivityTime);if(t<=0)return this.timer=void 0,void this.onStallDetected("no_activity");this.timer=setTimeout(e,t)};this.timer=setTimeout(e,this.thresholdMs)}startAdvisoryTimer(){if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{const r=e-(Date.now()-this.lastActivityTime);if(r<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();this.advisoryTimer=setTimeout(t,r)};this.advisoryTimer=setTimeout(t,e)}startHeartbeatOnlyTimer(){if(this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{const t=this.heartbeatOnlyThresholdMs-(Date.now()-this.lastMeaningfulActivityTime);if(t<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");this.heartbeatOnlyTimer=setTimeout(e,t)};this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){var t;const r=this.ctx.get(te),n=Object.assign({},e);(null===(t=null==r?void 0:r.modelDetails)||void 0===t?void 0:t.displayName)&&(n.model_name=r.modelDetails.displayName),this.abortedAt&&(n.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(n.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(n.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(n.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(n.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(n.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(n.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return n.activities=o.join("\n"),{reqId:null==r?void 0:r.requestId,stall:n}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=Date.now()-this.lastActivityTime;e<this.advisoryThresholdMs||(this.hasLoggedAdvisory=!0,this.reportAdvisory(e,this.advisoryThresholdMs))}reportAdvisory(e,t){try{const r=this.buildLogMetadata({duration_ms:e,threshold_ms:t,stall_type:"advisory_no_activity"});W.warn(this.ctx,"[NAL client stall detector] Advisory stall detected - no activity for advisory threshold period",r)}catch(e){console.error("Error logging advisory stall:",e)}}onStallDetected(e){if("heartbeat_only"===e){const t=Date.now(),r=t-this.lastActivityTime,n=t-this.lastMeaningfulActivityTime;if(r<this.thresholdMs&&n>=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){var r,n,o,s,i;const a=this.lastActivity,c=this.lastInboundMessage,l=this.lastOutboundMessage,u=this.ctx.get(te);try{const o=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),d="heartbeat_only"===e?"[NAL client stall detector] Stream receiving heartbeats only - no meaningful data for threshold period":"[NAL client stall detector] Bidirectional stream stall detected - no activity for threshold period";if(W.warn(this.ctx,d,o),q.increment(this.ctx,1,{activity_type:null!==(s=null==a?void 0:a.type)&&void 0!==s?s:"unknown",message_type:null!==(i=null==a?void 0:a.messageType)&&void 0!==i?i:"unknown"}),this.hasEverStalled||(this.hasEverStalled=!0,V.increment(this.ctx,1)),this.onStallCallback){const t=Date.now(),o={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:null==a?void 0:a.messageType,lastInboundMessageType:null==c?void 0:c.messageType,lastOutboundMessageType:null==l?void 0:l.messageType,requestId:null==u?void 0:u.requestId,modelName:null===(r=null==u?void 0:u.modelDetails)||void 0===r?void 0:r.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:null===(n=this.handlerTracker)||void 0===n?void 0:n.getHandlerStates()};try{this.onStallCallback(o)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{null===(o=this.onStall)||void 0===o||o.call(this)}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});W.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){var e,t;const r=Date.now()-this.lastActivityTime;this.emitLifecycleLog("[NAL client stall detector] Stream activity resumed after stall","recovered"),G.histogram(this.ctx,r,{activity_type:null!==(t=null===(e=this.lastActivity)||void 0===e?void 0:e.type)&&void 0!==t?t:"unknown"})}[Symbol.dispose](){void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=Date.now(),this.emitLifecycleLog("[NAL client stall detector] Stream stall detector disposed","disposed")}}const Z=(0,n.h)("@anysphere/agent-client:turn-runner");async function X(e,t,r,n){const o=r?100:1e3,s=null!=n?n:Math.min(o*Math.pow(2,e),6e4),i=void 0!==n?0:.2*s*Math.random();await new Promise(((e,r)=>{if(null==t?void 0:t.aborted)return void r(new x("Cancelled during backoff"));const n=setTimeout((()=>{null==t||t.removeEventListener("abort",o),e()}),s+i);function o(){clearTimeout(n),r(new x("Cancelled during backoff"))}null==t||t.addEventListener("abort",o,{once:!0})}))}var Q=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ee=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const te=(0,n.cF)(Symbol("agentStreamMetadata"),void 0),re=(0,n.h)("@anysphere/agent-client:abort"),ne=(0,n.h)("@anysphere/agent-client:retry"),oe=e=>{var t,r;const n=[];switch(n.push(e.message.case),e.message.case){case"conversationAction":n.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":n.push(e.message.value.message.case);break;case"interactionResponse":n.push(e.message.value.result.case);break;case"interactionUpdate":switch(n.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":n.push(null===(t=e.message.value.message.value.toolCall)||void 0===t?void 0:t.tool.case);break;case"toolCallDelta":n.push(null===(r=e.message.value.message.value.toolCallDelta)||void 0===r?void 0:r.delta.case)}break;case"interactionQuery":n.push(e.message.value.query.case)}return n.filter((e=>void 0!==e)).join(":")};async function se(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.LV.shellOutputDelta({case:"stdout",value:new f.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.LV.shellOutputDelta({case:"stderr",value:new f.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.LV.shellOutputDelta({case:"exit",value:new f.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function ie(e,t,r){return{sendUpdate:async(n,o)=>{var s;if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===(null===(s=o.message)||void 0===s?void 0:s.case)&&ne.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new x("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}const ae=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0;function ce(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function le(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}function ue(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}function de(e){return e instanceof Error?e.name:void 0}function pe(e){const t={errorName:de(e)};let r=e;for(let e=0;e<10&&void 0!==r;e++){if(ce(r)){const e=le(r),n=ue(e),o=de(e);return Object.assign(Object.assign({},t),{underlyingConnectError:{code:r.code,codeName:y.Code[r.code],cause:void 0!==n||void 0!==o?{code:n,name:o}:void 0}})}r=le(r)}return t}function he(e,t,r,n,o,s,i,a,c){const l=s||i,u=c?2:10,d=e instanceof b?e:j(e,{requestId:o});return t?l?!i&&n>=u?{action:"throw",error:new k("Connection stalled repeatedly",{cause:d.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:new k("Connection stalled",{cause:d.cause,requestId:o,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0}})}:d instanceof x&&!a&&function(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(ce(t)&&(t.code===y.Code.Canceled||t.code===y.Code.Aborted))return!0;t=le(t)}return!1}(d)?l?!i&&n>=u?{action:"throw",error:new k("Connection failed repeatedly",{cause:d.cause,requestId:o,displayInfo:{title:"Connection failed",detail:`The connection failed ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:d}:d instanceof x||d instanceof S||d instanceof E?{action:"throw",error:d}:d instanceof k&&M(d)?l?!i&&n>=u?{action:"throw",error:new k("Connection failed repeatedly",{cause:d.cause,requestId:o,displayInfo:{title:"Connection failed",detail:`The connection failed ${n} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:d}:l?!i&&r>=3?{action:"throw",error:d}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:{action:"throw",error:d}}class me{client;endpointUrl;constructor(e,t){this.client=e,this.endpointUrl=t}async run(e,t,r,n,o,s,i,a,c,l,u){return!0===u.useSharedTurnRunner?this.runWithSharedTurnRunner(e,t,r,n,o,s,i,a,c,l,u):this.runWithLegacyRetryLoop(e,t,r,n,o,s,i,a,c,l,u)}async runWithSharedTurnRunner(e,t,r,o,s,i,a,c,l,u,p){var h,m;const f={stack:[],error:void 0,hasError:!1};try{const g=null!==(m=p.generationUUID)&&void 0!==m?m:crypto.randomUUID(),v={value:!1},y={sources:[],abortReasonName:void 0,abortReasonMessage:void 0};let w=0,k=0;try{null===(h=p.onNetworkPhaseStart)||void 0===h||h.call(p)}catch(t){ne.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const S=Q(f,(0,n.VI)(e.withName("networkPhase")),!1);e=S.ctx,await async function(e){var t,r,n,o,s,i,a,c,l,u,p,h,m,f,g,v,y,w;const{ctx:b,checkpointHandler:k,runOptions:S,requestId:E,hooks:x,cancellation:_}=e,C=E,P=null!==(f=e.backoff)&&void 0!==f?f:(e,t)=>X(e,t,S.isRunningInTest,S.fixedRetryDelayMs);let R,T,I=e.state,A=e.action,j=0,O=E,D=0,M=0,N=!1;const $=()=>{var e;N&&(null===(e=S.onConnectionStateChange)||void 0===e||e.call(S,{state:"connected"}),N=!1)},L={handleCheckpoint:async(e,t,r)=>{var n;await k.handleCheckpoint(e,t,r),R=t,T=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible",$()},getLatestCheckpoint:()=>k.getLatestCheckpoint()};for(;;){if(b.canceled)throw _.toCancelledError(void 0,O);if(R=void 0,T=void 0,null===(t=x.beginAttempt)||void 0===t||t.call(x,{attempt:j,originalRequestId:C}),j>0?(O=crypto.randomUUID(),await(null===(r=S.onRetryStarting)||void 0===r?void 0:r.call(S,j,{actionCase:A.action.case,conversationState:I,isResume:"resumeAction"===A.action.case,attemptRequestId:O})),e.logging&&Z.info(b,`[${e.logging.tag}] Retrying attempt ${j}`,{attempt:j,actionCase:A.action.case,requestId:O,originalRequestId:C}),"resumeAction"===A.action.case&&(await(null===(n=S.onRetryResuming)||void 0===n?void 0:n.call(S,{checkpointState:I,nextAttempt:j,reason:"resume_action"})),e.logging&&Z.info(b,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:j,reason:"resume_action"}))):(e.logging&&Z.info(b,`[${e.logging.tag}] Initial request`,{attempt:j,actionCase:A.action.case,requestId:O}),!0===e.notifyInitialResume&&"resumeAction"===A.action.case&&(await(null===(o=S.onRetryResuming)||void 0===o?void 0:o.call(S,{checkpointState:I,nextAttempt:j,reason:"resume_action"})),e.logging&&Z.info(b,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:j,reason:"resume_action"}))),b.canceled)throw _.toCancelledError(void 0,O);try{return await x.runAttempt({state:I,action:A,checkpointHandler:L,attempt:j,attemptRequestId:O,notifyConnected:$}),$(),void(e.logging&&Z.info(b,`[${e.logging.tag}] Request successful`,{attempt:j,actionCase:A.action.case,requestId:O,originalRequestId:C}))}catch(t){if(!0===(null===(s=_.shortCircuit)||void 0===s?void 0:s.call(_,t)))throw _.toCancelledError(t,O);const r=!0===(null===(i=S.endlessRetries)||void 0===i?void 0:i.call(S)),n=x.classify(t,{attempt:j,attemptRequestId:O,originalRequestId:C,serverErrorRetries:D,transportErrorRetries:M,endlessRetries:r});if(e.logging){const o="retry"===n.action?`RETRY (countAsServerError=${n.countAsServerError}, countAsTransportError=${n.countAsTransportError})`:`THROW ${n.error.kind}`;Z.warn(b,`[AGENT_ERROR_DIAGNOSTICS] requestId=${O} originalRequestId=${C} decision=${o}`,Object.assign({decision:o,willRetry:"retry"===n.action,enableAgentRetries:null!==(g=S.enableAgentRetries)&&void 0!==g&&g,endlessRetries:r,isRunningInTest:null!==(v=S.isRunningInTest)&&void 0!==v&&v,serverErrorRetries:D,transportErrorRetries:M,attempt:j,requestId:O,originalRequestId:C},null===(c=(a=e.logging).diagnostics)||void 0===c?void 0:c.call(a,t)))}if("throw"===n.action){if(0===j){const t={attempt:0,actionCase:A.action.case,error:n.error,requestId:O,originalRequestId:C,enableAgentRetries:!0===S.enableAgentRetries,endlessRetries:r,stallAborted:!1,abortSources:[]};try{await(null===(l=S.onErrorNotRetried)||void 0===l?void 0:l.call(S,null!==(y=null===(u=x.buildNonRetriedErrorInfo)||void 0===u?void 0:u.call(x,t))&&void 0!==y?y:t))}catch(t){e.logging&&Z.warn(b,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(t),requestId:O,originalRequestId:C})}}throw e.logging&&Z.warn(b,`[${e.logging.tag}] Error not retryable`,Object.assign(Object.assign({attempt:j,actionCase:A.action.case},!0===e.logging.includeErrorObjects?{error:n.error}:{errorName:n.error.name}),{serverErrorRetries:D,transportErrorRetries:M})),n.error}const o=j+1;if("ineligible_terminal_turn"===T)return void(e.logging&&Z.warn(b,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:t instanceof Error?t.name:typeof t,errorMessage:t instanceof Error?t.message:String(t)}));null===(p=S.onConnectionStateChange)||void 0===p||p.call(S,{state:"reconnecting",attempt:o,trigger:null!==(w=null===(h=x.reconnectTrigger)||void 0===h?void 0:h.call(x,t,n,{originalRequestId:C,failedAttemptRequestId:O,nextAttempt:o}))&&void 0!==w?w:{originatingRequestId:C,attemptRequestId:O}}),N=!0,n.countAsServerError&&D++,n.countAsTransportError&&M++,j=o,void 0!==R&&(I=R,A=new d.QF({action:{case:"resumeAction",value:new d.qK}}),null===(m=x.onResumeFromCheckpoint)||void 0===m||m.call(x)),await P(j,b.signal)}}}({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:p,requestId:g,notifyInitialResume:!0,logging:{tag:"nal_agent_retries",includeErrorObjects:!0,diagnostics:e=>Object.assign({stallAborted:v.value,abortSources:[...y.sources],abortReasonName:y.abortReasonName},pe(e))},cancellation:{toCancelledError:()=>new x("Request cancelled")},hooks:{beginAttempt:()=>{v.value=!1,y.sources=[],y.abortReasonName=void 0,y.abortReasonMessage=void 0,k=++w},runAttempt:async({state:t,action:r,checkpointHandler:n,attempt:l,attemptRequestId:d,notifyConnected:h})=>{const m=ie(s,k,(()=>w));await this.runInternal(e,t,r,o,m,i,a,c,n,u,p,d,g,v,y,h,l)},classify:(e,t)=>{var r;return he(e,v.value,t.serverErrorRetries,t.transportErrorRetries,t.attemptRequestId,null!==(r=p.enableAgentRetries)&&void 0!==r&&r,t.endlessRetries,y.sources.length>0,p.isRunningInTest)},buildNonRetriedErrorInfo:e=>{var t;return Object.assign(Object.assign({},e),{enableAgentRetries:null!==(t=p.enableAgentRetries)&&void 0!==t&&t,stallAborted:v.value,abortSources:[...y.sources],abortReasonName:y.abortReasonName,abortReasonMessage:y.abortReasonMessage})},reconnectTrigger:(e,t,r)=>{var n,o,s;const i=pe(e),a=e instanceof b?e:j(e,{requestId:r.failedAttemptRequestId});return{errorClass:a.name,connectCode:null===(n=i.underlyingConnectError)||void 0===n?void 0:n.code,connectCodeName:null===(o=i.underlyingConnectError)||void 0===o?void 0:o.codeName,errorCode:null===(s=a.displayInfo)||void 0===s?void 0:s.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:v.value,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,endpointUrl:this.endpointUrl}},onResumeFromCheckpoint:()=>c.resetStream()}})}catch(e){f.error=e,f.hasError=!0}finally{ee(f)}}async runWithLegacyRetryLoop(e,t,r,o,s,i,a,c,l,u,p){var h,m,f,g,v,y,w,k,S,E,_,C,P;const R={stack:[],error:void 0,hasError:!1};try{const T=null!==(k=p.generationUUID)&&void 0!==k?k:crypto.randomUUID();let I=T;const{onConnectionStateChange:A}=p;let O=t,D=r,M=0,N=0,$=0;const L={value:!1},F={value:!1},U={value:!1},B={value:void 0},H={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},z=(e,t)=>{null==A||A({state:"reconnecting",attempt:e,trigger:t}),L.value=!0},W=()=>{L.value&&(null==A||A({state:"connected"}),L.value=!1)},q=t=>{if(!U.value)return!1;if("ineligible_terminal_turn"===B.value)return ne.warn(e,"[nal_agent_retries] Terminal checkpoint received before retryable error; completing without automatic resume",{errorName:t instanceof Error?t.name:typeof t,errorMessage:t instanceof Error?t.message:String(t)}),!0;const r=l.getLatestCheckpoint();return!!r&&(O=r,D=new d.QF({action:{case:"resumeAction",value:new d.qK}}),c.resetStream(),!1)},G={handleCheckpoint:async(e,t,r)=>{var n;await l.handleCheckpoint(e,t,r),U.value=!0,B.value=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};let V=0;try{null===(h=p.onNetworkPhaseStart)||void 0===h||h.call(p)}catch(t){ne.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const J=Q(R,(0,n.VI)(e.withName("networkPhase")),!1);for(e=J.ctx;!e.canceled;){F.value=!1,U.value=!1,B.value=void 0,H.sources=[],H.abortReasonName=void 0,H.abortReasonMessage=void 0;const t=++V;M>0?(I=crypto.randomUUID(),await(null===(m=p.onRetryStarting)||void 0===m?void 0:m.call(p,M,{actionCase:D.action.case,conversationState:O,isResume:"resumeAction"===D.action.case,attemptRequestId:I})),ne.info(e,`[nal_agent_retries] Retrying attempt ${M}`,{attempt:M,actionCase:D.action.case,requestId:I,originalRequestId:T})):ne.info(e,"[nal_agent_retries] Initial request",{attempt:M,actionCase:D.action.case,requestId:I}),"resumeAction"===D.action.case&&p.onRetryResuming&&(await p.onRetryResuming({checkpointState:O,nextAttempt:M,reason:"resume_action"}),ne.info(e,"[nal_agent_retries] Resuming from checkpoint",{nextAttempt:M,reason:"resume_action"}));const r=ie(s,t,(()=>V));try{return await this.runInternal(e,O,D,o,r,i,a,c,G,u,p,I,T,F,H,W,M),void ne.info(e,"[nal_agent_retries] Request successful",{attempt:M,actionCase:D.action.case,requestId:I,originalRequestId:T})}catch(t){const r=null!==(S=null===(f=p.endlessRetries)||void 0===f?void 0:f.call(p))&&void 0!==S&&S,n=pe(t),o=he(t,F.value,N,$,I,null!==(E=p.enableAgentRetries)&&void 0!==E&&E,r,H.sources.length>0,p.isRunningInTest),s="retry"===o.action?`RETRY (countAsServerError=${o.countAsServerError}, countAsTransportError=${o.countAsTransportError})`:`THROW ${o.error.kind}`;if(ne.warn(e,`[AGENT_ERROR_DIAGNOSTICS] requestId=${I} originalRequestId=${T} decision=${s}`,Object.assign({decision:s,willRetry:"retry"===o.action,enableAgentRetries:null!==(_=p.enableAgentRetries)&&void 0!==_&&_,endlessRetries:r,isRunningInTest:null!==(C=p.isRunningInTest)&&void 0!==C&&C,stallAborted:F.value,serverErrorRetries:N,transportErrorRetries:$,attempt:M,requestId:I,originalRequestId:T,abortSources:[...H.sources],abortReasonName:H.abortReasonName},n)),"throw"===o.action){if(0===M){const t={attempt:M,actionCase:D.action.case,error:o.error,requestId:I,originalRequestId:T,enableAgentRetries:null!==(P=p.enableAgentRetries)&&void 0!==P&&P,endlessRetries:r,stallAborted:F.value,abortSources:[...H.sources],abortReasonName:H.abortReasonName,abortReasonMessage:H.abortReasonMessage};try{await(null===(g=p.onErrorNotRetried)||void 0===g?void 0:g.call(p,t))}catch(t){ne.warn(e,"[nal_agent_retries] onErrorNotRetried callback failed",{error:String(t),requestId:I,originalRequestId:T})}}throw ne.warn(e,"[nal_agent_retries] Error not retryable",{attempt:M,actionCase:D.action.case,error:o.error,serverErrorRetries:N,transportErrorRetries:$}),o.error}const i=M+1;if(q(t))return;const a=t instanceof b?t:j(t,{requestId:I});z(i,{errorClass:a.name,connectCode:null===(v=n.underlyingConnectError)||void 0===v?void 0:v.code,connectCodeName:null===(y=n.underlyingConnectError)||void 0===y?void 0:y.codeName,errorCode:null===(w=a.displayInfo)||void 0===w?void 0:w.errorCode,countAsServerError:o.countAsServerError,countAsTransportError:o.countAsTransportError,stallAborted:F.value,originatingRequestId:T,attemptRequestId:I,endpointUrl:this.endpointUrl}),o.countAsServerError&&N++,o.countAsTransportError&&$++,M=i,await X(M,e.signal,p.isRunningInTest,p.fixedRetryDelayMs)}}throw new x("Request cancelled")}catch(e){R.error=e,R.hasError=!0}finally{ee(R)}}async runInternal(e,t,r,o,a,l,y,S,_,C,P,R,T,I,A,O,D,N="agent.request.attempt"){var $,L,U,B,z,W,q,G,V;const J={stack:[],error:void 0,hasError:!1};try{const Z=e,X=Q(J,(0,n.VI)(e.withName(N)),!1);X.span.setAttribute("agent.attempt",D),X.span.setAttribute("agent.request_id",R),X.span.setAttribute("agent.original_request_id",T),e=X.ctx,e=(0,n.Mf)(e,"agent.request_id",R),e=(e=(0,n.Mf)(e,"agent.original_request_id",T)).with(te,{requestId:R,rootParentRequestId:P.rootParentRequestId,modelDetails:o});const ee=new Set(A.sources);let ie=void 0!==A.abortReasonName||void 0!==A.abortReasonMessage;const ce=(t,r)=>{if(ee.has(t))return;ee.add(t),A.sources=[...ee];const n=(e=>{const t="string"==typeof(null==e?void 0:e.abortReasonName)?e.abortReasonName:void 0,r="string"==typeof(null==e?void 0:e.abortReasonMessage)?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);ie||void 0===n||(ie=!0,A.abortReasonName=n.abortReasonName,A.abortReasonMessage=n.abortReasonMessage),re.error(e,"Agent client stream abort",new Error(t),Object.assign({abortSource:t,requestId:R,conversationId:P.conversationId},null!=r?r:{}))};if(e.signal.aborted){const t=e.signal.reason;ce("ctx_signal_abort",(0,n.R5)(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;ce("ctx_signal_abort",(0,n.R5)(t))}),{once:!0});const[le,ue]=e.withCancel();if(null===($=S.signal)||void 0===$?void 0:$.aborted){const e=null===(U=S.signal)||void 0===U?void 0:U.reason;ce("conversation_action_abort",(0,n.R5)(e)),ue()}else null===(L=S.signal)||void 0===L||L.addEventListener("abort",(()=>{var e;const t=null===(e=S.signal)||void 0===e?void 0:e.reason;ce("conversation_action_abort",(0,n.R5)(t)),ue()}),{once:!0});if(e.canceled||le.canceled){const t={ctxCanceled:e.canceled,softCancel:le.canceled};throw ce("pre_run_cancel",t),new x("User aborted request")}const de=(0,n.VI)(e.withName("createControlledExecManager")),pe=i.n6.fromResources(l);de[Symbol.dispose]();const[he,me]=e.withCancel(),fe=new K,{failThresholdMs:ge,advisoryThresholdMs:ve}=(e=>{var t;const r=null!==(t=ae(null==e?void 0:e.failTimeoutMs))&&void 0!==t?t:3e4,n=ae(null==e?void 0:e.advisoryTimeoutMs);return{failThresholdMs:r,advisoryThresholdMs:void 0!==n&&n>0&&(r<=0||n<r)?n:void 0}})(P.stallDetectorConfig),ye=Q(J,new Y(he,{thresholdMs:ge,advisoryThresholdMs:ve,onStall:()=>{I.value=!0,ce("stall_detector",{thresholdMs:ge,advisoryThresholdMs:ve}),me()},onStallCallback:P.onStall,handlerTracker:fe}),!1),we=void 0!==P.prewarmedStream;let be,ke,Se,Ee;if(we){be=P.prewarmedStream.requestStream,ke=P.prewarmedStream.responseIterator;const e=P.prewarmedStream.abortController;if(he.signal.aborted){const t=null!==(W=he.signal.reason)&&void 0!==W?W:"stall_cancel_already_aborted";e.abort(t)}else he.signal.addEventListener("abort",(()=>{var t;const r=null!==(t=he.signal.reason)&&void 0!==t?t:"stall_cancel_aborted";e.abort(r)}),{once:!0});P.prewarmedStream=void 0}else be=(0,w.Jt)();const xe=new g.F8(be,(e=>(ye.reset("outbound_write",oe(e)),e))),_e=(0,n.VI)(e.withName("writeInitialRequest"));let Ce;if(we)Ce=xe.write(new p.KS({message:{case:"conversationAction",value:r}}));else{const s=C.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?v.Value.fromJson(e.inputSchema):void 0}))),i=new d.Mp({conversationState:t,action:r,modelDetails:o,requestedModel:P.requestedModel,mcpTools:new m.Or({mcpTools:s}),conversationGroupId:P.conversationGroupId,conversationId:P.conversationId,mcpFileSystemOptions:P.mcpFileSystemOptions,customSystemPrompt:P.customSystemPrompt,harness:P.harness,suggestNextPrompt:P.suggestNextPrompt,subagentTypeName:P.subagentTypeName,excludeWorkspaceContext:P.excludeWorkspaceContext,devRawModelSlug:P.devRawModelSlug,selectedSubagentModels:P.selectedSubagentModels,subagentModelOverrides:null!==(q=P.subagentModelOverrides)&&void 0!==q?q:[],selectedSubagentModelDetails:P.selectedSubagentModelsLegacy,preFetchedBlobs:null!==(G=P.preFetchedBlobs)&&void 0!==G?G:[],clientSupportsInlineImages:P.clientSupportsInlineImages,clientSupportsSendToUser:P.clientSupportsSendToUser,canCreateCloudSubagents:P.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:P.suppressSubagentProgressUpdateTool});if(Ce=xe.write(new p.KS({message:{case:"runRequest",value:i}})),le.canceled){const t={ctxCanceled:e.canceled,softCancel:le.canceled};throw ce("post_write_cancel",t),_e[Symbol.dispose](),new x("User aborted request")}const a=Object.assign(Object.assign({"x-request-id":R,"x-original-request-id":T},function(e){return Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.parentRequestId?{"x-parent-request-id":c(e.parentRequestId)}:{}),void 0!==e.rootParentRequestId?{"x-root-parent-request-id":c(e.rootParentRequestId)}:{}),void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":c(e.parentAgentToolCallId)}:{}),!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{})}(P)),null!==(V=P.headers)&&void 0!==V?V:{});Se=(0,n.VI)(e.withName("handshakeEstablishment")),ke=this.client.run(e,be,{signal:he.signal,headers:a,onHeader:P.onHeader,onNetworkStarted:()=>{void 0===Ee&&(Ee=performance.now())}})}const Pe=performance.now(),Re=()=>{var e,t;Se&&(Se[Symbol.dispose](),Se=void 0),O();const r=performance.now();null===(e=P.onFirstMessage)||void 0===e||e.call(P,r-Pe),void 0!==Ee&&(null===(t=P.onFirstMessageNetwork)||void 0===t||t.call(P,r-Ee))},Te=P.onFirstNonHeartbeatResponse?()=>{P.onFirstNonHeartbeatResponse(performance.now()-Pe,D)}:void 0,{interactionStream:Ie,execStream:Ae,checkpointStream:je,kvStream:Oe,done:De}=function(e,t,r,n,o,s,i){const a=(0,w.Jt)(),c=(0,w.Jt)(),l=(0,w.Jt)(),u=(0,w.Jt)();let d=!1,p=!1;return{interactionStream:a,execStream:c,checkpointStream:l,kvStream:u,done:async function(){let h,m,f=!1,g=!1;try{for await(const o of t){if(d||(d=!0,n()),"interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{null==i||i()}catch(t){ne.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",oe(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(f=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await a.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await c.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=f?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(g=!0),await l.write({checkpoint:o.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===o.message.case&&await u.write(o.message.value)}r.onStreamEnded()}catch(e){h=e}finally{if(m=h,f&&g&&void 0!==h&&!(null==o?void 0:o.aborted)&&!(null==s?void 0:s.aborted)&&function(e){const t=e instanceof b?e:j(e);return t instanceof k&&M(t)}(h)&&(ne.warn(e,"Ignoring transport close after terminal agent stream",{caughtError:h instanceof Error?`${h.name}: ${h.message}`:String(h)}),r.onStreamEnded(),m=void 0),f||(null==o?void 0:o.aborted)||(null==s?void 0:s.aborted)){if(!f&&!(null==o?void 0:o.aborted)){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${null==o?void 0:o.aborted}, parentSignal.aborted=${null==s?void 0:s.aborted}; firstMessageFired=${d}`;ne.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===h?(ne.warn(e,t),m=new k(t)):h instanceof Error&&"[aborted] aborted"===h.message?(ne.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new k(t,{cause:h})):ne.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:h instanceof Error?`${h.name}: ${h.message}`:String(h)})}a.close(),c.close(),l.close(),u.close()}if(void 0!==m)throw m}()}}(e,ke,ye,Re,le.signal,e.signal,Te);let Me;const Ne={handleCheckpoint:async(e,t,r)=>{var n;await _.handleCheckpoint(e,t,r),Me=null!==(n=null==r?void 0:r.resumeEligibility)&&void 0!==n?n:"eligible"},getLatestCheckpoint:()=>_.getLatestCheckpoint()};_e[Symbol.dispose]();const $e=5e3;let Le;const Fe=()=>{Le=setTimeout((()=>{xe.write(new p.KS({message:{case:"clientHeartbeat",value:new p.kA}})).then((()=>ye.onClientSentHeartbeat()),(()=>{})),Fe()}),$e)},Ue=()=>{void 0!==Le&&(clearTimeout(Le),Le=void 0)};Fe();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,o=new f.a({command:(null===(B=n.shellCommand)||void 0===B?void 0:B.command)||"",parsingResult:new f.HO,skipApproval:!0}),s=l.get(i.wv).execute(e,o,{execId:n.execId}),c=new H(Ie,a,new g.F8(xe,(e=>new p.KS({message:{case:"interactionResponse",value:e}}))));t={run:async e=>{await Promise.all([fe.track("handleShellStream",se(e,s,a)),fe.track("interactionController",c.run(e))])}}}else{const e=new H(Ie,a,new g.F8(xe,(e=>new p.KS({message:{case:"interactionResponse",value:e}}))));t={run:async t=>{await fe.track("interactionController",e.run(t))}}}void 0!==Ce&&await Promise.race([Ce,De.catch((()=>{}))]);const n=new g.F8(xe,(e=>{if(e instanceof h.yT)return new p.KS({message:{case:"execClientMessage",value:e}});if(e instanceof h.$Y)return new p.KS({message:{case:"execClientControlMessage",value:e}});throw new Error("Unknown exec message")})),c=new F(Ae,n,pe),d=new u.hC(Oe,new g.F8(xe,(e=>new p.KS({message:{case:"kvClientMessage",value:e}}))),y),m=new s(je,Ne,e);let v,w;const b={promise:new Promise(((e,t)=>{v=e,w=t})),resolve:v,reject:w};le.canceled?(b.resolve(),Ie.close()):le.signal.addEventListener("abort",(()=>{b.resolve(),Ie.close()}),{once:!0}),c.run(le).then(b.resolve).catch(b.reject);const k=Promise.allSettled([fe.track("streamSplitter",De.finally((()=>{Ue(),S.close(),n.close()}))),fe.track("execHandler",b.promise),t.run(e),fe.track("checkpointController",m.run()),fe.track("kvHandler",d.run(e)),fe.track("conversationActionManager",S.run(e,new g.F8(xe,(e=>new p.KS({message:{case:"conversationAction",value:e}})))))]);let _,j;const D={promise:new Promise(((e,t)=>{_=e,j=t})),resolve:_,reject:j};k.then(D.resolve).catch(D.reject),e.canceled?D.reject(new x("User aborted request")):e.signal.addEventListener("abort",(()=>D.reject(new x("User aborted request"))),{once:!0}),le.canceled?(me(),D.reject(new x("User aborted request"))):le.signal.addEventListener("abort",(()=>{me(),D.reject(new x("User aborted request"))}),{once:!0});const M=await D.promise,N=M[0],$=M[1],L=M[3],U=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===L.status)throw new E("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:R,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const W="ineligible_terminal_turn"===Me;if(W){const t=Object.assign(Object.assign({},"rejected"===N.status?{streamSplitter:U(N)}:{}),"rejected"===$.status?{execHandler:U($)}:{});Object.keys(t).length>0&&ne.warn(e,"Ignoring handler errors after terminal checkpoint",t)}if(!0===(null===(z=P.shouldUseAgentExecStreamStartTimeoutRecovery)||void 0===z?void 0:z.call(P))){if("rejected"===N.status&&!W)throw N.reason;if("rejected"===$.status&&!W)throw $.reason}if("rejected"===$.status&&!W)throw $.reason;if("rejected"===N.status&&!W)throw N.reason;le.canceled||await this.processUnprocessedMessages(Z,S,Ne,o,a,l,y,C,P,R,T,I,A,ye,O)}finally{Ue(),Se&&(Se[Symbol.dispose](),Se=void 0)}}catch(e){J.error=e,J.hasError=!0}finally{ee(J)}}async processUnprocessedMessages(e,t,r,n,o,s,i,a,c,l,u,p,h,m,f){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),m[Symbol.dispose]();const w=r.getLatestCheckpoint();try{await this.runInternal(e,v,new d.QF({action:{case:"userMessageAction",value:new d.Vt({userMessage:y})}}),n,o,s,i,t,r,a,c,l,u,p,h,f,0,"agent.request.queuedMessage")}catch(e){throw w===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),r("../proto/dist/generated/agent/v1/delete_tool_pb.js"),r("../proto/dist/generated/agent/v1/grep_exec_pb.js"),r("../proto/dist/generated/agent/v1/grep_tool_pb.js"),r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),r("../proto/dist/generated/agent/v1/ls_tool_pb.js"),r("../proto/dist/generated/agent/v1/read_tool_pb.js"),r("../proto/dist/generated/agent/v1/shell_tool_pb.js")},"../agent-core/dist/index.js"(e,t,r){r.d(t,{hg:()=>a,x1:()=>_,LV:()=>P,p_:()=>C,kj:()=>v,gR:()=>g});var n=r("../context/dist/index.js"),o=r("../proto/dist/generated/agent/v1/agent_pb.js"),s=r("../utils/dist/index.js");const i=(0,n.h)("ControlledConversationActionManager");class a{abortCallbacks=[];abortController=new AbortController;clientStream;abortStarted=!1;runActive=!1;unprocessedUserMessages=[];get signal(){return this.abortController.signal}constructor(){this.clientStream=(0,s.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortController.signal.aborted||this.abortStarted)return;const r=null==t?void 0:t.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,s=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new o.QF({action:{case:"cancelAction",value:new o.TT({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of s)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){var e;null===(e=this.clientStream)||void 0===e||e.close()}resetStream(){var e;null===(e=this.clientStream)||void 0===e||e.close(),this.clientStream=(0,s.Jt)(),this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new o.QF({action:{case:"userMessageAction",value:new o.Vt({userMessage:e})}}))}async run(e,t){this.runActive=!0;try{for await(const r of this.clientStream)try{await t.write(r)}catch(t){i.error(e,"Error writing conversation action",t)}}finally{this.runActive=!1}}dispose(){this.abortCallbacks.length=0}}(0,n.h)("RemoteConversationActionManager");const c=BigInt(0),l=BigInt(8),u=BigInt(16),d=BigInt(65535);function p(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function h(e){const t=e.split(".");if(4!==t.length)return;let r=c;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<l|BigInt(t)}return{version:4,value:r}}function m(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=h(n);if(!o)return;t.push(Number(o.value>>u&d)),t.push(Number(o.value&d))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function f(e){var t;return null!==(t=h(e))&&void 0!==t?t:function(e){const t=p(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=m(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<u|BigInt(t)),c)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=m(n),i=m(o);if(!s||!i)return;const a=s.length+i.length;return a>7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<<u|BigInt(t)),c)}}(e)}function g(e,t){const r=p(e),n=p(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=f(t.slice(0,r)),o=f(e);if(!n||!o||n.version!==o.version)return!1;const s=Number(t.slice(r+1)),i=4===n.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function v(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch(e){return}}(e);return!!r&&function(e,t){return t.some((t=>g(e,t)))}(r.hostname,t)}r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js");var y=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),w=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),b=(r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js")),k=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),S=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),E=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),x=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");Error;const _={webSearchApproved:e=>new o.Y5({id:e,result:{case:"webSearchRequestResponse",value:new x.lI({result:{case:"approved",value:new x.XJ}})}}),webSearchRejected:(e,t)=>new o.Y5({id:e,result:{case:"webSearchRequestResponse",value:new x.lI({result:{case:"rejected",value:new x.yc({reason:null!=t?t:""})}})}}),webFetchApproved:e=>new o.Y5({id:e,result:{case:"webFetchRequestResponse",value:new E.fS({result:{case:"approved",value:new E.Hs}})}}),webFetchRejected:(e,t)=>new o.Y5({id:e,result:{case:"webFetchRequestResponse",value:new E.fS({result:{case:"rejected",value:new E.m$({reason:null!=t?t:""})}})}}),askQuestion:(e,t)=>new o.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new o.zT({result:t})}}),switchModeApproved:e=>new o.Y5({id:e,result:{case:"switchModeRequestResponse",value:new S.w$({result:{case:"approved",value:new S.q5}})}}),switchModeRejected:(e,t)=>new o.Y5({id:e,result:{case:"switchModeRequestResponse",value:new S.w$({result:{case:"rejected",value:new S.rA({reason:null!=t?t:""})}})}}),createPlan:(e,t)=>new o.Y5({id:e,result:{case:"createPlanRequestResponse",value:new y.gz({result:t})}}),setupVmEnvironment:(e,t)=>new o.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),replaceEnv:(e,t)=>new o.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),prManagement:(e,t)=>new o.Y5({id:e,result:{case:"prManagementResult",value:t}}),mcpAuthApproved:e=>new o.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new k.h({result:{case:"approved",value:new k.D5}})}}),mcpAuthRejected:(e,t)=>new o.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new k.h({result:{case:"rejected",value:new k.OI({reason:null!=t?t:"Authentication was rejected"})}})}}),generateImageApproved:(e,t)=>new o.Y5({id:e,result:{case:"generateImageRequestResponse",value:new b.vW({result:{case:"approved",value:new b.l3({description:null!=t?t:""})}})}}),generateImageRejected:(e,t)=>new o.Y5({id:e,result:{case:"generateImageRequestResponse",value:new b.vW({result:{case:"rejected",value:new b.Uq({reason:null!=t?t:""})}})}})};function C(){return new w.HL({result:{case:"error",value:new w.K$({error:"PR management is only available in cloud agents"})}})}Error;const P={textDelta:e=>new o.Uq({message:{case:"textDelta",value:new o.Pt({text:e})}}),toolCallStarted:(e,t,r)=>new o.Uq({message:{case:"toolCallStarted",value:new o.xu({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new o.Uq({message:{case:"toolCallCompleted",value:new o.LL({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r)=>new o.Uq({message:{case:"toolCallDelta",value:new o.I0({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t)=>new o.Uq({message:{case:"thinkingDelta",value:new o.cH({text:e,thinkingStyle:t})}}),thinkingCompleted:e=>new o.Uq({message:{case:"thinkingCompleted",value:new o.tr({thinkingDurationMs:e})}}),userMessageAppended:e=>new o.Uq({message:{case:"userMessageAppended",value:new o.v$({userMessage:e})}}),partialToolCall:(e,t,r)=>new o.Uq({message:{case:"partialToolCall",value:new o.fx({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new o.Uq({message:{case:"tokenDelta",value:new o.Fy({tokens:e})}}),summary:e=>new o.Uq({message:{case:"summary",value:new o.EC({summary:e})}}),summaryStarted:()=>new o.Uq({message:{case:"summaryStarted",value:new o.lW}}),heartbeat:()=>new o.Uq({message:{case:"heartbeat",value:new o.RV}}),summaryCompleted:e=>new o.Uq({message:{case:"summaryCompleted",value:new o.ZM({hookMessage:e})}}),shellOutputDelta:e=>new o.Uq({message:{case:"shellOutputDelta",value:new o.Nn({event:e})}}),turnEnded(e){var t;return new o.Uq({message:{case:"turnEnded",value:new o.lJ(e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(null!==(t=e.reasoningTokens)&&void 0!==t?t:0)}:{})}})},stepStarted:e=>new o.Uq({message:{case:"stepStarted",value:new o.dw({stepId:BigInt(e)})}}),stepCompleted:(e,t)=>new o.Uq({message:{case:"stepCompleted",value:new o.Lr({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),promptSuggestion:e=>new o.Uq({message:{case:"promptSuggestion",value:new o.yf({suggestion:e})}}),activeBranchChange:(e,t)=>new o.Uq({message:{case:"activeBranchChange",value:new o.PS({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],s={})=>new o.Uq({message:{case:"feedbackRequest",value:new o.ap({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:s.title,negativeTitle:s.negativeTitle,commentPlaceholder:s.commentPlaceholder})}})}},"../agent-exec/dist/index.js"(e,t,r){r.d(t,{iK:()=>J,sn:()=>M,gl:()=>q,FH:()=>te,J6:()=>re,y7:()=>Le,h:()=>_,n6:()=>v,qL:()=>D.qL,VM:()=>He,Ok:()=>A,sO:()=>N,iZ:()=>$,$b:()=>Me,u:()=>Re,hv:()=>Ue,Rp:()=>L,w4:()=>F,zy:()=>O,Ij:()=>G,IG:()=>U,PE:()=>je,oG:()=>De,jH:()=>B,u8:()=>H,UO:()=>ze,bo:()=>W,S_:()=>Ne,rn:()=>Z,bL:()=>V,OD:()=>ee,Yi:()=>Y,pY:()=>Q,TG:()=>ne,TZ:()=>oe,Pi:()=>se,gh:()=>ie,Rd:()=>ae,qN:()=>ce,T0:()=>le,oh:()=>ue,_A:()=>de,ml:()=>X,pq:()=>Te,Mf:()=>pe,MZ:()=>Ie,oA:()=>Oe,Gu:()=>Ae,qk:()=>ye,wv:()=>we,Zn:()=>Be,sC:()=>We,TQ:()=>j,Ln:()=>be});var n=r("../context/dist/index.js"),o=r("../metrics/dist/index.js"),s=r("../proto/dist/generated/agent/v1/exec_pb.js"),i=r("../utils/dist/index.js");const a=/ \[git: ([^\]]*)\]/;function c(e,t,r){if("object"!=typeof t||null===t)return e;if(a.test(e))return e;const n=t,o=[];if("string"==typeof n.gitErrorCode&&n.gitErrorCode.length>0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i;return!0===(null==r?void 0:r.includeStderr)&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${i=n.stderr,i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}const l=(0,n.h)("SimpleControlledExecManager"),u=(0,o.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),d=(0,o.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),p=(0,o.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]});class h extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function m(e){return e instanceof h?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class f{exec;deserializeArgs;serializeResult;constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class g{exec;deserializeArgs;serializeStream;constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=r.exec.execute(e,o,{execId:t.execId});for await(const e of i){const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}(this)}}class v{handlers=[];runningExecs=new Map;includeGitStderrInThrows;constructor(e){var t;const r=null!==(t=null==e?void 0:e.includeGitStderrInThrows)&&void 0!==t&&t;this.includeGitStderrInThrows="function"==typeof r?r:()=>r}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){var r;const[n,o]=e.withCancel();this.runningExecs.set(t.id,o);const a=null!==(r=t.message.case)&&void 0!==r?r:"unknown";for(const e of this.handlers){const r=e.handle(n,t);if(void 0===r)continue;const o=r,l=(0,i.Jt)();let h;const f=()=>{h=setTimeout((()=>{l.write(new s.$Y({message:{case:"heartbeat",value:new s.VA({id:t.id})}})).then(f).catch((()=>{}))}),3e3)};f();const g=performance.now();return(async()=>{try{for await(const e of o)await l.write(e);await l.write(new s.$Y({message:{case:"streamClose",value:new s.D9({id:t.id})}})),d.increment(n,1,{exec_case:a})}catch(e){if(e instanceof i.W2)return;p.increment(n,1,{exec_case:a}),await l.write(new s.$Y({message:{case:"throw",value:new s.Fu({id:t.id,error:e instanceof Error?c(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:m(e)})}}))}finally{const e=performance.now()-g;u.histogram(n,e,{exec_case:a}),clearTimeout(h),l.close(),this.runningExecs.delete(t.id)}})(),l}this.runningExecs.delete(t.id);const h=`No handler found for server message of type ${t.message.case}`;return l.error(e,h,{messageCase:t.message.case}),p.increment(e,1,{exec_case:a}),async function*(){yield new s.$Y({message:{case:"throw",value:new s.Fu({id:t.id,error:h})}}),yield new s.$Y({message:{case:"streamClose",value:new s.D9({id:t.id})}})}()}static fromResources(e,t){const r=new v(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var y=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},w=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const b=(0,n.h)("ExecutorResource");class k{execManager;serializeArgs;deserializeResult;constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const a=y(o,(0,n.VI)(e.withName("ExecutorResource.execute")),!1),c=a.ctx;void 0!==(null==r?void 0:r.execId)&&a.span.setAttribute("exec.id",r.execId);const l=(0,n.mJ)(c),u=l?new s.Kg(l):void 0,d=this.execManager.createExecInstance(c,(e=>{const n=this.serializeArgs(e,t);return new s.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,spanContext:u})})),p=await(0,n.uj)(c.withName("ExecutorResource.sendAndAwaitFirstResult"),(()=>(0,i.ue)(d)));if(void 0===p)throw new Error("No exec result");const{firstItem:h,rest:m}=p;(0,n.uj)(c.withName("ExecutorResource.drainResultStream"),(async()=>{try{for await(const e of m);}catch(e){b.info(c,"Ignoring exec stream shutdown during detached drain",{error:e})}})).catch((()=>{}));const f=this.deserializeResult(h);if(void 0===f)throw new Error("No result value");return void 0!==(null==r?void 0:r.hookContextCollector)&&h.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...h.hookAdditionalContexts),f}catch(e){o.error=e,o.hasError=!0}finally{w(o)}}}class S{execManager;serializeArgs;deserializeStream;constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const i=y(o,(0,n.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,a=(0,n.mJ)(i),c=a?new s.Kg(a):void 0,l=this.execManager.createExecInstance(i,(e=>{const n=this.serializeArgs(e,t);return new s.Ye({id:n.id,message:n.message,execId:null==r?void 0:r.execId,spanContext:c})}));for await(const e of l){const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){o.error=e,o.hasError=!0}finally{w(o)}}}function E(e,t){return{symbol:Symbol(),remoteImplementation:e,registerControlledImplementation:t}}class x{resource;value;constructor(e,t){this.resource=e,this.value=t}}class _{resources=new Map;register(e,t){this.resources.set(e.symbol,new x(e,t))}get(e){var t;return null===(t=this.resources.get(e.symbol))||void 0===t?void 0:t.value}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class C{remoteAccessor;localResources=new Map;constructor(e,t){this.remoteAccessor=e;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?t.implementation:this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function P(e){return function(t,r){return new s.Ye({id:t,message:{case:e,value:r}})}}function R(e){return t=>{if(t.message.case===e)return t.message.value}}function T(e){return function(t,r){const n={case:e,value:r};return new s.yT({id:t,message:n})}}function I(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const A=E((e=>new k(e,P("backgroundShellSpawnArgs"),R("backgroundShellSpawnResult"))),((e,t)=>{t.register(new f(e,I("backgroundShellSpawnArgs"),T("backgroundShellSpawnResult")))})),j=E((e=>new k(e,P("writeShellStdinArgs"),R("writeShellStdinResult"))),((e,t)=>{t.register(new f(e,I("writeShellStdinArgs"),T("writeShellStdinResult")))}));function O(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}var D=r("../proto/dist/generated/agent/v1/agent_pb.js");const M="local",N=E((e=>new k(e,P("canvasDiagnosticsArgs"),R("canvasDiagnosticsResult"))),((e,t)=>{t.register(new f(e,I("canvasDiagnosticsArgs"),T("canvasDiagnosticsResult")))}));Error;const $=E((e=>new k(e,P("computerUseArgs"),R("computerUseResult"))),((e,t)=>{t.register(new f(e,I("computerUseArgs"),T("computerUseResult")))})),L=E((e=>new k(e,P("deleteArgs"),R("deleteResult"))),((e,t)=>{t.register(new f(e,I("deleteArgs"),T("deleteResult")))})),F=E((e=>new k(e,P("diagnosticsArgs"),R("diagnosticsResult"))),((e,t)=>{t.register(new f(e,I("diagnosticsArgs"),T("diagnosticsResult")))})),U=E((e=>new k(e,P("fetchArgs"),R("fetchResult"))),((e,t)=>{t.register(new f(e,I("fetchArgs"),T("fetchResult")))})),B=E((e=>new k(e,P("gitDiffRequest"),R("gitDiffResponse"))),((e,t)=>{t.register(new f(e,I("gitDiffRequest"),T("gitDiffResponse")))})),H=E((e=>new k(e,P("grepArgs"),R("grepResult"))),((e,t)=>{t.register(new f(e,I("grepArgs"),T("grepResult")))}));var z=r("../hooks/dist/index.js");const W=E((e=>new k(e,P("executeHookArgs"),R("executeHookResult"))),((e,t)=>{t.register(new f(e,I("executeHookArgs"),T("executeHookResult")))}));class q{hookExecutor;constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){var r,n,o;return null!==(o=null===(n=(r=this.hookExecutor).hasFailClosedHooksForStep)||void 0===n?void 0:n.call(r,e,t))&&void 0!==o&&o}async execute(e,t){var r,n,o,i,a,c,l,u,d,p,h,m,f,g,v,y,w,b,k;const S=t.request;if(!S)return new s.S1({response:void 0});switch(S.request.case){case"preCompact":{const e=S.request.value,t=Object.assign(Object.assign({conversation_id:null!==(r=e.conversationId)&&void 0!==r?r:"",generation_id:null!==(n=e.generationId)&&void 0!==n?n:"",model:null!==(o=e.model)&&void 0!==o?o:""},(0,z.U4)(e)),{trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction}),i=await this.hookExecutor.executeHookForStep(z._E.preCompact,t);return new s.S1({response:new s.w5({response:{case:"preCompact",value:new D.$_({userMessage:null==i?void 0:i.user_message})}})})}case"subagentStart":{const e=S.request.value,t=Object.assign(Object.assign({conversation_id:null!==(i=e.conversationId)&&void 0!==i?i:"",generation_id:null!==(a=e.generationId)&&void 0!==a?a:"",model:null!==(c=e.model)&&void 0!==c?c:""},(0,z.U4)(e)),{subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch}),r=await this.hookExecutor.executeHookForStep(z._E.subagentStart,t);return new s.S1({response:new s.w5({response:{case:"subagentStart",value:new D.W0({permission:null==r?void 0:r.permission,userMessage:null==r?void 0:r.user_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"subagentStop":{const e=S.request.value,t=Object.assign(Object.assign({conversation_id:null!==(l=e.conversationId)&&void 0!==l?l:"",generation_id:null!==(u=e.generationId)&&void 0!==u?u:"",model:null!==(d=e.model)&&void 0!==d?d:""},(0,z.U4)(e)),{subagent_id:e.subagentId,subagent_type:e.subagentType,status:e.status,duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:null!==(p=e.loopCount)&&void 0!==p?p:0,task:e.task,description:e.description}),r=await this.hookExecutor.executeHookForStep(z._E.subagentStop,t);return new s.S1({response:new s.w5({response:{case:"subagentStop",value:new D.AH({followupMessage:null==r?void 0:r.followup_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"preToolUse":{const e=S.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(h=e.conversationId)&&void 0!==h?h:"",generation_id:null!==(m=e.generationId)&&void 0!==m?m:"",model:null!==(f=e.model)&&void 0!==f?f:""},(0,z.U4)(e)),{tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd}),n=await this.hookExecutor.executeHookForStep(z._E.preToolUse,r);return new s.S1({response:new s.w5({response:{case:"preToolUse",value:new D.D2({permission:null==n?void 0:n.permission,userMessage:null==n?void 0:n.user_message,agentMessage:null==n?void 0:n.agent_message,updatedInput:(null==n?void 0:n.updated_input)?JSON.stringify(n.updated_input):void 0,additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUse":{const e=S.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(g=e.conversationId)&&void 0!==g?g:"",generation_id:null!==(v=e.generationId)&&void 0!==v?v:"",model:null!==(y=e.model)&&void 0!==y?y:""},(0,z.U4)(e)),{tool_name:e.toolName,tool_input:t,tool_output:e.toolOutput,duration:Number(e.durationMs),tool_use_id:e.toolUseId,cwd:e.cwd}),n=await this.hookExecutor.executeHookForStep(z._E.postToolUse,r);return new s.S1({response:new s.w5({response:{case:"postToolUse",value:new D.uB({additionalContext:null==n?void 0:n.additional_context})}})})}case"postToolUseFailure":{const e=S.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(w=e.conversationId)&&void 0!==w?w:"",generation_id:null!==(b=e.generationId)&&void 0!==b?b:"",model:null!==(k=e.model)&&void 0!==k?k:""},(0,z.U4)(e)),{tool_name:e.toolName,tool_input:t,error_message:e.errorMessage,failure_type:e.failureType,duration:Number(e.durationMs),tool_use_id:e.toolUseId,is_interrupt:e.isInterrupt}),n=await this.hookExecutor.executeHookForStep(z._E.postToolUseFailure,r);return new s.S1({response:new s.w5({response:{case:"postToolUseFailure",value:new D.U1({additionalContext:null==n?void 0:n.additional_context})}})})}default:return new s.S1({response:void 0})}}}(0,n.cF)(Symbol("execHookConversationId"),void 0),(0,n.cF)(Symbol("execHookGenerationId"),void 0),(0,n.cF)(Symbol("execHookModel"),void 0);const G=(0,n.cF)(Symbol("execHookWorkspaceRoots"),void 0),V=E((e=>new k(e,P("lsArgs"),R("lsResult"))),((e,t)=>{t.register(new f(e,I("lsArgs"),T("lsResult")))})),J="custom-user-tools";var K;new Set(["cursor-dev-control","cursor-ide-browser"]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(K||(K={}));const Y=E((e=>new k(e,P("mcpArgs"),R("mcpResult"))),((e,t)=>{t.register(new f(e,I("mcpArgs"),T("mcpResult")))})),Z=E((e=>new k(e,P("listMcpResourcesExecArgs"),R("listMcpResourcesExecResult"))),((e,t)=>{t.register(new f(e,I("listMcpResourcesExecArgs"),T("listMcpResourcesExecResult")))})),X=E((e=>new k(e,P("readMcpResourceExecArgs"),R("readMcpResourceExecResult"))),((e,t)=>{t.register(new f(e,I("readMcpResourceExecArgs"),T("readMcpResourceExecResult")))})),Q=E((e=>new k(e,P("mcpStateExecArgs"),R("mcpStateExecResult"))),((e,t)=>{t.register(new f(e,I("mcpStateExecArgs"),T("mcpStateExecResult")))}));r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");const ee=E((e=>new k(e,P("mcpAllowlistPrecheckArgs"),R("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new f(e,I("mcpAllowlistPrecheckArgs"),T("mcpAllowlistPrecheckResult")))})),te="mcps",re="tools";function ne(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch(e){return}}const oe=E((e=>new k(e,P("piBashArgs"),R("piBashResult"))),((e,t)=>{t.register(new f(e,I("piBashArgs"),T("piBashResult")))})),se=E((e=>new k(e,P("piEditArgs"),R("piEditResult"))),((e,t)=>{t.register(new f(e,I("piEditArgs"),T("piEditResult")))})),ie=E((e=>new k(e,P("piFindArgs"),R("piFindResult"))),((e,t)=>{t.register(new f(e,I("piFindArgs"),T("piFindResult")))})),ae=E((e=>new k(e,P("piGrepArgs"),R("piGrepResult"))),((e,t)=>{t.register(new f(e,I("piGrepArgs"),T("piGrepResult")))})),ce=E((e=>new k(e,P("piLsArgs"),R("piLsResult"))),((e,t)=>{t.register(new f(e,I("piLsArgs"),T("piLsResult")))})),le=E((e=>new k(e,P("piReadArgs"),R("piReadResult"))),((e,t)=>{t.register(new f(e,I("piReadArgs"),T("piReadResult")))})),ue=E((e=>new k(e,P("piWriteArgs"),R("piWriteResult"))),((e,t)=>{t.register(new f(e,I("piWriteArgs"),T("piWriteResult")))})),de=E((e=>new k(e,P("readArgs"),R("readResult"))),((e,t)=>{t.register(new f(e,I("readArgs"),T("readResult")))})),pe=E((e=>new k(e,P("redactedReadArgs"),R("redactedReadResult"))),((e,t)=>{t.register(new f(e,I("redactedReadArgs"),T("redactedReadResult")))}));var he=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),me=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),fe=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),ge=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),ve=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const ye=E((e=>new k(e,P("shellArgs"),R("shellResult"))),((e,t)=>{t.register(new f(e,I("shellArgs"),T("shellResult")))})),we=E((e=>new S(e,P("shellStreamArgs"),R("shellStream"))),((e,t)=>{t.register(new g(e,I("shellStreamArgs"),T("shellStream")))})),be=E((e=>new k(e,P("writeArgs"),R("writeResult"))),((e,t)=>{t.register(new f(e,I("writeArgs"),T("writeResult")))}));function ke(e,t){var r,n;return new ge.jn({command:null!==(r=t.command)&&void 0!==r?r:"",workingDirectory:null!==(n=t.workingDirectory)&&void 0!==n?n:"",error:e,isReadonly:!0})}function Se(e){return{execute:async(t,r)=>new ge.W4({result:{case:"permissionDenied",value:ke(e,r)}})}}function Ee(e){return{async*execute(t,r){yield new ge.FI({event:{case:"permissionDenied",value:ke(e,r)}})}}}function xe(e){return{execute:async(t,r)=>new he.Lt({result:{case:"permissionDenied",value:ke(e,r)}})}}function _e(e){return{execute:async(t,r)=>new me.Pi({result:{case:"permissionDenied",value:new me.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function Ce(e){return{execute:async(t,r)=>new fe.iz({result:{case:"permissionDenied",value:new fe.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}function Pe(e){return{execute:async(t,r)=>new he.nt({result:{case:"error",value:new he.Gv({error:e})}})}}function Re(e){return new C(e,function(e){const t=[[be,(r=e.errorMessage,{execute:async(e,t)=>new ve.v3({result:{case:"permissionDenied",value:new ve.U7({path:t.path,error:r,isReadonly:!0})}})})],[L,_e(e.errorMessage)],[Y,Ce(e.errorMessage)]];var r;return e.wrapShell&&t.push([ye,Se(e.errorMessage)],[we,Ee(e.errorMessage)],[A,xe(e.errorMessage)]),e.includeWriteBackgroundShellStdin&&t.push([j,Pe(e.errorMessage)]),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0}))}const Te=E((e=>new k(e,P("recordScreenArgs"),R("recordScreenResult"))),((e,t)=>{t.register(new f(e,I("recordScreenArgs"),T("recordScreenResult")))})),Ie=E((e=>new k(e,P("requestContextArgs"),R("requestContextResult"))),((e,t)=>{t.register(new f(e,I("requestContextArgs"),T("requestContextResult")))}));r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");const Ae=E((e=>new k(e,P("shellAllowlistPrecheckArgs"),R("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new f(e,I("shellAllowlistPrecheckArgs"),T("shellAllowlistPrecheckResult")))})),je=E((e=>new k(e,P("forceBackgroundShellArgs"),R("forceBackgroundShellResult"))),((e,t)=>{t.register(new f(e,I("forceBackgroundShellArgs"),T("forceBackgroundShellResult")))}));function Oe(e,t){e.hookApprovalRequirement=void 0!==t?new ge.In(t):void 0}function De(e){return e.hookApprovalRequirement}function Me(e){return new ge.In({kind:ge.b.FORCE_PROMPT,reason:e})}function Ne(e){return(null==e?void 0:e.kind)===ge.b.FORCE_PROMPT}r("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"),E((e=>new k(e,P("smartModeClassifierArgs"),R("smartModeClassifierResult"))),((e,t)=>{t.register(new f(e,I("smartModeClassifierArgs"),T("smartModeClassifierResult")))}));var $e=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");const Le="Sub-agent is currently running. You may send the follow-up message when it has completed.";class Fe extends Error{name="SubagentHostError";agentId;cause;constructor(e,t){super(e),this.agentId=null==t?void 0:t.agentId,this.cause=null==t?void 0:t.cause}}function Ue(e){const t=new Map;async function r(t,r,n){var o,s,i,a;let c;try{c=await e.createOrResumeSession(t,r);const a=await e.runSession(t,c,r,{execId:null==n?void 0:n.execId});return"error"===a.status?new $e.vS({result:{case:"error",value:new $e.od({agentId:c,error:a.error})}}):"aborted"===a.status?new $e.vS({result:{case:"error",value:new $e.od({agentId:c,error:null!==(o=a.error)&&void 0!==o?o:"Subagent was aborted by the user"})}}):"background"===a.status?new $e.vS({result:{case:"success",value:new $e.HJ({agentId:c,finalMessage:a.finalMessage,toolCallCount:null!==(s=a.toolCallCount)&&void 0!==s?s:0,backgroundReason:a.backgroundReason,transcriptPath:a.transcriptPath})}}):new $e.vS({result:{case:"success",value:new $e.HJ({agentId:c,finalMessage:a.finalMessage,toolCallCount:null!==(i=a.toolCallCount)&&void 0!==i?i:0})}})}catch(t){c&&e.releaseSession&&e.releaseSession(c);const n=t instanceof Error?t.message:String(t),o=null!==(a=null!=c?c:function(e){if(e instanceof Fe&&e.agentId)return e.agentId;if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.agentId?t.agentId:void 0}(t))&&void 0!==a?a:r.resumeAgentId;return new $e.vS({result:{case:"error",value:new $e.od(Object.assign(Object.assign({},o?{agentId:o}:{}),{error:n}))}})}}return{execute(e,n,o){const s=function(e){var t,r;if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,null!==(t=e.resumeAgentId)&&void 0!==t?t:"",null!==(r=e.forkAgentId)&&void 0!==r?r:""].join("\0")}(n);if(void 0===s)return r(e,n,o);const i=t.get(s);if(void 0!==i)return i;const a=r(e,n,o).finally((()=>{t.delete(s)}));return t.set(s,a),a}}}const Be=E((e=>new k(e,P("subagentArgs"),R("subagentResult"))),((e,t)=>{t.register(new f(e,I("subagentArgs"),T("subagentResult")))}));E((e=>new k(e,P("subagentAwaitArgs"),R("subagentAwaitResult"))),((e,t)=>{t.register(new f(e,I("subagentAwaitArgs"),T("subagentAwaitResult")))})),E((e=>new k(e,P("forceBackgroundSubagentArgs"),R("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new f(e,I("forceBackgroundSubagentArgs"),T("forceBackgroundSubagentResult")))}));class He{options;states=new Map;runCounterBySession=new Map;dispatchQueueBySession=new Map;dispatchInProgress=new Set;releaseRequestedBySession=new Set;constructor(e={}){this.options=e}getState(e){var t;return null!==(t=this.states.get(e))&&void 0!==t?t:{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:null==t?void 0:t.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){var t;const r=(null!==(t=this.runCounterBySession.get(e))&&void 0!==t?t:0)+1;return this.runCounterBySession.set(e,r),r}enqueueEvent(e,t){var r;const n=null!==(r=this.dispatchQueueBySession.get(e))&&void 0!==r?r:[];n.push(t),this.dispatchQueueBySession.set(e,n),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){null!=t||(t=e)}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){var r,n,o,s,i;const a=this.getState(e),{nextState:c,effects:l}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:Object.assign(Object.assign({},e),{queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)}),effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(a,t);this.states.set(e,c),null===(n=(r=this.options).onStateChange)||void 0===n||n.call(r,{sessionId:e,previousState:a,nextState:c});for(const t of l)switch(t.type){case"abortActiveRun":null===(o=t.abort)||void 0===o||o.call(t);break;case"startQueuedRun":null===(i=(s=this.options).onQueuedRunReady)||void 0===i||i.call(s,{sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const u=this.getState(e);"release"===t.type&&"idle"!==u.status&&this.releaseRequestedBySession.add(e),"idle"!==u.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function ze(e){return"string"==typeof e&&e.trim().length>0}r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");const We=E((e=>new k(e,P("webFetchAllowlistPrecheckArgs"),R("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new f(e,I("webFetchAllowlistPrecheckArgs"),T("webFetchAllowlistPrecheckResult")))}))},"../agent-transcript/dist/index.js"(e,t,r){r.d(t,{YF:()=>I,pr:()=>u,sk:()=>c});var n=r("../context/dist/index.js"),o=r("../proto/dist/generated/agent/v1/agent_pb.js"),s=r("../utils/dist/index.js");const i=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"];function a(e){return function(e,t){let r=e;for(const e of t){const t=new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi");r=r.replace(t,"")}return r.replace(/\n{3,}/g,"\n\n").trim()}(e,i)}function c(e){const t=(0,s.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,s.sh)(e.parentConversationId);return`${s.O2}/${r}/subagents/${t}.${e.ext}`}return`${s.O2}/${t}/${t}.${e.ext}`}function l(e){const t=(0,s.sh)(e.conversationId);return`${s.O2}/${t}.${e.ext}`}function u(e){var t,r;const n=null!==(t=e.exts)&&void 0!==t?t:["jsonl","txt"],o=null===(r=e.includeLegacy)||void 0===r||r,s=[],i=e=>{s.includes(e)||s.push(e)};for(const t of n)i(c({conversationId:e.conversationId,ext:t,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&i(c({conversationId:e.conversationId,ext:t,kind:"primary"})),o&&i(l({conversationId:e.conversationId,ext:t}));return s}var d;(()=>{var e;const t=null===(e=globalThis.Intl)||void 0===e?void 0:e.Segmenter;t&&new t(void 0,{granularity:"grapheme"})})(),r("../proto/dist/generated/aiserver/v1/chat_pb.js"),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(d||(d={}));var p=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},h=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function m(e){switch(e){case o.xy.AGENT:return"agent";case o.xy.ASK:return"ask";case o.xy.PLAN:return"plan";case o.xy.DEBUG:return"debug";case o.xy.TRIAGE:return"triage";case o.xy.PROJECT:return"project";case o.xy.MULTITASK:return"multitask";case o.xy.UNSPECIFIED:default:return"agent"}}function f(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function g(e,t){return t&&"object"==typeof t&&"Uint8Array"===t.__type&&"string"==typeof t.hex?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const v=new TextEncoder,y=new TextDecoder,w=new class{serialize(e){const t=JSON.stringify(e,f);return v.encode(t)}deserialize(e){const t=y.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,g):JSON.parse(t)}};function b(e){var t;const r=e.providerOptions;return!0===(null===(t=null==r?void 0:r.cursor)||void 0===t?void 0:t.isSummary)}async function k(e,t,r){const n=[];let o=0,s=0,i=0,a=0,c=0,l=0,u=0;for(const p of r){const r=await t.getBlob(e,p);if(r){if(r.length>5e6){n.push((void 0,{role:"assistant",content:`[Oversize transcript blob omitted: ${d=r.length,`${(d/1e6).toFixed(1)} MB`}]`})),c++,l+=r.length,u=Math.max(u,r.length);continue}try{const e=performance.now(),t=w.deserialize(r),c=performance.now()-e;n.push(t),o++,s+=r.length,i=Math.max(i,r.length),a+=c}catch(e){}}}var d;return{messages:n,hydratedBlobCount:o,hydratedBlobBytes:s,largestHydratedBlobBytes:i,totalDeserializeDurationMs:a,omittedOversizeBlobCount:c,omittedOversizeBlobBytes:l,largestOmittedOversizeBlobBytes:u}}function S(e,t){switch(e.type){case"text":return t?E(e.text):e.text;case"image":return"[Image]";case"file":return e.filename?`[File: ${e.filename}]`:"[File]";case"reasoning":return`[Thinking] ${e.text}`;case"redacted-reasoning":return"[Thinking]";case"tool-call":return`[Tool call] ${e.toolName}${function(e){if(null==e)return"";if("object"!=typeof e)return String(e);const t=e,r=Object.entries(t);return 0===r.length?"":`\n${r.map((([e,t])=>{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function E(e){return a(e)}function x(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function _(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?E(e):e;return r?x(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=x(t?E(e.text):e.text);return S(Object.assign(Object.assign({},e),{text:r}),!1)}return S(e,t)})).filter(Boolean).join("\n")}function C(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?E(n):n,s="assistant"===e.role?x(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?E(r.text):r.text,s="assistant"===e.role?x(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function P(e){return e.endsWith("\n")?e:`${e}\n`}function R(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify(Object.assign({type:"turn_ended"},t)))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function T(e){if("system"===e.role||b(e))return;const t=C(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class I{projectDir;blobStore;writeFile;options;constructor(e,t,r,n={}){var o,s,i;this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:null===(o=n.writeText)||void 0===o||o,writeJson:null!==(s=n.writeJson)&&void 0!==s&&s,writeJsonl:null!==(i=n.writeJsonl)&&void 0!==i&&i,pathResolver:n.pathResolver,appendFile:n.appendFile}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=c({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,s={}){const i={stack:[],error:void 0,hasError:!1};try{const a=p(i,(0,n.VI)(e.withName("writeFromState")),!1);try{const e=await async function(e,t,r){const s={stack:[],error:void 0,hasError:!1};try{const i=p(s,(0,n.VI)(e.withName("hydrateSummaryArchives")),!1);let a=0;const c=(0,n.OA)(i.ctx),l=[];let u=0,d=0,h=0,m=0,f=0,g=0,v=0;const y=await Promise.all(r.summaryArchives.map((async e=>{a++;const r=await t.getBlob(c,e);if(r)try{const e=o.An.fromBinary(r);return a+=e.summarizedMessages.length,await k(c,t,e.summarizedMessages)}catch(e){}return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}})));for(const e of y)l.push(...e.messages),u+=e.hydratedBlobCount,d+=e.hydratedBlobBytes,h=Math.max(h,e.largestHydratedBlobBytes),m+=e.totalDeserializeDurationMs,f+=e.omittedOversizeBlobCount,g+=e.omittedOversizeBlobBytes,v=Math.max(v,e.largestOmittedOversizeBlobBytes);i.span.setAttribute("getBlobCount",a),i.span.setAttribute("hydratedBlobCount",u),i.span.setAttribute("hydratedBlobBytes",d),i.span.setAttribute("largestHydratedBlobBytes",h),i.span.setAttribute("totalDeserializeDurationMs",m),i.span.setAttribute("omittedOversizeBlobCount",f),i.span.setAttribute("omittedOversizeBlobBytes",g),i.span.setAttribute("largestOmittedOversizeBlobBytes",v);const w=p(s,(0,n.VI)(e.withName("hydratePromptMessages")),!1),S=await k(c,t,r.rootPromptMessagesJson);w.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),w.span.setAttribute("hydratedBlobCount",S.hydratedBlobCount),w.span.setAttribute("hydratedBlobBytes",S.hydratedBlobBytes),w.span.setAttribute("largestHydratedBlobBytes",S.largestHydratedBlobBytes),w.span.setAttribute("totalDeserializeDurationMs",S.totalDeserializeDurationMs),w.span.setAttribute("omittedOversizeBlobCount",S.omittedOversizeBlobCount),w.span.setAttribute("omittedOversizeBlobBytes",S.omittedOversizeBlobBytes),w.span.setAttribute("largestOmittedOversizeBlobBytes",S.largestOmittedOversizeBlobBytes);const E=S.messages.filter((e=>"system"!==e.role&&!b(e)));return l.push(...E),l}catch(e){s.error=e,s.hasError=!0}finally{h(s)}}(a.ctx,this.blobStore,t),{overviewFactory:i}=s,c=R(s);if(0===e.length&&0===c.jsonlLines.length)return;let l;if((this.options.writeText||i)&&(l=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=_(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(e)),this.options.writeText){const e=null!=l?l:"",t=c.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${c.textSuffixes.join("\n")}`:c.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const n=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=C(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(e);if(n||c.jsonlLines.length>0){const e=Object.assign({mode:m(t.mode),messages:n?JSON.parse(n):[]},c.jsonFields);await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(e,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=T(e);t&&r.push(t)}return r.join("\n")}(e);let n=[t,...c.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&i&&(null==l?void 0:l.trim()))try{const e=(await i(l)).trim();e&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,e))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),P(n))}}catch(e){console.error("[TranscriptStore] Failed to write transcript:",e)}}catch(e){i.error=e,i.hasError=!0}finally{h(i)}}async writeFromStateIncremental(e,t,r,o,s={}){const i={stack:[],error:void 0,hasError:!1};try{const a=t.rootPromptMessagesJson.length,c=R(s),l=c.jsonlLines.length>0;if(a===o&&!l&&!s.overviewFactory)return a;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&o>0&&a>=o&&(a>o||l))||s.overviewFactory)return await this.writeFromStateFull(e,t,r,s),a;if(a===o&&l){try{await u(this.resolveFilePath(r,"jsonl"),P(c.jsonlLines.join("\n")))}catch(n){console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",n),await this.writeFromStateFull(e,t,r,s)}return a}const d=p(i,(0,n.VI)(e.withName("writeFromStateIncremental")),!1);try{const e=t.rootPromptMessagesJson.slice(o),n=await k(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",n.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",n.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",n.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",n.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",n.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",n.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",n.largestOmittedOversizeBlobBytes);const s=[];for(const e of n.messages){const t=T(e);t&&s.push(t)}if(s.push(...c.jsonlLines),s.length>0){const e=P(s.join("\n"));await u(this.resolveFilePath(r,"jsonl"),e)}}catch(n){console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",n),await this.writeFromStateFull(e,t,r,s)}return a}catch(e){i.error=e,i.hasError=!0}finally{h(i)}}}},"../constants/dist/index.js"(e,t,r){r.d(t,{pZY:()=>i,G$s:()=>a,tl5:()=>l,RJV:()=>d}),new Set(["agent-stores","shared-agent-stores"]);const n={clusters:{local:{managerUrl:"http://localhost:50051",httpProxyUrl:null,isLocal:!0,class:null,label:"Local",spaceliftStackId:null,portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},dev:{managerUrl:"https://dev.cursorvm-manager.com",httpProxyUrl:"10.0.29.128:8080",isLocal:!1,class:"external",label:"Dev",spaceliftStackId:"agent-runner-vpcs-dev",portalWebsite:{vncWebsocketOrigin:"wss://*.dev.cursorvm.com"},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},train1:{awsRegion:"us-east-1",managerUrl:"https://train1.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train1",spaceliftStackId:"agent-runner-vpcs-train1",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train2:{awsRegion:"us-east-1",managerUrl:"https://train2.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train2",spaceliftStackId:"agent-runner-vpcs-train2",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train3:{awsRegion:"us-east-1",managerUrl:"https://train3.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train3",spaceliftStackId:"agent-runner-vpcs-train3",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train4:{awsRegion:"us-east-2",managerUrl:"https://train4.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train4",spaceliftStackId:"agent-runner-vpcs-train4",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train5:{awsRegion:"us-west-2",managerUrl:"https://train5.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train5",spaceliftStackId:"agent-runner-vpcs-train5",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train8:{awsRegion:"us-east-1",managerUrl:"https://train8.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train8",spaceliftStackId:"agent-runner-vpcs-train8",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train9:{awsRegion:"us-west-2",managerUrl:"https://train9.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train9",spaceliftStackId:"agent-runner-vpcs-train9",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train10:{awsRegion:"us-west-2",managerUrl:"https://train10.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train10",spaceliftStackId:"agent-runner-vpcs-train10",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train11:{awsRegion:"us-west-2",managerUrl:"https://train11.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train11",spaceliftStackId:"agent-runner-vpcs-train11",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train12:{awsRegion:"eu-west-2",managerUrl:"https://train12.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train12",spaceliftStackId:"agent-runner-vpcs-train12",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},eval1:{awsRegion:"us-east-1",managerUrl:"https://eval1.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"eval1",spaceliftStackId:"agent-runner-vpcs-eval1",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"eval",show:!0},docsSite:{publishPublicIps:!1}},eval2:{awsRegion:"us-east-1",managerUrl:"https://eval2.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"eval2",spaceliftStackId:"agent-runner-vpcs-eval2",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"eval",show:!0},docsSite:{publishPublicIps:!1}},eval3:{awsRegion:"us-west-2",managerUrl:"https://eval3.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"eval3",spaceliftStackId:"agent-runner-vpcs-eval3",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"eval",show:!0},docsSite:{publishPublicIps:!1}},test1:{managerUrl:"https://test1.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"test1",spaceliftStackId:"agent-runner-vpcs-test1",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},test3:{awsRegion:"us-east-1",managerUrl:"https://test3.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"test3",spaceliftStackId:"agent-runner-vpcs-test3",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},"test2-gcp":{awsRegion:"us-east-1",managerUrl:"https://test2-gcp.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"test2-gcp",spaceliftStackId:"agent-runner-vpcs-test2-gcp",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},us1:{awsRegion:"us-west-2",managerUrl:"https://us1.cursorvm-manager.com",httpProxyUrl:"10.0.21.248:8080",isLocal:!1,class:"external",label:"us1",spaceliftStackId:"agent-runner-vpcs-us1",portalWebsite:{vncWebsocketOrigin:"wss://*.us1.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us1p:{awsRegion:"us-west-2",managerUrl:"https://us1p.cursorvm-manager.com",httpProxyUrl:"10.0.29.68:8080",isLocal:!1,class:"external",label:"us1 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us1p",portalWebsite:{vncWebsocketOrigin:"wss://*.us1p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us3:{awsRegion:"us-east-1",managerUrl:"https://us3.cursorvm-manager.com",httpProxyUrl:"10.0.25.8:8080",isLocal:!1,class:"external",label:"us3",spaceliftStackId:"agent-runner-vpcs-us3",portalWebsite:{vncWebsocketOrigin:"wss://*.us3.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us3p:{awsRegion:"us-east-1",managerUrl:"https://us3p.cursorvm-manager.com",httpProxyUrl:"10.0.26.30:8080",isLocal:!1,class:"external",label:"us3 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us3p",portalWebsite:{vncWebsocketOrigin:"wss://*.us3p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us4:{awsRegion:"us-west-2",managerUrl:"https://us4.cursorvm-manager.com",httpProxyUrl:"10.0.16.154:8080",isLocal:!1,class:"external",label:"us4",spaceliftStackId:"agent-runner-vpcs-us4",portalWebsite:{vncWebsocketOrigin:"wss://*.us4.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us4p:{awsRegion:"us-west-2",managerUrl:"https://us4p.cursorvm-manager.com",httpProxyUrl:"10.0.20.248:8080",isLocal:!1,class:"external",label:"us4 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us4p",portalWebsite:{vncWebsocketOrigin:"wss://*.us4p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us5:{awsRegion:"us-east-2",managerUrl:"https://us5.cursorvm-manager.com",httpProxyUrl:"10.0.28.203:8080",isLocal:!1,class:"external",label:"us5",spaceliftStackId:"agent-runner-vpcs-us5",portalWebsite:{vncWebsocketOrigin:"wss://*.us5.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us5p:{awsRegion:"us-east-2",managerUrl:"https://us5p.cursorvm-manager.com",httpProxyUrl:"10.0.25.35:8080",isLocal:!1,class:"external",label:"us5 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us5p",portalWebsite:{vncWebsocketOrigin:"wss://*.us5p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us6:{awsRegion:"us-east-2",managerUrl:"https://us6.cursorvm-manager.com",httpProxyUrl:"10.0.31.117:8080",isLocal:!1,class:"external",label:"us6",spaceliftStackId:"agent-runner-vpcs-us6",portalWebsite:{vncWebsocketOrigin:"wss://*.us6.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us6p:{awsRegion:"us-east-2",managerUrl:"https://us6p.cursorvm-manager.com",httpProxyUrl:"10.0.28.204:8080",isLocal:!1,class:"external",label:"us6 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us6p",portalWebsite:{vncWebsocketOrigin:"wss://*.us6p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us7:{awsRegion:"us-east-1",managerUrl:"https://us7.cursorvm-manager.com",httpProxyUrl:"10.0.56.33:8080",isLocal:!1,class:"external",label:"us7",spaceliftStackId:"agent-runner-vpcs-us7",portalWebsite:{vncWebsocketOrigin:"wss://*.us7.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us7p:{awsRegion:"us-east-1",managerUrl:"https://us7p.cursorvm-manager.com",httpProxyUrl:"10.0.26.89:8080",isLocal:!1,class:"external",label:"us7 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us7p",portalWebsite:{vncWebsocketOrigin:"wss://*.us7p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}}}},o=["dev","us1","us1p","us3","us3p","us4","us4p","us5","us5p","us6","us6p","us7","us7p","train1","train2","train3","train4","train5","train8","train9","train10","train11","train12","eval1","eval2","eval3","test1","test3","test2-gcp","local"];var s;!function(){const e=Object.keys(n.clusters),t=o,r=e.filter((e=>!t.includes(e))),s=t.filter((t=>!e.includes(t)));if(r.length>0||s.length>0)throw new Error(["[@anysphere/constants] anyrunClusterOrdering must exactly match anyrunClusterConfig.clusters keys.",r.length>0?`Missing from ordering: ${r.join(", ")}`:void 0,s.length>0?`Unknown in ordering: ${s.join(", ")}`:void 0].filter(Boolean).join(" "))}(),function(){const e=Object.keys(n.clusters).filter((e=>n.clusters[e].docsSite.publishPublicIps)).filter((e=>!("awsRegion"in n.clusters[e])));if(e.length>0)throw new Error(["[@anysphere/constants] docsSite.publishPublicIps=true clusters must define awsRegion.",e.length>0?`Missing AWS regions: ${e.join(", ")}`:void 0].filter(Boolean).join(" "))}(),new Set(["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm"]),function(e){e.github="github",e.githubEnterprise="github-enterprise",e.cursorGithub="cursor-github"}(s||(s={}));new Set(["Your environment snapshot has expired after inactivity.","Your environment snapshot is invalid.","The environment snapshot you requested does not exist, or you do not have permission to access it.","Failed to start the development environment. The update script in your configuration failed during VM startup.","Failed to start the development environment. The build process failed. Please check your Dockerfile."]);const i=8388608,a="https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg",c=["cursor"],l="http://localhost:8787/callback";function u(e){return`${e}://anysphere.cursor-mcp/oauth/callback`}function d(e){const t=new Set,r=void 0!==e&&function(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch(e){return!1}}(e);e&&!r&&t.add(e);for(const e of Array.from(new Set([...c])).map(u))t.add(e);return t.add("https://www.cursor.com/agents/mcp/oauth/callback"),t.add(l),e&&r&&t.add(e),Array.from(t)}const p={seatsCoupon:{production:"cvmQ9quG",test:"UXluQ9rM"},bugbotCoupon:null};function h(e){return[{kind:"composer",label:"Composer",productIdPrefix:`${e.prefix}-composer`,amount:{mode:"total",totalCents:e.composerTotalCents,months:6},months:6,frequency:"one_time",allowedModelIds:["github_bugbot"],allowedModelTags:["cursor-big"],priority:8,showInClient:!0},{kind:"general",label:"General",productIdPrefix:`${e.prefix}-general`,amount:{mode:"total",totalCents:e.generalTotalCents,months:6},months:6,frequency:"one_time",allowedModelIds:[],allowedModelTags:[],priority:10,showInClient:!0},{kind:"bugbot",label:"Bugbot",productIdPrefix:`${e.prefix}-bugbot`,amount:{mode:"fixed_monthly",centsPerMonth:1e5},months:6,frequency:"monthly",allowedModelIds:["github_bugbot"],allowedModelTags:[],priority:5,showInClient:!0}]}const m={key:"yc_batch",pools:h({prefix:"credit-grant-yc-batch",composerTotalCents:15e5,generalTotalCents:15e5}),coupons:p},f={key:"yc_standard",pools:h({prefix:"credit-grant-yc-standard",composerTotalCents:75e4,generalTotalCents:75e4}),coupons:p},g={standard:{referralDiscountId:"cursor-for-startups",creditLabel:"$5,000",durationMonths:6,coupons:{production:{seats:"px6DOlO1",bugbot:"Tmc1ZTk7"},test:{seats:"CNmegx7g",bugbot:"upIo5KlJ"}}},yc:{referralDiscountId:"cursor-for-startups-yc",creditLabel:"$60,000",durationMonths:12,coupons:{production:{seats:"pvrVSY2a",bugbot:"qJcxrNlY"},test:{seats:"CNmegx7g",bugbot:"upIo5KlJ"}}}};function v(e){return g[e]}m.pools,m.coupons,f.pools,f.coupons,v("yc").creditLabel,v("standard").creditLabel,new Set(["github.com","gitlab.com","bitbucket.org","bitbucket.com","codeberg.org","gitea.com","sr.ht"]),new Set(["pr_tab_init","pr_tab_refresh","pr_branch_poll","pr_metadata_refresh","pr_reviews_subtab","pr_diff_view","pr_status_pill","cloud_agent_pr_state","agent_tool_call","unknown"])},"../context-rpc/dist/index.js"(e,t,r){r.d(t,{ht:()=>l});var n=r("../context/dist/index.js"),o=(r("@connectrpc/connect"),r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js")),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js");function i(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function a(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const i=e=>{o||(o=!0,e?(null==t||t.recordException(e instanceof Error?e:new Error(String(e))),null==t||t.setStatus({code:s.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):null==t||t.setStatus({code:s.s.OK}),null==t||t.end(),null==r||r())};return{async next(){try{const e=await n.next();return e.done&&i(),e}catch(e){throw i(e),e}},return:async e=>(i(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(i(e),n.throw)return n.throw(e);throw e}}}}}function c(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r.forEach(((e,r)=>{t.set(r,e)})):Object.entries(r).forEach((([e,r])=>{t.set(e,r)})));return t}function l(e,t){const{injectTraceHeaders:r=!0,extractHeaders:l}=t;return new Proxy(e,{get(e,u){const d=e[u];return"function"!=typeof d?d:(p,h,m={})=>{const f=(0,n.fR)(p.withName(`rpc.${String(u)}`),{kind:o.v.CLIENT,attributes:{"rpc.method":String(u),"rpc.system":"connect"}}),g=(0,n.fU)(f);let v;try{let o;if(r&&(o=function(e){var t,r;const o=new Headers;try{const s=(0,n.fU)(e),i=null===(t=null==s?void 0:s.spanContext)||void 0===t?void 0:t.call(s);if((null==i?void 0:i.traceId)&&i.spanId){const e=null!==(r=i.traceFlags)&&void 0!==r?r:0,t=`00-${i.traceId}-${i.spanId}-${e.toString(16).padStart(2,"0")}`;if(o.set("traceparent",t),o.set("backend-traceparent",t),i.traceState){const e="function"==typeof i.traceState.serialize?i.traceState.serialize():String(i.traceState);o.set("tracestate",e)}}}catch(e){}return o}(f)),l){const e=l(f);e&&(o=c(o,e))}const u=c(m.headers,o),{signal:p,cleanup:w}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(f.signal,m.signal):{signal:m.signal,cleanup:void 0};v=w;const b=Object.assign(Object.assign({},m),{headers:u,signal:p}),k=d.call(e,h,b);return i(k)?a(k,g,v):null!==(y=k)&&"object"==typeof y&&"then"in y&&"function"==typeof y.then?k.then((e=>i(e)?a(e,g,v):(null==g||g.setStatus({code:s.s.OK}),null==g||g.end(),null==v||v(),e))).catch((e=>{throw null==g||g.recordException(e instanceof Error?e:new Error(String(e))),null==g||g.setStatus({code:s.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==g||g.end(),null==v||v(),e})):(null==g||g.setStatus({code:s.s.OK}),null==g||g.end(),null==v||v(),k)}catch(e){throw null==g||g.recordException(e instanceof Error?e:new Error(String(e))),null==g||g.setStatus({code:s.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==g||g.end(),null==v||v(),e}var y}}})}},"../cursor-config/dist/auth/index.js"(e,t,r){r("node:crypto?8af2");var n=r("../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/index.js");const o=process.env.HTTPS_PROXY||process.env.https_proxy||void 0;let s;try{s=void 0!==o&&o.length>0?new n.kT(o):void 0}catch(e){s=void 0}process.env.CURSOR_WEBSITE_URL,process.env.CURSOR_API_BASE_URL,Error},"../cursor-config/dist/dashboard.js"(e,t,r){r.a(e,(async(e,t)=>{try{r("../proto/dist/generated/aiserver/v1/dashboard_connect.js"),r("@connectrpc/connect");var n=r("@connectrpc/connect-node"),o=(r("../cursor-config/dist/auth/index.js"),e([n]));n=(o.then?(await o)():o)[0],t()}catch(e){t(e)}}))},"../cursor-config/dist/default-config-provider.js"(e,t,r){new(r("../proto/dist/generated/agent/v1/agent_pb.js").Gm)({modelId:"gpt-5",displayModelId:"gpt-5",displayName:"GPT-5",displayNameShort:"GPT-5",aliases:["gpt-5"]})},"../cursor-config/dist/file-based-config-provider.js"(e,t,r){r("node:fs"),r("node:fs/promises"),r("node:path"),r("../local-exec/dist/index.js"),r("zod"),r("../cursor-config/dist/paths.js"),r("../cursor-config/dist/schema.js"),new Set(["asb","staging"])},"../cursor-config/dist/index.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{Xq:()=>i.Xq,aK:()=>s.aK,mG:()=>s.mG}),r("../cursor-config/dist/auth/index.js");var o=r("../cursor-config/dist/dashboard.js"),s=(r("../cursor-config/dist/default-config-provider.js"),r("../cursor-config/dist/file-based-config-provider.js"),r("../cursor-config/dist/mcp/loader.js")),i=r("../cursor-config/dist/paths.js"),a=(r("../cursor-config/dist/permissions-file-provider.js"),r("../cursor-config/dist/project-permissions-file-provider.js"),r("../cursor-config/dist/read-only-file-based-permissions-provider.js"),r("../cursor-config/dist/schema.js"),e([o]));o=(a.then?(await a)():a)[0],n()}catch(e){n(e)}}))},"../cursor-config/dist/mcp/loader.js"(e,t,r){r.d(t,{aK:()=>u,mG:()=>l});var n=r("node:fs/promises"),o=r("node:os"),s=r("node:path"),i=r("../mcp-agent-exec/dist/index.js");class a{storage;prefix;constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class c{storage;prefix;constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class l{loaders;constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={};for(let e=0;e<o.length;e++){const t=o[e],r=this.loaders[e].prefix,n=t.getClients();for(const[e,t]of Object.entries(n)){const n=r+e;n in s||(s[n]=t)}}return new i.i9(s)}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){var t;for(const{loader:r,prefix:n}of this.loaders){if(!e.startsWith(n))continue;const o=e.slice(n.length);null===(t=r.clearClient)||void 0===t||t.call(r,o)}}clearAllMcpCaches(){var e;for(const{loader:t}of this.loaders)null===(e=t.clearAllMcpCaches)||void 0===e||e.call(t)}}class u{loader;constructor(e,t,r,n,u=!1,d,p,h=s.join((0,o.homedir)(),".cursor","mcp.json")){const m=Array.isArray(e)?e:[e],f=[];for(let e=0;e<m.length;e++){const t=m[e],r=s.join(t,".cursor","mcp.json"),n=`project-${e}-${s.basename(t)}-`;f.push({path:r,prefix:n})}f.push({path:h,prefix:"user-"});const g=new Map;for(const{path:e,prefix:t}of f)g.has(e)&&"user-"!==t||g.set(e,t);const v=[];for(const[e,o]of g){const s=u?"":o,l=new a(t,s),m=new c(n,s),f=e===h,g=[new i.mz,...f?[]:[new i.$b(m)],new i.XV(r),...p?[new i._x(p)]:[]];v.push({prefix:s,loader:new i.gT(e,l,g,d)})}this.loader=new l(v)}static init(e,t,r,o=!1,a){const c=new i.Q7(s.join(r,"mcp-auth.json"));(async function(e){await(0,n.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const l=o?{isServerApproved:()=>Promise.resolve(!0)}:new i.mF(s.join(r,"mcp-approvals.json"),t);return new u(t,c,e,l,!0,void 0,a)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}},"../cursor-config/dist/paths.js"(e,t,r){r.d(t,{Xq:()=>a}),r("node:crypto?8af2");var n=r("node:os"),o=r("node:path"),s=r("../utils/dist/index.js");function i(){return(0,o.join)(function(){const e=process.env.CURSOR_DATA_DIR;return(null==e?void 0:e.trim())?e:(0,o.join)((0,n.homedir)(),".cursor")}(),"projects")}function a(e){return(0,o.join)(i(),(0,s.r_)(e))}},"../cursor-config/dist/permissions-file-provider.js"(e,t,r){r("node:fs"),r("node:fs/promises"),r("node:path"),r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js"),r("../cursor-config/dist/paths.js"),r("../cursor-config/dist/project-permissions-file-provider.js")},"../cursor-config/dist/project-permissions-file-provider.js"(e,t,r){r("node:fs"),r("node:fs/promises"),r("node:path"),r("../local-exec/dist/index.js"),r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js")},"../cursor-config/dist/read-only-file-based-permissions-provider.js"(e,t,r){r("node:fs"),r("node:fs/promises"),r("../cursor-config/dist/schema.js")},"../cursor-config/dist/schema.js"(e,t,r){var n=r("../proto/dist/generated/agent/v1/agent_pb.js"),o=r("zod");const s=o.z.any().transform(((e,t)=>{if(e instanceof n.Gm)return e;try{return n.Gm.fromJson(e,{ignoreUnknownFields:!1})}catch(r){return t.addIssue({code:o.z.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)}),e}})),i=o.z.object({type:o.z.literal("command"),command:o.z.string().min(1),padding:o.z.number().int().min(0).optional(),updateIntervalMs:o.z.number().int().positive().optional(),timeoutMs:o.z.number().int().positive().optional()}),a=o.z.object({permissions:o.z.object({allow:o.z.array(o.z.string()),deny:o.z.array(o.z.string())})}),c=a.extend({version:o.z.number(),editor:o.z.object({vimMode:o.z.boolean(),defaultBehavior:o.z.enum(["ide","agent"]).optional()}),display:o.z.object({showLineNumbers:o.z.boolean().default(!1),showThinkingBlocks:o.z.boolean().default(!1),showStatusIndicators:o.z.boolean().default(!1),showStatusLineRunningTime:o.z.boolean().default(!1)}).default({showLineNumbers:!1,showThinkingBlocks:!1,showStatusIndicators:!1,showStatusLineRunningTime:!1}),notifications:o.z.boolean().default(!0),hints:o.z.boolean().default(!0),rewind:o.z.boolean().default(!0),suggestNextPrompt:o.z.boolean().default(!1),statusLine:i.optional(),channel:o.z.literal("static").or(o.z.literal("prod")).or(o.z.literal("lab")).or(o.z.literal("prod-stable-internal")).optional(),installedChannel:o.z.literal("static").or(o.z.literal("prod")).or(o.z.literal("lab")).or(o.z.literal("staging")).or(o.z.literal("prod-stable-internal")).optional(),model:s.optional(),bedrock:o.z.object({enabled:o.z.boolean().default(!1),mode:o.z.enum(["access-key","team-role"]).default("access-key"),region:o.z.string().optional(),testModel:o.z.string().optional(),teamRoleArn:o.z.string().optional(),teamExternalId:o.z.string().optional()}).optional(),awsAuthRefresh:o.z.string().optional(),hasChangedDefaultModel:o.z.boolean().default(!1).optional(),maxMode:o.z.boolean().default(!1).optional(),modelParameters:o.z.record(o.z.string(),o.z.array(o.z.object({id:o.z.string(),value:o.z.string()}))).optional(),selectedModel:o.z.object({modelId:o.z.string(),parameters:o.z.array(o.z.object({id:o.z.string(),value:o.z.string()}))}).optional(),privacyCache:o.z.object({ghostMode:o.z.boolean(),privacyMode:o.z.number().optional(),updatedAt:o.z.number()}).optional(),serverConfigCache:o.z.object({backendUrl:o.z.string(),authCacheKey:o.z.string().optional(),teamId:o.z.number().optional(),agentUrlConfig:o.z.object({agentUrl:o.z.string(),agentnUrl:o.z.string()}).optional(),cliSandboxDefaultEnabled:o.z.boolean().optional(),serverHttp2Config:o.z.number().optional(),updatedAt:o.z.number()}).optional(),authInfo:o.z.object({email:o.z.string().optional(),displayName:o.z.string().optional(),teamId:o.z.number().optional(),teamName:o.z.string().optional(),userId:o.z.number().optional(),authId:o.z.string().optional(),organizationId:o.z.string().optional()}).optional(),network:o.z.object({useHttp1ForAgent:o.z.boolean().default(!1)}).default({useHttp1ForAgent:!1}),approvalMode:o.z.enum(["allowlist","unrestricted","auto-review"]).default("allowlist").optional(),sandbox:o.z.object({mode:o.z.enum(["disabled","enabled"]).default("disabled"),networkAccess:o.z.preprocess((e=>"allowlist"===e?"user_config_with_defaults":"enabled"===e?"allow_all":e),o.z.enum(["user_config_only","user_config_with_defaults","allow_all"])).optional(),networkAllowlist:o.z.array(o.z.string()).default([]).optional()}).optional(),showSandboxIntro:o.z.boolean().default(!1).optional(),runEverythingSettingsPromptStreak:o.z.number().int().nonnegative().optional(),runEverythingSettingsPromptCooldownUntilMs:o.z.number().int().nonnegative().optional(),attribution:o.z.object({attributeCommitsToAgent:o.z.boolean().default(!0),attributePRsToAgent:o.z.boolean().default(!0)}).optional(),webFetchDomainAllowlist:o.z.array(o.z.string()).default([]).optional(),conversationClassificationScoredConversations:o.z.array(o.z.object({conversationId:o.z.string(),lastUpdatedAt:o.z.number()})).optional()}),l=a.strict().extend({});c.merge(l)},"../cursor-plugins/dist/index.js"(e,t,r){r.d(t,{WC:()=>Se,Nw:()=>mt,i3:()=>_r,xJ:()=>g,s4:()=>h,R3:()=>f,iU:()=>v,dB:()=>m,QY:()=>kr,wp:()=>hr,Y_:()=>lr,Nz:()=>o,nS:()=>Yt,kX:()=>Cr,Iq:()=>de,Du:()=>wr,Vw:()=>vr,Ak:()=>gr});var n=r("zod");const o={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},s=n.z.object({command:n.z.string().optional(),args:n.z.array(n.z.string()).optional(),env:n.z.record(n.z.string(),n.z.string()).optional(),url:n.z.string().optional(),headers:n.z.record(n.z.string(),n.z.string()).optional(),cwd:n.z.string().optional(),envFile:n.z.string().optional(),auth:n.z.object({CLIENT_ID:n.z.string(),CLIENT_SECRET:n.z.string().optional(),scopes:n.z.array(n.z.string()).optional()}).optional(),enabledTools:n.z.array(n.z.string()).optional()}),i=n.z.object({mcpServers:n.z.record(n.z.string(),s).optional()}),a=n.z.enum(["canvas"]),c=n.z.array(a).transform((e=>[...new Set(e)].sort()));var l=r("node:crypto?8af2");function u(e){return`user-settings:${t=e,(0,l.createHash)("sha256").update(t).digest("hex").slice(0,16)}`;var t}class d extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function p(e){const t=e.trim();if(!t)throw new d("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new d("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new d("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new d("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new d("Missing plugin name before @",e);if(!s)throw new d("Missing source after @",e);if(!r.test(o))throw new d("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new d("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new d("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new d("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new d("Missing Git URL after 'url:'",e);try{new URL(t)}catch(t){throw new d("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new d("Missing marketplace name",e);if(!r.test(a))throw new d("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function h(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("user-settings"===e.source)return u(e.sourceInfo.localPath);if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function m(e){return e.sourceInfo.name}function f(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function g(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function v(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}var y=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js"),w=r("node:path");const b=10485760,k=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,S=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json"],E=[".cursor-plugin",".claude-plugin"],x=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],_=n.z.object({source:n.z.literal("github"),repo:n.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:n.z.string().optional(),sha:n.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),C=n.z.object({source:n.z.literal("url"),url:n.z.string().url().endsWith(".git","URL must end with .git"),ref:n.z.string().optional(),sha:n.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),P=n.z.object({source:n.z.literal("git-subdir"),url:n.z.string().url().endsWith(".git","URL must end with .git"),path:n.z.string().min(1),ref:n.z.string().optional(),sha:n.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),R=n.z.union([n.z.string(),_,C,P]),T=n.z.object({name:n.z.string().min(1,"Author name is required"),email:n.z.string().email().optional()}),I=(n.z.object({name:n.z.string().min(1,"Owner name is required"),email:n.z.string().email().optional()}),n.z.enum(["string","number","integer","boolean","object","array","null"])),A=n.z.union([I,n.z.array(I).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:n.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function j(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:n.z.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:n.z.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:n.z.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:n.z.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:n.z.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:n.z.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:n.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const O=n.z.lazy((()=>n.z.object({type:A.optional(),title:n.z.string().optional(),description:n.z.string().optional(),default:n.z.unknown().optional(),enum:n.z.array(n.z.any()).nonempty().optional(),const:n.z.unknown().optional(),properties:n.z.record(n.z.string(),O).optional(),required:n.z.array(n.z.string()).optional(),additionalProperties:n.z.union([n.z.boolean(),O]).optional(),items:n.z.union([O,n.z.array(O)]).optional(),minLength:n.z.number().int().nonnegative().optional(),maxLength:n.z.number().int().nonnegative().optional(),minimum:n.z.number().optional(),maximum:n.z.number().optional(),exclusiveMinimum:n.z.number().optional(),exclusiveMaximum:n.z.number().optional(),multipleOf:n.z.number().positive().optional(),minItems:n.z.number().int().nonnegative().optional(),maxItems:n.z.number().int().nonnegative().optional(),uniqueItems:n.z.boolean().optional(),minProperties:n.z.number().int().nonnegative().optional(),maxProperties:n.z.number().int().nonnegative().optional()}).strict().superRefine(j)));function D(e){const t=O.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:n.z.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?{success:!0,data:t.data}:t}const M=n.z.unknown().superRefine(((e,t)=>{const r=D(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),N=(n.z.object({name:n.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>k.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:n.z.string().optional(),source:R,description:n.z.string().optional(),version:n.z.string().optional(),author:T.optional(),publisher:n.z.string().min(1).optional(),homepage:n.z.string().url().optional(),repository:n.z.string().url().optional(),license:n.z.string().optional(),keywords:n.z.array(n.z.string()).optional(),capabilities:c.optional(),logo:n.z.string().optional(),category:n.z.string().optional(),tags:n.z.array(n.z.string()).optional(),strict:n.z.boolean().default(!0),commands:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),agents:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),skills:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),rules:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),hooks:n.z.union([n.z.string(),n.z.record(n.z.unknown())]).optional(),variables:M.optional(),mcpServers:n.z.union([n.z.string(),n.z.record(n.z.unknown()),n.z.array(n.z.union([n.z.string(),n.z.record(n.z.unknown())]))]).optional()}),n.z.object({description:n.z.string().optional(),version:n.z.string().optional(),pluginRoot:n.z.string().optional()}),n.z.object({name:n.z.string().min(1).regex(k,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:n.z.string().optional(),description:n.z.string().optional(),version:n.z.string().optional(),author:T.optional(),publisher:n.z.string().min(1).optional(),homepage:n.z.string().url().optional(),repository:n.z.string().url().optional(),license:n.z.string().optional(),logo:n.z.string().optional(),keywords:n.z.array(n.z.string()).optional(),capabilities:c.optional(),commands:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),agents:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),skills:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),rules:n.z.union([n.z.string(),n.z.array(n.z.string())]).optional(),hooks:n.z.union([n.z.string(),n.z.record(n.z.unknown())]).optional(),variables:M.optional(),mcpServers:n.z.union([n.z.string(),n.z.record(n.z.unknown()),n.z.array(n.z.union([n.z.string(),n.z.record(n.z.unknown())]))]).optional()}));function $(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function L(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function F(e,t){if($(e)&&"string"==typeof e.name){const t=L(e.name);if(t.length>0)return t}return function(e){var t;const r=void 0!==e.repoName?L(e.repoName):"";return r.length>0?r:`cursor-marketplace-${null!==(t=e.fallbackId)&&void 0!==t?t:(0,l.randomUUID)()}`}(t)}function U(e){if($(e)&&$(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return Object.assign({name:t},void 0!==r?{email:r}:{})}return{name:"Unknown"}}function B(e){return"string"==typeof e?e:void 0}function H(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function z(e){return"string"==typeof e?e:H(e)}function W(e){if(!$(e)||!$(e.metadata))return;const t={description:B(e.metadata.description),version:B(e.metadata.version),pluginRoot:B(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function q(e){if(!$(e))return;const t=B(e.name);if(void 0===t||0===t.length)return;const r=B(e.email);return Object.assign({name:t},void 0!==r?{email:r}:{})}function G(e){if("string"==typeof e||$(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||$(e)));return t.length>0?t:void 0}}function V(e){if("string"==typeof e||$(e))return e}function J(e){if(void 0===e)return;const t=D(e);return t.success?t.data:void 0}function K(e,t={}){if(e.length>b)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!$(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],s=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!$(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:$(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:B(n.ref),sha:B(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:B(n.ref),sha:B(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:B(n.ref),sha:B(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:B(n.ref),sha:B(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=B(e.name);return{skippedEntry:Object.assign(Object.assign({index:t},void 0!==r&&r.length>0?{name:r}:{}),{error:`Plugin entry at index ${t} has no usable source`})}}const o=("string"==typeof e.name?L(e.name):"")||function(e){var t;if("string"==typeof e){const t=L((0,w.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const r=L(null!==(t=e.repo.split("/").at(-1))&&void 0!==t?t:"");return r.length>0?r:void 0}if("git-subdir"===e.source){const t=L((0,w.basename)(e.path));return t.length>0?t:void 0}let r=e.url;try{r=new URL(e.url).pathname}catch(e){}for(;r.endsWith("/");)r=r.slice(0,-1);r.toLowerCase().endsWith(".git")&&(r=r.slice(0,-4));const n=L((0,w.basename)(r));return n.length>0?n:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const s=c.safeParse(e.capabilities);if(void 0!==e.capabilities&&!s.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${s.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const i=s.success?s.data:void 0;return{entry:Object.assign({name:o,displayName:B(e.displayName),source:r,description:B(e.description),version:B(e.version),author:q(e.author),publisher:B(e.publisher),homepage:B(e.homepage),repository:B(e.repository),license:B(e.license),keywords:H(e.keywords),logo:B(e.logo),category:B(e.category),tags:H(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:z(e.commands),agents:z(e.agents),skills:z(e.skills),rules:z(e.rules),hooks:V(e.hooks),variables:J(e.variables),mcpServers:G(e.mcpServers)},void 0!==i&&{capabilities:i})}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):s.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(s.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:F(r,t),owner:U(r),description:B(r.description),plugins:n,metadata:W(r),skippedPluginEntries:o}}}function Y(e){if(e.length>b)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=N.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,error:`Invalid plugin manifest: ${r.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:r.error}}function Z(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function X(e){return!e.includes("..")&&!(0,w.isAbsolute)(e)&&!e.includes("://")}new y.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Q=r("node:fs/promises"),ee=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const te=/\$\{([^:}]+)(?::-([^}]*))?\}/g;function re(e,t){return ne(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>{var n;return null!==(n=e[r])&&void 0!==n?n:t.get(r.toLowerCase())}}(t))}function ne(e,t){if("string"==typeof e)return e.replace(te,((e,r,n)=>{const o=t(r);return void 0!==o?o:void 0!==n?n:e}));if(Array.isArray(e))return e.map((e=>ne(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=ne(o,t);return r}return e}function oe(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const se=[".mcp.json","mcp.json"],ie=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function ae(e,t){if(!function(e){return ie.has(e.toLowerCase())}(e))return!1;if("object"!=typeof t||null===t)return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function ce(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function le(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e=Object.assign({},o);if("string"==typeof o.command&&(e.command=oe(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?oe(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?oe(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=oe(o.cwd,t)),n[r]=e}return function(e,t){const r=null==t?void 0:t.cloudAgentEnvLookup,n=null==t?void 0:t.configuredVariables;return re(e,void 0!==r?r:e=>{const t=process.env[e];if(void 0!==t)return t;const r=null==n?void 0:n[e];return null!=r?"string"==typeof r?r:String(r):void 0})}(Object.assign(Object.assign({},e),{mcpServers:n}),r)}function ue(e,t,r){try{const n=(0,ee.qg)(e),o=i.safeParse(n);if(o.success&&o.data.mcpServers&&Object.keys(o.data.mcpServers).length>0)return le(o.data,t,r);const s={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!ae(e,t)&&ce(t)&&(s[e]=t);if(Object.keys(s).length>0){const e=i.safeParse({mcpServers:s});if(e.success)return le(e.data,t,r)}return null}catch(e){return null}}function de(e,t,r,n,o,s){var i,a;const c=[],l=e.mcpServers;if(!l)return c;for(const[e,u]of Object.entries(l)){const l=u,d=`plugin-${n}-${e}`,p=e;l.url?c.push({identifier:d,name:p,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:l.url,headers:l.headers,auth:l.auth,enabledTools:l.enabledTools,projectManaged:!1,pluginManaged:!0}):l.command&&c.push({identifier:d,name:p,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:l.command,args:null!==(i=l.args)&&void 0!==i?i:[],env:null!==(a=l.env)&&void 0!==a?a:{},cwd:l.cwd,envFile:l.envFile,enabledTools:l.enabledTools,projectManaged:!1,pluginManaged:!0})}return c}var pe=r("node:stream?a812"),he=r("node:stream/promises"),me=r("node:zlib?825c"),fe=r("../utils/dist/index.js"),ge=r("../../node_modules/.pnpm/tar@7.5.7/node_modules/tar/dist/esm/index.js"),ve=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const ye=".cache-complete";function we(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function be(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function ke(e){return(0,fe.Nz)(e)}class Se{constructor(e,t){var r,n;const o=null!==(r=null!=e?e:process.env.HOME)&&void 0!==r?r:"";this.cacheRoot=null!==(n=null==t?void 0:t.cacheRoot)&&void 0!==n?n:(0,w.join)(o,".cursor","plugins/cache")}getCacheDir(e){return function(e,t){return function(e,t,r,n){const o=[e,t,r];return void 0!==n&&o.push(n),(0,w.join)(...o)}(e,we(t.marketplaceSlug),be(t.pluginId),void 0!==t.version?ke(t.version):void 0)}(this.cacheRoot,e)}isCached(e){return ve(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{const e=(0,w.join)(t,ye);return(yield(0,Q.stat)(e)).isFile()}catch(e){return!1}}))}extractToCache(e){return ve(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,Q.mkdir)(t,{recursive:!0});const r=pe.Readable.from(e.tarball);return yield(0,he.pipeline)(r,(0,me.createGunzip)(),(0,ge.o6)({cwd:t,strip:1})),yield this.markCacheComplete(e),t}))}listCachedVersions(e){return ve(this,void 0,void 0,(function*(){const t=we(e.marketplaceSlug),r=be(e.pluginId),n=(0,w.join)(this.cacheRoot,t,r);try{return(yield(0,Q.readdir)(n,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(e){return[]}}))}removeVersion(e){return ve(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{yield(0,Q.rm)(t,{recursive:!0,force:!0})}catch(e){}}))}pruneOldVersions(e){return ve(this,void 0,void 0,(function*(){const t=yield this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>ke(e))));for(const n of t)r.has(n)||(yield this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n}))}))}markCacheComplete(e){return ve(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,Q.writeFile)((0,w.join)(t,ye),"")}))}}var Ee=r("node:os"),xe=r("node:util?085f");function _e(e,t){var r;const n=null!==(r=e.releaseTag)&&void 0!==r?r:t;if(e.releaseRepo&&e.releaseAsset&&n)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:n}}var Ce=r("node:child_process");const Pe=(0,xe.promisify)(Ce.execFile);function Re(){const e=["-c","credential.interactive=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Te(e,t){return r=this,n=void 0,s=function*(){const r=function(e){var t;const r=Object.assign(Object.assign({},process.env),{GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"});if(delete r.GIT_CONFIG_NOSYSTEM,!0===(null==e?void 0:e.sshBatchMode)){const e=(null===(t=process.env.GIT_SSH_COMMAND)||void 0===t?void 0:t.trim())||"ssh";r.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==(null==e?void 0:e.extraGitConfig)){const t=Object.entries(e.extraGitConfig);r.GIT_CONFIG_COUNT=String(t.length);for(const[e,[n,o]]of t.entries())r[`GIT_CONFIG_KEY_${e}`]=n,r[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:null==e?void 0:e.cwd,env:r}}({cwd:null==t?void 0:t.cwd,sshBatchMode:null==t?void 0:t.sshBatchMode,extraGitConfig:null==t?void 0:t.extraGitConfig});return Pe("git",[...Re(),...e],r)},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{c(s.next(e))}catch(e){t(e)}}function a(e){try{c(s.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(i,a)}c((s=s.apply(r,n||[])).next())}));var r,n,o,s}var Ie=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const Ae=/^[0-9a-f]{7,40}$/i,je=/^[0-9a-f]{40}$/i;function Oe(e){var t,r;if(void 0===e||""===e)return;const n=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e));return 0!==n.length?null!==(r=null===(t=n.find((e=>e.refName.endsWith("^{}"))))||void 0===t?void 0:t.sha)&&void 0!==r?r:n[0].sha:void 0}function De(e,t,r){return Ie(this,void 0,void 0,(function*(){const n=t.trim();if(je.test(n))return{fullSha:n.toLowerCase()};if(Ae.test(n)){try{const t=yield function(e,t,r){return Ie(this,void 0,void 0,(function*(){var n;const{stdout:o}=yield Te(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig});return null===(n=Oe(o))||void 0===n?void 0:n.toLowerCase()}))}(e,n,r);if(t)return{fullSha:t}}catch(e){}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=yield Te(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig}),n=Oe(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(yield Te(["ls-remote",e,n],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Oe(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}))}function Me(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")?"github":"gitlab.com"===t||t.endsWith(".gitlab.com")?"gitlab":"bitbucket.org"===t||t.endsWith(".bitbucket.org")?"bitbucket":"dev.azure.com"===t||"www.dev.azure.com"===t?"azure_devops":"generic"}function Ne(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch(e){return null}const r=t.pathname.replace(/\.git$/,"").split("/").filter(Boolean);if(r.length<2)return null;const[n,o]=r,s=t.hostname;return{provider:Me(s),owner:n,repo:o,host:s}}function $e(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")?"github.com":e}function Le(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,Ee.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function Fe(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function Ue(e,t){const r=(0,w.resolve)(e),n=(0,w.resolve)(e,t),o=(0,w.relative)(r,n);if(o.startsWith("..")||(0,w.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}var Be=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const He=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function ze(e){const t=(0,fe.Nz)(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":He.has(t.toLowerCase())?`_${t}`:t}const We=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user"],qe=["enotempty: directory not empty, rename","/_staging/"],Ge=["upload-pack: not our ref","server does not allow request for unadvertised object"];function Ve(e){const t=String(e).toLowerCase().replaceAll("\\","/");return We.some((e=>t.includes(e)))?"user_git_access":qe.every((e=>t.includes(e)))?"local_cache_race":Ge.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function Je(e){const t=Ne(e);if(null===t)throw new Error(`Invalid git URL: ${e}`);return{host:$e(t.host.replace(/^www\./i,"")),owner:t.owner.toLowerCase(),repo:t.repo.toLowerCase()}}const Ke=new Map;class Ye{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}cloneResolvedRef(e,t,r,n){return Be(this,void 0,void 0,(function*(){var o;const s={cwd:e,sshBatchMode:null==n?void 0:n.sshBatchMode,extraGitConfig:null===(o=this.options)||void 0===o?void 0:o.extraGitConfig};yield Te(["init"],s),yield Te(["fetch","--depth","1",t,r],s),yield Te(["checkout","FETCH_HEAD"],s)}))}createStagingDir(){return Be(this,void 0,void 0,(function*(){const e=(0,w.join)(this.cacheRoot,"_staging",(0,l.randomUUID)());return yield(0,Q.mkdir)(e,{recursive:!0}),e}))}moveToCanonicalDir(e,t){return Be(this,void 0,void 0,(function*(){return yield(0,Q.mkdir)((0,w.dirname)(t),{recursive:!0}),yield(0,Q.rm)(t,{recursive:!0,force:!0}),yield(0,Q.rename)(e,t),t}))}cleanStaleStagingDirs(){return Be(this,void 0,void 0,(function*(){const e=(0,w.join)(this.cacheRoot,"_staging");try{const t=yield(0,Q.readdir)(e,{withFileTypes:!0}),r=Date.now();yield Promise.all(t.filter((e=>e.isDirectory())).map((t=>Be(this,void 0,void 0,(function*(){try{const n=(0,w.join)(e,t.name),o=yield(0,Q.stat)(n);r-o.mtimeMs>Ye.STALE_STAGING_THRESHOLD_MS&&(yield(0,Q.rm)(n,{recursive:!0,force:!0}))}catch(e){}})))))}catch(e){}}))}getLegacyCloneDir(e,t){return(0,w.join)(this.cacheRoot,ze(e),ze(t))}getCanonicalCloneDir(e,t){const{host:r,owner:n,repo:o}=Je(e);return(0,w.join)(this.cacheRoot,ze(r),ze(n),ze(o),ze(t))}getCanonicalRepoRootDir(e){const{host:t,owner:r,repo:n}=Je(e);return(0,w.join)(this.cacheRoot,ze(t),ze(r),ze(n))}pruneSiblingCloneDirs(e,t,r){return Be(this,void 0,void 0,(function*(){const n=this.getCanonicalRepoRootDir(e),o=ze(t);try{const e=yield(0,Q.readdir)(n,{withFileTypes:!0});yield Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Q.rm)((0,w.join)(n,e.name),{recursive:!0,force:!0}))))}catch(e){}if(void 0!==r)try{yield(0,Q.rm)(r,{recursive:!0,force:!0})}catch(e){}}))}ensureCloned(e,t,r){return Be(this,arguments,void 0,(function*(e,t,r,n=o){const s=this.ensureClonedSerialized(e,t,r,n);return(0,fe.dY)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}))}ensureClonedSerialized(e,t,r,n){return Be(this,void 0,void 0,(function*(){const o=this.getCanonicalRepoRootDir(t),s=`${this.cacheRoot}:${o}`,i=Ke.get(s),a=(null!=i?i:Promise.resolve("")).catch((()=>{})).then((()=>this.ensureClonedImpl(e,t,r,n)));Ke.set(s,a);try{return yield a}finally{Ke.get(s)===a&&Ke.delete(s)}}))}ensureClonedImpl(e,t,r,n){return Be(this,void 0,void 0,(function*(){var o,s,i;n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const a=r.trim();let c,l=t.startsWith("git@")||t.startsWith("ssh://")?null:function(e){const t=Ne(e);return null!==t&&function(e){switch(e.provider){case"github":return!0;case"generic":return null===function(e){const t=e.toLowerCase();return t.includes("gitlab")?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(t)?`git@${t.host}:${t.owner}/${t.repo}.git`:null}(t);if(null!==l)try{c=(yield De(l,a,{sshBatchMode:!0,extraGitConfig:null===(o=this.options)||void 0===o?void 0:o.extraGitConfig})).fullSha}catch(e){n.log("error","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:Ve(e)}),l=null,c=(yield De(t,a,{extraGitConfig:null===(s=this.options)||void 0===s?void 0:s.extraGitConfig})).fullSha}else c=(yield De(t,a,{extraGitConfig:null===(i=this.options)||void 0===i?void 0:i.extraGitConfig})).fullSha;const u=this.getCanonicalCloneDir(t,c),d=this.getLegacyCloneDir(e,a);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${u}`,{marketplaceId:e,resolvedRef:c,originalRef:a});const p=performance.now(),h=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-p,t)};return(yield this.isCloneComplete(u))?(yield this.pruneSiblingCloneDirs(t,c,d),h("cache_hit"),u):(n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(u,t,l,c,d,r,n,h))}))}cloneViaStaging(e,t,r,n,o,s,i,a){return Be(this,void 0,void 0,(function*(){yield this.cleanStaleStagingDirs();const c=yield this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${c}`,{gitUrl:t,ref:s,cloneDir:e});try{if(null!==r)try{yield this.cloneResolvedRef(c,r,n,{sshBatchMode:!0})}catch(e){i.log("error","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:Ve(e)}),yield(0,Q.rm)(c,{recursive:!0,force:!0}),yield(0,Q.mkdir)(c,{recursive:!0}),yield this.cloneResolvedRef(c,t,n)}else yield this.cloneResolvedRef(c,t,n);const l=yield this.moveToCanonicalDir(c,e);return yield this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success"),l}catch(e){const r=Ve(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{try{yield(0,Q.rm)(c,{recursive:!0,force:!0})}catch(e){}}}))}isCloneComplete(e){return Be(this,void 0,void 0,(function*(){try{if(!(yield(0,Q.stat)(e)).isDirectory())return!1;const t=yield(0,Q.readdir)(e);return t.includes(".git")&&t.length>1}catch(e){return!1}}))}getPluginDir(e,t){return Ue(e,t)}copyPluginToDir(e,t){return Be(this,void 0,void 0,(function*(){yield(0,Q.mkdir)(t,{recursive:!0}),yield(0,Q.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}))}readManifest(e){return Be(this,arguments,void 0,(function*(e,t={}){var r;const n=function(e,t){var r,n;return JSON.stringify({clonePath:e,repoName:null!==(r=t.repoName)&&void 0!==r?r:null,fallbackId:null!==(n=t.fallbackId)&&void 0!==n?n:null})}(e,t);if(this.manifestCache.has(n))return null!==(r=this.manifestCache.get(n))&&void 0!==r?r:null;const o=yield function(e){return Be(this,arguments,void 0,(function*(e,t={}){for(const r of x){const n=(0,w.join)(e,r);let o;try{o=yield(0,Q.readFile)(n,"utf-8")}catch(e){continue}const s=K(o,t);if(s.success)return s.data}return null}))}(e,t);return this.manifestCache.set(n,o),o}))}resolvePluginPath(e,t){return Be(this,void 0,void 0,(function*(){var r;const n=yield this.readManifest(e);if(!n)return null;const o=n.plugins.find((e=>e.name===t.toLowerCase()));if(!o)return null;const s=Z(o.source,null===(r=n.metadata)||void 0===r?void 0:r.pluginRoot);return s&&X(s)?s:null}))}discoverPlugins(e){return Be(this,void 0,void 0,(function*(){const t=yield this.readManifest(e);return t?function(e){var t;const r=[],n=function(e,t){var r,n,o;const s=[];for(const i of e){const e=i.source;if("string"!=typeof e)switch(e.source){case"github":s.push({entry:i,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(r=e.sha)&&void 0!==r?r:e.ref});break;case"url":s.push({entry:i,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(n=e.sha)&&void 0!==n?n:e.ref});break;case"git-subdir":s.push({entry:i,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(o=e.sha)&&void 0!==o?o:e.ref,subdirPath:e.path})}else{const r=Z(e,t);null!==r?s.push({entry:i,kind:"local",localPath:r}):s.push({entry:i,kind:"unresolvable",rawSource:e})}}return s}(e.plugins,null===(t=e.metadata)||void 0===t?void 0:t.pluginRoot);for(const e of n){const{name:t,displayName:n,description:o,version:s}=e.entry,i={name:t,displayName:n,description:o,version:s};switch(e.kind){case"local":X(e.localPath)&&r.push(Object.assign(Object.assign({},i),{sourceType:"local",gitPath:e.localPath}));break;case"external-github":r.push(Object.assign(Object.assign({},i),{sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha}));break;case"external-url":r.push(Object.assign(Object.assign({},i),{sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha}));break;case"external-git-subdir":r.push(Object.assign(Object.assign({},i),{sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath}))}}return r}(t):[]}))}}Ye.STALE_STAGING_THRESHOLD_MS=3e5;var Ze=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const Xe=(0,xe.debuglog)("cursor-plugins");function Qe(e){var t;const r=null===(t=e.name)||void 0===t?void 0:t.trim();return void 0!==r&&r.length>0?r:e.pluginId}function et(e,t){return void 0!==(null==e?void 0:e.marketplace)?e.marketplace:void 0!==(null==e?void 0:e.marketplaceId)?(null!=t?t:[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function tt(e,t){var r,n;if(e.pinnedGitRef)return e.pinnedGitRef;if(null===(r=e.plugin)||void 0===r?void 0:r.gitRef)return e.plugin.gitRef;const o=et(e.plugin,t),s=null===(n=e.plugin)||void 0===n?void 0:n.gitUrl,i=null==o?void 0:o.gitUrl;return s&&i&&s!==i||!(null==o?void 0:o.gitRef)?"main":o.gitRef}const rt="backend-git://";function nt(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${rt}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}const ot="backend-release://";function st(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${ot}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function it(e){if(!e.startsWith(ot))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const at=/^[0-9a-f]{7,40}$/i;function ct(e){const t=Ne(e);return t?`${$e(t.host.replace(/^www\./i,"")).toLowerCase()}\0${t.owner.toLowerCase()}\0${t.repo.toLowerCase()}`:null}function lt(e,t){if(e.trim()===t.trim())return!0;const r=ct(e),n=ct(t);return null!==r&&r===n}const ut=104857600;function dt(e,t,r,n,o,s){return Ze(this,void 0,void 0,(function*(){const i=yield function(e){return Ze(this,void 0,void 0,(function*(){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/");if(3===t.length)return{apiBase:`https://${t[0]}/api/v3`,ownerRepo:`${t[1]}/${t[2]}`,host:t[0]};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,u=yield fetch(c,{headers:Object.assign({Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller"},a)});if(!u.ok)throw new Error(`Failed to fetch release from ${c}: ${u.status} ${u.statusText}`);const d=yield u.json(),p=d.assets.find((e=>e.name===r));if(!p){const e=d.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>ut)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const h=new URL(p.browser_download_url);if("https:"!==h.protocol||!pt(h.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${h.hostname}`);const m=yield fetch(p.browser_download_url,{headers:Object.assign({"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream"},a)});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!pt(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const f=Buffer.from(yield m.arrayBuffer());if(f.byteLength>ut)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${f.byteLength})`);if(e.expectedSha256){const t=(0,l.createHash)("sha256").update(f).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return f}))}({repo:e,asset:t,tag:r,expectedSha256:o,githubToken:s}),a=i.byteLength;yield(0,Q.mkdir)(n,{recursive:!0});const c=yield(0,Q.mkdtemp)((0,w.join)((0,Ee.tmpdir)(),"release-asset-")),u=(0,w.join)(c,"asset.tar.gz"),d=(0,w.join)(c,"extracted");try{yield(0,Q.writeFile)(u,i),yield(0,Q.mkdir)(d,{recursive:!0});let e=0,t=0;yield ge.x({file:u,cwd:d,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(a>0&&e/a>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=yield(0,Q.readdir)(d,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),s=r.filter((e=>e.isFile()));let c=d;if(1===o.length&&0===s.length){const e=(0,w.join)(d,o[0].name);(yield(0,Q.readdir)(e)).some((e=>E.includes(e)))&&(c=e)}const l=yield(0,Q.readdir)(c);yield Promise.all(l.map((e=>(0,Q.cp)((0,w.join)(c,e),(0,w.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{yield(0,Q.rm)(c,{recursive:!0,force:!0}).catch((()=>{}))}}))}function pt(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class ht{constructor(e,t,r,n,s){var i,a,c,l,u,d;this.getEffectiveUserPlugins=e;const p="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:s}:t,h=null!==(i=p.marketplaceCacheOptions)&&void 0!==i?i:n;this.pluginLogger=null!==(c=null!==(a=p.pluginLogger)&&void 0!==a?a:r)&&void 0!==c?c:o,this.extraGitConfig=p.extraGitConfig,this.githubToken=p.githubToken,this.marketplaceCache=p.marketplaceCacheRoot?new Ye(p.marketplaceCacheRoot,Object.assign(Object.assign({},h),{extraGitConfig:null!==(l=null==h?void 0:h.extraGitConfig)&&void 0!==l?l:p.extraGitConfig})):void 0;const m=null!==(u=p.listOptions)&&void 0!==u?u:s;this.allowedMarketplaceNames=(null==m?void 0:m.allowedMarketplaceNames)?new Set(m.allowedMarketplaceNames):void 0,this.enableInlinePlugins=null!==(d=null==m?void 0:m.enableInlinePlugins)&&void 0!==d&&d}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==(null==e?void 0:e.name)&&this.allowedMarketplaceNames.has(e.name)}listEnabledPlugins(e,t){return Ze(this,void 0,void 0,(function*(){var e,t,r,n,o,s,i,a,c,u,d,p,h,m,f;const g=yield this.getEffectiveUserPlugins(),v=null!==(e=g.plugins)&&void 0!==e?e:[],y=null!==(t=g.marketplaces)&&void 0!==t?t:[],w=[],b=[],k=new Map,S=(e,t)=>Ze(this,void 0,void 0,(function*(){const r=`${e}\0${t}`;let n=k.get(r);if(!n){const o=void 0!==this.extraGitConfig?{extraGitConfig:this.extraGitConfig}:void 0;n=(void 0!==o?yield De(e,t,o):yield De(e,t)).fullSha,k.set(r,n)}return n}));for(const e of v){if(!e.isEnabled||!(null===(r=e.plugin)||void 0===r?void 0:r.name))continue;const t=e.plugin,g=et(t,y);if(!this.isMarketplaceAllowed(g)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${null!==(n=null==g?void 0:g.name)&&void 0!==n?n:"<none>"} is not allowed`,{pluginId:t.name,marketplaceName:null==g?void 0:g.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const v=Qe({name:t.name,pluginId:void 0!==t.id?String(t.id):null!==(o=t.name)&&void 0!==o?o:""}),k=v;if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${v} without gitUrl (enableInlinePlugins=false)`,{pluginId:k});continue}const r=e.inlineContentJson;if(!r){this.pluginLogger.log("info",`Skipping DB-inline plugin ${v}: no inline content provided`,{pluginId:k});continue}const n=(0,l.createHash)("sha256").update(`${null!==(s=t.id)&&void 0!==s?s:"0"}:${null!==(i=t.updatedAt)&&void 0!==i?i:"0"}`).digest("hex").slice(0,40),o=(null==g?void 0:g.name)?{id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-inline`,name:g.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${k}`,{pluginId:k,marketplaceId:null!==(a=null==o?void 0:o.id)&&void 0!==a?a:"unknown",version:n}),w.push({pluginId:k,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:v,version:n,downloadUrl:`inline://${null!==(c=t.id)&&void 0!==c?c:k}`,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:o,inlineContentJson:r});continue}const E=t.gitUrl,x=tt(e,y),_=_e(t,x);let C;C=void 0!==_?st({repo:_.releaseRepo,asset:_.releaseAsset,tag:_.releaseTag}):nt(E,x,null!==(u=t.gitPath)&&void 0!==u?u:void 0);const P=null!==(d=null==g?void 0:g.gitRef)&&void 0!==d?d:x;let R;try{R=void 0!==_?`release/${_.releaseTag}`:yield S(E,x)}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${v}@${x}, skipping plugin`,{pluginId:k,ref:x,error:String(e)});const t=e instanceof Error?e.message:String(e);b.push({pluginName:v,pluginId:k,marketplaceName:null==g?void 0:g.name,errorMessage:t,errorType:/timed?\s*out/i.test(t)?"timeout":"clone"});continue}let T=P;if(null==g?void 0:g.gitUrl){const e=lt(E,g.gitUrl),t=e?E:g.gitUrl,r=e?x:P;try{T=yield S(t,r)}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${v} from ${t}@${r}, falling back to raw ref`,{pluginId:k,cacheRepoUrl:t,cacheRef:r,error:String(e)})}}const I=(null==g?void 0:g.name)?Object.assign({id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-${encodeURIComponent(null!==(p=g.gitUrl)&&void 0!==p?p:"project")}`,name:g.name},g.gitUrl&&{gitUrl:g.gitUrl,gitRef:T}):void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${k} from ${T} at ${t.gitPath}`,{pluginId:k,marketplaceId:null!==(h=null==I?void 0:I.id)&&void 0!==h?h:"unknown",gitPath:null!==(m=t.gitPath)&&void 0!==m?m:void 0,gitRef:T}),w.push({pluginId:k,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:v,version:R,downloadUrl:C,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:I,gitPath:null!==(f=t.gitPath)&&void 0!==f?f:void 0})}return{plugins:w,listFailures:b}}))}installPlugin(e,t){return Ze(this,void 0,void 0,(function*(){if(e.inlineContentJson)yield function(e){return t=this,r=void 0,o=function*(){var t,r;const{targetDir:n,inlineContentJson:o,pluginName:s}=e,i=JSON.parse(o);yield(0,Q.mkdir)(n,{recursive:!0});const a={};if(i.rules&&i.rules.length>0){const e=(0,w.join)(n,"rules");yield(0,Q.mkdir)(e,{recursive:!0});const t=[];for(const r of i.rules){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${(0,fe.Nz)(r.name)}.md`,o=[];o.push(`description: ${Fe(r.name)}`),r.globs&&r.globs.length>0&&o.push(`globs: ${Fe(r.globs.join(", "))}`),o.push(`alwaysApply: ${!0===r.isRequired}`);const s=`---\n${o.join("\n")}\n---\n\n`;yield(0,Q.writeFile)((0,w.join)(e,n),s+r.content,"utf-8"),t.push(`rules/${n}`)}t.length>0&&(a.rules=t)}if(i.commands&&i.commands.length>0){const e=(0,w.join)(n,"commands");yield(0,Q.mkdir)(e,{recursive:!0});const t=[];for(const r of i.commands){if(!r.content)continue;if(!1===r.isActive)continue;const n=`${(0,fe.Nz)(r.name)}.md`,o=r.description?`---\ndescription: ${Fe(r.description)}\n---\n\n`:"";yield(0,Q.writeFile)((0,w.join)(e,n),o+r.content,"utf-8"),t.push(`commands/${n}`)}t.length>0&&(a.commands=t)}if(i.hooks&&i.hooks.length>0){const e=(0,w.join)(n,"hooks");yield(0,Q.mkdir)(e,{recursive:!0});const o={};for(const e of i.hooks){const n=e.hookStep;n&&!1!==e.isActive&&Le(e)&&(o[n]||(o[n]=[]),"prompt"===e.hookType?o[n].push(Object.assign({type:"prompt",prompt:null!==(t=e.promptContent)&&void 0!==t?t:""},e.promptModel?{model:e.promptModel}:{})):o[n].push({type:"command",command:null!==(r=e.scriptContent)&&void 0!==r?r:""}))}yield(0,Q.writeFile)((0,w.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:o},null,2),"utf-8")}if(i.mcpServers&&i.mcpServers.length>0){const e={};for(const t of i.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&(yield(0,Q.writeFile)((0,w.join)(n,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8"))}const c=Object.assign({name:s},a),l=(0,w.join)(n,".cursor-plugin");yield(0,Q.mkdir)(l,{recursive:!0}),yield(0,Q.writeFile)((0,w.join)(l,"plugin.json"),JSON.stringify(c,null,2),"utf-8")},new((n=void 0)||(n=Promise))((function(e,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(i,a)}c((o=o.apply(t,r||[])).next())}));var t,r,n,o}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{if(null===it(e.downloadUrl))try{if(yield this.tryInstallFromMarketplaceCache(e,t))return}catch(t){this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}yield function(e,t){return Ze(this,arguments,void 0,(function*(e,t,r=o,n,s){const i=it(e.downloadUrl);if(i){if(e.gitPath){const r=yield(0,Q.mkdtemp)((0,w.join)((0,Ee.tmpdir)(),"release-plugin-"));try{yield dt(i.repo,i.asset,i.tag,r,null==s?void 0:s.expectedReleaseAssetSha256,null==s?void 0:s.githubToken);const n=Ue(r,e.gitPath);yield(0,Q.mkdir)(t,{recursive:!0}),yield(0,Q.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,Q.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else yield dt(i.repo,i.asset,i.tag,t,null==s?void 0:s.expectedReleaseAssetSha256,null==s?void 0:s.githubToken);return}const a=function(e){if(!e.startsWith(rt))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}(e.downloadUrl);if(!a)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const c=yield(0,Q.mkdtemp)((0,w.join)((0,Ee.tmpdir)(),"backend-plugin-"));try{let s;if(yield function(e,t,r){return Ze(this,arguments,void 0,(function*(e,t,r,n=o,s){const i=performance.now(),a=at.test(t);"HEAD"===t.toUpperCase()?yield Te(["clone","--depth","1",e,r],{extraGitConfig:s}):a?(yield Te(["init"],{cwd:r,extraGitConfig:s}),yield Te(["remote","add","origin",e],{cwd:r,extraGitConfig:s}),yield Te(["fetch","--depth","1","origin",t],{cwd:r,extraGitConfig:s}),yield Te(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:s})):yield Te(["clone","--depth","1","--branch",t,e,r],{extraGitConfig:s});const c=(performance.now()-i).toFixed(1);Xe("shallowClone %s@%s completed in %sms",e,t,c),n.log("info",`shallowClone ${e}@${t} completed in ${c}ms`)}))}(a.gitUrl,a.ref,c,r,n),a.gitPath)s=Ue(c,a.gitPath);else{const t=yield function(e,t){return Ze(this,void 0,void 0,(function*(){var r;for(const n of x){const o=(0,w.join)(e,n);let s;try{s=yield(0,Q.readFile)(o,"utf-8")}catch(e){continue}const i=K(s);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${n}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${n}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Z(c.source,null===(r=a.metadata)||void 0===r?void 0:r.pluginRoot);return l&&X(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}))}(c,e.name);if("resolved"===t.type)s=Ue(c,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);s=c}}yield(0,Q.mkdir)(t,{recursive:!0}),yield(0,Q.cp)(s,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,Q.rm)(c,{recursive:!0,force:!0}).catch((()=>{}))}}))}(e,t,this.pluginLogger,this.extraGitConfig,{githubToken:this.githubToken})}}))}tryInstallFromMarketplaceCache(e,t){return Ze(this,void 0,void 0,(function*(){var r,n,o,s;const i=this.marketplaceCache,a=e.marketplace;if(!i||!a||!a.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:null===(r=e.marketplace)||void 0===r?void 0:r.id}),!1;const c=yield i.ensureCloned(a.id,a.gitUrl,null!==(n=a.gitRef)&&void 0!==n?n:"main",this.pluginLogger),l=null!==(o=e.gitPath)&&void 0!==o?o:yield i.resolvePluginPath(c,e.name);if(!l)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:null===(s=e.marketplace)||void 0===s?void 0:s.id}),!1;const u=i.getPluginDir(c,l);return yield i.copyPluginToDir(u,t),!0}))}discoverMarketplacePlugins(e,t,r){return Ze(this,void 0,void 0,(function*(){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=yield n.ensureCloned(e,t,r);return n.discoverPlugins(o)}))}}function mt(e,t,r,n,o){return new ht(e,t,r,n,o)}var ft=r("../hooks/dist/index.js"),gt=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");function vt(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}var yt=r("../../node_modules/.pnpm/js-yaml@4.1.0/node_modules/js-yaml/dist/js-yaml.mjs"),wt=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const bt=[".md",".mdc",".markdown"],kt=[...bt,".txt"],St=/^---\s*\n([\s\S]*?)\n---/,Et="";function xt(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function _t(e){var t,r;const n=e.match(St);if(!n)return{};try{const e=yt.Ay.load(n[1],{schema:yt.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const o=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,s=Ct(null!==(t=e.environments)&&void 0!==t?t:null==o?void 0:o.environments);return{disabledEnvironments:Ct(null!==(r=e["disabled-environments"])&&void 0!==r?r:null==o?void 0:o.disabledEnvironments),environments:s,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch(e){const t=n[1],r=t.match(/^name:\s*(.+)$/m),o=t.match(/^description:\s*(.+)$/m);return r||o?{name:r?r[1].trim():void 0,description:o?o[1].trim():void 0}:{}}}function Ct(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Pt(e){return xt((0,w.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function Rt(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class Tt{constructor(e){this.fetcher=e}discoverComponents(){return wt(this,arguments,void 0,(function*(e={}){var t,r;const n=null!==(t=e.basePath)&&void 0!==t?t:"",o=n?`${n}/`:"",s=null!==(r=e.metadataOnly)&&void 0!==r&&r,i=e.manifest;let a;try{a=yield this.fetcher.listDirectory(n)}catch(e){a=[]}const c=new Set(a.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),l=new Set(a.filter((e=>"file"===e.type)).map((e=>e.name))),u=se.filter((e=>l.has(e))),d=a.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[p,h,m,f,g,v,...y]=yield Promise.all([d&&void 0===(null==i?void 0:i.skills)?this.discoverRootSkill(o,s):Promise.resolve(null),void 0!==(null==i?void 0:i.skills)?this.discoverFromManifestPaths(o,i.skills,!0,bt,s):c.has("skills")?this.discoverSkills(`${o}skills`,s):Promise.resolve([]),void 0!==(null==i?void 0:i.agents)?this.discoverFromManifestPaths(o,i.agents,!1,bt,s):c.has("agents")?this.discoverMarkdownComponents(`${o}agents`,bt,s):Promise.resolve([]),void 0!==(null==i?void 0:i.hooks)?this.discoverHooksFromManifest(o,i.hooks,s):c.has("hooks")?this.discoverHooksFromJson(`${o}hooks/hooks.json`,s):Promise.resolve([]),void 0!==(null==i?void 0:i.commands)?this.discoverFromManifestPaths(o,i.commands,!1,kt,s):c.has("commands")?this.discoverMarkdownComponents(`${o}commands`,kt,s):Promise.resolve([]),void 0!==(null==i?void 0:i.rules)?this.discoverFromManifestPaths(o,i.rules,!1,bt,s):c.has("rules")?this.discoverMarkdownComponents(`${o}rules`,bt,s):Promise.resolve([]),...u.map((e=>this.discoverMcpServers(`${o}${e}`)))]);let w=[];void 0!==(null==i?void 0:i.mcpServers)&&(w=yield this.extractMcpServersFromManifest(o,i.mcpServers));const b=this.mergeMcpServers(...y,w);return{skills:Rt(p?[p,...h]:h),agents:Rt(m),hooks:f,commands:Rt(g),rules:Rt(v),mcpServers:b}}))}discoverHooksFromJson(e){return wt(this,arguments,void 0,(function*(e,t=!1){try{if(!(yield this.fetcher.fileExists(e)))return[];const{content:r}=yield this.fetcher.fetchFile(e),n=JSON.parse(r);return!n.hooks||"object"!=typeof n.hooks||Array.isArray(n.hooks)?[]:Object.keys(n.hooks).map((r=>({name:xt(r),path:e,description:t?Et:`Hook: ${r}`})))}catch(e){return[]}}))}discoverHooksFromManifest(e,t){return wt(this,arguments,void 0,(function*(e,t,r=!1){var n;if("string"==typeof t){if(!X(t))return[];const n=`${e}${t.replace(/^\.\//,"")}`;return n.endsWith(".json")?this.discoverHooksFromJson(n,r):this.discoverHooksFromJson(`${n}/hooks.json`,r)}const o=null!==(n=t.hooks)&&void 0!==n?n:t;return!o||"object"!=typeof o||Array.isArray(o)?[]:Object.keys(o).map((e=>({name:xt(e),path:"manifest",description:r?Et:`Hook: ${e}`})))}))}discoverFromManifestPaths(e,t){return wt(this,arguments,void 0,(function*(e,t,r=!1,n=bt,o=!1){var s,i;if("string"==typeof t){if(!X(t))return[];const s=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(s,o):this.discoverMarkdownComponents(s,n,o)}const a=[];for(const n of t)try{if(!X(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!(yield this.fetcher.fileExists(e))){const e=t.replace(/\/$/,""),r=yield this.discoverSkills(e,o);a.push(...r);continue}let r=Pt(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t),n=o?Et:void 0;if(!o){const{content:t}=yield this.fetcher.fetchFile(e),o=_t(t);if(r=null!==(s=o.name)&&void 0!==s?s:r,n=o.description,r){const t={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:xt(r),path:e};void 0!==n&&(t.description=n),a.push(t)}continue}if(r){const t={name:xt(r),path:e};void 0!==n&&(t.description=n),a.push(t)}}else{if(!(yield this.fetcher.fileExists(t)))continue;let e=Pt(t),r=o?Et:void 0;if(!o){const{content:n}=yield this.fetcher.fetchFile(t),o=_t(n);e=null!==(i=o.name)&&void 0!==i?i:e,r=o.description}if(e){const n={name:xt(e),path:t};void 0!==r&&(n.description=r),a.push(n)}}}catch(e){}return a}))}extractMcpServersFromManifest(e,t){return wt(this,void 0,void 0,(function*(){const r=[];if("string"==typeof t){const n=yield this.loadMcpServersFromPath(e,t);r.push(...n)}else if(Array.isArray(t)){for(const n of t)if("string"==typeof n){const t=yield this.loadMcpServersFromPath(e,n);r.push(...t)}else if("object"==typeof n&&null!==n){const e=this.extractServersFromInlineConfig(n,"manifest");r.push(...e)}}else if("object"==typeof t&&null!==t){const e=this.extractServersFromInlineConfig(t,"manifest");r.push(...e)}return r}))}loadMcpServersFromPath(e,t){return wt(this,void 0,void 0,(function*(){var r;if(!X(t))return[];const n=`${e}${t}`;try{const{content:e}=yield this.fetcher.fetchFile(n),t=JSON.parse(e),o=null!==(r=t.mcpServers)&&void 0!==r?r:t;return"object"!=typeof o||null===o?[]:this.extractServersFromInlineConfig(o,n)}catch(e){return[]}}))}extractServersFromInlineConfig(e,t){const r=[];for(const[n,o]of Object.entries(e))"mcpServers"!==n&&!ae(n,o)&&ce(o)&&r.push({name:xt(n),path:t});return r}mergeMcpServers(...e){const t=new Set,r=[];for(const n of e)for(const e of n)t.has(e.name)||(t.add(e.name),r.push(e));return r}discoverMarkdownComponents(e){return wt(this,arguments,void 0,(function*(e,t=bt,r=!1,n=new Set){let o;try{o=yield this.fetcher.listDirectory(e,n)}catch(e){return[]}const s=o.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),i=o.filter((e=>"dir"===e.type)),[a,c]=yield Promise.all([Promise.all(s.map((e=>wt(this,void 0,void 0,(function*(){try{let t=Pt(e.name),n=r?Et:void 0;if(!r){const{content:r}=yield this.fetcher.fetchFile(e.path),o=_t(r);t=o.name?xt(o.name):t,n=o.description}if(!t)return null;const o={name:t,path:e.path};return void 0!==n&&(o.description=n),o}catch(e){return null}}))))),Promise.all(i.map((e=>this.discoverMarkdownComponents(e.path,t,r,n))))]);return[...a.filter((e=>null!==e)),...c.flat()]}))}discoverRootSkill(e){return wt(this,arguments,void 0,(function*(e,t=!1){try{const r=`${e}SKILL.md`,n=(0,w.basename)(e.replace(/[\\/]+$/,""));let o=xt(t?n||Pt(r):n),s=t?Et:void 0;if(!t){const{content:e}=yield this.fetcher.fetchFile(r),t=_t(e);if(o=t.name?xt(t.name):o,s=t.description,!o)return null;const n={disabledEnvironments:t.disabledEnvironments,environments:t.environments,name:o,path:r};return void 0!==s&&(n.description=s),n}return o?Object.assign({name:o,path:r},void 0!==s?{description:s}:{}):null}catch(e){return null}}))}discoverSkills(e){return wt(this,arguments,void 0,(function*(e,t=!1){let r;try{r=yield this.fetcher.listDirectory(e)}catch(e){return[]}const n=r.filter((e=>"dir"===e.type));return(yield Promise.all(n.map((e=>wt(this,void 0,void 0,(function*(){try{const r=`${e.path}/SKILL.md`;if(!(yield this.fetcher.fileExists(r)))return null;if(t){const t=xt(e.name);return t?{name:t,path:r,description:Et}:null}const{content:n}=yield this.fetcher.fetchFile(r),o=_t(n),s=o.name?xt(o.name):xt(e.name);if(!s)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:s,path:r};return void 0!==o.description&&(i.description=o.description),i}catch(e){return null}})))))).filter((e=>null!==e))}))}discoverMcpServers(e){return wt(this,void 0,void 0,(function*(){try{const{content:t}=yield this.fetcher.fetchFile(e),r=JSON.parse(t);if(r.mcpServers&&"object"==typeof r.mcpServers&&null!==r.mcpServers)return Object.keys(r.mcpServers).map((t=>({name:xt(t),path:e})));const n=[];for(const[e,t]of Object.entries(r))"mcpServers"!==e&&!ae(e,t)&&ce(t)&&n.push(e);return n.map((t=>({name:xt(t),path:e})))}catch(e){return[]}}))}}var It=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};function At(e){var t;const r=null!==(t=null!=e?e:process.env.HOME)&&void 0!==t?t:"";return(0,w.join)(r,".claude")}var jt=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};const Ot=[".cursor-plugin",".claude-plugin"];class Dt extends Error{constructor(e){super(e),this.name="UserSettingsParseError"}}function Mt(e){return jt(this,void 0,void 0,(function*(){const t=yield function(e){return jt(this,void 0,void 0,(function*(){try{return yield(0,Q.readFile)(function(e){return(0,w.join)(e,".cursor","settings.json")}(e),"utf-8")}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}))}(e);return void 0===t?{}:function(e){const t=[],r=(0,ee.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,ee._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Dt(`~/.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const n=r;return void 0!==n.enabled_plugins?Array.isArray(n.enabled_plugins)?{enabled_plugins:n.enabled_plugins.filter((e=>"string"==typeof e&&""!==e.trim()))}:{}:n}(t)}))}function Nt(e){return jt(this,void 0,void 0,(function*(){for(const t of Ot){const r=(0,w.join)(e,t);try{if((yield(0,Q.stat)(r)).isDirectory())return!0}catch(e){}}return!1}))}function $t(e,t){const r=(0,w.resolve)(t);return Ue(r,(0,w.resolve)((0,w.join)(r,e)))}function Lt(e,t){const r=e.trim();if((0,w.isAbsolute)(r))return(0,w.resolve)(r);if(r.startsWith("~/"))try{return $t(r.slice(2),t)}catch(e){return}try{return $t(r,t)}catch(e){return}}var Ft=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};function Ut(e){return Ft(this,void 0,void 0,(function*(){try{return(yield(0,Q.lstat)(e)).isSymbolicLink()}catch(e){return!1}}))}function Bt(e){return Ft(this,void 0,void 0,(function*(){if(yield Ut(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Q.readFile)(e,"utf-8")}))}function Ht(e){return Ft(this,void 0,void 0,(function*(){if((yield(0,Q.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}))}function zt(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}function Wt(e){return Ft(this,void 0,void 0,(function*(){var t;for(const r of S){const n=(0,w.join)(e,r);try{if(yield Ut(n))continue;if(!(yield(0,Q.stat)(n)).isFile())continue;yield Ht(n);const e=Y(yield Bt(n));if(!e.success)continue;const r=e.data,o=r.commands,s=r.agents,i=r.skills,a=r.rules,c=r.hooks,l=r.mcpServers,u=void 0!==o||void 0!==s||void 0!==i||void 0!==a||void 0!==c||void 0!==l,d="string"==typeof r.displayName?r.displayName:void 0,p="string"==typeof r.description?r.description:void 0,h=null===(t=r.author)||void 0===t?void 0:t.name,m=r.variables,f=r.capabilities,g=void 0!==d||void 0!==p||void 0!==h||void 0!==m||void 0!==f;if(!u&&!g)continue;return Object.assign(Object.assign({manifestFilePath:n},u&&{manifestOptions:{commands:o,agents:s,skills:i,rules:a,hooks:c,mcpServers:l}}),g&&{metadata:{displayName:d,description:p,authorName:h,variables:m,capabilities:f}})}catch(e){}}}))}function qt(e,t){return Ft(this,void 0,void 0,(function*(){const r=function(e,t){var r;const n=new Map,o=(0,w.resolve)(e),s=(0,w.resolve)(null!==(r=null==t?void 0:t.symlinkTargetRoot)&&void 0!==r?r:o),i=(0,Q.realpath)(s).catch((()=>s));function a(e){const t=(0,w.resolve)(e);try{return Ue(o,t)}catch(t){throw new Error(`Path escapes plugin directory: ${e}`)}}function c(e){return Ft(this,void 0,void 0,(function*(){const t=a(e),r=yield i,n=yield(0,Q.realpath)(t);try{return Ue(r,n)}catch(t){throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}))}return{listDirectory(t,r){return Ft(this,void 0,void 0,(function*(){const n=a(t?(0,w.join)(e,t):e);try{const e=yield c(n);if(null==r?void 0:r.has(e))return[];null==r||r.add(e);const o=yield(0,Q.readdir)(e,{withFileTypes:!0}),s=[];for(const e of o){const r=(0,w.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=yield c(r);o=(yield(0,Q.stat)(e)).isDirectory()?"dir":"file"}catch(e){continue}s.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return s}catch(e){return[]}}))},fetchFile(t){return Ft(this,void 0,void 0,(function*(){const r=n.get(t);if(void 0!==r)return{content:r};const o=a((0,w.join)(e,t)),s=yield c(o);yield Ht(s);const i=yield(0,Q.readFile)(s,"utf-8");return n.set(t,i),{content:i}}))},fileExists(t){return Ft(this,void 0,void 0,(function*(){try{const r=a((0,w.join)(e,t)),n=yield c(r);return(yield(0,Q.stat)(n)).isFile()}catch(e){return!1}}))}}}(e),n=new Tt(r),o=yield n.discoverComponents({manifest:t}),[s,i,a,c]=yield Promise.all([Gt(r,o.skills,e),Jt(r,o.agents,e),Kt(r,o.commands,e),Vt(r,o.rules,e)]);return{skills:s,agents:i,commands:a,rules:c}}))}function Gt(e,t,r){return Ft(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),s=Zt({content:oe(t,r),relativePath:o.path});s&&n.push(s)}catch(e){}return n}))}function Vt(e,t,r){return Ft(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),s=Zt({content:oe(t,r),relativePath:o.path});s&&n.push(Object.assign(Object.assign({},s),{name:o.name}))}catch(e){}return n}))}function Jt(e,t,r){return Ft(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),s=Xt({content:oe(t,r),relativePath:o.path});s&&n.push(s)}catch(e){}return n}))}function Kt(e,t,r){return Ft(this,void 0,void 0,(function*(){const n=[];for(const o of t)try{const{content:t}=yield e.fetchFile(o.path),s=Qt({content:oe(t,r),relativePath:o.path});s&&n.push(s)}catch(e){}return n}))}function Yt(e){if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Zt({content:e,relativePath:t}){var r,n,o,s,i;try{const a=gt(e),c=t.replace(/\\/g,"/"),l=c.split("/").filter((e=>e.length>0)),u=l.length>=2?l[l.length-2]:void 0,d=null!==(r=l[l.length-1])&&void 0!==r?r:c,p=null!=u?u:d.replace(/\.md$/i,""),h="string"==typeof a.data.name?a.data.name.trim():void 0,m=Ct(null!==(n=a.data.environments)&&void 0!==n?n:null===(o=a.data.metadata)||void 0===o?void 0:o.environments),f=Ct(null!==(s=a.data["disabled-environments"])&&void 0!==s?s:null===(i=a.data.metadata)||void 0===i?void 0:i.disabledEnvironments);return{path:t,name:h&&h.length>0?h:p,description:"string"==typeof a.data.description?a.data.description:void 0,globs:Yt(a.data.globs),alwaysApply:!0===a.data.alwaysApply,content:e,environments:m,disabledEnvironments:f}}catch(e){return null}}function Xt({content:e,relativePath:t}){var r,n;try{const o=gt(e),s=o.content.trim();if(!s)return null;let i;"string"==typeof o.data.tools?i=o.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(o.data.tools)&&(i=o.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=null!==(r=o.data.permissionMode)&&void 0!==r?r:o.data.permissionmode,c=(0,w.basename)(t);return{path:t,name:"string"==typeof o.data.name?o.data.name:(0,w.basename)(c,(0,w.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof o.data.description?o.data.description:void 0,tools:i,model:"string"==typeof o.data.model?o.data.model:"inherit",prompt:s,permissionMode:(n=a,"readonly"===(null!=n?n:"").trim().toLowerCase()?"readonly":"default")}}catch(e){return null}}function Qt({content:e,relativePath:t}){try{const r=gt(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const s=(0,w.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,w.basename)(s,(0,w.extname)(s)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch(e){return null}}function er(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}function tr(e,t,r){return Ft(this,void 0,void 0,(function*(){const n=e.replace(/^\.\//,"");if(!X(n))return null;const o=(0,w.join)(t,n);try{if(yield Ut(o))return null;if(!(yield(0,Q.stat)(o)).isFile())return null;yield Ht(o);const e=ue(yield Bt(o),t,r);return(null==e?void 0:e.mcpServers)&&0!==Object.keys(e.mcpServers).length?{config:e,sourcePath:o}:null}catch(e){return null}}))}function rr(e,t,r){if(t.mcpServers)for(const[n,o]of Object.entries(t.mcpServers))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}function nr(e,t,r,n){return Ft(this,void 0,void 0,(function*(){const o={mcpServers:{},mcpServerSourcePaths:{}};if("string"==typeof e){const r=yield tr(e,t,n);r&&rr(o,r.config,r.sourcePath)}else if(Array.isArray(e))for(const s of e)if("string"!=typeof s){if("object"==typeof s&&null!==s){const e=ue(JSON.stringify(s),t,n);(null==e?void 0:e.mcpServers)&&rr(o,e,r)}}else{const e=yield tr(s,t,n);e&&rr(o,e.config,e.sourcePath)}else if("object"==typeof e&&null!==e){const s=ue(JSON.stringify(e),t,n);(null==s?void 0:s.mcpServers)&&rr(o,s,r)}return 0===Object.keys(o.mcpServers).length?null:o}))}function or(e,t,r){return Ft(this,void 0,void 0,(function*(){let n={},o={};const s=null!=r?r:er(t);for(const t of se.map((e=>e))){const r=(0,w.join)(e,t);try{if((yield(0,Q.stat)(r)).isFile()){const t=ue(yield Bt(r),e,s);if(null==t?void 0:t.mcpServers)for(const[e,s]of Object.entries(t.mcpServers))void 0===n[e]&&(n[e]=s,o[e]=r)}}catch(e){}}for(const t of[".cursor-plugin",".claude-plugin"]){const r=(0,w.join)(e,t,"plugin.json");try{if(!(yield(0,Q.stat)(r)).isFile())continue;const t=Y(yield Bt(r));if(t.success){if(void 0!==t.data.mcpServers){const i=yield nr(t.data.mcpServers,e,r,s);(null==i?void 0:i.mcpServers)&&(n=Object.assign(Object.assign({},n),i.mcpServers),o=Object.assign(Object.assign({},o),i.mcpServerSourcePaths))}break}}catch(e){}}return 0===Object.keys(n).length?null:Object.assign({mcpServers:n},Object.keys(o).length>0&&{mcpServerSourcePaths:o})}))}function sr(e,t){return Ft(this,void 0,void 0,(function*(){var r;const n=yield or(e);if(n)return n;for(const n of x){const o=(0,w.join)(e,n);try{if(!(yield(0,Q.stat)(o)).isFile())continue;const n=yield(0,Q.readFile)(o,"utf-8"),s=JSON.parse(n).plugins;if(!Array.isArray(s))continue;const i=t.name,a=s.find((e=>e.name===i));if(!(null===(r=null==a?void 0:a.mcpServers)||void 0===r?void 0:r.length))continue;for(const t of a.mcpServers){const r=t.replace(/^\.\//,"");if(!X(r))continue;const n=(0,w.join)(e,r);try{yield Ht(n);const t=ue(yield Bt(n),e);if((null==t?void 0:t.mcpServers)&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,n])));return Object.assign(Object.assign({},t),{mcpServerSourcePaths:e})}}catch(e){}}return null}catch(e){}}return null}))}function ir(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?Object.assign(Object.assign({},e),{command:oe(e.command,t)}):"prompt"in e&&"string"==typeof e.prompt?Object.assign(Object.assign({},e),{prompt:oe(e.prompt,t)}):e)));return Object.assign(Object.assign({},e),{hooks:r})}function ar(e,t,r,n){return Ft(this,void 0,void 0,(function*(){if("object"==typeof r){const o=cr(r,t);return o&&"config"in o?Object.assign({config:ir(o.config,e)},void 0!==n&&{sourcePath:n}):o}let o,s,i;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!X(t))return;o=t.endsWith(".json")?(0,w.join)(e,t):(0,w.join)(e,t,"hooks.json")}else o=(0,w.join)(e,"hooks","hooks.json");try{if(yield Ut(o))return;if(!(yield(0,Q.stat)(o)).isFile())return}catch(e){return}try{yield Ht(o),s=yield(0,Q.readFile)(o,"utf-8")}catch(e){return}try{i=JSON.parse(s)}catch(e){return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const a=cr(i,t);return a&&"config"in a?{config:ir(a.config,e),sourcePath:o}:a}))}function cr(e,t){const r=(0,ft.fp)(e);if("cursor"===r){const r=e,n=(0,ft.RV)(r);return n.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${n.errors.join("; ")}`}}}if("claude-code"===r){const r=null==e?void 0:e.hooks;if(!r||0===Object.keys(r).length)return;const n=(0,ft.sl)(r),o=(0,ft.RV)(n);return o.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}}function lr(e,t,r,n){return Ft(this,void 0,void 0,(function*(){var o,s,i,a,c,l,u,d;const p=yield Wt(e),h=null!==(o=er(r))&&void 0!==o?o:(null==n?void 0:n.configuredVariables)?{configuredVariables:n.configuredVariables}:void 0,[m,f,g]=yield Promise.all([qt(e,null==p?void 0:p.manifestOptions),or(e,r,h),ar(e,t,null===(s=null==p?void 0:p.manifestOptions)||void 0===s?void 0:s.hooks,null==p?void 0:p.manifestFilePath)]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},m),void 0!==(null===(i=null==p?void 0:p.metadata)||void 0===i?void 0:i.displayName)&&{displayName:p.metadata.displayName}),void 0!==(null===(a=null==p?void 0:p.metadata)||void 0===a?void 0:a.description)&&{description:p.metadata.description}),void 0!==(null===(c=null==p?void 0:p.metadata)||void 0===c?void 0:c.authorName)&&{authorName:p.metadata.authorName}),{variablesSchema:null===(l=null==p?void 0:p.metadata)||void 0===l?void 0:l.variables,mcpConfig:f,capabilities:null!==(d=null===(u=null==p?void 0:p.metadata)||void 0===u?void 0:u.capabilities)&&void 0!==d?d:[],hooks:g})}))}function ur(e,t){return Ft(this,void 0,void 0,(function*(){var r,n,o,s,i,a;const c=yield Wt(e),[l,u,d]=yield Promise.all([qt(e,null==c?void 0:c.manifestOptions),sr(e,t),ar(e,t.raw,null===(r=null==c?void 0:c.manifestOptions)||void 0===r?void 0:r.hooks,null==c?void 0:c.manifestFilePath)]),p={source:"claude-plugin",sourceInfo:t};return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:p,installPath:e},void 0!==(null===(n=null==c?void 0:c.metadata)||void 0===n?void 0:n.displayName)&&{displayName:c.metadata.displayName}),void 0!==(null===(o=null==c?void 0:c.metadata)||void 0===o?void 0:o.description)&&{description:c.metadata.description}),void 0!==(null===(s=null==c?void 0:c.metadata)||void 0===s?void 0:s.authorName)&&{authorName:c.metadata.authorName}),l),{mcpConfig:null!=u?u:void 0,capabilities:null!==(a=null===(i=null==c?void 0:c.metadata)||void 0===i?void 0:i.capabilities)&&void 0!==a?a:[],hooks:d})}))}function dr(e,t,r){return Ft(this,void 0,void 0,(function*(){const n=`${r.name}@${r.version}`,{displayName:o,description:s,authorName:i,variablesSchema:a,skills:c,rules:l,agents:u,commands:d,mcpConfig:p,capabilities:h,hooks:m}=yield lr(e,n,r),f={source:t,sourceInfo:r};return Object.assign(Object.assign(Object.assign(Object.assign({identifier:f,installPath:e},void 0!==o&&{displayName:o}),void 0!==s&&{description:s}),void 0!==i&&{authorName:i}),{variablesSchema:a,skills:c,rules:l,agents:u,commands:d,mcpConfig:null!=p?p:void 0,capabilities:h,hooks:m})}))}function pr(e,t){return Ft(this,arguments,void 0,(function*(e,t,r={}){var n,s;const i=null!==(n=r.log)&&void 0!==n?n:o,a=performance.now(),c=yield function(e){return It(this,void 0,void 0,(function*(){const t=At(e),r=(0,w.join)(t,"plugins","installed_plugins.json");try{const e=yield(0,Q.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir);if(!(null==c?void 0:c.plugins))return i.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-a).toFixed(1)}ms)`),[];const l=yield function(e){return It(this,void 0,void 0,(function*(){const t=At(e),r=(0,w.join)(t,"settings.json");try{const e=yield(0,Q.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir),u=e?(0,w.resolve)(e):void 0,d=function(e,t,r,n){var o;const s=null==e?void 0:e.plugins;if(!s||"object"!=typeof s)return[];const i=null!==(o=null==t?void 0:t.enabledPlugins)&&void 0!==o?o:{},a={};(null==r?void 0:r.enabledPlugins)&&Object.assign(a,r.enabledPlugins);const c=void 0!==n?vt(n):void 0,l=new Set,u=[];for(const[e,t]of Object.entries(s)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==c&&!1===a[e])continue;let r;void 0!==c&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&vt(t.projectPath)===c&&!0===a[e]))),r||!0!==i[e]||(r=t.find((e=>"user"===e.scope))),(null==r?void 0:r.installPath)&&!l.has(e)&&(u.push({pluginId:e,installPath:r.installPath}),l.add(e))}return u}(c,l,u?yield function(e){return It(this,void 0,void 0,(function*(){const t={enabledPlugins:{}};let r=!1;const n=(0,w.join)(e,".claude","settings.json");try{const e=yield(0,Q.readFile)(n,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch(e){}const o=(0,w.join)(e,".claude","settings.local.json");try{const e=yield(0,Q.readFile)(o,"utf-8"),n=JSON.parse(e);n.enabledPlugins&&(Object.assign(t.enabledPlugins,n.enabledPlugins),r=!0)}catch(e){}return r?t:null}))}(u):null,u),h=[],m=r.onError;for(const{pluginId:e,installPath:t}of d)try{const r=performance.now(),n=p(e),o=yield ur(t,n);h.push(o),i.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(m)try{m(p(e),r)}catch(t){m({name:null!==(s=e.split("@")[0])&&void 0!==s?s:e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return i.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-a).toFixed(1)}ms (${d.length} resolved, ${h.length} loaded)`),h}))}Error;function hr(e){return Ft(this,arguments,void 0,(function*(e,t={}){var r,n,s,i,a,c;const l=null!==(r=t.log)&&void 0!==r?r:o,d=performance.now(),p=null===(n=t.loadClaude)||void 0===n||n,h=null===(s=t.loadUserLocal)||void 0===s||s,m=null!==(i=t.loadUserSettings)&&void 0!==i&&i,f=null!==(a=t.marketplaceSources)&&void 0!==a?a:[],g=null!==(c=t.loadCursorFirstParty)&&void 0!==c?c:f.length>0,v=[],y=[];let b;p&&v.push(pr(e,void 0,{userHomeDir:t.userHomeDir,onError:t.onError,log:l})),g&&f.length>0&&(b=Promise.all(f.map((e=>{var r,n;return function(e){return Ft(this,void 0,void 0,(function*(){var t,r,n,s,i,a,c,l;const u=null!==(t=e.log)&&void 0!==t?t:o,d=performance.now(),{client:p,userId:h,teamId:m,onCursorError:f,pruneOldVersions:g}=e,v=[],y=null!==(r=e.cacheManager)&&void 0!==r?r:new Se(e.userHomeDir),w=performance.now(),b=yield p.listEnabledPlugins(h,m);u.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-w).toFixed(1)}ms (${b.plugins.length} plugins)`);const k=[];if(b.listFailures){v.push(...b.listFailures);for(const e of b.listFailures)k.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const S=new Map;for(const e of b.plugins)try{const t=null===(n=e.marketplace)||void 0===n?void 0:n.name;if(!t){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);v.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),f&&f(e,t);continue}const r=`${t}/${e.pluginId}`;let o,c=S.get(r);if(c||(c={slug:t,pluginId:e.pluginId,versions:[]},S.set(r,c)),c.versions.push(e.version),yield y.isCached({marketplaceSlug:t,pluginId:e.pluginId,version:e.version}))o=y.getCacheDir({marketplaceSlug:t,pluginId:e.pluginId,version:e.version}),u.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${o}`,{marketplaceSlug:t,pluginId:e.pluginId,gitRef:e.version,marketplaceId:null===(s=e.marketplace)||void 0===s?void 0:s.id});else{const r=y.getCacheDir({marketplaceSlug:t,pluginId:e.pluginId,version:e.version});u.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${r}`,{marketplaceSlug:t,pluginId:e.pluginId,gitRef:e.version,marketplaceId:null===(i=e.marketplace)||void 0===i?void 0:i.id}),yield(0,Q.mkdir)(r,{recursive:!0});try{yield p.installPlugin(e,r),yield y.markCacheComplete({marketplaceSlug:t,pluginId:e.pluginId,version:e.version})}catch(e){try{yield(0,Q.rm)(r,{recursive:!0,force:!0})}catch(e){}throw e}o=r}const l=null===(a=e.marketplace)||void 0===a?void 0:a.name,d=void 0!==l&&"cursor-public"!==l&&l.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:l,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},m=yield dr(o,d,h);k.push(m);try{yield y.pruneOldVersions({marketplaceSlug:t,pluginId:e.pluginId,keepVersions:[e.version]})}catch(e){}}catch(t){u.captureException(t,{error_type:"load_plugin_from_marketplace"});const r=t instanceof Error?t:new Error(String(t));v.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:null===(c=e.marketplace)||void 0===c?void 0:c.name,errorMessage:r.message,errorType:zt(r)});const n=null===(l=e.marketplace)||void 0===l?void 0:l.name,o=void 0!==n&&"cursor-public"!==n&&n.length>0;k.push({identifier:{source:o?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:n,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:r.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),f&&f(e,r)}if(g)for(const{slug:e,pluginId:t,versions:r}of S.values())try{yield y.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch(e){}return u.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-d).toFixed(1)}ms (${k.length} plugins loaded, ${v.length} failures)`),{plugins:k,failures:v}}))}(Object.assign(Object.assign({},e),{userHomeDir:null!==(r=e.userHomeDir)&&void 0!==r?r:t.userHomeDir,log:null!==(n=e.log)&&void 0!==n?n:l}))})))),h&&v.push(function(){return Ft(this,arguments,void 0,(function*(e={}){var t,r,n;const s=null!==(t=e.log)&&void 0!==t?t:o,i=performance.now(),a=null!==(r=e.userHomeDir)&&void 0!==r?r:process.env.HOME;if(!a)return s.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const c=(0,w.join)(a,".cursor","plugins","local");let l;try{l=yield(0,Q.readdir)(c,{withFileTypes:!0})}catch(e){return s.log("info",`loadUserLocalPlugins: ${c} not found or not readable (${(performance.now()-i).toFixed(1)}ms)`),[]}const u=yield(0,Q.realpath)(c).catch((()=>(0,w.resolve)(c))),d=[];for(const t of l){if(!t.isDirectory()&&!t.isSymbolicLink())continue;if(t.name.startsWith("."))continue;const r=(0,w.join)(c,t.name);try{if(t.isSymbolicLink()){let e;try{e=yield(0,Q.realpath)(r)}catch(e){s.log("warn",`loadUserLocalPlugin ${t.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Ue(u,e)}catch(r){s.log("warn",`loadUserLocalPlugin ${t.name} rejected: symlink target ${e} is outside ${c}`);continue}}if(!(yield(0,Q.stat)(r)).isDirectory()){t.isSymbolicLink()&&s.log("warn",`loadUserLocalPlugin ${t.name} rejected: symlink target is not a directory`);continue}const o=performance.now(),i=yield null===(n=e.localPluginVariablesLookup)||void 0===n?void 0:n.call(e,t.name),{displayName:a,description:l,authorName:p,variablesSchema:h,skills:m,rules:f,agents:g,commands:v,mcpConfig:y,capabilities:w,hooks:b}=yield lr(r,t.name,void 0,{configuredVariables:i}),k={source:"user-local",sourceInfo:{name:t.name,localPath:r}};d.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:k,installPath:r},void 0!==a&&{displayName:a}),void 0!==l&&{description:l}),void 0!==p&&{authorName:p}),{variablesSchema:h,skills:m,rules:f,agents:g,commands:v,mcpConfig:null!=y?y:void 0,capabilities:w,hooks:b})),s.log("info",`loadUserLocalPlugin ${t.name} loaded in ${(performance.now()-o).toFixed(1)}ms`)}catch(e){s.log("error",`loadUserLocalPlugin ${t.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return s.log("info",`loadUserLocalPlugins completed in ${(performance.now()-i).toFixed(1)}ms (${d.length} plugins loaded)`),d}))}({userHomeDir:t.userHomeDir,log:l,localPluginVariablesLookup:t.localPluginVariablesLookup})),m&&v.push(function(){return Ft(this,arguments,void 0,(function*(e={}){var t,r,n;const s=null!==(t=e.log)&&void 0!==t?t:o,i=performance.now(),a=null!==(r=e.userHomeDir)&&void 0!==r?r:process.env.HOME;if(!a)return s.log("info","loadUserSettingsPlugins: no home directory available, skipping"),[];let c;try{c=yield function(e){return jt(this,void 0,void 0,(function*(){var t;const r=null!==(t=(yield Mt(e)).enabled_plugins)&&void 0!==t?t:[];if(0===r.length)return[];const n=[],o=new Set;for(const t of r){const r=Lt(t,e);if(void 0!==r)try{if(!(yield(0,Q.stat)(r)).isDirectory())continue;if(yield Nt(r)){const e=yield(0,Q.realpath)(r).catch((()=>r));o.has(e)||(o.add(e),n.push({originalPath:t,resolvedPath:e,isDiscovered:!1}));continue}const e=yield(0,Q.readdir)(r,{withFileTypes:!0}),s=yield(0,Q.realpath)(r).catch((()=>r));for(const i of e){if(!i.isDirectory()&&!i.isSymbolicLink())continue;if(i.name.startsWith("."))continue;const e=(0,w.join)(r,i.name);try{if(i.isSymbolicLink()&&Ue(s,yield(0,Q.realpath)(e)),!(yield(0,Q.stat)(e)).isDirectory())continue;if(yield Nt(e)){const r=yield(0,Q.realpath)(e).catch((()=>e));o.has(r)||(o.add(r),n.push({originalPath:t,resolvedPath:r,isDiscovered:!0}))}}catch(e){}}}catch(e){}}return n}))}(a)}catch(e){return s.log("error",`loadUserSettingsPlugins: failed to resolve paths from settings: ${e instanceof Error?e.message:String(e)}`),[]}if(0===c.length)return s.log("info",`loadUserSettingsPlugins: no plugin paths found in ~/.cursor/settings.json (${(performance.now()-i).toFixed(1)}ms)`),[];const l=[];for(const{originalPath:t,resolvedPath:r,isDiscovered:o}of c)try{const i=performance.now(),a=(0,w.basename)(r),c=u(r),d=yield null===(n=e.localPluginVariablesLookup)||void 0===n?void 0:n.call(e,c),{displayName:p,description:h,authorName:m,variablesSchema:f,skills:g,rules:v,agents:y,commands:b,mcpConfig:k,capabilities:S,hooks:E}=yield lr(r,a,void 0,{configuredVariables:d}),x={source:"user-settings",sourceInfo:{name:null!=p?p:a,localPath:r,originalSettingsPath:t,isDiscovered:o}};l.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:x,installPath:r},void 0!==p&&{displayName:p}),void 0!==h&&{description:h}),void 0!==m&&{authorName:m}),{variablesSchema:f,skills:g,rules:v,agents:y,commands:b,mcpConfig:null!=k?k:void 0,capabilities:S,hooks:E})),s.log("info",`loadUserSettingsPlugin ${a} loaded in ${(performance.now()-i).toFixed(1)}ms`)}catch(e){const t=e instanceof Error?e.name:"Error";s.log("error",`loadUserSettingsPlugin failed for ${(0,w.basename)(r)}: ${t}`)}return s.log("info",`loadUserSettingsPlugins completed in ${(performance.now()-i).toFixed(1)}ms (${l.length} plugins loaded from ${c.length} paths)`),l}))}({userHomeDir:t.userHomeDir,log:l,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[k,S]=yield Promise.all([Promise.all(v),null!=b?b:Promise.resolve([])]),E=[];for(const e of S)E.push(...e.plugins),y.push(...e.failures);E.push(...k.flat());const x=new Set,_=[];for(const e of E){const t=yield(0,Q.realpath)(e.installPath).catch((()=>e.installPath));x.has(t)||(x.add(t),_.push(e))}const C=new Map,P=[];for(const e of _){const t=mr(e);if(void 0!==t){const r=C.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=P.findIndex((e=>mr(e)===t&&e.loadError));-1!==r&&P.splice(r,1),C.set(t,!0),P.push(e);continue}C.set(t,n)}P.push(e)}const R=performance.now()-d;return l.log("info",`loadAllPlugins completed in ${R.toFixed(1)}ms (claude=${p}, userLocal=${h}, userSettings=${m}, marketplace=${f.length} sources, total=${P.length} plugins, failures=${y.length})`),{plugins:P,failures:y}}))}function mr(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function fr(e,t={}){return Object.assign(Object.assign({},e),{model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools})}function gr(e){return yr(e,(e=>e.skills))}function vr(e){return yr(e,(e=>e.rules))}function yr(e,t){const r=[];for(const o of e){const e=h(o.identifier),s=`plugin:${e}`,i=m(o.identifier),a=f(o.identifier),c=g(o.identifier),l=v(o.identifier);for(const u of t(o)){const t=(0,w.join)(o.installPath,u.path),{type:d,globs:p,description:h}=(n=u).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:u.content,type:d,globs:p,description:h,pluginIdentifier:e,gitRemoteOrigin:s,plugin:i,marketplace:a,pluginId:c,marketplaceId:l,environments:u.environments,disabledEnvironments:u.disabledEnvironments})}}var n;return r}function wr(e,t={stripModel:!0,stripTools:!0}){var r;const n=[];for(const o of e){const e=m(o.identifier),s=f(o.identifier),i=g(o.identifier),a=v(o.identifier);for(const c of o.agents){const l=fr(c,t),u=(0,w.join)(o.installPath,l.path);n.push({name:l.name,description:null!==(r=l.description)&&void 0!==r?r:"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:s,pluginId:i,marketplaceId:a})}}return n}(0,w.join)((0,Ee.homedir)(),".claude","plugins","marketplaces"),r("node:url?7874"),r("node:fs"),Error;var br=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};function kr(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch(e){return!1}}class Sr extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function Er(e){return br(this,void 0,void 0,(function*(){try{return yield(0,Q.readFile)(function(e){return(0,w.join)(e,".cursor","settings.json")}(e),"utf-8")}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}))}function xr(e){return br(this,void 0,void 0,(function*(){const t=yield Er(e);return void 0===t?{}:function(e){const t=[],r=(0,ee.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,ee._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Sr(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const n=r;return void 0===n.plugins||"object"==typeof n.plugins&&null!==n.plugins&&!Array.isArray(n.plugins)?n:{}}(t)}))}function _r(e){return br(this,void 0,void 0,(function*(){const t=yield xr(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||kr(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}))}function Cr(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}},"../cursor-sdk-local-runtime/dist/adapters/default-node-host-adapters.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{H:()=>d});var o=r("../context/dist/index.js"),s=r("../cursor-config/dist/index.js"),i=r("../local-exec/dist/index.js"),a=e([s]),c=a.then?(await a)():a;s=c[0];const l=new i.xK,u={async resolveWorkspaceState(e){var t,r,n,a,c,u,d;const p=null!==(n=null!==(r=e.workingDirectory)&&void 0!==r?r:e.projectRoot)&&void 0!==n?n:null===(t=e.workspaceRoots)||void 0===t?void 0:t[0],h=null!==(a=e.projectRoot)&&void 0!==a?a:void 0!==p?null!==(c=await(0,i.ky)((0,o.q6)(),l,p))&&void 0!==c?c:p:void 0,m=null!==(u=e.workspaceRoots)&&void 0!==u?u:void 0!==h?[h]:void 0!==p?[p]:[];return{workingDirectory:p,projectRoot:h,projectDirectory:null!==(d=e.projectDirectory)&&void 0!==d?d:void 0!==h?(0,s.Xq)(h):void 0,workspaceRoots:m,createdAt:new Date}}};function d(e={}){var t;return{workspace:null!==(t=e.workspace)&&void 0!==t?t:u,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}n()}catch(p){n(p)}}))},"../cursor-sdk-local-runtime/dist/adapters/index.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{H:()=>o.H});var o=r("../cursor-sdk-local-runtime/dist/adapters/default-node-host-adapters.js"),s=e([o]),i=s.then?(await s)():s;o=i[0],n()}catch(e){n(e)}}))},"../cursor-sdk-local-runtime/dist/agent-host/agent-session-runner.js"(e,t,r){r.d(t,{B:()=>c});var n=r("../agent-core/dist/index.js"),o=r("../proto/dist/generated/agent/v1/agent_pb.js"),s=r("../cursor-sdk-local-runtime/dist/utils/logger.js");function i(e){var t;if("userMessageAction"===e.action.case)return null===(t=e.action.value.userMessage)||void 0===t?void 0:t.text}function a(e,t,r){var n,o;const s=null===(n=e.runOptions)||void 0===n?void 0:n.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:null!==(o=null==s?void 0:s.modelId)&&void 0!==o?o:"unknown",modelId:null==s?void 0:s.modelId,modelParams:null==s?void 0:s.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function c(e,t,r){const{hooks:c}=r,[u,d]=e.withCancel(),p=new n.hg;let h=r.initialState;const m={async handleCheckpoint(e,t){var n;h=t,await(null===(n=r.onCheckpoint)||void 0===n?void 0:n.call(r,t))},getLatestCheckpoint:()=>h};let f="completed";const g=Date.now();return{done:(async()=>{var e,n,d,g,v,y,w,b,k;const S=a(r,0,i(t));try{const t=await(null===(e=null==c?void 0:c.onSessionStart)||void 0===e?void 0:e.call(c,S));if(null==t?void 0:t.blocked)throw f="error",new Error(null!==(w=t.blockedReason)&&void 0!==w?w:"Session blocked by sessionStart hook")}catch(e){if("completed"!==f)throw e;s.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let E=t,x=0;for(;E;){const e=a(r,x,i(E));try{await(null===(n=null==c?void 0:c.onBeforeSubmitPrompt)||void 0===n?void 0:n.call(c,e))}catch(e){s.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}const t=0===x?r.preFetchedBlobs:void 0;try{await r.agentClient.run(u,h,E,void 0,r.interactionListener,r.resources,r.blobStore,p,m,null!==(b=r.mcpTools)&&void 0!==b?b:[],Object.assign(Object.assign(Object.assign({conversationId:r.conversationId},r.runOptions),{subagentModelOverrides:null!==(k=null===(d=r.runOptions)||void 0===d?void 0:d.subagentModelOverrides)&&void 0!==k?k:[]}),void 0!==t?{preFetchedBlobs:t}:{}))}catch(t){throw f=l(t)?"aborted":"error",null==(_="aborted"===f?null===(g=null==c?void 0:c.onTurnAborted)||void 0===g?void 0:g.call(c,e):null===(v=null==c?void 0:c.onTurnError)||void 0===v?void 0:v.call(c,e))||_.catch((e=>{s.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)})),t}let w;try{w=await(null===(y=null==c?void 0:c.onTurnCompleted)||void 0===y?void 0:y.call(c,e))}catch(e){throw f="error",e}const S="string"==typeof w?w.trim():"";0!==S.length?(x+=1,p.resetStream(),C=S,E=new o.QF({action:{case:"userMessageAction",value:new o.Vt({userMessage:new o.RG({text:C})})}})):E=void 0}var _,C})().finally((async()=>{var e,t;const r=Date.now()-g;try{await(null===(e=null==c?void 0:c.onSessionEnd)||void 0===e?void 0:e.call(c,f,r))}catch(e){s.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(null===(t=null==c?void 0:c.dispose)||void 0===t?void 0:t.call(c))}catch(e){s.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){d()}}}function l(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}},"../cursor-sdk-local-runtime/dist/agent-host/default-local-workspace-runtime.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{O:()=>v});var o=r("../local-exec/dist/index.js"),s=r("../proto/dist/generated/agent/v1/subagents_pb.js"),i=r("../shell-exec/dist/index.js"),a=r("../cursor-sdk-local-runtime/dist/core/index.js"),c=r("../cursor-sdk-local-runtime/dist/core/workspace-runtime.js"),l=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),u=e([a,c]);[a,c]=u.then?(await u)():u;class d{async requestApproval(e){return{approved:!0}}}class p{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class h{async open(e,t){}async getDiagnostics(e,t){return[]}}class m{async getCodebaseReference(e,t){}}class f{inner;constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return Object.assign(Object.assign({},t),{servers:t.servers.filter((e=>"needsAuth"!==e.status))})}}class g{subagents;constructor(e){this.subagents=e.map((e=>new s.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:s.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}async function v(e){var t,r,n,s,u,v,y,w,b;const{workingDirectory:k,projectDir:S}=e,E=(0,a.Ob)(e.settingSources),x=null!==(r=e.teamSettingsService)&&void 0!==r?r:(0,a.GG)(),_=null!==(n=e.defaultSandboxPolicy)&&void 0!==n?n:{type:"insecure_none"},C=null!==(s=e.getSandboxSupported)&&void 0!==s?s:()=>(0,i.K3)(_,{ctx:e.initializationCtx}),P=null!==(u=e.getSandboxEnabled)&&void 0!==u?u:()=>"insecure_none"!==_.type&&C(),R=new o.xK,T=new o.E1(R,x,[k]),I=new h,A=new m,j=null===(t=e.getSmartModeClassifierAutoModeEnabled)||void 0===t?void 0:t.call(e),O=new p(j?"allowlist":null!==(v=e.approvalMode)&&void 0!==v?v:"unrestricted",_,x,null!==(y=e.respectAdminControls)&&void 0!==y&&y),D=e.pendingDecisionProvider,M={executeIndexedGrep:void 0},N=()=>!0,$=(0,a.ue)(E,"plugins"),L=null!==(w=e.importThirdPartyPlugins)&&void 0!==w&&w,F=null===(b=e.mcpMetaToolEnabled)||void 0===b||b,U=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,B=void 0!==e.customSubagents&&e.customSubagents.length>0,H=U||(0,a.ue)(E,"project")||(0,a.ue)(E,"user")||$,z=(0,a.ue)(E,"project")||(0,a.ue)(E,"user")||(0,a.ue)(E,"mdm"),W=(0,a.ue)(E,"team"),q=W&&void 0!==e.dashboardTransport,G=(0,a.ue)(E,"project")||(0,a.ue)(E,"user")||W||q||$,V=t=>(0,c.c)({workingDirectory:k,adapters:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.includeMcp?{mcp:(0,a.$r)({teamSettingsService:x,initializationCtx:e.initializationCtx,importThirdPartyPlugins:L,ignoreApprovals:!0,includeProjectMcp:(0,a.ue)(E,"project"),includeUserMcp:(0,a.ue)(E,"user"),includePluginMcp:$,inlineMcpServers:e.mcpServers})}:{}),$?{pluginBootstrap:(0,a.VR)({importThirdPartyPlugins:L,dashboardTransport:e.dashboardTransport})}:{}),z?{hooks:(0,a.vk)({includeProjectHooks:(0,a.ue)(E,"project"),includeUserHooks:(0,a.ue)(E,"user"),includeEnterpriseHooks:(0,a.ue)(E,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{}),G?{localExtensibility:(0,a.sP)({includeProjectExtensibility:(0,a.ue)(E,"project"),includeUserExtensibility:(0,a.ue)(E,"user"),includeManagedSkills:q,includeTeamExtensibility:W,includePluginExtensibility:$,teamSettingsService:x,getThirdPartyExtensibilityEnabled:N,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:L})}:{}),{resourceFactory:(0,a.T9)({ignoreService:T,grepProvider:M,workspacePaths:[k],diagnosticsProvider:I,repositoryProvider:A,projectDir:null!=S?S:k,shellManager:void 0,defaultSandboxPolicy:_,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:P,getSandboxSupported:C,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:F,createMcpStateAccessor:e=>new f(new o.Zc(e)),createSessionMcpLease:(t,r)=>(0,a.$r)({teamSettingsService:x,initializationCtx:e.initializationCtx,importThirdPartyPlugins:!1,ignoreApprovals:!0,includeProjectMcp:!1,includeUserMcp:!1,includePluginMcp:!1,inlineMcpServers:r}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{var t;const r=null!=D?D:new d;return{pendingDecisionStore:r,fileChangeTracker:new o.$1(k),permissionsService:new o.kh(T,r,O,x,k,null!==(t=e.respectAdminControls)&&void 0!==t&&t)}}}),resourceWrappers:z?[(0,a.Pq)()]:[]}),B?{workspaceServicesContributors:[{contributeServices:t=>{var r;const n=new g(null!==(r=e.customSubagents)&&void 0!==r?r:[]),s=t.services.subagentsService;return{subagentsService:void 0===s?n:new o.o_([n,s])}}}]}:{})});if(!H)return V({includeMcp:!1});try{return await V({includeMcp:!0})}catch(e){return l.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:k,projectDir:S,enablePlugins:$,importThirdPartyPlugins:L}),V({includeMcp:!1})}}n()}catch(y){n(y)}}))},"../cursor-sdk-local-runtime/dist/agent-host/index.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{Bq:()=>o.B,O:()=>a.O,Oh:()=>s.O,vW:()=>i.v,xK:()=>c.xK});var o=r("../cursor-sdk-local-runtime/dist/agent-host/agent-session-runner.js"),s=r("../cursor-sdk-local-runtime/dist/agent-host/default-local-workspace-runtime.js"),i=r("../cursor-sdk-local-runtime/dist/agent-host/local-hooks-session-adapter.js"),a=r("../cursor-sdk-local-runtime/dist/agent-host/local-subagent-host-adapter.js"),c=r("../cursor-sdk-local-runtime/dist/agent-host/local-transcript-writer.js"),l=e([s,a,c]);[s,a,c]=l.then?(await l)():l,n()}catch(e){n(e)}}))},"../cursor-sdk-local-runtime/dist/agent-host/local-hooks-session-adapter.js"(e,t,r){r.d(t,{v:()=>s});var n=r("../hooks/dist/index.js"),o=r("../cursor-sdk-local-runtime/dist/utils/logger.js");function s(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(n._E.sessionStart)||t.hooksConfigLease.hasHookForStep(n._E.sessionEnd)||t.hooksConfigLease.hasHookForStep(n._E.stop)||t.hooksConfigLease.hasHookForStep(n._E.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:s}=r;let i;return{async onSessionStart(e){if(i=e,s.hasHooksForStep(n._E.sessionStart))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},(0,n.U4)(e)),{is_background_agent:!1}),r=await s.executeHookForStep(n._E.sessionStart,t);if(r)return r.env&&s.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){o.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){var r,a,c;if(s.hasHooksForStep(n._E.sessionEnd))try{const o=Object.assign(Object.assign({conversation_id:null!==(r=null==i?void 0:i.conversationId)&&void 0!==r?r:"",generation_id:null!==(a=null==i?void 0:i.generationId)&&void 0!==a?a:"",model:null!==(c=null==i?void 0:i.model)&&void 0!==c?c:"unknown"},i?(0,n.U4)(i):{}),{reason:e,duration_ms:t,is_background_agent:!1,final_status:e});await s.executeHookForStep(n._E.sessionEnd,o)}catch(e){o.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{s.clearSessionEnvironment()}else s.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){var t;if(s.hasHooksForStep(n._E.beforeSubmitPrompt))try{const r=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},(0,n.U4)(e)),{prompt:null!==(t=e.promptText)&&void 0!==t?t:"",attachments:[]});await s.executeHookForStep(n._E.beforeSubmitPrompt,r)}catch(e){o.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!s.hasHooksForStep(n._E.stop))return;const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},(0,n.U4)(e)),{status:"completed",loop_count:e.loopCount}),r=await s.executeHookForStep(n._E.stop,t),o="string"==typeof(null==r?void 0:r.followup_message)?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(s.hasHooksForStep(n._E.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},(0,n.U4)(e)),{status:"error",loop_count:e.loopCount});await s.executeHookForStep(n._E.stop,t)}catch(e){o.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(s.hasHooksForStep(n._E.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},(0,n.U4)(e)),{status:"aborted",loop_count:e.loopCount});await s.executeHookForStep(n._E.stop,t)}catch(e){o.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}},"../cursor-sdk-local-runtime/dist/agent-host/local-subagent-host-adapter.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{O:()=>b});var o=r("node:crypto?8af2"),s=r("../agent-core/dist/index.js"),i=r("../agent-exec/dist/index.js"),a=r("../agent-kv/dist/index.js"),c=r("../proto/dist/generated/agent/v1/agent_pb.js"),l=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),u=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),d=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),p=r("../cursor-sdk-local-runtime/dist/agent-host/local-transcript-writer.js"),h=e([p]),m=h.then?(await h)():h;p=m[0];const f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,g="User aborted/interrupted manually.";function v(e){if(!f.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}function y(e){const t=new a.We,r=(0,a.sh)(e),n=new a.pH(new a.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n}function w(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return s.x1.webSearchRejected(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return s.x1.webFetchRejected(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return s.x1.switchModeRejected(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new l.tz({result:{case:"rejected",value:new l.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return s.x1.askQuestion(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}class b{sessions=new Map;backgroundRuns=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor(e){var t;this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=null!==(t=e.mcpTools)&&void 0!==t?t:[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new i.VM}async createOrResumeSession(e,t){var r;if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const n=t.resumeAgentId;if(n&&v(n),n&&!t.prompt)return n;if(n&&(0,i.UO)(t.prompt)&&this.isBackgroundRunBusy(n))throw new Error(i.y7);if(n&&this.sessions.get(n))return n;const s=null!=n?n:(0,o.randomUUID)(),a=y(s),c=new p.xK({workspacePath:this.workspacePath,conversationId:s,parentConversationId:this.parentConversationId,blobStore:a.getBlobStore()});return this.sessions.set(s,{agentStore:a,transcriptWriter:c,toolCallId:t.toolCallId}),this.registerParentChildLink(s,t.parentConversationId),null===(r=this.onSessionCreated)||void 0===r||r.call(this,{agentId:s,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),s}async runSession(e,t,r,n){var o;if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const s=this.sessions.get(t);if(!s)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,o]=e.withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,s),o),{status:"background",backgroundReason:i.qL.AGENT_REQUEST,toolCallCount:0}}const a=await this.executeSubagent(e,t,r,s);return null===(o=this.onSessionCompleted)||void 0===o||o.call(this,t,a),a}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r){const n=this.lifecycleStore.startRun(e,{abort:r}),o=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),s={runId:n,promise:o};this.backgroundRuns.set(e,s),this.backgroundPromises.add(o),o.then((t=>{var r;this.lifecycleStore.finishRun(e,n);const o=this.backgroundRuns.get(e);if((null==o?void 0:o.runId)===n){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,t),this.maybeCleanupReleasedSession(e);try{null===(r=this.onSessionCompleted)||void 0===r||r.call(this,e,t)}catch(t){d.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(o)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){var t;this.pendingReleaseSessions.delete(e);const r=this.sessions.get(e);if(!r)return;const n=this.parentChildIds.get(e);if(n)for(const e of n)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),r.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),null===(t=this.onSessionReleased)||void 0===t||t.call(this,e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch(e){return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new u.Pw(Object.assign(Object.assign({},r),{prompt:c,resumeAgentId:t,runInBackground:!1})),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,s,i){var a,c;let l,d,p=0;for(let h=0;h<i;h++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};const i=0===h?r.prompt:this.computeContinuationNudge(s,p,l),m=0===h?new u.Pw(Object.assign(Object.assign({},r),{runInBackground:!1})):new u.Pw(Object.assign(Object.assign({},r),{prompt:i,resumeAgentId:t,runInBackground:!1}));if(d=await this.executeSubagentOnce(e,t,m,n),"completed"!==d.status)return d;const f=null!==(a=d.toolCallCount)&&void 0!==a?a:0,g=null!==(c=d.finalMessage)&&void 0!==c?c:"";if(void 0!==l&&g.includes(l))return d;f>0?(p=0,l=void 0):(p+=1,l=p>=s.idleThreshold?`DONE_${(0,o.randomUUID)().replace(/-/g,"").slice(0,8)}`:void 0)}return null!=d?d:{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}async executeSubagentOnce(e,t,r,n){var o,a,l;let u,p=0;const h=new c.QF({action:{case:"userMessageAction",value:new c.Vt({userMessage:new c.RG({text:r.prompt})})}}),m=new c.Gm({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(m.credentials=r.credentials);const f=new s.hg,v={sendUpdate:async(e,r)=>{var n,o;"tokenDelta"===r.message.case&&(null===(n=this.onSubagentTokenDelta)||void 0===n||n.call(this,t,r.message.value.tokens)),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||null===(o=this.onInteractionUpdate)||void 0===o||o.call(this,t,r),"toolCallCompleted"===r.message.case&&p++,"textDelta"===r.message.case&&(u=(null!=u?u:"")+r.message.value.text)},query:async(e,t)=>w(t)},y={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const s=null===(o=r.rootParentConversationId)||void 0===o?void 0:o.trim(),c=null===(a=r.parentConversationId)||void 0===a?void 0:a.trim(),l=void 0!==s&&""!==s?s:void 0!==c&&""!==c?c:t,d=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),w=r.readonly?(0,i.u)(d):d;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),h,m,v,w,n.agentStore.getBlobStore(),f,y,[...this.mcpTools],{conversationGroupId:l,conversationId:t,subagentTypeName:r.subagentType||void 0,headers:this.headers,endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:g}:{status:"success"}),{status:"completed",finalMessage:u,toolCallCount:p}}catch(r){const o=r instanceof Error?r.message:String(r);return d.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,null!==(l=n.agentStore.getLatestCheckpoint())&&void 0!==l?l:n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:g}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:g}:{status:"error",error:t}}isAwaitBackgroundMode(e){var t;if(!Boolean(e.resumeAgentId&&!(0,i.UO)(e.prompt)&&!0===e.readonly&&!0!==e.runInBackground))return!1;if(0===(null!==(t=e.parentConversationId)&&void 0!==t?t:"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){var r,n,o,s;const i=null==t?void 0:t.trim();if(!i||i===e||!this.sessions.has(i))return;const a=this.childParentIds.get(e);if(a===i)return;a&&(null===(r=this.parentChildIds.get(a))||void 0===r||r.delete(e),0===(null!==(o=null===(n=this.parentChildIds.get(a))||void 0===n?void 0:n.size)&&void 0!==o?o:0)&&this.parentChildIds.delete(a)),this.childParentIds.set(e,i);const c=null!==(s=this.parentChildIds.get(i))&&void 0!==s?s:new Set;c.add(e),this.parentChildIds.set(i,c)}removeParentChildLink(e){var t;const r=this.childParentIds.get(e);if(!r)return;this.childParentIds.delete(e);const n=this.parentChildIds.get(r);null==n||n.delete(e),0===(null!==(t=null==n?void 0:n.size)&&void 0!==t?t:0)&&this.parentChildIds.delete(r)}enqueueChildCompletion(e,t){var r,n;const o=this.childParentIds.get(e);if(!o)return;const s=null!==(r=this.queuedChildCompletions.get(o))&&void 0!==r?r:[];s.push({agentId:e,success:"completed"===t.status,finalMessage:"completed"===t.status?null!==(n=t.finalMessage)&&void 0!==n?n:"":"error"===t.status?t.error:"Subagent was aborted by the user"}),this.queuedChildCompletions.set(o,s),this.removeParentChildLink(e);const i=this.childCompletionWaiters.get(o);if(i){this.childCompletionWaiters.delete(o);for(const e of i)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){var t,r;return(null!==(r=null===(t=this.parentChildIds.get(e))||void 0===t?void 0:t.size)&&void 0!==r?r:0)>0}drainChildCompletions(e){var t;const r=null!==(t=this.queuedChildCompletions.get(e))&&void 0!==t?t:[];return this.queuedChildCompletions.delete(e),r}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{var o;const s=null!==(o=this.childCompletionWaiters.get(e))&&void 0!==o?o:new Set,i=()=>{c(),r()},a=()=>{c(),n(new Error("aborted"))},c=()=>{s.delete(i),0===s.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",a)};s.add(i),this.childCompletionWaiters.set(e,s),t.addEventListener("abort",a,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t=e.success?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}n()}catch(k){n(k)}}))},"../cursor-sdk-local-runtime/dist/agent-host/local-transcript-writer.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{xK:()=>h});var o=r("node:fs/promises"),s=r("node:path"),i=r("../agent-transcript/dist/index.js"),a=r("../cursor-config/dist/index.js"),c=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),l=e([a]);const u=(a=(l.then?(await l)():l)[0]).Xq;function d(e,t){const r=(0,i.sk)({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(u(e),r)}async function p(e,t){const r=(0,s.dirname)(e);await(0,o.mkdir)(r,{recursive:!0}),await(0,o.writeFile)(e,t,"utf-8")}class h{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;writeChain=Promise.resolve();constructor(e){this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.projectDir=u(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=(0,i.sk)({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new i.YF(this.projectDir,e.blobStore,p,Object.assign({writeText:!1,writeJsonl:!0},t?{pathResolver:t}:{})),this.nestedSubagentTranscriptStore=new i.YF(this.projectDir,e.blobStore,p,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=(0,i.sk)({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){c.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{var r;await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const n=null!==(r=t.subagentStates)&&void 0!==r?r:{};for(const[t,r]of Object.entries(n))(null==r?void 0:r.conversationState)&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,r.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=(0,i.sk)({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return d(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}n()}catch(m){n(m)}}))},"../cursor-sdk-local-runtime/dist/core/cursor-config-mcp.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{GG:()=>w,sP:()=>b});var o=r("node:fs/promises"),s=r("node:os"),i=r("node:path"),a=r("../context/dist/index.js"),c=r("../cursor-config/dist/index.js"),l=r("../local-exec/dist/index.js"),u=r("../mcp-agent-exec/dist/index.js"),d=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),p=r("../cursor-sdk-local-runtime/dist/core/plugin-bootstrap-types.js"),h=e([c]),m=h.then?(await h)():h;c=m[0];class f extends u.uz{runtimeManager;disposed=!1;constructor(e){super(e),this.runtimeManager=e}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class g{storagePath;constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,o.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,o.mkdir)((0,i.dirname)(this.storagePath),{recursive:!0}),await(0,o.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class v{pluginMcpService;importThirdPartyPlugins;constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return d.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&x(r))continue;const e=(0,u.Zj)(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):d.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class y{servers;constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:E(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function w(){return{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}}}function b(e={}){var t,r,n;const o=null!==(t=e.teamSettingsService)&&void 0!==t?t:{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},s=null!==(r=e.ignoreApprovals)&&void 0!==r&&r,c=null!==(n=e.importThirdPartyPlugins)&&void 0!==n&&n;return{async createLease(t){var r,n,d,h,m,w;const b=t.workspaceState,E=null!==(r=b.projectRoot)&&void 0!==r?r:b.workingDirectory,x=b.projectDirectory;if(!E||!x)return new u.LK;const _=new g((0,i.join)(x,"mcp-disabled.json")),C=k({teamSettingsService:o,projectRoot:E,projectDirectory:x,ignoreApprovals:s,disabledStore:_,includeProjectMcp:null===(n=e.includeProjectMcp)||void 0===n||n,includeUserMcp:null===(d=e.includeUserMcp)||void 0===d||d}),P=[],R=null!==(h=e.inlineMcpServers)&&void 0!==h?h:{};if(Object.keys(R).length>0){const e=new u.Q7((0,i.join)(x,"mcp-auth.json")),t=[new u.mz,new u.XV(o)];P.push({prefix:"",loader:new u.xz(new y(R),e,t)})}const T=(0,p.CD)(t.services.pluginBootstrapOutputs);if(T&&(null===(m=e.includePluginMcp)||void 0===m||m)){const e=new u.mF((0,i.join)(x,"mcp-approvals.json"),E),t=new u.Q7((0,i.join)(x,"mcp-auth.json")),r=[new u.mz];s||r.push(new u.$b(e)),r.push(new u.XV(o),new u._x(_));const n=new l.gR(T.pluginsService),a=new u.xz(new v(n,c),t,r);P.push({prefix:"",loader:a})}if(C&&P.push({prefix:"",loader:C}),0===P.length)return new u.LK;const I=S(P),A=await I.load(null!==(w=e.initializationCtx)&&void 0!==w?w:(0,a.q6)(),e.cache);return new f(A)}}}function k(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:o,disabledStore:a,includeProjectMcp:l,includeUserMcp:d}=e;if(l&&d)return c.aK.init(t,r,n,o,a);if(!l&&!d)return;const p=new u.Q7((0,i.join)(n,"mcp-auth.json")),h=o?{isServerApproved:()=>Promise.resolve(!0)}:new u.mF((0,i.join)(n,"mcp-approvals.json"),r),m=[new u.mz,new u.$b(h),new u.XV(t),new u._x(a)],f=[];return l&&f.push({prefix:"",loader:new u.gT((0,i.join)(r,".cursor","mcp.json"),p,m)}),d&&f.push({prefix:"",loader:new u.gT((0,i.join)((0,s.homedir)(),".cursor","mcp.json"),p,m)}),S(f)}function S(e){return 1===e.length?e[0].loader:new c.mG(e)}function E(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?Object.assign(Object.assign({},r),{type:"sse"}):r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function x(e){return"claude-plugin"===e.pluginSource}n()}catch(_){n(_)}}))},"../cursor-sdk-local-runtime/dist/core/hooks-runtime.js"(e,t,r){r.d(t,{vk:()=>Ze,Pq:()=>Xe});var n=r("node:child_process"),o=r("node:os"),s=r("node:path"),i=r("../hooks/dist/index.js"),a=r("node:fs/promises"),c=r("node:stream/promises"),l=r("../agent-transcript/dist/index.js"),u=r("../context/dist/index.js"),d=r("../utils/dist/index.js");class p extends Error{reason;failureType="permission_denied";constructor(e){super(`Hook denied: ${e}`),this.name="HookDeniedError",this.reason=e}}class h extends Error{reason;failureType="error";cause;constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.name="FailClosedError",this.reason=e,this.cause=t}}const m="To view or modify configured hooks, go to Cursor Settings > Hooks.",f="Agent note: Do not suggest workarounds to the blocked tool.";function g(e){return e.includes(f)?e:`${e}\n\n${f}`}function v(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function y(e,t){return g(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${m}`)}function w(e){return function(e){return e instanceof p}(e)||function(e){return e instanceof h}(e)}class b{workspacePath;globalContext;shellExecutor;promptHookClient;teamHooksReadyPromise;onHookExecution;options;sessionEnv;config;constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.teamHooksReadyPromise=s,this.onHookExecution=i,this.options=a,this.config=e}emitHookExecution(e){var t,r;const n=Object.assign(Object.assign({},e),{transportMode:null!==(r=e.transportMode)&&void 0!==r?r:"prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode()});try{null===(t=this.onHookExecution)||void 0===t||t.call(this,n)}catch(e){}}getCommandHookPayloadTransportMode(){var e;return"stdin"===(null===(e=this.options)||void 0===e?void 0:e.commandHookPayloadTransport)?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,c.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}setSessionEnvironment(e){this.sessionEnv=Object.assign(Object.assign({},this.sessionEnv),e)}clearSessionEnvironment(){this.sessionEnv=void 0}async getTranscriptPathIfExists(e){try{const t=(0,d.Rv)((0,o.homedir)(),this.workspacePath),r=(0,l.pr)({conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of r)try{return await(0,a.access)(e),e}catch(e){}return null}catch(e){return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,d.Rv)((0,o.homedir)(),this.workspacePath),n=(0,l.pr)({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,a.access)(e),e}catch(e){}return null}catch(e){return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks].some((t=>{const r=null==t?void 0:t.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,this.config.userHooks];for(const n of r){const r=null==n?void 0:n.hooks[e];if(r&&(t?(0,i.Qk)(r,t):r).some((e=>!0===e.failClosed)))return!0}return!1}getCwdForSource(e){var t,r,n,o;const s=this.config.configDirs;switch(e){case"enterprise":return null!==(t=null==s?void 0:s.enterprise)&&void 0!==t?t:this.workspacePath;case"team":return null!==(r=null==s?void 0:s.team)&&void 0!==r?r:this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":default:return this.workspacePath;case"user":return null!==(n=null==s?void 0:s.user)&&void 0!==n?n:this.workspacePath;case"claude-user":return null!==(o=null==s?void 0:s.claudeUser)&&void 0!==o?o:this.workspacePath}}buildHookEnvironment(e){return Object.assign(Object.assign(Object.assign(Object.assign({CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version},this.globalContext.user_email&&{CURSOR_USER_EMAIL:this.globalContext.user_email}),e&&{CURSOR_TRANSCRIPT_PATH:e}),{CLAUDE_PROJECT_DIR:this.workspacePath}),this.sessionEnv)}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=r.loop_count,o=t.loop_limit;return null!==o&&(void 0===o?n>=i.aX:n>=o)}async executeHookForStep(e,t){var r,n,o,s,a,c,l,u;this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const d=(0,i.yW)(e),p=t,h=d?null:p.conversation_id?await this.getTranscriptPathIfExists(p.conversation_id):null;let m;if(e===i._E.subagentStop){const e=t;m=e.subagent_id?await this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const f=d?void 0:null!==(u=p.session_id)&&void 0!==u?u:p.conversation_id,g=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),void 0!==f&&{session_id:f}),{hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.globalContext.user_email}),!d&&{transcript_path:h}),e===i._E.subagentStop&&{agent_transcript_path:null!=m?m:null}),v=(0,i.bi)(e,g),y=[],w=(e,t)=>{if(!e)return;const r=(0,i.Qk)(e,v),n=this.getCwdForSource(t);for(const e of r)(0,i.uu)(e)?this.promptHookClient&&y.push({type:"prompt",script:e,source:t}):(0,i.Xz)(e)&&y.push({type:"command",script:e,cwd:n,source:t})};if(w(null===(r=this.config.enterpriseHooks)||void 0===r?void 0:r.hooks[e],"enterprise"),w(null===(n=this.config.teamHooks)||void 0===n?void 0:n.hooks[e],"team"),w(null===(o=this.config.projectHooks)||void 0===o?void 0:o.hooks[e],"project"),w(null===(s=this.config.userHooks)||void 0===s?void 0:s.hooks[e],"user"),w(null===(a=this.config.claudeProjectLocalHooks)||void 0===a?void 0:a.hooks[e],"claude-project-local"),w(null===(c=this.config.claudeProjectHooks)||void 0===c?void 0:c.hooks[e],"claude-project"),w(null===(l=this.config.claudeUserHooks)||void 0===l?void 0:l.hooks[e],"claude-user"),0!==y.length)return this.executeAllAndMerge(e,y,g)}async executeAllAndMerge(e,t,r){const n=t.map((async(t,n)=>{const{source:o,attribution:s}=t;try{return"prompt"===t.type?this.executePromptHook(e,t.script,r,o,n,s):this.executeCommandHook(e,t.script,t.cwd,r,o,n,s)}catch(r){if(!0===t.script.failClosed){const t=v(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),s=(0,i.FS)(e,t);if(s)return{success:!0,data:s,source:o,index:n}}return{success:!1,source:o,index:n}}})),o=await Promise.all(n),s=[];for(const e of o)e.success&&void 0!==e.data&&s.push(e.data);return(0,i.wb)(e,s)}async executeCommandHook(e,t,r,n,o,s,a){var c,l,u,d,p,h,m,f;if(this.shouldSkipHookDueToLoopLimit(e,t,n))return{success:!1,source:o,index:s};const g=Date.now(),y=Buffer.byteLength(JSON.stringify(n),"utf8");let w;try{w=await this.executeCommandScript({script:t,cwd:r,request:n})}catch(r){const n=r instanceof Error?r.message:String(r),c=n.toLowerCase().includes("timed out"),l=Date.now()-g,u=c?"timeout":"spawn_error";if(!0===t.failClosed){const r=v(`Hook "${t.command}" execution failed: ${n}`),d=(0,i.FS)(e,r);if(d)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:c?"timeout":"blocked",latencyMs:l,payloadSizeBytes:y,errorClass:u,failClosed:!0,timedOut:c},a)),{success:!0,data:d,source:o,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:c?"timeout":"failed",latencyMs:l,payloadSizeBytes:y,errorClass:u,failClosed:!0===t.failClosed,timedOut:c},a)),{success:!1,source:o,index:s}}if(w.exitCode===i.LQ){const r=(0,i.Uv)(w.stdout,w.stderr,t.command),n=(0,i.FS)(e,r);return n?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,failClosed:!0===t.failClosed,exitCode:w.exitCode},a)),{success:!0,data:n,source:o,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,failClosed:!0===t.failClosed,exitCode:w.exitCode},a)),{success:!1,source:o,index:s})}if(0!==w.exitCode&&null!==w.exitCode){if(!0===t.failClosed){const r=v(`Hook "${t.command}" failed with exit code ${w.exitCode}${w.stderr?`: ${w.stderr.trim()}`:""}`),n=(0,i.FS)(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"exit_nonzero",failClosed:!0,exitCode:w.exitCode},a)),{success:!0,data:n,source:o,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:w.exitCode},a)),{success:!1,source:o,index:s}}const b=w.stdout.trim();if(!b){if(!0===t.failClosed){const r=v(`Hook "${t.command}" returned no output.`),n=(0,i.FS)(e,r);if(n)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"empty_stdout",failClosed:!0,exitCode:null!==(l=w.exitCode)&&void 0!==l?l:void 0},a)),{success:!0,data:n,source:o,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:null!==(u=w.exitCode)&&void 0!==u?u:void 0},a)),{success:!1,source:o,index:s}}const k=(0,i.x9)(b);if(void 0===k){const r=(0,i.Vf)({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(d=w.exitCode)&&void 0!==d?d:void 0},a)),{success:!0,data:r.blockResponse,source:o,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(p=w.exitCode)&&void 0!==p?p:void 0},a)),{success:!1,source:o,index:s})}const S=(0,i.jO)(e,k,{enableClaudeNestedHookSpecificOutputCompatibility:null===(c=this.options)||void 0===c?void 0:c.enableClaudeNestedHookSpecificOutputCompatibility});if(S.success){const r=S.data,n="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:n?"blocked":"success",latencyMs:w.duration,payloadSizeBytes:y,failClosed:!0===t.failClosed,exitCode:null!==(h=w.exitCode)&&void 0!==h?h:void 0},a)),{success:!0,data:S.data,source:o,index:s}}const E=(0,i.Vf)({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return E.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"blocked",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(m=w.exitCode)&&void 0!==m?m:void 0},a)),{success:!0,data:E.blockResponse,source:o,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"command",status:"failed",latencyMs:w.duration,payloadSizeBytes:y,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(f=w.exitCode)&&void 0!==f?f:void 0},a)),{success:!1,source:o,index:s})}async executePromptHook(e,t,r,n,o,s){var a,c;if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const l=1e3*(null!==(a=t.timeout)&&void 0!==a?a:i.yB),d=Date.now(),p=Buffer.byteLength(JSON.stringify(r),"utf8"),h=(0,u.q6)(),[m,f]=h.withTimeoutAndCancel(l);try{const a=JSON.parse(JSON.stringify(r)),l=await this.promptHookClient.evaluatePromptHook(m,{prompt:t.prompt,hookInputJson:a,modelName:t.model});if(l.ok){const r=(0,i.D3)(e);return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-d,payloadSizeBytes:p,failClosed:!0===t.failClosed},s)),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=null!==(c=l.reason)&&void 0!==c?c:"Prompt hook blocked this action",a=(0,i.FS)(e,r);return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-d,payloadSizeBytes:p,failClosed:!0===t.failClosed},s)),a?{success:!0,data:a,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const a=r instanceof Error?r.message:String(r),c=a.toLowerCase().includes("abort")||a.toLowerCase().includes("timed out"),l=c?"timeout":"prompt_error";if(!0===t.failClosed){const t=v(`Prompt hook failed: ${a}`),r=(0,i.FS)(e,t);if(r)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:c?"timeout":"blocked",latencyMs:Date.now()-d,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:c},s)),{success:!0,data:r,source:n,index:o}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"prompt",status:c?"timeout":"failed",latencyMs:Date.now()-d,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:c},s)),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){var t;const{script:r,cwd:n,request:c}=e,l=1e3*(null!==(t=r.timeout)&&void 0!==t?t:i.yB),d=Date.now(),p=JSON.stringify(c);let h;const m=new AbortController,f=setTimeout((()=>{m.abort()}),l);try{const e="win32"===process.platform,t=this.getCommandHookPayloadTransportMode(),g=this.shouldUseCommandHookDirectStdinTransport();let v;if(g)v=r.command;else if("windows_temp_file"===t){h=await(0,a.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(h,"payload.json");await(0,a.writeFile)(e,p,{encoding:"utf8",flag:"wx"}),v=(0,i.q3)(e,r.command)}else v=e?`@'\n${p.replace(/'/g,"''")}\n'@ | & ${r.command}`:`${r.command} <<'CURSOR_HOOK_EOF'\n${p}\nCURSOR_HOOK_EOF`;const y=c,w=this.buildHookEnvironment(y.transcript_path),b={};for(const[e,t]of Object.entries(w))void 0!==t&&(b[e]=t);const k=(0,u.q6)();let S="",E="",x=null,_=!1;for await(const e of this.shellExecutor.execute(k,v,{workingDirectory:n,signal:m.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:b,pipeStdin:g}))switch(e.type){case"stdin_ready":g&&(await this.writeCommandHookStdinPayload(e.stdin,p),_=!0);break;case"stdout":S+=e.data.toString("utf8");break;case"stderr":E+=e.data.toString("utf8");break;case"exit":x=e.code}if(g&&!_)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(f);const C=Date.now()-d;if(m.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:S,stderr:E,exitCode:x,duration:C}}catch(e){if(clearTimeout(f),Date.now(),m.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(h)try{await(0,a.rm)(h,{recursive:!0,force:!0})}catch(e){}}}}function k(e){switch(null!=e?e:(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}class S{fileReader;paths;logger;constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=async(e,t,n,o,i,a,c)=>{if(e)try{if(!await this.fileReader.exists(e))return;const a=await this.fileReader.readFile(e);if(!a)return;const{config:l,error:u}=c(a);l?(r[n]=l,((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)):u&&r.errors.push({source:t,message:`${i} at ${e}: ${u}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},o=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise"},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team"},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user"},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project"}];for(const e of o)await n(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,(t=>this.parseAndValidate(t,e.source)));const i=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user"},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project"},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local"}];for(const e of i)await n(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,(t=>this.parseClaudeConfig(t,e.source)));return this.dedupeClaudeHooksAgainstCursorHooks(r),r}getHookKey(e){return(0,i.uu)(e)?`prompt:${e.prompt}`:`command:${e.command}`}dedupeClaudeHooksAgainstCursorHooks(e){const t=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks],r=new Map;for(const e of t)if(null==e?void 0:e.hooks)for(const[t,n]of Object.entries(e.hooks)){if(!n)continue;let e=r.get(t);e||(e=new Set,r.set(t,e));for(const t of n)e.add(this.getHookKey(t))}const n=(e,t)=>{if(null==e?void 0:e.hooks)for(const[n,o]of Object.entries(e.hooks)){if(!o)continue;const s=r.get(n);if(!s||0===s.size)continue;const i=o.filter((e=>{const r=this.getHookKey(e);return!s.has(r)||(this.logger.info(`Removed duplicate ${t} hook for ${n}: ${r}`),!1)}));i.length!==o.length&&(e.hooks[n]=i)}};n(e.claudeUserHooks,"claude-user"),n(e.claudeProjectHooks,"claude-project"),n(e.claudeProjectLocalHooks,"claude-project-local")}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!(0,i.DP)(t))return{};const r=(0,i.eg)(t);if(!r||0===Object.keys(r).length)return{};const n=(0,i.sl)(r,this.logger),o=(0,i.RV)(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const r=this.parseJSONC(e),n=(0,i.RV)(r);if(!n.isValid)return{error:`Invalid ${t} config: ${n.errors.join("; ")}`};const o=r;return o.hooks?{config:o}:{error:`Invalid ${t} config: missing 'hooks' property`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks];for(const e of r)if(null==e?void 0:e.hooks)for(const r of Object.keys(e.hooks))t.add(r);return t}}class E{config;configuredSteps;constructor(e){this.config=e,this.configuredSteps=S.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var x=r("node:crypto?8af2"),_=r("node:perf_hooks?b4d9");function C(e,t){void 0!==e&&t.length>0&&e.push(...t)}class P extends Error{hookEventName;actualLength;maxLength;constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var R=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function T({hookEventName:e,additionalContext:t}){const r=function(e){const t=null==e?void 0:e.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new P({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new R.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(i.Qu).map((e=>{if(!function(e){return e===i._E.sessionStart||e===i._E.beforeSubmitPrompt||e===i._E.preToolUse||e===i._E.postToolUse||e===i._E.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const I=(0,u.h)("generic-hooks");function A(e,t,r,n){try{return T({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof P)return I.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const j=e=>Math.round(1e3*e)/1e3;function O(e,t,r,n,o,s){var a,c,l,u,d,p,h;const m=n(e),f=null!==(u=null===(a=o.getToolCallId)||void 0===a?void 0:a.call(o,t))&&void 0!==u?u:(0,x.randomUUID)(),g=null!==(d=null===(c=o.getExtraHookFields)||void 0===c?void 0:c.call(o,t))&&void 0!==d?d:{},v={baseHookRequest:m,toolUseId:f,toolInput:o.createToolInput(t),extraHookFields:g,hookContextCollector:null!==(h=null!==(p=null==s?void 0:s.hookContextCollector)&&void 0!==p?p:null===(l=o.getHookContextCollector)||void 0===l?void 0:l.call(o,t))&&void 0!==h?h:[]},y=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:a}=n;const{baseHookRequest:c,toolUseId:l}=n;return{fireFailureAsync:async(n,u,d,p=!1)=>{try{const h=await t.executeHookForStep(i._E.postToolUseFailure,Object.assign(Object.assign(Object.assign({},c),{tool_name:r,tool_input:o,error_message:u,failure_type:d,duration:n,tool_use_id:l,is_interrupt:p}),s));C(a,A(e,r,i._E.postToolUseFailure,null==h?void 0:h.additional_context))}catch(t){I.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,u)=>{try{const d=await t.executeHookForStep(i._E.postToolUse,Object.assign(Object.assign(Object.assign({},c),{tool_name:r,tool_input:o,tool_output:u,duration:n,tool_use_id:l}),s));C(a,A(e,r,i._E.postToolUse,null==d?void 0:d.additional_context))}catch(t){I.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,v);return{hookContext:v,helpers:y}}async function D(e,t,r,n,o,s,a,c){var l,u;const{baseHookRequest:d,toolUseId:p,extraHookFields:h}=n;try{const c=await r.executeHookForStep(i._E.preToolUse,Object.assign(Object.assign(Object.assign({},d),{tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:p}),h));if("deny"===(null==c?void 0:c.permission)){const r=c.user_message||`${s.toolName} blocked by preToolUse hook`,l=g(r);try{C(n.hookContextCollector,T({hookEventName:i._E.preToolUse,additionalContext:c.additional_context}))}catch(t){if(!(t instanceof P))throw t;I.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:a(t,l),reason:l}}(null==c?void 0:c.updated_input)&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,c.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),C(n.hookContextCollector,T({hookEventName:i._E.preToolUse,additionalContext:null==c?void 0:c.additional_context}))}catch(n){const c=null!==(u=null===(l=r.hasFailClosedHooksForStep)||void 0===l?void 0:l.call(r,i._E.preToolUse,s.toolName))&&void 0!==u&&u,d=n instanceof P;if(c){const e=v(`${d?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:a(t,e),reason:e}}I.warn(e,d?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",Object.assign({toolName:s.toolName,error:n instanceof Error?n.message:String(n)},d?{actualLength:n.actualLength,maxLength:n.maxLength}:{}))}if(c)try{const s=await c({ctx:e,args:t,baseHookRequest:d,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:p,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(w(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:a(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function M(e){return e.toolCallId}function N(e,t,r,n){return{async execute(o,s,i){var a,c,l,u,d,p,h,m,f,g;const{hookContext:v,helpers:y}=O(o,s,t,r,n,i);let b;try{b=await D(o,s,t,v,y,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw null===(a=n.runCleanup)||void 0===a||a.call(n,v.toolUseId),e}if("rejected"===b.type)return null===(c=n.runCleanup)||void 0===c||c.call(n,v.toolUseId),b.result;const k=_.performance.now();try{const r=await e.execute(o,s,i),a=j(_.performance.now()-k);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:r,baseHookRequest:v.baseHookRequest,hookExecutor:t,toolInput:y.getToolInput(),toolUseId:v.toolUseId,executionDurationMs:a,extraHookFields:v.extraHookFields});if(void 0!==e)return await y.fireSuccessAsync(a,JSON.stringify(n.createSuccessOutput(s,e))),null===(l=n.runCleanup)||void 0===l||l.call(n,v.toolUseId),e}catch(e){if(w(e))return await y.fireFailureAsync(a,e.reason,e.failureType),null===(u=n.runCleanup)||void 0===u||u.call(n,v.toolUseId),n.createRejectedResult(s,e.reason);I.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(r)?await y.fireSuccessAsync(a,JSON.stringify(n.createSuccessOutput(s,r))):await y.fireFailureAsync(a,n.getErrorMessage(r),null!==(f=null===(d=n.getFailureType)||void 0===d?void 0:d.call(n,r))&&void 0!==f?f:"error",null!==(g=null===(p=n.isInterrupt)||void 0===p?void 0:p.call(n,r))&&void 0!==g&&g),null===(h=n.runCleanup)||void 0===h||h.call(n,v.toolUseId),r}catch(e){const t=j(_.performance.now()-k);throw await y.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),null===(m=n.runCleanup)||void 0===m||m.call(n,v.toolUseId),e}}}}function*$(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}class L{async readFile(e){try{return await a.readFile(e,"utf-8")}catch(e){if("ENOENT"===(null==e?void 0:e.code))return;throw e}}async exists(e){try{return await a.access(e),!0}catch(e){return!1}}}var F=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");class U{innerExecutor;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new F.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=new F.bb(Object.assign(Object.assign(Object.assign({},e),o&&{hooksAdditionalContext:o}),s&&{hooksConfig:s}));return new F._G({result:{case:"success",value:new F.yW({requestContext:t})}})}return n}}var B=r("../agent-exec/dist/index.js"),H=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),z=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),W=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function q(e){return!!e&&e.type!==W.vc.INSECURE_NONE&&e.type!==W.vc.UNSPECIFIED}const G="Shell";async function V({hookExecutor:e,baseHookRequest:t,command:r,cwd:n,sandbox:o}){const s=await e.executeHookForStep(i._E.beforeShellExecution,Object.assign(Object.assign({},t),{command:r,cwd:n,sandbox:o}));if("deny"===(null==s?void 0:s.permission)){const e=y("Command execution",s.user_message);throw new p(e)}if("ask"===(null==s?void 0:s.permission))return(0,B.$b)(s.user_message)}const J={toolName:G,getToolCallId:M,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new H.Lt({result:{case:"rejected",value:new z.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",s=q(t.sandboxPolicy);(0,B.oA)(t,await V({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:s}))}};class K{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,J)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Y={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new H.nt({result:{case:"error",value:new H.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class Z{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,Y)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var X=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");const Q={toolName:"ComputerUse",getToolCallId:M,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new X.ks({result:{case:"error",value:new X.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class ee{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,Q)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var te=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");const re={toolName:"Delete",getToolCallId:M,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new te.Pi({result:{case:"rejected",value:new te.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class ne{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,re)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var oe=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");const se={toolName:"ReadLints",getToolCallId:M,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new oe.Ek({result:{case:"rejected",value:new oe.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ie{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,se)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var ae=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js");const ce={toolName:"Fetch",getToolCallId:M,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new ae.uN({result:{case:"error",value:new ae.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class le{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,ce)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var ue=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const de={toolName:"Grep",getToolCallId:M,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new ue.Ud({result:{case:"error",value:new ue.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class pe{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,de)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var he=r("../proto/dist/generated/agent/v1/ls_exec_pb.js");const me={toolName:"List",getToolCallId:M,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new he.fv({result:{case:"rejected",value:new he.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class fe{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,me)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var ge=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),ve=r("@bufbuild/protobuf");const ye=(0,u.h)("hooks-exec:mcp");function we(e,t,r,n){try{return T({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof P)return ye.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class be{innerExecutor;hookExecutor;baseHookRequestExtractor;mcpLease;constructor(e,t,r,n){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n}async execute(e,t,r){var n,o,s,a,c,l;if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);const u=this.baseHookRequestExtractor(e),d=(0,x.randomUUID)(),p=null!==(a=null==r?void 0:r.hookContextCollector)&&void 0!==a?a:[];let h=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])));const m=`MCP:${t.toolName}`;try{const r=await this.hookExecutor.executeHookForStep(i._E.preToolUse,Object.assign(Object.assign({},u),{tool_name:m,tool_input:h,tool_use_id:d}));if("deny"===(null==r?void 0:r.permission)){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{C(p,T({hookEventName:i._E.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof P))throw t;ye.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:m,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,u,m,h,t,"permission_denied",0,d,!1,p),new ge.iz({result:{case:"permissionDenied",value:new ge.HQ({error:y("MCP tool execution",t),isReadonly:!1})}})}if(null==r?void 0:r.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))void 0!==n&&(t.args[e]=ve.Value.fromJson(n));h=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])))}catch(t){ye.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}C(p,T({hookEventName:i._E.preToolUse,additionalContext:null==r?void 0:r.additional_context}))}catch(t){const r=null!==(c=null===(o=(n=this.hookExecutor).hasFailClosedHooksForStep)||void 0===o?void 0:o.call(n,i._E.preToolUse,m))&&void 0!==c&&c,s=t instanceof P;if(r){const r=v(`${s?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,u,m,h,r,"error",0,d,!1,p),new ge.iz({result:{case:"permissionDenied",value:new ge.HQ({error:y("MCP tool execution",r),isReadonly:!1})}})}ye.warn(e,s?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",Object.assign({toolName:m,error:t instanceof Error?t.message:String(t)},s?{actualLength:t.actualLength,maxLength:t.maxLength}:{}))}const f=await(null===(s=this.mcpLease)||void 0===s?void 0:s.getClient(e,t.providerIdentifier)),g=null==f?void 0:f.config;let w;const b=g&&"url"in g&&g.url?g.url:void 0;w=void 0!==b?{url:b}:g&&"command"in g?{command:[g.command,...null!==(l=g.args)&&void 0!==l?l:[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const k=Object.assign({mcp_server_name:t.providerIdentifier},void 0!==b?{mcp_server_url:b}:{}),S=Object.assign(Object.assign(Object.assign(Object.assign({},u),{tool_name:t.toolName,tool_input:JSON.stringify(h)}),k),w),E=await this.hookExecutor.executeHookForStep(i._E.beforeMCPExecution,S);if("deny"===(null==E?void 0:E.permission)){const t=y("MCP tool execution",E.user_message);return await this.firePostToolUseFailureAsync(e,u,m,h,t,"permission_denied",0,d,!1,p),new ge.iz({result:{case:"permissionDenied",value:new ge.HQ({error:t,isReadonly:!1})}})}const R=_.performance.now();try{const n=await this.innerExecutor.execute(e,t,r),o=j(_.performance.now()-R);let s="{}";if("success"===n.result.case)try{const e=n.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));s=JSON.stringify({content:e,isError:n.result.value.isError})}catch(t){ye.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),s=JSON.stringify({error:"Failed to serialize result"})}else"error"===n.result.case?s=JSON.stringify({error:n.result.value.error}):"rejected"===n.result.case?s=JSON.stringify({rejected:!0,reason:n.result.value.reason}):"permissionDenied"===n.result.case&&(s=JSON.stringify({permissionDenied:!0,error:n.result.value.error}));const a=Object.assign(Object.assign(Object.assign({},u),{tool_name:t.toolName,tool_input:JSON.stringify(h),result_json:s,duration:o}),k);await this.hookExecutor.executeHookForStep(i._E.afterMCPExecution,a);const c=await this.firePostToolUse(e,u,m,h,s,o,d,p);if(void 0!==(null==c?void 0:c.updated_mcp_tool_output))try{const e=c.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new ge._Z({content:{case:"text",value:new ge.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new ge._Z({content:{case:"text",value:new ge.zN({text:String(e.text)})}})):t.push(new ge._Z({content:{case:"text",value:new ge.zN({text:JSON.stringify(e)})}}))}else t.push(new ge._Z({content:{case:"text",value:new ge.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new ge.iz({result:{case:"success",value:new ge.QW({content:t,isError:r})}})}catch(t){return ye.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),n}return n}catch(t){const r=j(_.performance.now()-R),n=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,u,m,h,n,"error",r,d,!1,p),t}}async firePostToolUse(e,t,r,n,o,s,a,c){try{const l=await this.hookExecutor.executeHookForStep(i._E.postToolUse,Object.assign(Object.assign({},t),{tool_name:r,tool_input:n,tool_output:o,duration:s,tool_use_id:a}));return C(c,we(e,r,i._E.postToolUse,null==l?void 0:l.additional_context)),l}catch(t){return void ye.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,a,c,l,u){try{const d=await this.hookExecutor.executeHookForStep(i._E.postToolUseFailure,Object.assign(Object.assign({},t),{tool_name:r,tool_input:n,error_message:o,failure_type:s,duration:a,tool_use_id:c,is_interrupt:l}));C(u,we(e,r,i._E.postToolUseFailure,null==d?void 0:d.additional_context))}catch(t){ye.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const ke={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new ge.kP({result:{case:"error",value:new ge.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class Se{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,ke)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Ee={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new ge.ZD({result:{case:"error",value:new ge.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class xe{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,Ee)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var _e=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Ce={toolName:"Read",getToolCallId:M,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new _e.sV({result:{case:"rejected",value:new _e.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o}=e;if("success"!==r.result.case)return;const s="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${null!=e?e:"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${m}`}(t,e instanceof Error?e.message:String(e));throw new h(r,e)}}((()=>o.executeHookForStep(i._E.beforeReadFile,Object.assign(Object.assign({},n),{content:s,file_path:t.path,attachments:[]}))),"File read");if("deny"===(null==a?void 0:a.permission)){const e=y("File read",a.user_message);throw new p(e)}}};class Pe{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,Ce)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var Re=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js");const Te={toolName:"RecordScreen",getToolCallId:M,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new Re.Tj({result:{case:"failure",value:new Re.yH({error:t})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class Ie{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,Te)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function Ae(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const je={toolName:G,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return Object.assign({command:e.command,cwd:t},"number"==typeof r&&r>0&&{timeout:r})},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new z.W4({result:{case:"rejected",value:new z.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&!0===e.result.value.aborted,createSuccessOutput:(e,t)=>({output:Ae(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"";(0,B.oA)(t,await V({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:q(t.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s}=e,a=Ae(r);await o.executeHookForStep(i._E.afterShellExecution,Object.assign(Object.assign({},n),{command:t.command,output:a,duration:s,sandbox:q(t.requestedSandboxPolicy)}))}};class Oe{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=N(e,t,r,je)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class De{output="";exitEvent;onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){var e,t;return null!==(t=null===(e=this.exitEvent)||void 0===e?void 0:e.aborted)&&void 0!==t&&t}getExitCode(){var e,t;return null!==(t=null===(e=this.exitEvent)||void 0===e?void 0:e.code)&&void 0!==t?t:0}}const Me={toolName:G,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return Object.assign({command:e.command,cwd:t},"number"==typeof r&&r>0&&{timeout:r})},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new z.FI({event:{case:"rejected",value:new z.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new z.FI({event:{case:"hookContext",value:new z.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new De,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n}=e,o=t.workingDirectory||"",s=q(t.requestedSandboxPolicy);(0,B.oA)(t,await V({hookExecutor:n,baseHookRequest:r,command:t.command,cwd:o,sandbox:s}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s}=e,a=q(t.requestedSandboxPolicy);await n.executeHookForStep(i._E.afterShellExecution,Object.assign(Object.assign({},r),{command:t.command,output:o.getOutput(),duration:s,sandbox:a}))}};class Ne{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){var a,c,l,u;const{hookContext:d,helpers:p}=O(o,s,t,r,n,i),h=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,m=await D(o,s,t,d,p,n,((e,t)=>n.createRejectedEvent(e,t)),h);if("rejected"===m.type){yield m.result;for(const e of $(n,d))yield e;return}const f=_.performance.now(),g=n.createResultCollector();let v=!1;try{for await(const t of e.execute(o,s,i))g.onEvent(t),yield t}catch(e){v=!0;const t=j(_.performance.now()-f),r=e instanceof Error?e.message:String(e);await p.fireFailureAsync(t,r,"error");for(const e of $(n,d))yield e;throw e}const y=j(_.performance.now()-f);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:d.baseHookRequest,hookExecutor:t,toolInput:p.getToolInput(),toolUseId:d.toolUseId,extraHookFields:d.extraHookFields,collector:g,executionDurationMs:y})}catch(e){I.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(!v)if(g.isAborted())await p.fireFailureAsync(y,"Command was aborted","error",!0);else if(null===(l=null===(a=n.isStreamSuccess)||void 0===a?void 0:a.call(n,g))||void 0===l||l)await p.fireSuccessAsync(y,JSON.stringify(n.createSuccessOutput(s,g)));else{const e=null!==(u=null===(c=n.getStreamErrorMessage)||void 0===c?void 0:c.call(n,s,g))&&void 0!==u?u:`Command failed with exit code ${g.getExitCode()}`;await p.fireFailureAsync(y,e,"error")}for(const e of $(n,d))yield e}}}(e,t,r,Me)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var $e=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),Le=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");class Fe{wrappedExecutor;constructor(e,t,r){const n=new Map;this.wrappedExecutor=N(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:M,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new $e.v3({result:{case:"error",value:new $e.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async e=>{const{args:r,toolUseId:n}=e;let o,s=!1;try{(await(0,a.stat)(r.path)).size>262144?s=!0:o=await(0,d.yR)(r.path)}catch(e){}t.set(n,{contentBeforeWrite:o,fileTooLarge:s})},runCleanup:e=>{t.delete(e)},runPostExecutionHooks:async r=>{const{args:n,result:o,baseHookRequest:s,toolUseId:a}=r,c=t.get(a);if("success"!==o.result.case)return;const{contentBeforeWrite:l,fileTooLarge:u}=null!=c?c:{fileTooLarge:!1};let p;p=u||void 0===l?[{old_string:"",new_string:n.fileText}]:l===n.fileText?[]:function(e,t){const r=(0,Le.YB)("","",e,t,"","",{context:0});return 0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(l,n.fileText);const h=Object.assign(Object.assign({},s),{file_path:n.path,edits:p}),m=await e.executeHookForStep(i._E.afterFileEdit,h);if(n.returnFileContentAfterWrite&&void 0!==m){const e=o.result.value.path;try{const t=await(0,d.yR)(e),r=(0,d.lt)(t),n=Buffer.byteLength(t,"utf8");return new $e.v3({result:{case:"success",value:new $e.j6(Object.assign(Object.assign({},o.result.value),{fileContentAfterWrite:t,linesCreated:r,fileSize:n}))}})}catch(e){return}}}}}(t,n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class Ue{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){var t;if(e.symbol===B.bo.symbol)return new B.gl(this.hookExecutor);const r=this.innerAccessor.get(e);return e.symbol===B.qk.symbol?new Oe(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.wv.symbol?new Ne(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.Ln.symbol?new Fe(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.Yi.symbol?new be(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease):e.symbol===B._A.symbol||e.symbol===B.Mf.symbol?new Pe(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.bL.symbol?new fe(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.u8.symbol?new pe(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.IG.symbol?new le(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.Rp.symbol?new ne(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.w4.symbol?new ie(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.rn.symbol?new Se(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.ml.symbol?new xe(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.Ok.symbol?new K(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.TQ.symbol?new Z(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.iZ.symbol?new ee(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.pq.symbol?new Ie(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.MZ.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new U(r,null!==(t=this.hooksAdditionalContextPromise)&&void 0!==t?t:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease):r}*entries(){var e;for(const[t,r]of this.innerAccessor.entries())t.symbol===B.qk.symbol?yield[t,new Oe(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.wv.symbol?yield[t,new Ne(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.Ln.symbol?yield[t,new Fe(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.Yi.symbol?yield[t,new be(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease)]:t.symbol===B._A.symbol||t.symbol===B.Mf.symbol?yield[t,new Pe(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.bL.symbol?yield[t,new fe(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.u8.symbol?yield[t,new pe(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.IG.symbol?yield[t,new le(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.Rp.symbol?yield[t,new ne(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.w4.symbol?yield[t,new ie(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.rn.symbol?yield[t,new Se(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.ml.symbol?yield[t,new xe(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.Ok.symbol?yield[t,new K(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.TQ.symbol?yield[t,new Z(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.iZ.symbol?yield[t,new ee(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.pq.symbol?yield[t,new Ie(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.MZ.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[t,new U(r,null!==(e=this.hooksAdditionalContextPromise)&&void 0!==e?e:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease)]:yield[t,r];yield[B.bo,new B.gl(this.hookExecutor)]}}var Be,He=r("../shell-exec/dist/index.js");const ze={cursor_version:null!==(Be=process.env.AGENT_CLI_STATIC_VERSION)&&void 0!==Be?Be:"1.0.0",user_email:null};function We(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>We(null!=e?e:t),async*execute(e,r,o={}){var s,a,c,l,u,d;const p=null!==(u=o.workingDirectory)&&void 0!==u?u:t;t=p;const h=function(e){return"win32"===process.platform?{executable:(0,He.oG)(),args:[...i.iY,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),m=(0,n.spawn)(h.executable,[...h.args],{cwd:p,env:Object.assign(Object.assign({},process.env),null!==(d=o.env)&&void 0!==d?d:{}),signal:o.signal,stdio:[!0===o.pipeStdin?"pipe":"ignore","pipe","pipe"]}),f=[];let g,v,y=!1;const w=()=>{null==g||g(),g=void 0},b=e=>{f.push(e),w()};for(m.on("spawn",(()=>{var e;!0===o.pipeStdin&&b({type:"stdin_ready",stdin:null!==(e=m.stdin)&&void 0!==e?e:void 0})})),null===(s=m.stdout)||void 0===s||s.setEncoding("utf8"),null===(a=m.stdout)||void 0===a||a.on("data",(e=>{b({type:"stdout",data:String(e)})})),null===(c=m.stderr)||void 0===c||c.setEncoding("utf8"),null===(l=m.stderr)||void 0===l||l.on("data",(e=>{b({type:"stderr",data:String(e)})})),m.on("error",(e=>{v=e,y=!0,w()})),m.on("close",(e=>{b({type:"exit",code:e}),y=!0}));!y||f.length>0;)0!==f.length?yield f.shift():await new Promise((e=>{g=e}));if(void 0!==v)throw v}};return r}function qe(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function Ge(e){return"string"==typeof e&&e.length>0?e:void 0}function Ve(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function Je(e){if(Array.isArray(e)&&e.every(Ve))return e.map((e=>({id:e.id,value:e.value})))}class Ke{innerAccessor;sessionHooksRuntime;constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ye(e,t={}){const r=await new S(new L,function(e,t){var r,n,i,a,c;const l=null!==(n=null!==(r=e.projectRoot)&&void 0!==r?r:e.workingDirectory)&&void 0!==n?n:e.workspaceRoots[0],u=null===(i=t.includeProjectHooks)||void 0===i||i,d=null===(a=t.includeUserHooks)||void 0===a||a;return{enterpriseConfigPath:null===(c=t.includeEnterpriseHooks)||void 0===c||c?k():void 0,userConfigPath:d?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:d?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:u&&void 0!==l?(0,s.join)(l,".cursor","hooks.json"):void 0,claudeProjectConfigPath:u&&void 0!==l?(0,s.join)(l,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:u&&void 0!==l?(0,s.join)(l,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new E(r),a=function(e){var t,r,n;return null!==(n=null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workingDirectory)&&void 0!==r?r:e.workspaceRoots[0])&&void 0!==n?n:process.cwd()}(e),c=function(e){var t;return Object.freeze(Object.assign(Object.assign({},ze),null!==(t=e.globalContext)&&void 0!==t?t:{}))}(t);return{projectDir:e.projectRoot,workspacePath:a,hooksConfig:r,hooksConfigLease:n,globalContext:c,createSessionRuntime(){var e;const o=new b(r,a,c,(null!==(e=t.createTerminalExecutor)&&void 0!==e?e:We)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(0,i.S6)(t.useCommandHookStdinTransport)});return{hookExecutor:o,hooksConfigLease:n,async dispose(){o.clearSessionEnvironment()}}},async dispose(){}}}function Ze(e={}){return{createHooksRuntime:t=>Ye(t.workspaceState,e)}}function Xe(){return{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!("object"==typeof(r=t)&&null!==r&&"hooksConfigLease"in r&&"createSessionRuntime"in r&&"function"==typeof r.createSessionRuntime&&function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources)))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new Ke(new Ue(e.resources,n.hookExecutor,(()=>function(e,t){var r,n,o,s;const a=null!==(n=null!==(r=qe(t,Ge,"conversationId","conversation_id"))&&void 0!==r?r:e.sessionId)&&void 0!==n?n:"",c=null!==(o=qe(t,Ge,"generationId","generation_id"))&&void 0!==o?o:a,l=null!==(s=qe(t,Ge,"model"))&&void 0!==s?s:"unknown",u=qe(t,Ge,"modelId","model_id"),d=qe(t,Je,"modelParams","model_params");return Object.assign({conversation_id:a,generation_id:c,model:l},(0,i.U4)({modelId:u,modelParams:d}))}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}}},"../cursor-sdk-local-runtime/dist/core/index.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{$r:()=>o.sP,GG:()=>o.GG,Ob:()=>l.Ob,Pq:()=>s.Pq,T9:()=>c.T,VR:()=>a.V,sP:()=>i.s,ue:()=>l.ue,vk:()=>s.vk});var o=r("../cursor-sdk-local-runtime/dist/core/cursor-config-mcp.js"),s=r("../cursor-sdk-local-runtime/dist/core/hooks-runtime.js"),i=r("../cursor-sdk-local-runtime/dist/core/local-extensibility.js"),a=r("../cursor-sdk-local-runtime/dist/core/local-plugins-bootstrap.js"),c=r("../cursor-sdk-local-runtime/dist/core/local-resource-provider.js"),l=(r("../cursor-sdk-local-runtime/dist/core/runtime-state.js"),r("../cursor-sdk-local-runtime/dist/core/session-runtime.js"),r("../cursor-sdk-local-runtime/dist/core/setting-sources.js")),u=r("../cursor-sdk-local-runtime/dist/core/workspace-runtime.js"),d=e([o,u]);[o,u]=d.then?(await d)():d,n()}catch(e){n(e)}}))},"../cursor-sdk-local-runtime/dist/core/local-extensibility.js"(e,t,r){r.d(t,{s:()=>p});var n=r("node:fs/promises"),o=r("node:os"),s=r("../context/dist/index.js"),i=r("../local-exec/dist/index.js"),a=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js"),c=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),l=r("@connectrpc/connect"),u=r("../cursor-sdk-local-runtime/dist/disposable.js"),d=r("../cursor-sdk-local-runtime/dist/core/plugin-bootstrap-types.js");function p(e={}){var t,r,n,p,f,g;const v=null!==(t=e.getThirdPartyExtensibilityEnabled)&&void 0!==t?t:()=>!0,y=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,b=null===(n=e.includeProjectExtensibility)||void 0===n||n,k=null===(p=e.includeUserExtensibility)||void 0===p||p,S=null===(f=e.includeManagedSkills)||void 0===f||f,E=null===(g=e.includePluginExtensibility)||void 0===g||g,x=new i.xK,_=(0,o.homedir)(),C=(0,i.c$)(_).dirPath;let P,R=!0;return{async prepareLocalExtensibility(){R=S&&await async function(e){if(!e)return!1;const t=(0,l.createClient)(a.I,e),r=await(0,i.W3)((0,s.q6)(),{getManagedSkills:async()=>{var e;return null!==(e=(await t.getManagedSkills(new c.X8g({}))).skills)&&void 0!==e?e:[]}});return"synced"===r.status}(e.dashboardTransport)},async loadLocalExtensibility(t){var r,n;const o=t.workspaceState,a=null!==(r=o.projectRoot)&&void 0!==r?r:o.workingDirectory;if(!a)return P=void 0,{cursorRulesService:w(),getAgentSkills:async e=>[]};const c=(0,s.q6)(),l=null===(n=e.loadNestedRules)||void 0===n||n,u=function(e,t){const r=h(t);return{getAllCursorRules:async t=>m(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(b?new i.KO(c,x,a,l,v,void 0):w(),{allowedRoots:b?[a]:[],excludedRoots:[]}),p=function(e,t){const r=h(t);return{getAllCursorRules:async t=>m(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>m(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new i.EV(c,b?[a]:[],_,x,l,void 0,v,Promise.resolve(),"sdk"),{allowedRoots:[...b?[a]:[],...k?[_]:[],...R?[C]:[]],excludedRoots:R?[]:[C]}),f=b?new i.Vz(a,v):new i.Kp,g=(0,d.CD)(t.services.pluginBootstrapOutputs),S=g&&E?new i.Rx(c,(()=>({importThirdPartyPlugins:y})),void 0,g.pluginsService):void 0,T=g&&E?new i._J((()=>({importThirdPartyPlugins:y})),g.pluginsService):void 0,I=new i.Px([u,p,...S?[S]:[]]),A=new i.NB([p,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:b?[a]:[],userHomeDirectory:_}))),j=new i.o_([f,...T?[T]:[]]);return P={localRulesService:u,localSkillsService:p,localSubagentsService:f,pluginSkillsService:S,pluginSubagentsService:T,mergedCursorRulesService:I,mergedAgentSkillsService:A,mergedSubagentsService:j},{cursorRulesService:I,getAgentSkills:e=>A.getAllAgentSkills(e),subagentsService:j}},async disposeLocalExtensibility(){if(!P)return;const e=P;P=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await(0,u.v)(e)}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}(e)}}}function h(e){const t=Promise.all(e.allowedRoots.map(v)),r=Promise.all(e.excludedRoots.map(v));return async e=>{const[n,o,s]=await Promise.all([y(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>f(n,e)))&&o.some((e=>f(n,e)))}}async function m(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function f(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function g(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function v(e){try{return g(await(0,n.realpath)(e))}catch(t){return g(e)}}async function y(e){try{return g(await(0,n.realpath)(e))}catch(e){return}}function w(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}},"../cursor-sdk-local-runtime/dist/core/local-plugins-bootstrap.js"(e,t,r){r.d(t,{V:()=>p});var n=r("node:os"),o=r("node:path"),s=r("../cursor-plugins/dist/index.js"),i=r("../local-exec/dist/index.js"),a=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js"),c=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),l=r("@connectrpc/connect"),u=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),d=r("../cursor-sdk-local-runtime/dist/core/plugin-bootstrap-types.js");function p(e={}){var t,r,p,m;const f=null!==(t=e.userHomeDirectory)&&void 0!==t?t:(0,n.homedir)(),g=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,v=null!==(p=e.pluginLogger)&&void 0!==p?p:{log(e,t,r){switch(e){case"warn":u.Jz.warn("[local-plugins-bootstrap]",t,null!=r?r:{});break;case"error":u.Jz.error("[local-plugins-bootstrap]",t,null!=r?r:{})}},increment(){},distribution(){},captureException(e,t){u.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,null!=t?t:{})}},y=h(e.marketplaceOptions),w=void 0!==e.dashboardTransport,b=null!==(m=e.loadCursorFirstParty)&&void 0!==m?m:y||w;return{async loadPluginBootstrapOutputs(t){var r;const n=function(e){var t,r;return null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workspaceRoots[0])&&void 0!==r?r:e.workingDirectory}(t.workspaceState),{discoveredEntries:p,failures:m}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await(0,s.i3)(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(n),y=null!==(r=e.marketplaceOptions)&&void 0!==r?r:e.dashboardTransport?function(e){const t=(0,o.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,l.createClient)(a.I,e.dashboardTransport),n=(0,s.Nw)((async()=>{try{return await r.getEffectiveUserPlugins(new c.EwF({}))}catch(e){return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),i=e.workspacePath,u=(0,s.Nw)((async()=>{var e,t;if(void 0===i)return{plugins:[]};try{const n=await(0,s.i3)(i);if(0===n.length)return{plugins:[]};const o=n.filter((e=>e.entry.gitUrl)),a=n.filter((e=>!e.entry.gitUrl)),l=o.filter((({entry:e})=>{const t=e.gitUrl;return!t||(0,s.QY)(t)})).map((({key:e,entry:t})=>{const r=(0,s.kX)(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let u=[];if(a.length>0)try{const n=a.map((e=>{const t=(0,s.kX)(e.key);return new c.vwy({name:t.name,marketplaceName:t.marketplaceName})}));u=null!==(t=null===(e=(await r.resolvePluginsByRef(new c.WvV({refs:n}))).plugins)||void 0===e?void 0:e.map((e=>({plugin:e,isEnabled:!0}))))&&void 0!==t?t:[]}catch(e){}return{plugins:[...l,...u]}}catch(e){return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new s.WC(e.userHomeDirectory),pruneOldVersions:!0},{client:u,userId:"",cacheManager:new s.WC(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:n,userHomeDirectory:f}):void 0,w=h(y),k=new i.Np(void 0!==n?[n]:[],f,(()=>({importThirdPartyPlugins:g,loadCursorFirstParty:b})),y,v);let S=[];const E=[...m];try{S=await k.getAllEnabledPlugins()}catch(e){E.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}p.length>0&&!w&&E.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:n,discoveredEntryCount:p.length}});const x={kind:d.hS,discoveredEntries:p,loadedPlugins:S,loadFailures:k.getLoadFailures(),bootstrapFailures:E,pluginsService:k,async dispose(){}};for(const e of E)u.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:n,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of x.loadFailures)u.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:n,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[x]}}}function h(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}},"../cursor-sdk-local-runtime/dist/core/local-resource-provider.js"(e,t,r){r.d(t,{T:()=>c});var n=r("../local-exec/dist/index.js"),o=r("../mcp-agent-exec/dist/index.js"),s=r("../cursor-sdk-local-runtime/dist/disposable.js");class i{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}class a extends n.Dv{sessionMcpLease;constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await(0,s.v)(this.sessionMcpLease)}}}function c(e){const t=new n.xK;return{async createResources(r){var c,l,u,d,p,h,m,f;const g=null!==(u=null===(c=e.createSessionDependencies)||void 0===c?void 0:c.call(e,r))&&void 0!==u?u:{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!g.pendingDecisionStore||!g.fileChangeTracker||!g.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const v=null!==(d=r.workspaceServices.cursorRulesService)&&void 0!==d?d:new i,y=null!==(p=r.workspaceServices.subagentsService)&&void 0!==p?p:new n.Kp,w=null!==(h=r.workspaceServices.mcpLease)&&void 0!==h?h:new o.LK,b=void 0!==r.options.mcpServersOverride&&void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):void 0,k=null!=b?b:w,S=(0,n.jM)(k,null!==(m=r.options.extraMcpTools)&&void 0!==m?m:[]);try{const o={pendingDecisionStore:g.pendingDecisionStore,fileChangeTracker:g.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:g.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:S,mcpStateAccessor:null===(l=e.createMcpStateAccessor)||void 0===l?void 0:l.call(e,S),cursorRulesService:v,subagentsService:y,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:null!==(f=e.defaultSandboxPolicy)&&void 0!==f?f:{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills};return void 0===b?new n.Dv(o):new a(o,b)}catch(e){throw await(0,s.v)(b),e}}}}},"../cursor-sdk-local-runtime/dist/core/plugin-bootstrap-types.js"(e,t,r){r.d(t,{CD:()=>o,hS:()=>n});const n="cursor-plugins/local";function o(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===n)return r}},"../cursor-sdk-local-runtime/dist/core/runtime-state.js"(e,t,r){r.d(t,{P:()=>u,Q:()=>l});var n=r("../cursor-sdk-local-runtime/dist/disposable.js");const o=["cursorRulesService","getAgentSkills","subagentsService"],s=new WeakSet;function i(e){("object"==typeof e&&null!==e||"function"==typeof e)&&s.add(e)}function a(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&s.has(e)}function c(e,t){const r=Object.keys(t).filter((e=>!o.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${o.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of o)Object.hasOwn(t,r)&&(e[r]=t[r])}async function l(e,t,r){var n,o,s;const a={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{a.config=e.config?await e.config.loadConfig(t):void 0,a.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:a});a.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):a.pluginBootstrapOutputs,a.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,a.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,(null===(n=e.localExtensibility)||void 0===n?void 0:n.prepareLocalExtensibility)&&await e.localExtensibility.prepareLocalExtensibility(o());const l=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==l&&(i(l.cursorRulesService),i(l.subagentsService),Object.assign(a,l));for(const t of null!==(s=e.workspaceServicesContributors)&&void 0!==s?s:[]){const e=await t.contributeServices(o());void 0!==e&&c(a,e)}return a}catch(t){try{await u(a,{disposeLocalExtensibility:null===(o=e.localExtensibility)||void 0===o?void 0:o.disposeLocalExtensibility})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function u(e,t){const r=null==t?void 0:t.preserveSharedContributorsFrom;let o;const s=async e=>{try{await(0,n.v)(e)}catch(e){null!=o||(o=e)}};if(e.subagentsService===(null==r?void 0:r.subagentsService)||a(e.subagentsService)||await s(e.subagentsService),e.cursorRulesService===(null==r?void 0:r.cursorRulesService)||a(e.cursorRulesService)||await s(e.cursorRulesService),null==t?void 0:t.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){null!=o||(o=e)}await s(e.hooksRuntime),await s(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await(0,n.v)(e[r])}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){null!=o||(o=e)}if(void 0!==o)throw o}},"../cursor-sdk-local-runtime/dist/core/session-runtime.js"(e,t,r){r.d(t,{$:()=>i});var n=r("node:crypto?8af2"),o=r("../cursor-sdk-local-runtime/dist/disposable.js");async function s(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const s=e[n];if(!t.has(s)){t.add(s);try{await(0,o.v)(s)}catch(e){null!=r||(r=e)}}}if(void 0!==r)throw r}async function i(e){var t,r,o,i,a,c,l,u;const d={sessionId:null!==(a=null===(t=e.options)||void 0===t?void 0:t.sessionId)&&void 0!==a?a:(0,n.randomUUID)(),createdAt:new Date},p=Object.freeze(Object.assign({},null!==(c=null===(r=e.options)||void 0===r?void 0:r.metadata)&&void 0!==c?c:{})),h={options:null!==(l=e.options)&&void 0!==l?l:{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:d,metadata:p,getAgentSkills:e.workspaceServices.getAgentSkills};let m,f;const g=[];try{m=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(h):void 0,f=m,g.push(m);for(const t of null!==(u=e.adapters.resourceWrappers)&&void 0!==u?u:[])f=await t.wrapResources(Object.assign(Object.assign({},h),{baseResources:m,resources:f})),g.push(f);await(null===(i=null===(o=e.adapters.lifecycle)||void 0===o?void 0:o.onSessionCreated)||void 0===i?void 0:i.call(o,d))}catch(e){try{await s(g)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let v=!1;return{state:d,resources:{base:m,wrapped:f},metadata:p,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){var t,r;if(!v){v=!0;try{await s(g)}finally{await(null===(r=null===(t=e.adapters.lifecycle)||void 0===t?void 0:t.onSessionDisposed)||void 0===r?void 0:r.call(t,d))}}}}}},"../cursor-sdk-local-runtime/dist/core/setting-sources.js"(e,t,r){r.d(t,{Ob:()=>s,ue:()=>i});const n=["project","user","team","mdm","plugins"],o=new Set([...n,"all"]);function s(e){if(void 0===e||0===e.length)return a([]);for(const t of e)if(!o.has(t))throw new Error(`Unsupported setting source "${String(t)}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return Object.assign(Object.assign({},a(n)),{all:!0})}return a(e)}function i(e,t){return e[t]}function a(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}},"../cursor-sdk-local-runtime/dist/core/workspace-runtime.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{c:()=>u});var o=r("../cursor-sdk-local-runtime/dist/adapters/index.js"),s=r("../cursor-sdk-local-runtime/dist/policy/index.js"),i=r("../cursor-sdk-local-runtime/dist/core/runtime-state.js"),a=r("../cursor-sdk-local-runtime/dist/core/session-runtime.js"),c=e([o]),l=c.then?(await c)():c;async function u(e={}){var t,r;const n=(0,o.H)(e.adapters),c=await n.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),l=await(0,s.Zp)(null!==(r=e.policyAdapter)&&void 0!==r?r:(0,s.hx)(),{workspaceState:c});let u=await(0,i.Q)(n,c,l),d=!1,p=Promise.resolve();const h=e=>{const t=p.then(e);return p=t.catch((()=>{})),t},m=null===(t=n.localExtensibility)||void 0===t?void 0:t.disposeLocalExtensibility;return{state:c,get services(){return u},policy:l,async createSessionRuntime(e={}){if(d)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return(0,a.$)({options:e,workspaceState:c,workspaceServices:u,policy:l,adapters:n})},async reload(){d||await h((async()=>{var e,t;if(d)return;const r=u,o=await(0,i.Q)(n,c,l);d?await(0,i.P)(o,{disposeLocalExtensibility:m}):(u=o,await(0,i.P)(r,{preserveSharedContributorsFrom:o,disposeLocalExtensibility:m}),await(null===(t=null===(e=n.lifecycle)||void 0===e?void 0:e.onWorkspaceReload)||void 0===t?void 0:t.call(e,c)))}))},async dispose(){d||(d=!0,await h((async()=>{var e;try{await(0,i.P)(u,{disposeLocalExtensibility:m})}finally{await(null===(e=n.lifecycle)||void 0===e?void 0:e.dispose())}})))}}}o=l[0],n()}catch(d){n(d)}}))},"../cursor-sdk-local-runtime/dist/disposable.js"(e,t,r){async function n(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}r.d(t,{v:()=>n})},"../cursor-sdk-local-runtime/dist/index.js"(e,t,r){r.a(e,(async(e,n)=>{try{r.d(t,{Bq:()=>s.Bq,GG:()=>i.GG,O:()=>s.O,Ob:()=>i.Ob,Oh:()=>s.Oh,ni:()=>a.ni,vW:()=>s.vW,xK:()=>s.xK});var o=r("../cursor-sdk-local-runtime/dist/adapters/index.js"),s=r("../cursor-sdk-local-runtime/dist/agent-host/index.js"),i=r("../cursor-sdk-local-runtime/dist/core/index.js"),a=(r("../cursor-sdk-local-runtime/dist/policy/index.js"),r("../cursor-sdk-local-runtime/dist/utils/index.js")),c=e([o,s,i]);[o,s,i]=c.then?(await c)():c,n()}catch(e){n(e)}}))},"../cursor-sdk-local-runtime/dist/policy/index.js"(e,t,r){r.d(t,{hx:()=>s,Zp:()=>i});const n=Object.freeze({}),o=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:n});function s(e={}){const t=Object.freeze(Object.assign(Object.assign({},o.metadata),e.metadata)),r=Object.assign(Object.assign(Object.assign({},o),e),{metadata:t});return{name:"permissive-sdk-local",resolvePolicy:()=>r}}async function i(e,t){return e.resolvePolicy(t)}},"../cursor-sdk-local-runtime/dist/utils/index.js"(e,t,r){r.d(t,{ni:()=>n.ni});var n=r("../cursor-sdk-local-runtime/dist/utils/logger.js")},"../cursor-sdk-local-runtime/dist/utils/logger.js"(e,t,r){r.d(t,{Jz:()=>c,ni:()=>i});var n=r("node:async_hooks?2c30");let o={warn:console.warn.bind(console),error:console.error.bind(console)};const s=new n.AsyncLocalStorage;function i(e,t){return s.run(e,t)}function a(){var e;return null!==(e=s.getStore())&&void 0!==e?e:o}const c={warn(...e){a().warn(...e)},error(...e){a().error(...e)}}},"../hooks/dist/index.js"(e,t,r){r.d(t,{yB:()=>C,aX:()=>P,LQ:()=>I,Qu:()=>_,_E:()=>n,iY:()=>X,q3:()=>Q,D3:()=>z,FS:()=>H,fp:()=>f,eg:()=>h,bi:()=>g,Qk:()=>v,Uv:()=>B,S6:()=>Z,Vf:()=>U,DP:()=>m,Xz:()=>T,uu:()=>R,yW:()=>M,wb:()=>L,x9:()=>q,U4:()=>x,sl:()=>p,jO:()=>j,RV:()=>re});const n={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},o={PreToolUse:n.preToolUse,PermissionRequest:null,PostToolUse:n.postToolUse,UserPromptSubmit:n.beforeSubmitPrompt,Stop:n.stop,SubagentStop:n.subagentStop,SessionStart:n.sessionStart,SessionEnd:n.sessionEnd,PreCompact:n.preCompact,Notification:null},s=Object.fromEntries(Object.entries(o).filter((e=>null!==e[1])).map((([e,t])=>[t,e]))),i={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},a=["Glob"],c=["Notification","PermissionRequest"],l={warn:()=>{},info:()=>{}};function u(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?Object.assign({type:"prompt",prompt:e.prompt},r):null:e.command?Object.assign({type:"command",command:e.command},r):null}function d(e,t,r=l){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=l){if(""===e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=i[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):a.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=u(t,o);e&&n.push(e)}return n}function p(e,t=l){const r={};for(const[n,s]of Object.entries(e)){const e=n;if(c.includes(e)){t.warn(`Claude Code event "${e}" is not supported in Cursor and will be ignored`);continue}const i=o[e];if(!i){t.warn(`Unknown Claude Code event "${e}", skipping`);continue}const a=[];if(Array.isArray(s))for(const r of s){const n=d(r,e,t);a.push(...n)}else void 0!==s&&t.warn(`Claude Code event "${e}" has invalid value (expected array), skipping`);if(a.length>0){const e=r[i]||[];r[i]=[...e,...a]}}return{version:1,hooks:r}}function h(e){return e.hooks}function m(e,t={}){if("object"!=typeof e||null===e)return!1;if(!("hooks"in e))return!1;const r=e.hooks;if("object"!=typeof r||null===r)return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in o&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if("object"==typeof e&&null!==e&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}function f(e){if("object"!=typeof e||null===e)return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if("object"!=typeof t||null===t)continue;const r=t;if("hooks"in r&&Array.isArray(r.hooks))return"claude-code";if("command"in r||"prompt"in r||"type"in r)return"cursor"}return"unknown"}function g(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return t.command||void 0;case"beforeMCPExecution":case"afterMCPExecution":{const e=t;return e.tool_name?`MCP:${e.tool_name}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return t.subagent_type||void 0;case"preToolUse":case"postToolUse":case"postToolUseFailure":return t.tool_name||void 0;default:return}}function v(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch(e){return!0}}(e,t)))}const y=e=>"string"==typeof e,w=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),b=(e,t=[])=>({isValid:e,errors:t});function k(e,t,r){void 0===e||y(e)||r.push(`${t} must be a string if provided`)}const S=e=>{const t=[];return w(e)?b(!0):(t.push("Expected an object"),b(!1,t))},E=e=>{const t=[],r=S(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),b(0===t.length,t)};function x(e){const t=e.modelId,r=e.modelParams;return Object.assign(Object.assign({},void 0!==t&&{model_id:t}),void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{})}const _=new Set([n.sessionStart,n.beforeSubmitPrompt,n.preToolUse,n.postToolUse,n.postToolUseFailure]),C=60,P=5;function R(e){return"prompt"===e.type}function T(e){return"command"===e.type||void 0===e.type}const I=2,A={[n.beforeShellExecution]:E,[n.beforeMCPExecution]:E,[n.afterShellExecution]:e=>{const t=S(e);return t.isValid,t},[n.afterMCPExecution]:e=>{const t=S(e);return t.isValid,t},[n.beforeReadFile]:e=>{const t=[],r=S(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),b(0===t.length,t)},[n.afterFileEdit]:e=>{const t=S(e);return t.isValid,t},[n.beforeTabFileRead]:e=>{const t=[],r=S(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),b(0===t.length,t)},[n.afterTabFileEdit]:e=>S(e),[n.beforeSubmitPrompt]:e=>{const t=S(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||y(e.additional_context)||r.push("additional_context must be a string if provided"),b(0===r.length,r)},[n.stop]:e=>{const t=S(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),b(0===r.length,r)},[n.afterAgentResponse]:e=>{const t=S(e);return t.isValid,t},[n.afterAgentThought]:e=>{const t=S(e);return t.isValid,t},[n.sessionStart]:e=>{const t=S(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(w(e.env))for(const[t,n]of Object.entries(e.env))y(t)||r.push(`env key "${t}" must be a string`),y(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||y(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||y(e.user_message)||r.push("user_message must be a string if provided"),b(0===r.length,r)},[n.sessionEnd]:e=>{const t=S(e);return t.isValid?b(!0,[]):t},[n.preCompact]:e=>{const t=S(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return b(!0,[]);const r=[];if(!w(e))return r.push("PreCompact response must be an object"),b(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),b(0===r.length,r)},[n.subagentStart]:e=>{const t=S(e);if(!t.isValid)return t;const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||y(n.user_message)||r.push("user_message must be a string if provided"),b(0===r.length,r)},[n.subagentStop]:e=>{const t=S(e);if(!t.isValid)return t;const r=[];return void 0!==e&&"object"==typeof e&&null!==e&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),b(0===r.length,r)},[n.preToolUse]:e=>{const t=[],r=S(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),k(e.additional_context,"additional_context",t),b(0===t.length,t)},[n.postToolUse]:e=>{const t=[],r=S(e);return r.isValid?(k(e.additional_context,"additional_context",t),b(0===t.length,t)):r},[n.postToolUseFailure]:e=>{const t=S(e);if(!t.isValid)return t;const r=[];return k(e.additional_context,"additional_context",r),b(0===r.length,r)},[n.workspaceOpen]:e=>{const t=S(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{y(e)?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),b(0===r.length,r)}},j=(e,t,r)=>{const o=function(e,t,r){let o;return o=e===n.preToolUse?function(e,t){if(!V(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!G(t))return r;const n=J(e);if(!K(n,"PreToolUse"))return r;const o=Object.assign({},r);let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),V(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===n.stop?Y(t,r,"Stop"):e===n.subagentStop?Y(t,r,"SubagentStop"):t,function(e,t,r,n){var o;if(!_.has(e)||!V(r)||void 0!==r.additional_context)return r;const i=V(t)?null!==(o=function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t))&&void 0!==o?o:function(e,t,r){if(!G(r))return;const n=s[e];if(void 0===n)return;const o=J(t);return K(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===i?r:Object.assign(Object.assign({},r),{additional_context:i})}(e,t,o,r)}(e,t,r),i=(0,A[e])(o);return i.isValid?{success:!0,data:o}:{success:!1,errors:i.errors}},O=[n.beforeShellExecution,n.beforeMCPExecution,n.beforeReadFile,n.beforeTabFileRead,n.subagentStart,n.preToolUse],D=[n.workspaceOpen];function M(e){return D.includes(e)}function N(e,t){const r=[];return(null==e?void 0:e.trim())&&r.push(e.trim()),(null==t?void 0:t.trim())&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function $(e,t){if(e||t)return Object.assign(Object.assign({},e||{}),t||{})}function L(e,t){var r;if(0===t.length)return;if(1===t.length)return t[0];const o=O.includes(e),s=e===n.sessionStart,i=e===n.workspaceOpen,a=_.has(e),c={};for(const e of t){const t=e;for(const[e,n]of Object.entries(t))if(void 0!==n)if(i&&"pluginPaths"===e&&Array.isArray(n)){const t=null!==(r=c[e])&&void 0!==r?r:[],o=new Set(t),s=[...t];for(const e of n)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=n,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?a&&"additional_context"===e&&"string"==typeof n?c[e]=N(c[e],n):"continue"!==e||"boolean"!=typeof n?c[e]=s&&"env"===e&&"object"==typeof n&&null!==n?$(c[e],n):n:void 0===c[e]?c[e]=n:c[e]=c[e]&&n:c[e]=N(c[e],n)}var l,u;return c}function F(e){return O.includes(e)}function U({step:e,command:t,failClosed:r,kind:n}){const o=F(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:H(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function B(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}function H(e,t){return F(e)?{permission:"deny",user_message:t}:e===n.beforeSubmitPrompt||e===n.sessionStart?{continue:!1,user_message:t}:e===n.stop?{}:void 0}function z(e){return F(e)?{permission:"allow"}:e===n.beforeSubmitPrompt||e===n.sessionStart?{continue:!0}:e===n.stop?{}:void 0}function W(e){try{return{value:JSON.parse(e)}}catch(e){return}}function q(e){const t=e.trim();if(0===t.length)return;const r=W(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=W(t.slice(e));if(void 0!==r)return r.value}}function G(e){var t;return null!==(t=null==e?void 0:e.enableClaudeNestedHookSpecificOutputCompatibility)&&void 0!==t&&t}function V(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function J(e){if(!V(e))return;const t=e.hookSpecificOutput;return V(t)?t:void 0}function K(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function Y(e,t,r){if(!V(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return Object.assign(Object.assign({},n),{followup_message:n.reason.trim()});if(!G(t))return n;const o=J(e),s=K(o,r)?o:void 0,i=void 0!==s?Object.assign(Object.assign({},n),s):n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?Object.assign(Object.assign({},i),{followup_message:i.reason.trim()}):n}function Z(e){return!0===e?"stdin":"legacy"}const X=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function Q(e,t){const r=e.replace(/'/g,"''"),n=function(e){const t=e.trimStart();if(0===t.length)return e;if(t.startsWith("&"))return e;const r=t.charAt(0);return"'"===r||'"'===r?`& ${e}`:e}(t);return`$OutputEncoding = [System.Text.Encoding]::UTF8; Get-Content -LiteralPath '${r}' -Raw | & { $input | ${n} }`}const ee=e=>{const t=[];if(!w(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),b(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{y(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(y(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{y(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{var r;if(void 0!==e.matcher)if(y(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(n){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${null!==(r=null==n?void 0:n.message)&&void 0!==r?r:String(n)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),b(0===t.length,t)},te=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),b(!1,r);for(let n=0;n<e.length;n++){const o=ee(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return b(0===r.length,r)},re=e=>{const t=[];if(!w(e))return t.push("Hooks config must be an object"),b(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!w(e.hooks))return t.push("Config hooks must be an object"),b(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(n),o=e.hooks;for(const[e,n]of Object.entries(o))if(r.includes(e)){if(void 0!==n){const r=te(n,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return b(0===t.length,t)}},"../local-exec/dist/index.js"(e,t,r){r.d(t,{EV:()=>tt,w:()=>ta,zM:()=>ea,Rx:()=>nt,_J:()=>mt,$1:()=>ur,kh:()=>Yi,E1:()=>ye,KO:()=>et,xK:()=>hr,gR:()=>wi,Np:()=>ki,Dv:()=>Ks,Vz:()=>dt,NB:()=>ri,Px:()=>Qe,o_:()=>ht,Kp:()=>st,S5:()=>er,Zc:()=>vs,jM:()=>ir,mA:()=>ds,W3:()=>vi,ky:()=>de,c$:()=>je,_5:()=>Fr});var n=r("node:fs/promises"),o=r("node:path"),s=r("node:buffer?4cd4"),i=r("node:fs"),a=r("../agent-exec/dist/index.js"),c=r("../context/dist/index.js"),l=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),u=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),d=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),p=r("../utils/dist/index.js");const h="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",m="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",f=/\$\(|`|<\(|>\(/,g=/[;&|]/;let v,y,w,b;function k(){if(void 0===v){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();v=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return v}function S(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function E(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function x(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function _(){if(void 0===b){const e=(process.env[h]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${h} (expected "allow" or "deny"); using "deny".`);const r=E("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[m]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=E(m)),b={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:E("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:x("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return b}function C(e,t,r={}){const n=[S(e),S(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function P(e,t){const r=function(){const e=_();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===y&&(y=C("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),y);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(f.test(e))return r;const s=(void 0===w&&(w=C("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),w);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||g.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=_();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}var R=r("../proto/dist/generated/agent/v1/sandbox_pb.js"),T=r("../shell-exec/dist/index.js");function I(e){if(!e)return;let t;return"allow"===e.default?t=R.h1.ALLOW:"deny"===e.default&&(t=R.h1.DENY),new R.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new R.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function A(e){const t=function(e){if(!e)return;const t={};if(void 0!==e.version&&(t.version=e.version),void 0!==e.defaultAction)switch(e.defaultAction){case R.h1.ALLOW:t.default="allow";break;case R.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,T.T6)():(0,T.Po)())}function j(e){if(!e)return{type:"insecure_none"};switch(e.type){case R.vc.INSECURE_NONE:case R.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case R.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:A(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};case R.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:A(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};default:return{type:"insecure_none"}}}function O(e){if(e)return"insecure_none"===e.type?new R.Mw({type:R.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new R.Mw({type:R.vc.WORKSPACE_READWRITE,networkAccess:(0,T.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:I(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):"workspace_readonly"===e.type?new R.Mw({type:R.vc.WORKSPACE_READONLY,networkAccess:(0,T.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:I(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):new R.Mw({type:R.vc.INSECURE_NONE})}async function D(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function M(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}var N=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $=(0,c.h)("local-exec:background-shell");function L(e,t,r){return"permissionsConfig"===r.type&&r.isReadonly?new l.Lt({result:{case:"permissionDenied",value:new u.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new l.Lt({result:{case:"rejected",value:new u.pZ({command:e,workingDirectory:t,reason:M(r)})}})}class F{id;abortController;disposed=!1;completed=!1;completionListeners=[];completion;stdin;pid;constructor(e,t){this.id=e,this.abortController=t}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function U(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function B(e){e().catch((()=>{}))}const H=65536;class z{args;regex;limit;carryover="";matchedOccurrences=0;emittedNotifications=0;pendingBatch;flushTimer;finished=!1;constructor(e){if(this.args=e,this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=d.L3.compile(e.config.pattern,d.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>H){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=H)this.observe(e.slice(t,t+H));return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrences<this.limit&&n.find();){const e=n.group()??"";n.end()>t&&this.queueMatch(e)}this.carryover=r.slice(-1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer())}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${i.slice(0,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}})}}class W{innerFactory;projectDir;backgroundWorkRegistry;constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n){if(!this.backgroundWorkRegistry||!n)return;if(0===n.pattern.trim().length)return;const s=o.join(this.projectDir,"terminals",`${t}.txt`);try{return new z({shellId:t,outputPath:s,config:n,conversationId:r??a.sn,registry:this.backgroundWorkRegistry})}catch(r){return void(void 0!==e&&$.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class q{async spawn(e,t){const r=new AbortController,n=new F(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){}return B((()=>U(n,o))),n}async adopt(e){const t=new F(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,B((()=>U(t,e.eventIterator))),t}}function G(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function V(e){const t=String(e.runningForMs).padEnd(9," ");let r="---\n";return void 0!==e.pid&&0!==e.pid&&(r+=`pid: ${e.pid}\n`),r+=`cwd: ${G(e.cwd)}\n`,r+=`command: ${G(e.command)}\n`,r+=`started_at: ${e.startedAt}\n`,r+=`running_for_ms: ${t}\n`,r+="---\n",r}class J{innerFactory;projectDir;constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=o.join(this.projectDir,"terminals");await(0,n.mkdir)(r,{recursive:!0});const s=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,s)}createLoggingExecutor(e,t,r){const a=e.execute.bind(e);return{...e,execute:async function*(e,c){let l,u,d,p=!1,h=!1;const m=Date.now(),f=new Date(m).toISOString();let g;const v=async e=>{if(u)try{await u.write(e)}catch(e){}},y=t.shellId,w=o.join(r,`${y}.txt`),b=()=>{void 0!==d&&(clearInterval(d),d=void 0)},k=async e=>{if(h)return;h=!0,g=e;const r=Date.now()-m,o=V({pid:e,cwd:t.workingDirectory,command:t.command,startedAt:f,runningForMs:r});await(0,n.writeFile)(w,o,"utf8"),d=setInterval((()=>{(async()=>{if(!l)return;const e=Date.now()-m,r=V({pid:g,cwd:t.workingDirectory,command:t.command,startedAt:f,runningForMs:e});try{await l.write(r,0,"utf8")}catch(e){}})()}),5e3)},S=async()=>{l||(l=await i.promises.open(w,"r+")),u||(u=await i.promises.open(w,"a"))};try{for await(const t of a(e,c)){if("stdout"===t.type)h||(await k(),await S()),await v(t.data);else if("stderr"===t.type)h||(await k(),await S()),await v(t.data);else if("stdin_ready"!==t.type||p){if("exit"===t.type){b(),h||(await k(),await S());const e=Date.now()-m,r=c.showElapsedTime?`\n---\nexit_code: ${t.code??"unknown"}\nelapsed_ms: ${e}\nended_at: ${(new Date).toISOString()}\n---\n`:`\n---\nexit_code: ${t.code??"unknown"}\nended_at: ${(new Date).toISOString()}\n---\n`;await v(r)}}else{p=!0,h||(await k(t.pid),await S());const e=t.stdin;if(e){const t=e=>{if(null==e)return;const t="string"==typeof e?e:s.Buffer.isBuffer(e)?e.toString():String(e);if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;v(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}yield t}}catch(e){b();const t=c.signal?.aborted??!1;if(!t&&(h||(await k(),await S()),u)){const t=Date.now()-m,r=G(e instanceof Error?e.message:"Unknown error"),n=c.showElapsedTime?`\n---\nerror: ${r}\nelapsed_ms: ${t}\nended_at: ${(new Date).toISOString()}\n---\n`:`\n---\nerror: ${r}\nended_at: ${(new Date).toISOString()}\n---\n`;await v(n)}if(!t)throw e}finally{if(b(),l)try{await l.close()}catch{}if(u)try{await u.close()}catch{}}}}}async adopt(e){const t=o.join(this.projectDir,"terminals");await(0,n.mkdir)(t,{recursive:!0});const r=o.join(t,`${e.shellId}.txt`),s=e.startTime,a=new Date(s).toISOString(),c=Date.now()-s,l=V({pid:e.pid,cwd:e.workingDirectory,command:e.command,startedAt:a,runningForMs:c})+(e.initialOutput??"");await(0,n.writeFile)(r,l,"utf8");const u=await i.promises.open(r,"r+");let d;try{d=await i.promises.open(r,"a")}catch(e){throw await u.close(),e}let p=!1,h=setInterval((()=>{const t=Date.now()-s,r=V({pid:e.pid,cwd:e.workingDirectory,command:e.command,startedAt:a,runningForMs:t});u.write(r,0,"utf8").catch((()=>{}))}),5e3);const m=async()=>{if(!p){p=!0,void 0!==h&&(clearInterval(h),h=void 0);try{await u.close()}catch{}try{await d.close()}catch{}}},f=async e=>{try{await d.write(e)}catch(e){}},g={next:async()=>{try{const t=await e.eventIterator.next();if(!t.done){const r=t.value;if("stdout"===r.type)await f(r.data);else if("stderr"===r.type)await f(r.data);else if("exit"===r.type){const t=Date.now()-s,n=e.showElapsedTime?`\n---\nexit_code: ${r.code??"unknown"}\nelapsed_ms: ${t}\nended_at: ${(new Date).toISOString()}\n---\n`:`\n---\nexit_code: ${r.code??"unknown"}\nended_at: ${(new Date).toISOString()}\n---\n`;await f(n),await m()}}return t}catch(e){throw await m(),e}},return:async()=>(await m(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0})};return this.innerFactory.adopt({...e,eventIterator:g})}}class K{factory;backgroundWorkRegistry;runningShells=new Map;nextShellId=function(){return 1e3+Math.floor(999e3*Math.random())}();constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:(0,a.zy)(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n){if(!this.backgroundWorkRegistry)return;const o=n.aborted?"aborted":0===n.code?"success":"error",s=n.aborted||null===n.code||0===n.code?void 0:`exit_code=${n.code}`,i=String(e);this.backgroundWorkRegistry.enqueue({conversationId:t??a.sn,id:i,source:"shell",payload:{taskId:i,kind:"shell",status:o,title:r,...s?{detail:s}:{},...n.outputPath?{outputPath:n.outputPath}:{},reason:"task_finished"}})}async spawn(e,t){const r=await this.factory.spawn(e,t);return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:Date.now()}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.conversationId,e.description||e.command,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id)})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,void 0,e.description||e.command,r),this.cleanupShell(t.id)})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}class Y{inner;ownerConversationId;constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class Z{permissionsService;coreExecutor;ignoreService;backgroundShellManager;constructor(e,t,r,n,o,s,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=s&&void 0!==i?new Y(s,i):s,c=o??function(e){const t=new q;return new J(t,e)}(n),l=new W(c,n,a);this.backgroundShellManager=new K(l,a)}getManager(){return this.backgroundShellManager}dispose(){this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?j(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(),i=(0,p.o1)(s);if(!t.parsingResult)return new l.Lt({result:{case:"error",value:new l.Of({command:n,workingDirectory:i,error:"Parsing result is required"})}});let u=o;if($.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:t.parsingResult.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i},o);if("block"===r.kind)return $.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),L(n,i,r.reason);$.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:(0,a.oG)(t)},o);if("block"===r.kind)return $.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),L(n,i,r.reason);u=r.policy,$.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(k()&&(u=P(n,t.parsingResult),"insecure_none"!==u.type)){const e=await this.ignoreService.getCursorIgnoreMapping();u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=u?{perRepo:u}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new l.Lt({result:{case:"success",value:new l.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(e){return new l.Lt({result:{case:"error",value:new l.Of({command:n,workingDirectory:i,error:e instanceof Error?e.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{N(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}r("node:async_hooks?2c30");var X=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),Q=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),ee=r("../proto/dist/generated/agent/v1/subagents_pb.js"),te=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js"),re=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),ne=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js"),oe=r("node:os"),se=r("node:util?085f"),ie=r("../cursor-plugins/dist/index.js");var ae=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ce(e,{root:t,includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1,source:l="ripwalk"}){const u=["--files","--hidden","--no-require-git","--no-config","--color=never"];c&&u.push("--follow"),a&&u.push("--no-ignore-vcs"),o&&u.push("--case-sensitive");for(const e of s)u.push("--cursor-ignore",e);for(const e of r)u.push("--iglob",e);for(const e of n)u.push("--iglob",`!${e}`);let d,p=!1;const h=new Promise((e=>{d=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,T.spawnInSandbox)((0,T.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(!o.stdout)throw new Error("No stdout from ripgrep process");const a=new Promise((t=>{e.signal.aborted?t("aborted"):e.signal.addEventListener("abort",(()=>t("aborted")),{once:!0})}));return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a,[Symbol.dispose](){o.kill()}}}(e,u,t,i),!1);let o=0;const s=async function*(e){let t="";for await(const r of e){t+=r.toString();const e=t.split("\n");t=e.pop()??"",yield*e}t&&(yield t)}(n.stdout)[Symbol.asyncIterator]();for(;;){const e=await Promise.race([s.next(),n.aborted]);if("aborted"===e){p=!0,d(!0);break}if(e.done)break;o++,yield e.value}if(o>0);else if(!p){const e=await n.processExit;if(0!==e&&1!==e){const t=n.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}p||d(!1)}catch(e){r.error=e,r.hasError=!0}finally{ae(r)}}(),didTimeout:h}}function le({root:e,includeGlobs:t=[],excludeGlobs:r=[],caseSensitive:n=!1,cursorIgnoreFiles:o=[],sandboxPolicy:s={type:"insecure_none"},noIgnoreVcs:i=!1,followSymlinks:a=!1}){return JSON.stringify({root:e,includeGlobs:t,excludeGlobs:r,caseSensitive:n,cursorIgnoreFiles:o,sandboxPolicy:s,noIgnoreVcs:i,followSymlinks:a})}class ue{cache;constructor(e=2e4){this.cache=new p.Hc({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(le(e))}walk(e,t){const r=le(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))},c=(l=e.signal,new Promise((e=>{l.aborted?e("aborted"):l.addEventListener("abort",(()=>e("aborted")),{once:!0})})));var l;return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const e=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),c.then((()=>({type:"aborted"})))]);if("aborted"===e.type)return o=!0,void a(!0);if("lines"===e.type)return a(!1),void(yield*e.lines);this.cache.get(r)===n&&this.cache.delete(r)}let s,i;const l={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};l.linesPromise.catch((()=>{})),this.cache.set(r,l);const u=[];let d,p=!1;try{const r=ce(e,t);for await(const e of r.lines)u.push(e),yield e;if(await r.didTimeout)return o=!0,d=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);p=!0}catch(e){throw d=e,e}finally{p?s?.(u):(this.cache.get(r)===l&&this.cache.delete(r),i?.(d??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}async function de(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}async function pe(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function he(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return e.username="",e.password="",e.toString()}catch{return t}}function me(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}const fe=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];var ge=r("../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js");async function ve(e){if(!(0,o.isAbsolute)(e))return null;const t=await(0,p.DN)(e);return null===t?null:t}class ye{ignoreServicePromise;constructor(e,t,r){this.ignoreServicePromise=be.init((0,c.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e){return this.ignoreServicePromise.then((t=>t.isCursorIgnored(e)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}}const we=Math.min(8,Math.max(1,Math.floor(oe.default.availableParallelism()/2)));class be{gitExecutor;gitIgnoreMapping;cursorIgnoreMapping;teamSettingsService;rootDirectories;static ripwalkCache;gitIgnoreCache=new p.qK({max:2e3});cursorIgnoreCache=new p.qK({max:2e3});gitRootCache=new p.qK({max:1e3});gitRemoteUrlCache=new p.qK({max:200});hasGitDirCache=new p.qK({max:1e3});static promiseQueue=new p.TJ({max:we});gitParsedIgnoreCache=new Map;cursorParsedIgnoreCache=new Map;gitRepoMappingPromise;constructor(e,t,r,n,o){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o}static getRipwalkCache(){return be.ripwalkCache??=new ue,be.ripwalkCache}getIgnoreInstance(e,t,r){let n=r.get(e);return n||(n=re().add(t),r.set(e,n)),n}hasNoWorkspaceFolders(){return 0===Object.keys(this.gitIgnoreMapping).length&&0===Object.keys(this.cursorIgnoreMapping).length}async resolveLookupRoot(e){return await(0,p.DN)(e)??(0,p.o1)(e)}static async init(e,t,r,n){const o=await(0,p.PH)(r,(async e=>{const t=await(0,p.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),s={},i={},a=(await(0,p.PH)(o,(r=>de(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([n?n.getTeamRepos():Promise.resolve(void 0),be.initializeIgnoreMapping(a,".gitignore",s),be.initializeIgnoreMapping(o,".cursorignore",i)]),new be(t,s,i,n,o)}static async preloadHierarchy(e,t,r,n){let s=(0,p.o1)(e);const i=(0,o.parse)(s).root;for(;s!==i;){if(n?.has(s)){const e=(0,o.dirname)(s);if(e===s)break;s=e;continue}void 0===r[s]&&await be.handleHierarchyIgnore(s,t,r),n?.add(s);const e=(0,o.dirname)(s);if(e===s)break;s=e}}static async handleHierarchyIgnore(e,t,r){const s=(0,o.join)(e,t);try{await(0,n.access)(s,n.default.constants.F_OK);const t=await(0,p.yR)(s),o=be.parseIgnoreRules(t);r[e]=o}catch(n){"ENOENT"===n.code||console.error(`Error reading ${t} file at ${s}:`,n),r[e]=[]}}static async initializeIgnoreMapping(e,t,r){try{const n=be.deduplicateRootDirectories(e),s=await be.promiseQueue.enqueueList(n,(e=>be.findFilesWithRipgrep(e,t))),i=Array.from(s.values()).flat();await Promise.all(i.map((async e=>{try{const t=await(0,p.yR)(e),n=be.parseIgnoreRules(t),s=(0,o.dirname)(e);r[s]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const a=new Set;for(const e of n)await be.preloadHierarchy(e,t,r,a)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t){const r=(0,c.q6)(),n=[],s={root:e,includeGlobs:[`**/${t}`],excludeGlobs:fe,source:"ignore_scan"},i=be.getRipwalkCache().walk(r,s);for await(const t of i.lines)n.push((0,o.join)(e,t));return n}async handleManualLookupWhenNoWorkspaceDirs(e,t){const r={};let n=(0,o.dirname)(e);const s=(0,o.parse)(n).root;for(;;){const e=(0,o.join)(n,t);try{const t=await(0,p.yR)(e),o=be.parseIgnoreRules(t);o.length>0&&(r[n]=o)}catch{}if(n===s)break;n=(0,o.dirname)(n)}return this.testIgnored(e,r,((e,t)=>re().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e){return this.checkCursorIgnored(e)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore");const t=this.cursorIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const r=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,o.dirname)((0,p.o1)(e));const s=[],i=(0,o.parse)(n).root;for(;n!==i;){if(this.rootDirectories.some((e=>(0,p.ZU)({basePath:e,targetPath:n})))){n=(0,o.dirname)(n);continue}if(void 0!==r[n])break;s.push(n);const e=(0,o.dirname)(n);if(e===n)break;n=e}s.length>0&&(await be.promiseQueue.enqueueList(s,(e=>be.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,s]of Object.entries(t)){if(0===s.length)continue;if(!(0,p.ZU)({basePath:n,targetPath:e}))continue;const t=(0,o.relative)(n,e);if(""===t)continue;const i=r(n,s),a=(0,p.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>this.getIgnoreInstance(e,t,r)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,s]of Object.entries(this.cursorIgnoreMapping)){if(0===s.length)continue;if(!(0,p.ZU)({basePath:t,targetPath:e}))continue;const i=(0,o.join)(e,".cursorignore");try{await(0,n.access)(i),r.push(i)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,p.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear()}async handleCursorIgnoreCreated(e){const t=(0,o.dirname)(e),r=await(0,p.yR)(e),n=be.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,o.dirname)(e),r=await(0,p.yR)(e),n=be.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,o.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,p.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const s=[],i=[],a=[];let c=t;const l=(0,o.parse)(c).root;for(;c!==l;){i.push(c),void 0===this.hasGitDirCache.get(c)&&a.push(c);const e=(0,o.dirname)(c);if(e===c)break;c=e}if(a.length>0){const e=a.map((e=>(0,n.access)((0,o.join)(e,".git"),n.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of i)!0===this.hasGitDirCache.get(e)&&s.push(e);return this.gitRootCache.set(t,s),s}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=await this.findGitRootsForFile(e);if(0===t.length)return!1;const r=await(this.teamSettingsService?.getTeamRepos());if(!r||!r.repos)return!1;for(const n of t){let t;this.gitRemoteUrlCache.has(n)?t=this.gitRemoteUrlCache.get(n):(t=await pe((0,c.q6)(),this.gitExecutor,n),void 0!==t&&this.gitRemoteUrlCache.set(n,t));const s=r.repos.filter((e=>void 0!==t&&this.doesRepoUrlMatch(e.url,t)));if(0===s.length)continue;const i=(0,o.relative)(n,e)||".";for(const e of s)for(const t of e.patterns||[])if(this.matchGlob(t.pattern,i))return!0}return!1}doesRepoUrlMatch(e,t){if(e.trim().toLowerCase().replace(/\.git$/i,""),e.includes("*")){if("*"===e.trim())return!0;const r=me(e).toLowerCase(),n=me(t).toLowerCase();return this.matchRepoUrlGlob(r,n)}return me(e).toLowerCase()===me(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return ge(r)(t)}catch{return r===t}}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();if(0===n.size)return[];const s=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,o.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>this.doesRepoUrlMatch(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,o.join)(l,e).replace(/\\/g,"/"):e,s.push(r),r.endsWith("/**")||s.push(`${r}/**`)}}return s}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],s=(0,c.q6)();for(const e of this.rootDirectories){const i=(0,p.o1)(e);try{await(0,n.access)((0,o.join)(i,".git"),n.default.constants.F_OK),t.includes(i)||t.push(i)}catch{}let a=(0,o.dirname)(i);const c=(0,o.parse)(a).root;for(;a!==c&&""!==a;){try{await(0,n.access)((0,o.join)(a,".git"),n.default.constants.F_OK),t.includes(a)||t.push(a)}catch{}const e=(0,o.dirname)(a);if(e===a)break;a=e}try{const e={root:i,includeGlobs:["**/.git/config"],excludeGlobs:r,noIgnoreVcs:!0,source:"ignore_scan"},n=be.getRipwalkCache().walk(s,e);for await(const e of n.lines){const r=(0,o.join)(i,e),n=(0,o.dirname)(r),s=(0,o.dirname)(n);t.includes(s)||t.push(s)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await pe(s,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}var ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Se=[{pattern:/[/\\]\.cursor[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.agents[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.codex[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.cursor[/\\]skills-cursor[/\\]/i,requiresThirdParty:!1}],Ee=/[/\\]\.cursor[/\\]rules[/\\]/i,xe=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],_e=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Ce(e,t){const r=e.replace(/\\/g,"/"),n=(0,o.basename)(r);if(_e.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Ee.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Se)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of xe)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Pe{root;gitExecutor;userHomeDirectory;getThirdPartyExtensibilityEnabled;static ripwalkCache;constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Pe.ripwalkCache??=new ue,Pe.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,c.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]};if((0,o.resolve)(this.root)===(0,o.resolve)(this.userHomeDirectory))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await de(e,this.gitExecutor,(0,o.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const s=this.getThirdPartyExtensibilityEnabled(),i=this.buildIncludeGlobs(s),a={root:this.root,includeGlobs:i,excludeGlobs:fe,followSymlinks:!0,source:"nested_extensibility"},l={rules:[],skills:[],markdown:[],agents:[]},u=Pe.getRipwalkCache();try{const e=u.walk(r.ctx,a);try{for await(const t of e.lines){const e=Ce(t,s);e&&l[e].push((0,o.resolve)(this.root,t))}}finally{u.delete(a)}}catch{}return r.span.setAttribute("nested_extensibility.rules",l.rules.length),r.span.setAttribute("nested_extensibility.skills",l.skills.length),r.span.setAttribute("nested_extensibility.markdown",l.markdown.length),r.span.setAttribute("nested_extensibility.agents",l.agents.length),l}catch(e){t.error=e,t.hasError=!0}finally{ke(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Re=new Set(["node_modules",".git",".svn",".hg","__pycache__",".cache","dist","build",".next",".nuxt"]);async function Te({rootDir:e,includeFile:t,maxDepth:r=10,skipDirectories:s=Re,containmentRootDir:i}){const a=[],c=[{dir:e,depth:0}],l=new Set,u=void 0!==i?await(0,n.realpath)(i):null,d=e=>{if(null===u)return!0;const t=(0,o.relative)(u,e);return""===t||!t.startsWith("..")&&!(0,o.isAbsolute)(t)};for(;c.length>0;){const e=c.pop();if(void 0===e)continue;const{dir:i,depth:u}=e;if(u>r)continue;try{const e=await(0,n.realpath)(i);if(!d(e))continue;if(l.has(e))continue;l.add(e)}catch{continue}const p=await(0,n.readdir)(i,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==p)for(const e of p){const r=(0,o.join)(i,e.name);let l=e.isDirectory(),d=e.isFile();if(e.isSymbolicLink())try{const e=await(0,n.stat)(r);l=e.isDirectory(),d=e.isFile()}catch{continue}if(l){if(s.has(e.name))continue;c.push({dir:r,depth:u+1})}else d&&t(e.name)&&a.push(r)}}return a.sort(((e,t)=>e.localeCompare(t))),a}const Ie=new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]);function Ae(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean),r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&Ie.has(o)}function je(e){return{dirPath:(0,o.join)(e,".cursor","skills-cursor"),scope:"builtin",source:"builtin"}}function Oe(e,t){const r=[];return t&&r.push({dirPath:(0,o.join)(e,".claude","skills"),scope:"project",source:"workspace"},{dirPath:(0,o.join)(e,".codex","skills"),scope:"project",source:"workspace"}),r.push({dirPath:(0,o.join)(e,".agents","skills"),scope:"project",source:"workspace"},{dirPath:(0,o.join)(e,".cursor","skills"),scope:"project",source:"workspace"}),r}function De(e,t){const r=[];return t&&r.push({dirPath:(0,o.join)(e,".claude","skills"),scope:"user",source:"user"},{dirPath:(0,o.join)(e,".codex","skills"),scope:"user",source:"user"}),r.push({dirPath:(0,o.join)(e,".agents","skills"),scope:"user",source:"user"},{dirPath:(0,o.join)(e,".cursor","skills"),scope:"user",source:"user"}),r}var Me=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $e=(0,c.h)("local-exec:cursor-rules");async function Le(e){return await Te({rootDir:e,includeFile:e=>"SKILL.md"===e})}function Fe(e){return He(e.data?.environments??e.data?.metadata?.environments)??[]}function Ue(e){return He(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Be(e){return He(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function He(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function ze(e,t){const r=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return r.length>0&&!r.includes(t)}function We(e){return e.slice(0,1536)}async function qe(e){const t=await(0,p.yR)(e);return{skillFilePath:e,content:t,parsed:te(t)}}function Ge(e){return!0===e.data?.alwaysApply}function Ve({skillFilePath:e,content:t,parsed:r}){if(Ge(r))return new Q.DX({fullPath:e,content:t,type:new Q.f5({type:{case:"global",value:new Q.i9}}),environments:Fe(r),disabledEnvironments:Ue(r),scopedTo:Be(r)});const n="string"==typeof r.data?.description?We(r.data.description):void 0;return n?new Q.DX({fullPath:e,content:t,type:new Q.f5({type:{case:"agentFetched",value:new Q.Xo({description:n})}}),environments:Fe(r),disabledEnvironments:Ue(r),scopedTo:Be(r)}):new Q.DX({fullPath:e,parseError:"Description is required",scopedTo:Be(r),type:new Q.f5({type:{case:"agentFetched",value:new Q.Xo}})})}function Je({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?We(r.data.description):"",o=(0,ie.nS)(r.data?.paths??r.data?.globs);return new X.N({fullPath:e,content:t,description:n,globs:o??[],parseError:n?void 0:"Description is required",environments:Fe(r),disabledEnvironments:Ue(r),scopedTo:Be(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function Ke({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Q.DX({fullPath:e,parseError:t,type:new Q.f5({type:{case:"agentFetched",value:new Q.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new X.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${n}`}))}function Ye(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+9)}`:e}function Ze(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Xe(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=e.slice(r+1).trim(),c=Ze(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=t.slice(o+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Ze(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}class Qe{cursorRulesServices;static CHANGE_COALESCE_MS=1e3;onChangeCallbacks=new Set;disposeChangeListeners;changeTimer;constructor(e){this.cursorRulesServices=e}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Me(t,(0,c.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,se.debuglog)("Failed to load cursor rules from service:",e),[]))))),o=(await Promise.all(n)).flat(),s=new Set,i=[];for(const e of o){const t=Ye(e.fullPath);s.has(t)||(s.add(t),i.push(e))}return i}catch(e){t.error=e,t.hasError=!0}finally{Ne(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),Qe.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}class et{gitExecutor;rootDirectory;loadNestedRules;getThirdPartyExtensibilityEnabled;static ripwalkCache;_rules;loadTraceId=void 0;unsubscribeWatcher;onChangeCallbacks=new Set;ignoreService;nestedExtensibilityService;constructor(e,t,r,n,o,s,i,a){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=o,this.nestedExtensibilityService=new Pe(r,t,(0,oe.homedir)(),o),this.ignoreService=i??new ye(t,void 0,[this.rootDirectory]);const l=performance.now();if(this._rules=this.load(e,a).then((t=>{try{$e.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-l),ruleCount:t.length})}catch{}return t})).catch((e=>((0,se.debuglog)("Failed to load cursor rules:",e),[]))),s){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules"];this.unsubscribeWatcher=s.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,c.q6)(),n=Me(t,(0,c.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Ne(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,se.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return et.ripwalkCache??=new ue,et.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1),o=this._rules;this._rules=(async()=>[...(await o).filter((e=>e.fullPath!==t)),...(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)))])().catch((e=>((0,se.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}isRuleMarkdownFile(e){return"CLAUDE.md"===e||"CLAUDE.local.md"===e||"AGENTS.md"===e}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),s=(0,o.basename)(t);if(".cursorrules"===s){const e=(0,o.resolve)(this.rootDirectory),t=await de(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(s.endsWith(".mdc"))try{const e=Xe(await(0,p.yR)(t));if(e)return[{filename:(0,o.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(s))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,o.dirname)(t),s)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const s=(0,o.resolve)(this.rootDirectory),i=await de(n.ctx,this.gitExecutor,s)||s,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,s);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const p=(await Promise.all([a,l,u,d])).flat(),h=new Map;for(const e of p)h.set(e.path,e);return[...h.values()].map((e=>this.toCursorRule(e)))}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,o.join)(t,".cursorrules");if((await(0,n.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await(0,p.yR)(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Me(t,(0,c.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Ne(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Q.i9};else{const r=(0,ie.nS)(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Q.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Q.Xo({description:We(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Q._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Q.DX({fullPath:e.path,content:e.body,type:new Q.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),s=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,o.join)(i,".cursor","rules");s.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,e):[])());const t=[];a&&t.push("CLAUDE.md","CLAUDE.local.md"),t.push("AGENTS.md");for(const e of t)s.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const r=(0,o.dirname)(i);if(r===i)break;i=r}const l=(await Promise.all(s)).flat();return n.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async loadRulesFromMarkdownFile(e,t,r){const s={stack:[],error:void 0,hasError:!1};try{Me(s,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,o.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,n.stat)(e)).isFile()){const t=await(0,p.yR)(e);return[{filename:(0,o.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){s.error=e,s.hasError=!0}finally{Ne(s)}}async isCursorIgnored(e){try{const t=await ve((0,o.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),s=(await Promise.all(t.map((async e=>{try{const t=Xe(await(0,p.yR)(e));if(t)return{filename:(0,o.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",s.length),s}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),s=(await Promise.all(t.map((async e=>{try{const t=(0,o.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,o.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",s.length),s}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),s=[];try{const e={root:t,includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=et.getRipwalkCache().walk(n.ctx,e);for await(const e of r.lines){const r=(0,o.join)(t,e);s.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",s.length),s}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Me(r,(0,c.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,n.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}}class tt{workspacePaths;userHomeDirectory;gitExecutor;initialBuiltinSkillsSyncPromise;_rules;_agentSkills;watchersByFolder=new Map;onChangeCallbacks=new Set;foldersToWatch;fileWatcher;getThirdPartyExtensibilityEnabled;surface;nestedExtensibilityEntries;constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.surface=c,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Pe(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const u=performance.now(),d=this.loadAll(e,l).then((t=>{try{$e.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,se.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=d.then((e=>e.rules)),this._agentSkills=d.then((e=>e.agentSkills)),this.setupWatchers(this.foldersToWatch)}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,o.join)(r,".cursor","rules"));for(const n of Oe(r,e))t.add(n.dirPath)}for(const r of De(this.userHomeDirectory,e))t.add(r.dirPath);return t.add(je(this.userHomeDirectory).dirPath),Array.from(t)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,c.q6)(),n=Me(t,(0,c.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Ne(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){return await this._rules}reload(e){const t=this.computeFoldersToWatch(),r=new Set(this.foldersToWatch),n=new Set(t),o=this.foldersToWatch.filter((e=>!n.has(e)));this.removeWatchers(o);const s=t.filter((e=>!r.has(e)));this.setupWatchers(s),this.foldersToWatch=t;const i=this.loadAll(e).catch((e=>((0,se.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{Me(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1);const s=t.endsWith("SKILL.md")?t:(0,o.join)(t,"SKILL.md"),i=qe(s);i.catch((()=>{}));const a=async(e,t)=>{const r=(await e).filter((e=>e.fullPath!==s));if(Ae(s))return r;try{await(0,n.stat)(s);const e=await i;if(ze(e.parsed,this.surface))return r;const o=t(e);return void 0===o?r:[...r,o]}catch{return r}};this._rules=a(this._rules,(e=>Ve(e))).catch((e=>((0,se.debuglog)("Failed to load Agent Skills at path:",e),[]))),this._agentSkills=a(this._agentSkills,(e=>Ge(e.parsed)?void 0:Je(e))).catch((e=>((0,se.debuglog)("Failed to load Agent Skills (proto) at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}async getAllAgentSkills(e){return await this._agentSkills}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],s=[],i=new Set;for(const e of this.foldersToWatch){const t=(await Le(e)).filter((e=>!Ae(e))),r=await Promise.all(t.map((async e=>{try{return await qe(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})));for(const e of r)if(i.add(e.skillFilePath),"error"in e)Ke({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(ze(e.parsed,this.surface))continue;o.push(Ve(e)),Ge(e.parsed)||s.push(Je(e))}}const a=(await Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{(0,se.debuglog)("cursor-rules-service")("Failed to discover nested agent skills: %O",e)})))))).flatMap((e=>e?.skills??[])).filter((e=>!Ae(e))),l=[],u=new Set;for(const e of a)i.has(e)||u.has(e)||(u.add(e),l.push(e));const d=await Promise.all(l.map((async e=>{try{return await qe(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})));for(const e of d)if(i.add(e.skillFilePath),"error"in e)Ke({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(ze(e.parsed,this.surface))continue;o.push(Ve(e)),Ge(e.parsed)||s.push(Je(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s}}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}}function rt(e){let t;switch(e.type){case"global":t=new Q.f5({type:{case:"global",value:new Q.i9}});break;case"fileGlobbed":t=new Q.f5({type:{case:"fileGlobbed",value:new Q.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Q.f5({type:{case:"agentFetched",value:new Q.Xo({description:We(e.description??"")})}});break;case"manuallyAttached":t=new Q.f5({type:{case:"manuallyAttached",value:new Q._u}});break;default:e.type,t=new Q.f5({type:{case:"manuallyAttached",value:new Q._u}})}return new Q.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class nt{getImportSettings;pluginsService;_rules;_agentSkills;onChangeCallbacks=new Set;currentImportSettings;constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this.currentImportSettings=this.getImportSettings();const o=performance.now(),s=this.loadAll(e).then((t=>{try{$e.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,se.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]})));this._rules=s.then((e=>e.rules)),this._agentSkills=s.then((e=>e.agentSkills))}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t;const r=this.loadAll(e,!0).catch((e=>((0,se.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]})));this._rules=r.then((e=>e.rules)),this._agentSkills=r.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Me(r,(0,c.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),s=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=(0,ie.Ak)(e),a=(0,ie.Vw)(e);for(const e of[...r,...a])s.push(rt(e));for(const t of e){const e=`plugin:${(0,ie.s4)(t.identifier)}`,r=(0,ie.dB)(t.identifier),n=(0,ie.R3)(t.identifier),s=(0,ie.xJ)(t.identifier),a=(0,ie.iU)(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===te(c.content).data?.["disable-model-invocation"]}catch{}i.push(new X.N({fullPath:(0,o.join)(t.installPath,c.path),content:c.content,description:We(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:s,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",s.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:s,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Ne(r)}}}const ot=(0,se.debuglog)("local-subagents");class st{async getAllSubagents(){return[]}async reload(){return[]}}function it(e){return"true"===(e??"").trim().toLowerCase()}function at(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=it(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?ee.b$.READONLY:ee.b$.DEFAULT,u=it(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function ct(e){const t=(0,o.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function lt(e){return(0,o.basename)(e,(0,o.extname)(e)).replace(/[\s_]+/g,"-")}async function ut(e,t){return await Te({rootDir:e,includeFile:ct,containmentRootDir:t})}class dt{workspacePath;cursorAgentsSource;subagents;getThirdPartyExtensibilityEnabled;constructor(e,t,r="workspace"){this.workspacePath=e,this.cursorAgentsSource=r,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(ot("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(ot("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,o.resolve)(this.workspacePath),t=[{dirPath:(0,o.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&t.push({dirPath:(0,o.join)(e,".claude","agents"),source:"claude"}),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:s}of e){const e=await ut(r,this.workspacePath);for(const r of e){const e=(0,o.basename)(r);try{if(!(await(0,n.stat)(r)).isFile())continue}catch(e){ot("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const n=at(await(0,p.yR)(r));if(!n)continue;t.push(new ee.zz({fullPath:r,name:n.name||lt(e),description:n.description??"",tools:n.tools,model:n.model??"inherit",forceDefaultModel:n.forceDefaultModel,prompt:n.prompt,permissionMode:n.permissionMode,isBackground:n.isBackground,source:s}))}catch(e){ot("Failed to parse subagent file %s: %o",r,e)}}}return t}}const pt=new Set(["claude-code-tutor"]);class ht{subagentsServices;constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(ot("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)pt.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class mt{getSettings;pluginsService;_subagentsCache=[];_loadId=0;_loadPromise=null;_loadedOnce=!1;constructor(e,t){this.getSettings=e,this.pluginsService=t,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(ot("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=(0,ie.Du)(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?ee.b$.READONLY:ee.b$.DEFAULT;t.push(new ee.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}var ft=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),gt=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),vt=r("../proto/dist/generated/agent/v1/utils_pb.js");class yt{getCanvasDiagnostics;constructor(e){this.getCanvasDiagnostics=e}async execute(e,t){try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?wt(t.path,"diagnostics unavailable"):new ft.GL({result:{case:"success",value:new ft.uX({path:t.path,diagnostics:e.map(bt)})}})}catch(e){return wt(t.path,e instanceof Error?e.message:String(e))}}}function wt(e,t){return new ft.GL({result:{case:"error",value:new ft.HW({path:e,error:t})}})}function bt(e){return new gt.oQ({severity:kt(e.severity),range:new vt.Q6({start:new vt.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new vt.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function kt(e){switch(e){case 1:return gt.h_.ERROR;case 2:return gt.h_.WARNING;case 3:return gt.h_.INFORMATION;case 4:return gt.h_.HINT;default:return gt.h_.UNSPECIFIED}}var St=r("node:crypto?8af2"),Et=r("../metrics/dist/index.js"),xt=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),_t=r("node:child_process");function Ct(e,t,r){return new Promise(((n,o)=>{const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0};(0,_t.execFile)(e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}xt.w3.UNSPECIFIED,xt.w3.LEFT,xt.w3.MIDDLE,xt.w3.RIGHT,xt.w3.BACK,xt.w3.FORWARD,xt.Dh.UNSPECIFIED,xt.Dh.UP,xt.Dh.DOWN,xt.Dh.LEFT,xt.Dh.RIGHT,(0,Et.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,Et.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,Et.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,c.h)("computer-use");const Pt=(0,se.promisify)(_t.execFile);function Rt(e,t){const r=e/t;return{display:{width:e,height:t},api:{width:1280,height:Math.round(1280/r)}}}async function Tt(e){const{stdout:t}=await Pt("xrandr",["--display",e],{timeout:5e3}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Rt(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}var It,At,jt,Ot,Dt,Mt=r("@bufbuild/protobuf");!function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ARROW=1]="ARROW",e[e.POINTER=2]="POINTER",e[e.TEXT=3]="TEXT",e[e.WAIT=4]="WAIT",e[e.CROSSHAIR=5]="CROSSHAIR",e[e.MOVE=6]="MOVE",e[e.RESIZE_NS=7]="RESIZE_NS",e[e.RESIZE_EW=8]="RESIZE_EW",e[e.RESIZE_NWSE=9]="RESIZE_NWSE",e[e.RESIZE_NESW=10]="RESIZE_NESW",e[e.NOT_ALLOWED=11]="NOT_ALLOWED",e[e.GRAB=12]="GRAB",e[e.GRABBING=13]="GRABBING"}(It||(It={})),Mt.proto3.util.setEnumType(It,"agent.v1.CursorType",[{no:0,name:"CURSOR_TYPE_UNSPECIFIED"},{no:1,name:"CURSOR_TYPE_ARROW"},{no:2,name:"CURSOR_TYPE_POINTER"},{no:3,name:"CURSOR_TYPE_TEXT"},{no:4,name:"CURSOR_TYPE_WAIT"},{no:5,name:"CURSOR_TYPE_CROSSHAIR"},{no:6,name:"CURSOR_TYPE_MOVE"},{no:7,name:"CURSOR_TYPE_RESIZE_NS"},{no:8,name:"CURSOR_TYPE_RESIZE_EW"},{no:9,name:"CURSOR_TYPE_RESIZE_NWSE"},{no:10,name:"CURSOR_TYPE_RESIZE_NESW"},{no:11,name:"CURSOR_TYPE_NOT_ALLOWED"},{no:12,name:"CURSOR_TYPE_GRAB"},{no:13,name:"CURSOR_TYPE_GRABBING"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SLOW=1]="SLOW",e[e.MELLOW=2]="MELLOW",e[e.QUICK=3]="QUICK",e[e.RAPID=4]="RAPID"}(At||(At={})),Mt.proto3.util.setEnumType(At,"agent.v1.MotionStyle",[{no:0,name:"MOTION_STYLE_UNSPECIFIED"},{no:1,name:"MOTION_STYLE_SLOW"},{no:2,name:"MOTION_STYLE_MELLOW"},{no:3,name:"MOTION_STYLE_QUICK"},{no:4,name:"MOTION_STYLE_RAPID"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LOADING_WAIT=1]="LOADING_WAIT",e[e.VIEWING_RESULT=2]="VIEWING_RESULT",e[e.THINKING_PAUSE=3]="THINKING_PAUSE",e[e.LONG_OPERATION=4]="LONG_OPERATION"}(jt||(jt={})),Mt.proto3.util.setEnumType(jt,"agent.v1.IdleClassification",[{no:0,name:"IDLE_CLASSIFICATION_UNSPECIFIED"},{no:1,name:"IDLE_CLASSIFICATION_LOADING_WAIT"},{no:2,name:"IDLE_CLASSIFICATION_VIEWING_RESULT"},{no:3,name:"IDLE_CLASSIFICATION_THINKING_PAUSE"},{no:4,name:"IDLE_CLASSIFICATION_LONG_OPERATION"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SINGLE=1]="SINGLE",e[e.DOUBLE=2]="DOUBLE",e[e.TRIPLE=3]="TRIPLE",e[e.RIGHT=4]="RIGHT",e[e.MIDDLE=5]="MIDDLE"}(Ot||(Ot={})),Mt.proto3.util.setEnumType(Ot,"agent.v1.ClickType",[{no:0,name:"CLICK_TYPE_UNSPECIFIED"},{no:1,name:"CLICK_TYPE_SINGLE"},{no:2,name:"CLICK_TYPE_DOUBLE"},{no:3,name:"CLICK_TYPE_TRIPLE"},{no:4,name:"CLICK_TYPE_RIGHT"},{no:5,name:"CLICK_TYPE_MIDDLE"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.KEY_COMBO=1]="KEY_COMBO",e[e.KEY_SINGLE=2]="KEY_SINGLE",e[e.TEXT_TYPED=3]="TEXT_TYPED"}(Dt||(Dt={})),Mt.proto3.util.setEnumType(Dt,"agent.v1.KeystrokeEventType",[{no:0,name:"KEYSTROKE_EVENT_TYPE_UNSPECIFIED"},{no:1,name:"KEYSTROKE_EVENT_TYPE_KEY_COMBO"},{no:2,name:"KEYSTROKE_EVENT_TYPE_KEY_SINGLE"},{no:3,name:"KEYSTROKE_EVENT_TYPE_TEXT_TYPED"}]);class Nt extends Mt.Message{executionTimestampMs=Mt.protoInt64.zero;action;commandDurationMs=Mt.protoInt64.zero;positionBefore;positionAfter;cursorTypeAfter=It.UNSPECIFIED;constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.InputEvent";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"execution_timestamp_ms",kind:"scalar",T:3},{no:2,name:"action",kind:"message",T:xt.ho},{no:3,name:"command_duration_ms",kind:"scalar",T:3},{no:4,name:"position_before",kind:"message",T:xt.xp},{no:5,name:"position_after",kind:"message",T:xt.xp},{no:6,name:"cursor_type_after",kind:"enum",T:Mt.proto3.getEnumType(It)}]));static fromBinary(e,t){return(new Nt).fromBinary(e,t)}static fromJson(e,t){return(new Nt).fromJson(e,t)}static fromJsonString(e,t){return(new Nt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Nt,e,t)}}class $t extends Mt.Message{videoTimestampMs=Mt.protoInt64.zero;x=0;y=0;cursorType=It.UNSPECIFIED;velocity=0;constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.CursorPathKeyframe";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"x",kind:"scalar",T:5},{no:3,name:"y",kind:"scalar",T:5},{no:4,name:"cursor_type",kind:"enum",T:Mt.proto3.getEnumType(It)},{no:5,name:"velocity",kind:"scalar",T:2}]));static fromBinary(e,t){return(new $t).fromBinary(e,t)}static fromJson(e,t){return(new $t).fromJson(e,t)}static fromJsonString(e,t){return(new $t).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals($t,e,t)}}class Lt extends Mt.Message{style=At.UNSPECIFIED;keyframes=[];constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.CursorPath";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"style",kind:"enum",T:Mt.proto3.getEnumType(At)},{no:2,name:"keyframes",kind:"message",T:$t,repeated:!0}]));static fromBinary(e,t){return(new Lt).fromBinary(e,t)}static fromJson(e,t){return(new Lt).fromJson(e,t)}static fromJsonString(e,t){return(new Lt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Lt,e,t)}}class Ft extends Mt.Message{startMs=Mt.protoInt64.zero;endMs=Mt.protoInt64.zero;centerX=0;centerY=0;suggestedZoom=0;actionType="";actionIndex=0;importanceScore=0;context="";constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.ZoomCandidate";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"center_x",kind:"scalar",T:5},{no:4,name:"center_y",kind:"scalar",T:5},{no:5,name:"suggested_zoom",kind:"scalar",T:2},{no:6,name:"action_type",kind:"scalar",T:9},{no:7,name:"action_index",kind:"scalar",T:5},{no:8,name:"importance_score",kind:"scalar",T:5},{no:9,name:"context",kind:"scalar",T:9}]));static fromBinary(e,t){return(new Ft).fromBinary(e,t)}static fromJson(e,t){return(new Ft).fromJson(e,t)}static fromJsonString(e,t){return(new Ft).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Ft,e,t)}}class Ut extends Mt.Message{startMs=Mt.protoInt64.zero;endMs=Mt.protoInt64.zero;durationMs=Mt.protoInt64.zero;classification=jt.UNSPECIFIED;suggestedSpeed=0;precedingActionType="";followingActionType="";constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.IdlePeriod";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"duration_ms",kind:"scalar",T:3},{no:4,name:"classification",kind:"enum",T:Mt.proto3.getEnumType(jt)},{no:5,name:"suggested_speed",kind:"scalar",T:2},{no:6,name:"preceding_action_type",kind:"scalar",T:9},{no:7,name:"following_action_type",kind:"scalar",T:9}]));static fromBinary(e,t){return(new Ut).fromBinary(e,t)}static fromJson(e,t){return(new Ut).fromJson(e,t)}static fromJsonString(e,t){return(new Ut).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Ut,e,t)}}class Bt extends Mt.Message{videoTimestampMs=Mt.protoInt64.zero;x=0;y=0;clickType=Ot.UNSPECIFIED;actionIndex=0;hasModifiers=!1;constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.ClickEffectKeyframe";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"x",kind:"scalar",T:5},{no:3,name:"y",kind:"scalar",T:5},{no:4,name:"click_type",kind:"enum",T:Mt.proto3.getEnumType(Ot)},{no:5,name:"action_index",kind:"scalar",T:5},{no:6,name:"has_modifiers",kind:"scalar",T:8}]));static fromBinary(e,t){return(new Bt).fromBinary(e,t)}static fromJson(e,t){return(new Bt).fromJson(e,t)}static fromJsonString(e,t){return(new Bt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Bt,e,t)}}class Ht extends Mt.Message{videoTimestampMs=Mt.protoInt64.zero;displayText="";eventType=Dt.UNSPECIFIED;displayDurationMs=Mt.protoInt64.zero;actionIndex=0;constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.KeystrokeEvent";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"display_text",kind:"scalar",T:9},{no:3,name:"event_type",kind:"enum",T:Mt.proto3.getEnumType(Dt)},{no:4,name:"display_duration_ms",kind:"scalar",T:3},{no:5,name:"action_index",kind:"scalar",T:5}]));static fromBinary(e,t){return(new Ht).fromBinary(e,t)}static fromJson(e,t){return(new Ht).fromJson(e,t)}static fromJsonString(e,t){return(new Ht).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Ht,e,t)}}class zt extends Mt.Message{videoPath="";videoDurationMs=Mt.protoInt64.zero;videoWidth=0;videoHeight=0;actionCount=0;zoomCandidates=[];idlePeriods=[];clickEffects=[];keystrokeEvents=[];cursorPaths=[];constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.DecisionInput";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"video_path",kind:"scalar",T:9},{no:2,name:"video_duration_ms",kind:"scalar",T:3},{no:3,name:"video_width",kind:"scalar",T:5},{no:4,name:"video_height",kind:"scalar",T:5},{no:5,name:"action_count",kind:"scalar",T:5},{no:10,name:"zoom_candidates",kind:"message",T:Ft,repeated:!0},{no:11,name:"idle_periods",kind:"message",T:Ut,repeated:!0},{no:12,name:"click_effects",kind:"message",T:Bt,repeated:!0},{no:13,name:"keystroke_events",kind:"message",T:Ht,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:Lt,repeated:!0}]));static fromBinary(e,t){return(new zt).fromBinary(e,t)}static fromJson(e,t){return(new zt).fromJson(e,t)}static fromJsonString(e,t){return(new zt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(zt,e,t)}}class Wt extends Mt.Message{candidateIndex=0;zoomOverride;startMsOverride;endMsOverride;constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.ZoomSelection";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"zoom_override",kind:"scalar",T:2,opt:!0},{no:3,name:"start_ms_override",kind:"scalar",T:3,opt:!0},{no:4,name:"end_ms_override",kind:"scalar",T:3,opt:!0}]));static fromBinary(e,t){return(new Wt).fromBinary(e,t)}static fromJson(e,t){return(new Wt).fromJson(e,t)}static fromJsonString(e,t){return(new Wt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Wt,e,t)}}class qt extends Mt.Message{candidateIndex=0;speedOverride;constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.SpeedupSelection";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"speed_override",kind:"scalar",T:2,opt:!0}]));static fromBinary(e,t){return(new qt).fromBinary(e,t)}static fromJson(e,t){return(new qt).fromJson(e,t)}static fromJsonString(e,t){return(new qt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(qt,e,t)}}class Gt extends Mt.Message{cursorStyle=At.UNSPECIFIED;selectedZooms=[];selectedSpeedups=[];showClickEffects=!1;selectedClickEffects=[];showKeystrokes=!1;cuts=[];constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.DecisionOutput";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"cursor_style",kind:"enum",T:Mt.proto3.getEnumType(At)},{no:2,name:"selected_zooms",kind:"message",T:Wt,repeated:!0},{no:3,name:"selected_speedups",kind:"message",T:qt,repeated:!0},{no:4,name:"show_click_effects",kind:"scalar",T:8},{no:5,name:"selected_click_effects",kind:"scalar",T:5,repeated:!0},{no:6,name:"show_keystrokes",kind:"scalar",T:8},{no:7,name:"cuts",kind:"message",T:Vt,repeated:!0}]));static fromBinary(e,t){return(new Gt).fromBinary(e,t)}static fromJson(e,t){return(new Gt).fromJson(e,t)}static fromJsonString(e,t){return(new Gt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Gt,e,t)}}class Vt extends Mt.Message{startMs=Mt.protoInt64.zero;endMs=Mt.protoInt64.zero;reason="";constructor(e){super(),Mt.proto3.util.initPartial(e,this)}static runtime=Mt.proto3;static typeName="agent.v1.VideoCut";static fields=Mt.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"reason",kind:"scalar",T:9}]));static fromBinary(e,t){return(new Vt).fromBinary(e,t)}static fromJson(e,t){return(new Vt).fromJson(e,t)}static fromJsonString(e,t){return(new Vt).fromJsonString(e,t)}static equals(e,t){return Mt.proto3.util.equals(Vt,e,t)}}Mt.Message,Mt.proto3,Mt.proto3.util.newFieldList((()=>[{no:1,name:"raw_video_path",kind:"scalar",T:9},{no:2,name:"duration_ms",kind:"scalar",T:3},{no:3,name:"display_width",kind:"scalar",T:5},{no:4,name:"display_height",kind:"scalar",T:5},{no:5,name:"api_width",kind:"scalar",T:5},{no:6,name:"api_height",kind:"scalar",T:5},{no:7,name:"recording_start_epoch_ms",kind:"scalar",T:3},{no:10,name:"input_events",kind:"message",T:Nt,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:Lt,repeated:!0},{no:30,name:"zoom_candidates",kind:"message",T:Ft,repeated:!0},{no:31,name:"idle_periods",kind:"message",T:Ut,repeated:!0},{no:32,name:"click_effects",kind:"message",T:Bt,repeated:!0},{no:33,name:"keystroke_events",kind:"message",T:Ht,repeated:!0},{no:40,name:"decision_input",kind:"message",T:zt},{no:41,name:"decision_output",kind:"message",T:Gt},{no:50,name:"polished_video_path",kind:"scalar",T:9}]));class Jt{config;xScaleUp;yScaleUp;xScaleDown;yScaleDown;constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Kt={left_ptr:It.ARROW,arrow:It.ARROW,default:It.ARROW,top_left_arrow:It.ARROW,hand:It.POINTER,hand1:It.POINTER,hand2:It.POINTER,pointer:It.POINTER,pointing_hand:It.POINTER,xterm:It.TEXT,ibeam:It.TEXT,text:It.TEXT,watch:It.WAIT,wait:It.WAIT,progress:It.WAIT,left_ptr_watch:It.WAIT,crosshair:It.CROSSHAIR,cross:It.CROSSHAIR,tcross:It.CROSSHAIR,move:It.MOVE,fleur:It.MOVE,size_all:It.MOVE,sb_v_double_arrow:It.RESIZE_NS,v_double_arrow:It.RESIZE_NS,ns_resize:It.RESIZE_NS,row_resize:It.RESIZE_NS,top_side:It.RESIZE_NS,bottom_side:It.RESIZE_NS,sb_h_double_arrow:It.RESIZE_EW,h_double_arrow:It.RESIZE_EW,ew_resize:It.RESIZE_EW,col_resize:It.RESIZE_EW,left_side:It.RESIZE_EW,right_side:It.RESIZE_EW,top_left_corner:It.RESIZE_NWSE,bottom_right_corner:It.RESIZE_NWSE,nwse_resize:It.RESIZE_NWSE,size_fdiag:It.RESIZE_NWSE,top_right_corner:It.RESIZE_NESW,bottom_left_corner:It.RESIZE_NESW,nesw_resize:It.RESIZE_NESW,size_bdiag:It.RESIZE_NESW,not_allowed:It.NOT_ALLOWED,no_drop:It.NOT_ALLOWED,forbidden:It.NOT_ALLOWED,circle:It.NOT_ALLOWED,grab:It.GRAB,openhand:It.GRAB,grabbing:It.GRABBING,closedhand:It.GRABBING};class Yt{events=[];recordingStartTime=0;lastKnownPosition={x:0,y:0};isRunning=!1;pending=Promise.resolve();env;scaler;constructor(e){const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jt(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=It.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ct("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ct("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Kt[t]??It.ARROW}try{const e=await Ct("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Kt))if(e.toLowerCase().includes(t))return r}catch{}return It.ARROW}catch{return It.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}var Zt=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");const Xt=1048576,Qt=52428800;var er;!function(e){e.Write="write",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(er||(er={}));var tr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class rr{pendingDecisionProvider;fileChangeTracker;permissionsService;workspacePath;onDeleteForAiTracking;constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const o=t.path,s=(0,p.o1)(o,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,s,"");if(i){const e=await D(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Zt.Pi({result:{case:"rejected",value:new Zt.iq({path:s,reason:e||""})}}),onPermissionDenied:(e,t)=>new Zt.Pi({result:{case:"permissionDenied",value:new Zt.QG({path:s,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await this.pendingDecisionProvider.requestApproval({type:er.Delete,details:{path:s},toolCallId:t.toolCallId});if(!a.approved)return new Zt.Pi({result:{case:"rejected",value:new Zt.iq({path:s,reason:a.reason||""})}});let l;try{l=await(0,n.stat)(s)}catch(e){return"ENOENT"===e.code?new Zt.Pi({result:{case:"fileNotFound",value:new Zt.n0({path:s})}}):new Zt.Pi({result:{case:"error",value:new Zt.GU({path:s,error:e.message})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Zt.Pi({result:{case:"notFile",value:new Zt.LX({path:s,actualType:e})}})}const u=l.size;let d;if(u<=Qt)try{d=await(0,p.yR)(s)}catch{}const h=d??"";try{await(0,n.unlink)(s)}catch(e){return"EACCES"===e.code?new Zt.Pi({result:{case:"permissionDenied",value:new Zt.QG({path:s,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new Zt.Pi({result:{case:"fileBusy",value:new Zt.vX({path:s})}}):new Zt.Pi({result:{case:"error",value:new Zt.GU({path:s,error:e.message})}})}if(this.fileChangeTracker&&void 0!==d){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(s,d,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:s}).catch((()=>{})),new Zt.Pi({result:{case:"success",value:new Zt.fl({path:s,deletedFile:s,fileSize:BigInt(u),prevContent:h})}})}catch(e){r.error=e,r.hasError=!0}finally{tr(r)}}}var nr=r("../proto/dist/generated/agent/v1/mcp_pb.js");class or{inner;extraTools;constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===a.iK));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new nr.I0({serverIdentifier:a.iK,serverName:a.iK,instructions:`User-defined tools for this session (server "${a.iK}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class sr extends or{observableInner;constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}function ir(e,t){return 0===t.length?e:"onDidChange"in(r=e)&&"function"==typeof r.onDidChange?new sr(e,t):new or(e,t);var r}var ar=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),cr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class lr{async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new ar.uN({result:{case:"success",value:new ar.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new ar.uN({result:{case:"error",value:new ar.fk({url:n,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{cr(r)}}}class ur{workspacePath;changes=new Map;listeners=new Set;constructor(e){this.workspacePath=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n){const o=this.changes.get(e);if(o){const t=o.before,s=n||o.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:s};this.changes.set(e,n),this.notify(n)}}else{const o={path:e,before:t,after:r,metadata:n};this.changes.set(e,o),this.notify(o)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,n.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await(0,p.x3)(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}}var dr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const pr=(0,se.promisify)(_t.execFile);class hr{async exec(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(o,(0,c.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:s,stderr:i}=await pr("git",r,{cwd:t,timeout:n?.timeout});return{exitCode:0,stdout:s.toString(),stderr:i.toString()}}catch(e){o.error=e,o.hasError=!0}finally{dr(o)}}}var mr=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const fr=-(2**31),gr=2**31-1;function vr(e){return Number.isNaN(e)?0:e<fr?fr:e>gr?gr:e}function yr(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return vr(Math.trunc(e))}var wr=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const br="agent-tools",kr=52428800;var Sr=r("../mcp-agent-exec/dist/index.js"),Er=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");let xr;function _r(){if(void 0===xr){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw xr===e&&(xr=void 0),t}));xr=e}return xr}const Cr=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},Pr=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Rr=e=>Cr().encode(e),Tr=1048576,Ir=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Ar=(e,t,r=1024)=>{let n=e,o=t;return e>t?e>r&&(n=r,o=Math.max(1,Math.round(t*r/e))):t>r&&(o=r,n=Math.max(1,Math.round(e*r/t))),{width:n,height:o,needsResize:n!==e||o!==t}},jr=async e=>{if(Pr(e))return(async e=>{const t=(e=>{if(!Pr(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}})(e);if(void 0!==t&&!Ar(t.width,t.height,1280).needsResize&&e.length<=Tr)return{data:Ir(e),mimeType:"image/webp"};const r=await(n=e,Cr().decode(n));var n;const o=(await _r()).fromBitmap({data:Buffer.from(r.data),width:r.width,height:r.height});let{width:s,height:i,needsResize:a}=Ar(o.bitmap.width,o.bitmap.height,1280);a&&o.resize({w:s,h:i});let c=await Rr({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});for(;c.length>Tr&&s>1&&i>1;)s=Math.max(1,Math.round(.8*s)),i=Math.max(1,Math.round(.8*i)),o.resize({w:s,h:i}),c=await Rr({data:o.bitmap.data,width:o.bitmap.width,height:o.bitmap.height});return{data:Ir(c),mimeType:"image/webp"}})(e);const t=await _r(),r=await t.read(e),n=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(r),{width:o,height:s,needsResize:i}=Ar(r.width,r.height);if(!i&&e.length<=Tr)return{data:Ir(e),mimeType:n};let a=o,c=s;i&&r.resize({w:a,h:c});let l=await r.getBuffer(n);for(;l.length>Tr&&a>1&&c>1;)a=Math.max(1,Math.round(.8*a)),c=Math.max(1,Math.round(.8*c)),r.resize({w:a,h:c}),l=await r.getBuffer(n);return{data:Ir(l),mimeType:n}};"function"==typeof SuppressedError&&SuppressedError,(0,Et.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),(0,Et.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),(0,Et.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),(0,Et.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),(0,Et.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),(0,Et.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),(0,c.h)("McpFileSystemWriter");const Or="mcp_auth";["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");var Dr=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Nr=(0,c.h)("local-exec:mcp");async function $r(e,t){const r=o.default.join(t,br),s=o.default.join(r,`${(0,St.randomUUID)()}.txt`);await(0,n.mkdir)(o.default.dirname(s),{recursive:!0});const i=e.slice(0,kr),a=i.split("\n").length,c=Buffer.byteLength(i,"utf8");return await(0,n.writeFile)(s,i,"utf8"),new Er._Z({content:{case:"text",value:new Er.zN({text:"",outputLocation:new vt.pV({filePath:s,sizeBytes:BigInt(c),lineCount:BigInt(a)})})}})}function Lr(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Fr(e,t,r){const n=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t);if(n)return await D(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Er.iz({result:{case:"error",value:new Er.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:er.Mcp,details:{name:n.name,toolName:n.toolName,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId},toolCallId:t.toolCallId});return o.approved?t.smartModeApprovalOnly?new Er.iz({result:{case:"approved",value:new Er.Ke}}):null:new Er.iz({result:{case:"rejected",value:new Er.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Er.iz({result:{case:"error",value:new Er.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new Er.iz({result:{case:"permissionDenied",value:new Er.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}})??void 0}class Ur{toolSet;permissionsService;pendingDecisionProvider;projectDir;fileOutputThresholdBytes;elicitationFactory;constructor(e,t,r,n,o=4e4,s){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Dr(r,(0,c.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,o=await this.toolSet.getTools(n),s=Array.from(new Set(o.map((e=>e.clientKey)))).sort(),i=o.find((e=>e.providerIdentifier===t.providerIdentifier&&e.toolName===t.toolName)),a=await Fr(n,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:i});if(void 0!==a)return a;const l=await this.toolSet.getToolSet(n);let u;try{u=await l.execute(t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(r instanceof Sr.U$&&t.providerIdentifier.length>0&&!o.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new Sr.bm(t.providerIdentifier,s)),r instanceof Sr.bm)return new Er.iz({result:{case:"serverNotFound",value:new Er.JL({name:r.serverName,availableServers:r.availableServers})}});if(r instanceof Sr.U$)return new Er.iz({result:{case:"toolNotFound",value:new Er.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const d=[];for(const e of u.content){const t=e.type;if("text"===t){const t=e;d.push({kind:"text",text:t.text})}else if("resource"===t){const t=e;t.resource?.text&&d.push({kind:"text",text:t.resource.text})}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),n=await jr(r);d.push({kind:"contentItem",item:new Er._Z({content:{case:"image",value:new Er.do({data:n.data,mimeType:n.mimeType})}})})}else if("image"!==t){const t=(0,Sr.SW)(e);d.push({kind:"text",text:t})}}const p=await async function({fileOutputThresholdBytes:e,pendingContentItems:t,projectDir:r}){const n=t.filter((e=>"text"===e.kind)).map((e=>e.text)).join("\n\n"),o=e>0&&Buffer.byteLength(n,"utf8")>e;let s=!1;const i=[];for(const e of t)"contentItem"!==e.kind?o?s||(i.push(await $r(n,r)),s=!0):i.push((a=e.text,new Er._Z({content:{case:"text",value:new Er.zN({text:a})}}))):i.push(e.item);var a;return i}({fileOutputThresholdBytes:this.fileOutputThresholdBytes,pendingContentItems:d,projectDir:this.projectDir}),h=u.structuredContent&&"object"==typeof u.structuredContent&&!Array.isArray(u.structuredContent)?Mt.Struct.fromJson(u.structuredContent):void 0,m=new Er.QW({content:p,isError:u.isError,structuredContent:h});return new Er.iz({result:{case:"success",value:m}})}catch(e){r.error=e,r.hasError=!0}finally{Mr(r)}}}class Br{mcpLease;constructor(e){this.mcpLease=e}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Dr(r,(0,c.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{const e=new Set,r=await this.mcpLease.getTools(n);for(const t of r)e.add(t.providerIdentifier),e.add(`user-${t.providerIdentifier}`);const o=await this.mcpLease.getClients(n),s=[];if(t.server){const e=o[t.server];if(!e)return new Er.kP({result:{case:"error",value:new Er.w2({error:`Server "${t.server}" not found`})}});const r=await this.listResourcesFromClient(n,e,t.server);s.push(...r)}else for(const[t,r]of Object.entries(o)){if(e.size>0&&!e.has(t))continue;const o=await this.listResourcesFromClient(n,r,t);s.push(...o)}return new Er.kP({result:{case:"success",value:new Er.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Er.kP({result:{case:"error",value:new Er.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{Mr(r)}}async listResourcesFromClient(e,t,r){if("ready"!==(await t.getState(e)).kind)return[];const n=await t.listResources(e);return n&&n.resources?n.resources.map((e=>new Er.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class Hr{mcpLease;projectDir;permissionsService;pendingDecisionProvider;workspacePaths;constructor(e,t=".",r,n=[],o){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(a.Ij),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const s=Dr(r,(0,c.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,i=t.smartModeApproval?.reason;if(void 0!==i){if(void 0===this.pendingDecisionProvider)return new Er.ZD({result:{case:"error",value:new Er.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:er.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:Mt.Value.fromJson(t.server),uri:Mt.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:Mt.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:i,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Er.ZD({result:{case:"rejected",value:new Er.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}const a=(await this.mcpLease.getClients(s))[t.server];if(!a)return new Er.ZD({result:{case:"error",value:new Er.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(s)).kind)return new Er.ZD({result:{case:"error",value:new Er.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(s,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Er.ZD({result:{case:"notFound",value:new Er.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=t.downloadPath.replace(/^\/+/,""),i=o.default.join(this.resolveProjectDir(s),e);if(await(0,n.mkdir)(o.default.dirname(i),{recursive:!0}),r.text)await(0,n.writeFile)(i,r.text,"utf8");else if(r.blob){const e=Buffer.from(r.blob,"base64");await(0,n.writeFile)(i,e)}return new Er.ZD({result:{case:"success",value:new Er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType})}})}if(r.text)return new Er.ZD({result:{case:"success",value:new Er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Er.ZD({result:{case:"success",value:new Er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"blob",value:e}})}})}return new Er.ZD({result:{case:"error",value:new Er.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return Nr.warn(s,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Er.ZD({result:{case:"error",value:new Er.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{Mr(r)}}}async function zr(e,t){const r=Lr(t),s=(0,o.join)(e,a.FH,r,a.J6);let i;try{i=await(0,n.readdir)(s)}catch(e){if("ENOENT"===e?.code)return{toolNames:[],toolsDirExists:!1};throw e}const c=await Promise.all(i.map((async e=>{if(e.endsWith(".json"))try{const t=await(0,n.readFile)((0,o.join)(s,e),"utf8");return(0,a.TG)(t)}catch{return}}))),l=new Set;for(const e of c)e&&l.add(e);return{toolNames:Array.from(l).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Wr=(0,c.h)("local-exec:mcp-disk-freshness-on-access"),qr="/mcps/",Gr=(0,Et.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Vr=(0,Et.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Jr=(0,Et.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Kr=(0,Et.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),Yr=new Map;function Zr(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Xr({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Wr.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Lr(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Wr.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Gr.increment(e,1,{...l,outcome:c}),Vr.histogram(e,i.length,l),Jr.histogram(e,a.length,l),Kr.histogram(e,i.length+a.length,l),"mismatch"===c&&Wr.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Qr(e,t,r,n=zr){if(void 0===r||(void 0===(o=r)||!Zr(o).includes(qr)))return;var o;const s=function(e){const t=Zr(e),r=t.indexOf(qr);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=Yr.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{Yr.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Lr(r.serverIdentifier);await Xr({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Xr({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Wr.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);Yr.set(i,d)}var en=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},tn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function rn(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}function nn(e,t,r){const n=function(e,t){let r;for(const n of t)(0,p.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,o.resolve)(e,t),r);return void 0===n||n===e}const on=(0,c.h)("local-exec/grep");function sn(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function an(e){try{return(0,i.existsSync)(e)}catch{return"check_failed"}}function cn(e,t,r,n){return{...un(e),...n,cwd:t,cwdExists:an(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function ln(e){return new Error(`Path does not exist: ${e}`)}function un(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,i.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,i.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,o.dirname)(e);try{t.parentDirExists=(0,i.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,i.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,o.dirname)(r);try{t.grandparentDirExists=(0,i.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,i.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,i.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const s="node_modules.asar.unpacked";if(e.includes(s)){const r=e.split(s)[0];if(r){const e=r.concat("node_modules.asar");try{t.asarExists=(0,i.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(s);try{if(t.asarUnpackedDirExists=(0,i.existsSync)(n),t.asarUnpackedDirExists){const e=(0,o.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,i.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dn{ignoreService;grepProvider;workspacePath;static MAIN_TIMEOUT_MS=25e3;static INDEXED_GREP_TIMEOUT_MS=25e3;static INDEXED_GREP_CONTEXT_TIMEOUT_MS=dn.INDEXED_GREP_TIMEOUT_MS+100;static HARD_MAX_OUTPUT_LINES=1e4;static CLIENT_LIMIT_LINES=2e3;singleWorkspacePath;mcpStateAccessor;constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor}computeRelativeTarget(e,t){const r=(0,p.o1)(e,this.singleWorkspacePath);return r===t?".":(0,o.relative)(t,r)}async buildArgs(e,t,r){const n=[],o=await this.ignoreService.listCursorIgnoreFilesByRoot(e);for(const e of o)n.push("--cursor-ignore",e);if("content"===r)n.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&n.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&n.push("--after-context",String(t.contextAfter)),n.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&n.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)n.push("-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${r}`);n.push("-c","--with-filename")}!0===t.caseInsensitive?n.push("--ignore-case"):n.push("--case-sensitive"),t.type&&n.push("--type",t.type),t.glob&&n.push("--iglob",t.glob),t.multiline&&n.push("--multiline","--multiline-dotall");const s=t.sort??"modified";if("none"!==s){const e=!0===t.sortAscending?"--sort":"--sortr";n.push(e,s)}return n.push("--no-config","--color=never"),n.push("--hidden"),n.push("--follow"),n.push("--regexp",t.pattern),n.push("--"),n.push(t.path?this.computeRelativeTarget(t.path,e):"."),n}async filterBlockedFiles(e,t){const r=[];for(const n of e){const e=await ve((0,p.o1)(n.file,t));null===e||await this.isPostRipgrepBlocked(e)||r.push(n)}return r}async isPostRipgrepBlocked(e){const[t,r]=await Promise.all([this.ignoreService.isCursorIgnored(e),this.ignoreService.isRepoBlocked(e)]);return t||r}async runFilesMode(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=en(s,(0,c.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),a=await this.buildArgs(t,r,"files_with_matches"),l=await this.executeRg(i.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{files:u,totalFiles:d,clientTruncated:h,ripgrepTruncated:m}=function(e,t,r){const n=e.trim(),o=""!==n?rn(n):[],s=o.length,i=o.slice(0,t),a=o.length>t;return{files:i,totalFiles:vr(s),clientTruncated:a,ripgrepTruncated:s>=r}}(l.stdout,dn.CLIENT_LIMIT_LINES,dn.HARD_MAX_OUTPUT_LINES),f=[];for(const e of u){const r=await ve((0,p.o1)(e,t));null===r||await this.isPostRipgrepBlocked(r)||f.push(e)}const g=u.length-f.length,v=new mr.T7({files:f,totalFiles:vr(d-g),clientTruncated:h,ripgrepTruncated:m});return new mr.vD({result:{case:"files",value:v}})}catch(e){s.error=e,s.hasError=!0}finally{tn(s)}}async runCountMode(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=en(s,(0,c.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),a=await this.buildArgs(t,r,"count"),l=await this.executeRg(i.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{counts:u,totalFiles:d,totalMatches:p,clientTruncated:h,ripgrepTruncated:m}=function(e,t,r){const n=e.trim(),o=""!==n?rn(n):[],s=[];for(const e of o){if(""===e||void 0===e)continue;const t=e.lastIndexOf(":");if(t<=0)continue;const r=e.substring(t+1).trim(),n=parseInt(r,10);if(!Number.isFinite(n))continue;const o=e.substring(0,t);s.push({file:o,count:n})}const i=s.length,a=s.reduce(((e,t)=>e+t.count),0),c=s.slice(0,t),l=s.length>t;return{counts:c,totalFiles:vr(i),totalMatches:vr(a),clientTruncated:l,ripgrepTruncated:i>=r}}(l.stdout,dn.CLIENT_LIMIT_LINES,dn.HARD_MAX_OUTPUT_LINES),f=await this.filterBlockedFiles(u,t),g=f.reduce(((e,t)=>e+t.count),0),v=u.length-f.length,y=u.reduce(((e,t)=>e+t.count),0)-g,w=new mr.xA({counts:f.map((e=>new mr.sS({file:e.file,count:vr(e.count)}))),totalFiles:vr(d-v),totalMatches:vr(p-y),clientTruncated:h,ripgrepTruncated:m});return new mr.vD({result:{case:"count",value:w}})}catch(e){s.error=e,s.hasError=!0}finally{tn(s)}}async runContentMode(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=en(s,(0,c.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),a=await this.buildArgs(t,r,"content"),l=await this.executeRg(i.ctx,t,a,void 0,n,o);if((""!==l.stderr||2===l.exitCode)&&""===l.stdout.trim())throw new Error(l.stderr||`ripgrep exited with code ${l.exitCode}`);const{byFile:u,totalLines:d,totalMatchedLines:p,clientTruncated:h,ripgrepTruncated:m}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{en(o,(0,c.VI)(n.withName("parseContentOutput")),!1);const s=""===e.trim()?[]:rn(e);s.length>0&&""===s[s.length-1]&&s.pop();const i=new Map,a=new Set;let l=0,u=0;for(const e of s){if(void 0===e)continue;if("--"===e)continue;const[r,n]=e.split("\0",2);if(void 0===r||void 0===n)continue;const o=/^(\d+)([:-])(.*)$/.exec(n);if(!o)continue;const s=o[1],c=o[2],d=o[3]??"",p=parseInt(s,10);if(!Number.isFinite(p))continue;const h="-"===c;if(!1===h&&l++,a.has(r)||a.add(r),u>=t)continue;const m=i.get(r)??{file:r,matches:[]};m.matches.push({lineNumber:p,content:d,isContextLine:h}),i.set(r,m),u++}const d=a.size;return{byFile:i,totalLines:vr(s.length),totalMatchedLines:vr(l),totalFiles:vr(d),clientTruncated:u>=t,ripgrepTruncated:s.length>=r}}catch(e){o.error=e,o.hasError=!0}finally{tn(o)}}(l.stdout,dn.CLIENT_LIMIT_LINES,dn.HARD_MAX_OUTPUT_LINES,i.ctx),f=Array.from(u.values()),g=await this.filterBlockedFiles(f,t),v=f.filter((e=>!g.includes(e))),y=v.reduce(((e,t)=>e+t.matches.length),0),w=v.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),b=new mr.Zp({matches:g.map((e=>new mr.uI({file:e.file,matches:e.matches.map((e=>new mr.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:vr(d-y),totalMatchedLines:vr(p-w),clientTruncated:h,ripgrepTruncated:m});return new mr.vD({result:{case:"content",value:b}})}catch(e){s.error=e,s.hasError=!0}finally{tn(s)}}async executeIndexedGrepWithTimeout(e,t,r,n){if(void 0===this.grepProvider.executeIndexedGrep)return;const[o,s]=e.withTimeoutAndCancel(dn.INDEXED_GREP_CONTEXT_TIMEOUT_MS);try{return await(0,p.dY)(this.grepProvider.executeIndexedGrep(o,t,r),dn.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${dn.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof p.MU)return void on.warn(e,"indexed_grep.timeout_fallback",n);throw t}finally{s()}}async executeRg(e,t,r,n,o,s){const i=(0,c.VI)(e.withName("LocalGrepExecutor.executeRg")),a="utf8",l=8388608;return n=n??dn.HARD_MAX_OUTPUT_LINES,new Promise(((c,u)=>{let d=!1,p=!1;const h=()=>{p||(p=!0,i.span.end())};let m,f;try{const e=o;m=(0,T.spawnInSandbox)((0,T.Ko)(),r,{cwd:t},e),0}catch(r){if(h(),sn(r)){const n=r,o=(0,T.Ko)();if(on.error(e,"rg_diagnostics.spawn_throw",void 0,cn(o,t,n,s)),!1===an(t))return u(ln(t))}return u(r)}const g=[],v=[];let y=0,w=0,b=0,k=!1;f=setTimeout((()=>{if(!d)try{h(),u(new Error(`Timed out after ${dn.MAIN_TIMEOUT_MS/1e3}s`)),m.kill()}catch{}}),dn.MAIN_TIMEOUT_MS),m.stdout?.on("data",(e=>{if(y+=e.length,void 0!==n&&!0!==k){let t=-1,r=0;for(let o=0;o<e.length;o++)if(10===e[o]&&(r++,b+r>=n)){t=o+1,k=!0;try{m.kill()}catch{}break}b+=r;const o=t>=0?e.subarray(0,t):e;y<=l&&g.push(o)}else!0!==k&&y<=l&&g.push(e)})),m.stderr?.on("data",(e=>{w+=e.length,w<=l&&v.push(e)})),m.on("error",(r=>{if(clearTimeout(f),h(),sn(r)){const n=(0,T.Ko)(),o=r;if(on.error(e,"rg_diagnostics.spawn_enoent",void 0,cn(n,t,o,s)),!1===an(t))return void u(ln(t))}u(r)})),m.on("close",(e=>{d=!0,clearTimeout(f);const t=Buffer.concat(g).toString(a),r=Buffer.concat(v).toString(a);h(),c({stdout:t,stderr:r,exitCode:e??0})}))}))}async execute(e,t,r){const s={stack:[],error:void 0,hasError:!1};try{const a=en(s,(0,c.VI)(e.withName("LocalGrepExecutor.execute")),!1),l=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],u=t.outputMode??"content",d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:l},h=j(t.sandboxPolicy);try{const r=this.grepProvider.getWorktreeGuardInfo?.(l);if((0,p.fl)({targetPath:t.path,workspacePaths:l,mainWorktreePath:r?.mainWorktreePath}))return new mr.Ud({result:{case:"error",value:new mr.ts({error:p.PS})}});if(t.path){const r=await ve((0,p.o1)(t.path,this.singleWorkspacePath));if(null===r)return new mr.Ud({result:{case:"error",value:new mr.ts({error:(i=t.path,`Path '${i}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`)})}});if(await this.ignoreService.isCursorIgnored(r))return new mr.Ud({result:{case:"error",value:new mr.ts({error:`Path '${t.path}' is filtered out by .cursorignore`})}});void 0!==this.mcpStateAccessor&&Qr(e,this.mcpStateAccessor,r)}let n={};const s=await this.executeIndexedGrepWithTimeout(a.ctx,l,t,d);if(void 0!==s)n=s;else for(const e of l){if(!1===an(e))return new mr.Ud({result:{case:"error",value:new mr.ts({error:`Path does not exist: ${e}`})}});let r;if("content"===u)r=await this.runContentMode(a.ctx,e,t,h,d);else if("files_with_matches"===u)r=await this.runFilesMode(a.ctx,e,t,h,d);else{if("count"!==u)throw new Error(`Unknown output mode: ${u}`);r=await this.runCountMode(a.ctx,e,t,h,d)}n[e]=r}const c=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,o.resolve)(e))))],n={};for(const[t,s]of Object.entries(e)){const e=(0,o.resolve)(t),i=t=>nn(e,t,r),a=s.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);n[t]=new mr.vD({result:{case:"content",value:new mr.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-o),totalMatchedLines:Math.max(0,e.totalMatchedLines-s)})}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e)));n[t]=new mr.vD({result:{case:"files",value:new mr.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;n[t]=new mr.vD({result:{case:"count",value:new mr.xA({...e,counts:r,totalFiles:Math.max(0,e.totalFiles-(e.counts.length-r.length)),totalMatches:Math.max(0,e.totalMatches-o)})}});break}default:n[t]=s}}return n}(n,l),m=new mr._0({pattern:t.pattern,path:t.path,outputMode:u,workspaceResults:c});return new mr.Ud({result:{case:"success",value:m}})}catch(e){if(t.path){const e=(0,p.o1)(t.path,this.singleWorkspacePath);try{await(0,n.stat)(e)}catch(t){return new mr.Ud({result:{case:"error",value:new mr.ts({error:`Path does not exist: ${e}`})}})}}return new mr.Ud({result:{case:"error",value:new mr.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){s.error=e,s.hasError=!0}finally{tn(s)}var i}}var pn=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),hn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},mn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class fn{permissionsService;ignoreService;workspacePath;constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{hn(r,(0,c.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const o=(0,p.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,n.stat)(o)}catch(e){return"ENOENT"===e.code?(0,p.jq)(o)?new pn.fv({result:{case:"error",value:new pn.uj({path:o,error:"No active terminals."})}}):new pn.fv({result:{case:"error",value:new pn.uj({path:o,error:`Path does not exist: ${o}`})}}):new pn.fv({result:{case:"error",value:new pn.uj({path:o,error:e.message})}})}if(!r.isDirectory())return new pn.fv({result:{case:"error",value:new pn.uj({path:o,error:`Path is not a directory: ${o}`})}});const s=j(t.sandboxPolicy),i=t.timeoutMs??5e3,a=e.withTimeout(i),{tree:c,didTimeout:l}=await this.getDirectoryTree(a,o,t.ignore,s);return l?new pn.fv({result:{case:"timeout",value:new pn.ze({directoryTreeRoot:c})}}):new pn.fv({result:{case:"success",value:new pn.PC({directoryTreeRoot:c})}})}catch(e){return new pn.fv({result:{case:"error",value:new pn.uj({path:o,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{mn(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return hn(o,(0,c.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{mn(o)}}async buildTreeFromRipgrepStream(e,t,r,n,s){const i={stack:[],error:void 0,hasError:!1};try{hn(i,(0,c.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,o.resolve)(t),l=new pn.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(a,l);const d={charactersUsed:a.length,budgetExceeded:!1},[p,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),m=[...r,...h],{lines:f,didTimeout:g}=ce(e,{root:t,excludeGlobs:m,caseSensitive:!0,cursorIgnoreFiles:p,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,o.resolve)(t,e),n=await ve(r);null===n||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,u,d,s)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){i.error=e,i.hasError=!0}finally{mn(i)}}addPathToTree(e,t,r,n,s){const i=(0,o.basename)(e),a=(0,o.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=s){const e=new pn.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,o.dirname)(e);if(n===e)break;e=n}}const s=(0,o.extname)(e);let i=a;for(;i.startsWith(t);){const e=r.get(i);e&&(e.fullSubtreeExtensionCounts[s]??=0,e.fullSubtreeExtensionCounts[s]=vr(e.fullSubtreeExtensionCounts[s]+1),e.numFiles??=0,e.numFiles=vr(e.numFiles+1));const t=(0,o.dirname)(i);if(t===i)break;i=t}}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const s=(0,o.dirname)(e);s!==e&&s.startsWith(t)&&this.ensureDirectoryPath(s,t,r,n);const i=new pn.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(s);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,o.basename)(e.absPath).localeCompare((0,o.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}var gn=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),vn=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const yn=51200;function wn(e){return Buffer.byteLength(e,"utf8")}function bn(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function kn(e){return new vn.d({truncated:e.truncated,truncatedBy:e.truncatedBy??"",totalLines:e.totalLines,outputLines:e.outputLines,outputBytes:e.outputBytes,maxLines:e.maxLines,maxBytes:e.maxBytes,firstLineExceedsLimit:e.firstLineExceedsLimit??!1,lastLinePartial:e.lastLinePartial??!1})}function Sn(e,t){const r=t?.maxLines??2e3,n=t?.maxBytes??yn,o=e.split("\n"),s=o.length;if(wn(o[0]??"")>n)return{content:"",truncation:kn({truncated:!0,truncatedBy:"bytes",totalLines:s,outputLines:0,outputBytes:0,maxLines:r,maxBytes:n,firstLineExceedsLimit:!0})};const i=[];let a,c=0;for(let e=0;e<o.length;e++){if(i.length>=r){a="lines";break}const t=o[e],s=i.length>0?1:0,l=wn(t)+s;if(c+l>n){a="bytes";break}i.push(t),c+=l}return{content:i.join("\n"),truncation:kn({truncated:void 0!==a,truncatedBy:a,totalLines:s,outputLines:i.length,outputBytes:c,maxLines:r,maxBytes:n})}}function En(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var xn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});async function _n(e){const{content:t,truncation:r}=function(e){const t=yn,r=e.split("\n"),n=r.length,o=[];let s,i=0,a=!1;for(let e=r.length-1;e>=0;e--){if(o.length>=2e3){s="lines";break}const n=r[e],c=o.length>0?1:0,l=wn(n)+c;if(i+l>t){if(s="bytes",0===o.length){const e=Buffer.from(n,"utf8");o.unshift(e.subarray(Math.max(0,e.length-t)).toString("utf8")),i=wn(o[0]),a=!0}break}o.unshift(n),i+=l}return{content:o.join("\n"),truncation:kn({truncated:void 0!==s,truncatedBy:s,totalLines:n,outputLines:o.length,outputBytes:i,maxLines:2e3,maxBytes:t,lastLinePartial:a})}}(e||"(no output)");if(!r.truncated)return{output:t};const s=await(0,n.mkdtemp)((0,o.join)((0,oe.tmpdir)(),"pi-bash-")),i=(0,o.join)(s,"output.log");await(0,n.writeFile)(i,e,"utf8");const a=r.totalLines-r.outputLines+1,c=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${bn(r.outputBytes)} of line ${c} (${bn(yn)} limit). Full output: ${i}]`:`[Showing lines ${a}-${c} of ${r.totalLines}. Full output: ${i}]`}`,fullOutputPath:i,truncation:r}}class Cn{shellExecutor;constructor(e){this.shellExecutor=e}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiBashExecutor.execute")),!1),s=await this.shellExecutor.execute(o.ctx,function(e,t){const r=void 0!==e.timeout&&e.timeout>0?Math.round(1e3*e.timeout):2147483647,n=e.command.trim().split(/\s+/)[0]??"";return new u.a({command:e.command,timeout:r,toolCallId:t?.execId??"",fileOutputThresholdBytes:BigInt(0),parsingResult:new u.HO({parsingFailed:!1,executableCommands:[{name:n,fullText:e.command,args:[]}]})})}(t,r),r);switch(s.result.case){case"success":{const e=await _n(`${s.result.value.stdout}${s.result.value.stderr}`);return new gn.AH({result:{case:"success",value:new gn.cV(e)}})}case"failure":{const e=await _n(`${s.result.value.stdout}${s.result.value.stderr}`);return new gn.AH({result:{case:"success",value:new gn.cV({...e,output:`${e.output}\n\nCommand exited with code ${s.result.value.exitCode}`})}})}case"timeout":return this.error(`Command timed out after ${Math.round(s.result.value.timeoutMs/1e3)} seconds`);case"rejected":return this.error(s.result.value.reason||"Command aborted");case"permissionDenied":case"spawnError":return this.error(s.result.value.error);default:return this.error("Command failed")}}catch(e){n.error=e,n.hasError=!0}finally{xn(n)}}error(e){return new gn.AH({result:{case:"error",value:new gn.bD({error:e})}})}}var Pn=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function Rn(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;case"userRejected":return e.reason??"User rejected the operation";case"permissionsConfig":return e.isReadonly?"Blocked by readonly permissions configuration":"Blocked by permissions configuration";case"cursorFiles":return"Path is blocked because it is a Cursor internal file";case"unsafeResolution":return e.message;case"needsApproval":return e.approvalReason}}var Tn=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function In(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function An(e){return e.normalize("NFKC").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,"-").replace(/\u00a0/g," ").split("\n").map((e=>e.trimEnd())).join("\n")}function jn(e,t){if(0===t.length)return 0;let r=0,n=e.indexOf(t);for(;-1!==n;)r++,n=e.indexOf(t,n+t.length);return r}function On(e,t){const r=e.split("\n"),n=t.split("\n"),o=Math.max(r.length,n.length);for(let e=0;e<o;e++)if(r[e]!==n[e])return e+1}const Dn=new Map;async function Mn(e,t){const r=await async function(e){try{return await(0,n.realpath)(e)}catch{return e}}(e),o=Dn.get(r)??Promise.resolve();let s;const i=new Promise((e=>{s=e})),a=o.then((()=>i));Dn.set(r,a),await o;try{return await t()}finally{s(),Dn.get(r)===a&&Dn.delete(r)}}var Nn=r("node:url?7874");function $n(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,Nn.fileURLToPath)(r)),("~"===r||r.startsWith("~/"))&&(r=(0,o.join)((0,oe.homedir)(),r.slice(2))),(0,o.normalize)((0,o.isAbsolute)(r)?r:(0,o.resolve)(t??process.cwd(),r))}var Ln=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Fn{permissionsService;writeExecutor;workspacePath;constructor(e,t,r){this.permissionsService=e,this.writeExecutor=t,this.workspacePath=r}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,c.VI)(e.withName("LocalPiEditExecutor.execute")),!1),i=$n(t.path,this.workspacePath);return Mn(i,(async()=>{const e=await this.permissionsService.shouldBlockRead(i);if(e)return this.error(`Read blocked: ${Rn(e)}`);try{if((await(0,n.stat)(i)).isDirectory())return this.error(`Path is a directory: ${i}`);const e=(await(0,n.readFile)(i)).toString("utf8"),o=function(e,t,r){if(0===r.length)throw new Error("edits must contain at least one replacement.");const{bom:n,text:o}=65279===(s=t).charCodeAt(0)?{bom:s[0],text:s.slice(1)}:{bom:"",text:s};var s;const i=function(e){return e.includes("\r\n")?"\r\n":"\n"}(o),a=In(o),{matches:c,matchedContent:l}=function(e,t){const r=[];let n=!1;for(const o of t){if(0===o.oldText.length)throw new Error("oldText must not be empty.");const t=In(o.oldText),s=jn(e,t);if(1!==s){if(s>1)throw new Error("oldText must be unique in the file.");n=!0;break}r.push({index:e.indexOf(t),length:t.length,replacement:In(o.newText)})}if(!n)return{matches:r,matchedContent:e};const o=An(e),s=[];for(const e of t){const t=An(In(e.oldText)),r=jn(o,t);if(0===r)throw new Error("oldText was not found in the file.");if(r>1)throw new Error("oldText must be unique in the file.");s.push({index:o.indexOf(t),length:t.length,replacement:An(In(e.newText))})}return{matches:s,matchedContent:o}}(a,r),u=function(e,t){const r=[...t].sort(((e,t)=>e.index-t.index));for(let e=1;e<r.length;e++){const t=r[e-1];if(r[e].index<t.index+t.length)throw new Error("edits must not overlap.")}let n=e;for(const e of r.reverse())n=n.slice(0,e.index)+e.replacement+n.slice(e.index+e.length);return n}(l,c);if(u===a)throw new Error("edits did not change the file.");const d=n+function(e,t){return"\n"===t?e:e.replace(/\n/g,"\r\n")}(u,i),p=(0,Tn.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:p,patch:p,firstChangedLine:On(a,u)}}(t.path,e,t.edits),a=await this.writeExecutor.execute(s.ctx,new wr.hY({path:i,fileText:o.newContent,toolCallId:r?.execId??""}),r);switch(a.result.case){case"success":return new Pn.u7({result:{case:"success",value:new Pn.uL({output:`Successfully replaced ${t.edits.length} block(s) in ${t.path}.`,diff:o.diff,patch:o.patch,firstChangedLine:o.firstChangedLine})}});case"rejected":return new Pn.u7({result:{case:"rejected",value:new Pn.pE({reason:a.result.value.reason})}});default:return this.error(this.writeErrorMessage(a.result.value,t.path))}}catch(e){return this.error(e instanceof Error?e.message:"Unknown edit error")}}))}catch(e){o.error=e,o.hasError=!0}finally{Ln(o)}}writeErrorMessage(e,t){if(null!=e&&"object"==typeof e&&"error"in e){const t=e.error;if("string"==typeof t)return t}return`Failed to edit ${t}`}error(e){return new Pn.u7({result:{case:"error",value:new Pn.Nd({error:e})}})}}var Un=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),Bn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Hn(e){return e.split(o.sep).join("/")}class zn{permissionsService;workspacePath;constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiFindExecutor.execute")),!1);const s=$n(t.path||".",this.workspacePath),i=await this.permissionsService.shouldBlockRead(s);if(i)return this.error(`Find blocked: ${Rn(i)}`);try{if(!(await(0,n.stat)(s)).isDirectory())return this.error(`Not a directory: ${s}`);const e=Math.max(1,t.limit??1e3),r=await async function(e,t,r){const s=[];return await async function e(i){if(s.length>=t)return;const a=await(0,n.readdir)(i,{withFileTypes:!0});for(const n of a){if(s.length>=t)return;if(".git"===n.name||"node_modules"===n.name)continue;const a=(0,o.join)(i,n.name);await r(a)&&(s.push(a+(n.isDirectory()?o.sep:"")),n.isDirectory()&&await e(a))}}(e),s}(s,e,(async e=>!await this.permissionsService.shouldBlockRead(e))),i=t.pattern.includes("/")&&!t.pattern.startsWith("**/")?`**/${t.pattern}`:t.pattern,a=r.map((e=>({raw:e,relative:Hn((0,o.relative)(s,e))}))).filter((({relative:e})=>(0,ne.xF)(e,i,{dot:!0})));if(0===a.length)return this.success("No files found matching pattern");const c=Sn(a.map((e=>e.relative)).join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=r.length>=e?e:void 0,u=[];return void 0!==l&&u.push(`${e} results limit reached. Use limit=${2*e} for more, or refine pattern`),c.truncation.truncated&&u.push(`${bn(yn)} limit reached`),this.success(u.length>0?`${c.content}\n\n[${u.join(". ")}]`:c.content,{resultLimitReached:l,truncation:c.truncation.truncated?c.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown find error")}}catch(e){r.error=e,r.hasError=!0}finally{Bn(r)}}success(e,t){return new Un.bT({result:{case:"success",value:new Un.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new Un.bT({result:{case:"error",value:new Un.Uy({error:e})}})}}var Wn=r("node:readline"),qn=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),Gn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Vn{permissionsService;workspacePath;constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiGrepExecutor.execute")),!1);const o=$n(t.path||".",this.workspacePath),s=await this.permissionsService.shouldBlockRead(o);if(s)return this.error(`Search blocked: ${Rn(s)}`);try{const e=(await(0,n.stat)(o)).isDirectory(),r=["--json","--line-number","--color=never","--hidden"];t.ignoreCase&&r.push("--ignore-case"),t.literal&&r.push("--fixed-strings"),void 0!==t.glob&&r.push("--glob",t.glob),r.push("--",t.pattern,o);const s=(0,_t.spawn)((0,T.Ko)(),r,{stdio:["ignore","pipe","pipe"]}),i=[];let a="",c=!1;const l=Math.max(1,t.limit??100),u=(0,Wn.createInterface)({input:s.stdout});s.stderr?.on("data",(e=>{a+=e.toString()})),u.on("line",(e=>{if(i.length>=l||0===e.trim().length)return;const t=JSON.parse(e);if("match"!==t.type)return;const r=t.data?.path?.text,n=t.data?.line_number;void 0!==r&&void 0!==n&&(i.push({filePath:r,lineNumber:n,lineText:t.data?.lines?.text?.replace(/\n$/,"")}),i.length>=l&&(c=!0,s.kill()))}));const d=await new Promise(((e,t)=>{s.on("error",t),s.on("close",e)}));if(u.close(),!c&&0!==d&&1!==d)return this.error(a.trim()||`ripgrep exited with code ${d}`);if(0===i.length)return this.success("No matches found");const p=[];for(const e of i)await this.permissionsService.shouldBlockRead(e.filePath)||p.push(e);if(0===p.length)return this.success("No matches found");const{output:h,linesTruncated:m}=await this.formatMatches(p,o,e,Math.max(0,t.context??0)),f=Sn(h,{maxLines:Number.MAX_SAFE_INTEGER}),g=[];return c&&g.push(`${l} matches limit reached. Use limit=${2*l} for more, or refine pattern`),f.truncation.truncated&&g.push(`${bn(yn)} limit reached`),m&&g.push("Some lines truncated to 500 chars. Use read tool to see full lines"),this.success(g.length>0?`${f.content}\n\n[${g.join(". ")}]`:f.content,{matchLimitReached:c?l:void 0,linesTruncated:m,truncation:f.truncation.truncated?f.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown grep error")}}catch(e){r.error=e,r.hasError=!0}finally{Gn(r)}}async formatMatches(e,t,r,s){const i=[];let a=!1;for(const c of e){const e=r?(0,o.relative)(t,c.filePath):(0,o.basename)(c.filePath);if(0===s&&void 0!==c.lineText){const t=En(c.lineText);a=a||t.wasTruncated,i.push(`${e}:${c.lineNumber}: ${t.text}`);continue}const l=(await(0,n.readFile)(c.filePath,"utf8")).replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n"),u=Math.max(1,c.lineNumber-s),d=Math.min(l.length,c.lineNumber+s);for(let t=u;t<=d;t++){const r=En(l[t-1]??"");a=a||r.wasTruncated,i.push(t===c.lineNumber?`${e}:${t}: ${r.text}`:`${e}-${t}- ${r.text}`)}}return{output:i.join("\n"),linesTruncated:a}}success(e,t){return new qn.mr({result:{case:"success",value:new qn.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new qn.mr({result:{case:"error",value:new qn.hP({error:e})}})}}var Jn=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),Kn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Yn{permissionsService;workspacePath;constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiLsExecutor.execute")),!1);const s=$n(t.path||".",this.workspacePath),i=await this.permissionsService.shouldBlockRead(s);if(i)return this.error(`List blocked: ${Rn(i)}`);try{if(!(await(0,n.stat)(s)).isDirectory())return this.error(`Not a directory: ${s}`);const e=Math.max(1,t.limit??500),r=(await(0,n.readdir)(s)).sort(((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))),i=[];let a=!1;for(const t of r){if(i.length>=e){a=!0;break}try{const e=(0,o.join)(s,t);if(await this.permissionsService.shouldBlockRead(e))continue;const r=await(0,n.stat)(e);i.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===i.length)return this.success("(empty directory)");const c=Sn(i.join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),l=[];return a&&l.push(`${e} entries limit reached. Use limit=${2*e} for more`),c.truncation.truncated&&l.push(`${bn(yn)} limit reached`),this.success(l.length>0?`${c.content}\n\n[${l.join(". ")}]`:c.content,{entryLimitReached:a?e:void 0,truncation:c.truncation.truncated?c.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown ls error")}}catch(e){r.error=e,r.hasError=!0}finally{Kn(r)}}success(e,t){return new Jn.pX({result:{case:"success",value:new Jn.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new Jn.pX({result:{case:"error",value:new Jn.iG({error:e})}})}}var Zn=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),Xn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Qn{permissionsService;workspacePath;constructor(e,t){this.permissionsService=e,this.workspacePath=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalPiReadExecutor.execute")),!1);const s=function(e,t){const r=$n(e,t);if((0,i.existsSync)(r))return r;for(const e of function(e){const t=(0,o.dirname)(e),r=e.slice(t.length+1),n=new Set;return n.add(e),n.add((0,o.join)(t,r.normalize("NFD"))),n.add((0,o.join)(t,r.replace(/'/g,"’"))),n.add((0,o.join)(t,r.replace(/ /g," "))),n.add((0,o.join)(t,r.replace(/'/g,"’").normalize("NFD"))),[...n]}(r))if((0,i.existsSync)(e))return e;return r}(t.path,this.workspacePath),a=await this.permissionsService.shouldBlockRead(s);if(a)return this.error(`Read blocked: ${Rn(a)}`);try{if((await(0,n.stat)(s)).isDirectory())return this.error(`Path is a directory: ${s}`);const e=(await(0,n.readFile)(s)).toString("utf8").split("\n"),r=void 0!==t.offset?Math.max(0,t.offset-1):0;if(r>=e.length)return this.error(`Offset ${t.offset} is beyond end of file (${e.length} lines total)`);const o=void 0!==t.limit?e.slice(r,r+t.limit).join("\n"):e.slice(r).join("\n"),{content:i,truncation:a}=Sn(o),c=r+1;let l=i;if(a.firstLineExceedsLimit)l=`[Line ${c} is ${bn(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${bn(yn)} limit. Use bash: sed -n '${c}p' ${t.path} | head -c 51200]`;else if(a.truncated){const t=c+a.outputLines-1;l+=`\n\n[Showing lines ${c}-${t} of ${e.length}. Use offset=${t+1} to continue.]`}else if(void 0!==t.limit&&r+t.limit<e.length){const n=r+t.limit+1;l+=`\n\n[${e.length-(r+t.limit)} more lines in file. Use offset=${n} to continue.]`}return new Zn.Q({result:{case:"success",value:new Zn.yP({output:l,truncation:a.truncated?a:void 0})}})}catch(e){return this.error(e instanceof Error?e.message:"Unknown read error")}}catch(e){r.error=e,r.hasError=!0}finally{Xn(r)}}error(e){return new Zn.Q({result:{case:"error",value:new Zn.tB({error:e})}})}}var eo=r("../proto/dist/generated/agent/v1/pi_write_exec_pb.js"),to=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class ro{writeExecutor;workspacePath;constructor(e,t){this.writeExecutor=e,this.workspacePath=t}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,c.VI)(e.withName("LocalPiWriteExecutor.execute")),!1),s=$n(t.path,this.workspacePath);return Mn(s,(async()=>{const e=await this.writeExecutor.execute(o.ctx,new wr.hY({path:s,fileText:t.content,toolCallId:r?.execId??""}),r);switch(e.result.case){case"success":return new eo.hO({result:{case:"success",value:new eo.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new eo.hO({result:{case:"rejected",value:new eo.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new eo.hO({result:{case:"error",value:new eo.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new eo.hO({result:{case:"error",value:new eo.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){n.error=e,n.hasError=!0}finally{to(n)}}}class no{shellStdinWriter;constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new l.nt({result:{case:"error",value:new l.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new l.nt({result:{case:"success",value:new l.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var oo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js");function so(e,t){const r=new oo.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=o.execId,i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var io=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class ao{workspacePath;diagnosticsProvider;constructor(e,t){this.workspacePath=e,this.diagnosticsProvider=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let o;!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,o]=e.withTimeoutAndCancel(1e4);try{const r=(0,p.o1)(t.path,this.workspacePath);try{const e=await(0,n.stat)(r);if(!e.isFile()&&!e.isDirectory())return new gt.Ek({result:{case:"fileNotFound",value:new gt.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new gt.Ek({result:{case:"fileNotFound",value:new gt.Mu({path:t.path})}});if("EACCES"===e.code)return new gt.Ek({result:{case:"permissionDenied",value:new gt.RP({path:t.path})}});throw e}const o=(0,p.o1)(r,this.workspacePath),s=new p.qA(o);await this.diagnosticsProvider.open(e,s);const i=(await this.diagnosticsProvider.getDiagnostics(e,s)).map((e=>this.convertDiagnostic(e)));return new gt.Ek({result:{case:"success",value:new gt.a1({path:t.path,diagnostics:i,totalDiagnostics:i.length})}})}catch(r){return e.canceled?new gt.Ek({result:{case:"error",value:new gt.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new gt.Ek({result:{case:"error",value:new gt.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{o()}}catch(e){r.error=e,r.hasError=!0}finally{io(r)}}convertDiagnostic(e){return new gt.oQ({severity:this.convertSeverity(e.severity),range:e.range?new vt.Q6({start:new vt.yX({line:e.range.start.line,column:e.range.start.character}),end:new vt.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:e.message,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return gt.h_.ERROR;case 2:return gt.h_.WARNING;case 3:return gt.h_.INFORMATION;case 4:return gt.h_.HINT;default:return gt.h_.UNSPECIFIED}}}Error,r("../../node_modules/.pnpm/which@4.0.0/node_modules/which/lib/index.js");const co="win32"===process.platform;function lo(e,t){return co&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==o.sep&&(e+=o.sep),t.startsWith(e))}process.platform;var uo=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))};function po(e){return uo(this,void 0,void 0,(function*(){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=yield function(e,t){return uo(this,void 0,void 0,(function*(){const r=new Map;if(0===t.length)return r;try{const n=yield new Promise(((r,n)=>{const o=(0,_t.spawn)("git",["check-attr","linguist-generated","--stdin"],{cwd:e});let s="";o.stdout.on("data",(e=>{s+=e.toString()})),o.stdin.write(`${t.join("\n")}\n`),o.stdin.end(),o.on("close",(e=>{r(s)})),o.on("error",(e=>{n(e)}))}));for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch(e){}return r}))}(t,r);return yield Promise.all(r.map((e=>uo(this,void 0,void 0,(function*(){const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new ho(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=yield n(e);if(void 0!==t&&function(e,t){return new ho(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))))),o}))}class ho{constructor(e,t){this.name=e,this.extname=o.extname(e).toLowerCase(),this.getContent=t}get lines(){var e;if(void 0===this.cachedLines){const t=null===(e=this.getContent)||void 0===e?void 0:e.call(this);this.cachedLines=t?t.split("\n"):[]}return this.cachedLines}get data(){var e;return null===(e=this.getContent)||void 0===e?void 0:e.call(this)}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?<!-)\.)+(com|edu|gov|in|me|net|org|fm|io)/.test(this.name)}goLock(){return/(Gopkg|glide)\.lock/.test(this.name)}packageResolved(){return/Package\.resolved/.test(this.name)}poetryLock(){return/poetry\.lock/.test(this.name)}pdmLock(){return/pdm\.lock/.test(this.name)}uvLock(){return/uv\.lock/.test(this.name)}pixiLock(){return/pixi\.lock/.test(this.name)}esyLock(){return/(^|\/)(\w+\.)?esy\.lock$/.test(this.name)}npmShrinkwrapOrPackageLock(){return/npm-shrinkwrap\.json/.test(this.name)||/package-lock\.json/.test(this.name)}pnpmLock(){return/pnpm-lock\.yaml/.test(this.name)}bunLock(){return/(?:^|\/)bun\.lockb?$/.test(this.name)}terraformLock(){return/(?:^|\/)\.terraform\.lock\.hcl$/.test(this.name)}generatedYarnPlugnplay(){return/(^|\/)\.pnp\..*$/.test(this.name)}godeps(){return/Godeps\//.test(this.name)}generatedByZephir(){return/\.zep\.(c|h|php)$/.test(this.name)}htmlcov(){return/(?:^|\/)htmlcov\//.test(this.name)}gradleWrapper(){return/(?:^|\/)gradlew(?:\.bat)?$/i.test(this.name)}mavenWrapper(){return/(?:^|\/)mvnw(?:\.cmd)?$/i.test(this.name)}pipenvLock(){return/Pipfile\.lock/.test(this.name)}generatedPascalTlb(){return/_tlb\.pas$/i.test(this.name)}generatedSqlxQuery(){return/(?:^|\/)\.sqlx\/query-[a-f\d]{64}\.json$/.test(this.name)}sourceMapByName(){return/\.(css|js)\.map$/i.test(this.name)}maybeMinified(){return[".js",".css"].includes(this.extname)}minifiedFiles(){return!(!this.maybeMinified()||0===this.lines.length)&&this.lines.reduce(((e,t)=>e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*((null==r?void 0:r.length)||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*((null==n?void 0:n.length)||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("<doc>")&&(this.lines[2]||"").includes("<assembly>")&&(this.lines[this.lines.length-2]||"").includes("</doc>")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include <jni.h>")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){var e;if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>/<!-- Generated by pkgdown: do not edit by hand -->/.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>/<!--\s+Generated by Doxygen\s+[.0-9]+\s*-->/i.test(e))))return!0;const t=this.lines.slice(0,31).join(" ").match(/<meta(\s+[^>]+)>/gi);if(!t)return!1;for(const r of t){const t=this.extractHtmlMeta(r);if("generator"===(null===(e=t.name)||void 0===e?void 0:e.toLowerCase())&&(t.content||t.value)){const e=t.content||t.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(e))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}r("node:events?d66f"),Error;var mo=r("../proto/dist/generated/aiserver/v1/utils_pb.js");const fo=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,go=/^(a|b|i|w|c|o|1|2)\//,vo=e=>{const t=e?.match(fo);return t?.map((e=>e.replace(go,"").replace(/("|')$/,"")))},yo=/^\\?['"]|\\?['"]$/g,wo=e=>{let t=bo(e,"-+").trim();return t=So(t),t.replace(yo,"").replace(go,"")},bo=(e,t)=>{if(e=xo(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=Eo(t);return e.replace(new RegExp(`^${r}+`),"")},ko=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,So=e=>{const t=ko.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},Eo=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${xo(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,xo=e=>`${e??""}`,_o=(0,c.h)("local-git-diff");async function Co(e,t,r={}){const n=await new Promise(((n,o)=>{const s=(0,_t.spawn)("git",t,{cwd:e});let i="",a="";s.stdout.on("data",(e=>{i+=e.toString()})),s.stderr.on("data",(e=>{a+=e.toString()})),s.on("close",(e=>{0===e||!0===r.ignoreErrors?n(i):o(new Error(`Git command failed with code ${e}: ${a}`))})),s.on("error",(e=>{!0===r.ignoreErrors?n(i):o(e)}))}));return!0===r.shouldNotTrimOutput?n:n.trim()}function Po(e){const t=(e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{const[t,o]=vo(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},l=()=>{n&&!n.chunks.length||c()},u=e=>+(e||1),d=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},p=[[/^diff\s/,c],[/^new file mode (\d+)$/,(e,t)=>{l(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{l(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{l(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{l(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{l(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{l(),n.from=wo(e)}],[/^\+\+\+\s/,e=>{l(),n.to=wo(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||c(e);const[r,l,d,p]=t.slice(1);s=+r,i=+d,o={content:e,changes:[],oldStart:+r,oldLines:u(l),newStart:+d,newLines:u(p)},a={oldLines:u(l),newLines:u(p)},n.chunks.push(o)}],[/^\$/,d]],h=[[/^\$/,d],[/^-/,e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)}],[/^\+/,e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)}],[/^\s+/,e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--}]],m=e=>{a?(e=>{for(const[t,r]of h){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of p){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)m(e);return r})(e);return new mo.o$({diffs:t.map((e=>function(e){const t=new mo.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new mo.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:mo.Wf.UNSPECIFIED})}const Ro=["main","master","develop"];class To{async execute(e,t){return async function(e,t,r){const s=function(e){switch(e){case mo.ek.NAME_STATUS:return mo.ek.NAME_STATUS;case mo.ek.NAME_STATUS_AND_NUMSTAT:return mo.ek.NAME_STATUS_AND_NUMSTAT;case mo.ek.FILE_DIFFS:return mo.ek.FILE_DIFFS;case mo.ek.DIFFS_WITH_BEFORE_AND_AFTER:return mo.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return mo.ek.FILE_DIFFS}}(r.outputFormat),i=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await Co(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of Ro){const r=`origin/${t}`;try{return await Co(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await Co(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await Co(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(t);return r.mergeBase&&(e=(await Co(t,["merge-base",e,r.ref.length>0?r.ref:"HEAD"])).trim()),e})(),a=["diff","--no-color"];r.includeSpaceChanges||a.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&a.push(`-U${r.unifiedContextLines}`),a.push(i),r.ref.length>0&&a.push(r.ref),r.targetPaths.length>0&&(a.push("--"),a.push(...r.targetPaths));const c=await Co(t,a,{shouldNotTrimOutput:!0}),l=Po(c);let u=[];if(r.maxUntrackedFiles>0){u=await async function(e,t){let r=(await Co(e,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return r.length>t&&(r=r.slice(0,t)),(await Promise.all(r.map((async t=>{try{return{contents:await n.readFile(o.default.join(e,t),"utf8"),path:t}}catch{return}})))).filter((e=>void 0!==e))}(t,r.maxUntrackedFiles);for(const e of u){const r=await Co(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});l.diffs.push(...Po(r).diffs)}}if(s!==mo.ek.FILE_DIFFS)for(const e of l.diffs)e.chunks=[];if(s===mo.ek.DIFFS_WITH_BEFORE_AND_AFTER){const s=r.ref.length>0?r.ref:"HEAD";await Promise.all(l.diffs.map((async a=>{try{if("/dev/null"!==a.from)try{a.beforeFileContents=await Co(t,["show",`${i}:${a.from}`],{shouldNotTrimOutput:!0})}catch{a.beforeFileContents=""}else a.beforeFileContents="";if("/dev/null"!==a.to)if(r.ref.length>0)try{a.afterFileContents=await Co(t,["show",`${s}:${a.to}`],{shouldNotTrimOutput:!0})}catch{a.afterFileContents=""}else try{a.afterFileContents=await n.readFile(o.default.join(t,a.to),"utf8")}catch{try{a.afterFileContents=await Co(t,["show",`${s}:${a.to}`],{shouldNotTrimOutput:!0})}catch{a.afterFileContents=""}}else a.afterFileContents=""}catch(t){_o.error(e,"Error fetching file contents for diff",t)}})))}const d=new Map;for(const e of l.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&d.set(t,e)}const p=[...d.keys()],h=r.ref.length>0?r.ref:"HEAD";try{const e=await po({repoRoot:t,filePaths:p,getContent:async e=>{const r=d.get(e);if(r){if(void 0!==r.afterFileContents)return r.afterFileContents;try{if(r.to&&"/dev/null"!==r.to)return await Co(t,["show",`${h}:${r.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=d.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){_o.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const m=!0===r.computePatchId?await async function(e,t){if(0!==t.length)return(await new Promise(((r,n)=>{const o=(0,_t.spawn)("git",["patch-id","--stable"],{cwd:e});let s="",i="";o.stdout.on("data",(e=>{s+=e.toString()})),o.stderr.on("data",(e=>{i+=e.toString()})),o.on("close",(e=>{0===e?r(s):n(new Error(`git patch-id failed with code ${e}: ${i}`))})),o.on("error",n),o.stdin.end(t)}))).trim().split(/\s+/)[0]||void 0}(t,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(c,function(e){const t=[];for(const r of e){const e=r.contents.split("\n"),n=e.length;t.push(`diff --git a/${r.path} b/${r.path}`),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),t.push(`@@ -0,0 +1${1===n?"":","+n} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(u))):void 0,f=!0===r.returnHeadSha?(await Co(t,["rev-parse","HEAD"])).trim():void 0,g=!0===r.returnHeadSha?(await Co(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,v=new mo.df({diff:l,submoduleDiffs:[],patchId:m,headSha:f,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const e=v.toBinary().byteLength;if(e>y)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${y} byte limit`)}return v}(e,t.cwd,t)}}var Io=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class Ao{permissionsService;constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName});return new Io.M({allowlisted:r})}}var jo=r("../constants/dist/index.js"),Oo=r("../proto/dist/generated/agent/v1/read_exec_pb.js"),Do=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Mo=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const No=(0,c.h)("LocalReadExecutor"),$o=async(e,t,r,n)=>{const o=setTimeout((()=>{No.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function Lo(e){return e>=32&&e<=126||9===e||10===e||13===e}const Fo=Buffer.from("\n---\n");const Uo=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function Bo(e){const t=(0,o.extname)(e).toLowerCase(),r=""===t?"Binary files without an extension are not supported by the read executor":`Binary files of type ${t} are not supported by the read executor`;return new Oo.sV({result:{case:"invalidFile",value:new Oo.cW({path:e,reason:r})}})}function Ho(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{content:e,rangeApplied:!1};if(""===e)return{content:e,rangeApplied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):t),s=n<0?Math.max(0,t+n):Math.max(0,n-1);if(s>=t)return{content:e,rangeApplied:!1};const i=Math.min(t,s+o);return{content:e.split("\n").slice(s,i).join("\n"),rangeApplied:!0}}function zo(e,t,r=jo.pZY){if(0===t.length)return e;const n=r-e.text.length;return n<=0?{text:e.text,truncated:!0}:t.length>n?{text:e.text+t.slice(0,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function Wo(e,t){const r=zo(e,t);return{text:r.text,truncated:r.truncated}}function qo(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=zo(n,"\n")),n=zo(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function Go(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}class Vo extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function Jo(e,t,r,n){const o=void 0!==r.offset||void 0!==r.limit,s=(r.offset??1)<0,a=r.offset??1,c=Math.max(0,a-1),l=void 0===r.limit?void 0:c+r.limit,u=s?Math.abs(a):0,d=[];let h=0,m=!1;const f=[];let g=0,v=!1;const y=[];let w=0,b=!1,k={text:"",truncated:!1},S=0,E=0,x=0,_=!1,C=!1;const P=e=>{let t=e;return!_&&t.length>0&&(_=!0,65279===t.charCodeAt(0)&&(C=!0,t=t.slice(1))),t},R=(e,t)=>{const r=S;if(t&&(e.text.endsWith("\r")?E++:x++),((e,t)=>{if(m&&h>=jo.pZY)return;const r=d.length>0?1:0;let n=jo.pZY-h;if(r>0){if(n<=0)return void(m=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};d.push(o),h+=r+o.line.text.length,(e.truncated||o.line.truncated)&&(m=!0)})(e,t),s){if(u>0){for(y.push({line:e,hasNewline:t}),w+=e.text.length+1;y.length>u;){const e=y.shift();void 0!==e&&(w-=e.line.text.length+1)}for(;y.length>1&&w>jo.pZY;){const e=y.shift();void 0!==e&&(w-=e.line.text.length+1,b=!0)}}}else o&&r>=c&&(void 0===l||r<l)&&((e,t)=>{if(v&&g>=jo.pZY)return;const r=f.length>0?1:0;let n=jo.pZY-g;if(r>0){if(n<=0)return void(v=!0);n--}const o=e.text.length>n?{line:{text:e.text.slice(0,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};f.push(o),g+=r+o.line.text.length,e.truncated&&(v=!0),o.line.truncated&&(v=!0)})(e,t);S++};for await(const r of async function*(e,t,r){if("strictUtf8"===r.kind){const r=new se.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),n=(0,i.createReadStream)(t,{highWaterMark:65536,signal:e.signal});try{for await(const e of n){const t=r.decode(e,{stream:!0});t.length>0&&(yield t)}const e=r.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new Vo;throw e}return}const n=(0,i.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe(Do.decodeStream(r.decoderEncoding));for await(const e of n)yield"string"==typeof e?e:String(e)}(e,t,n)){const e=P(r).split("\n");for(let t=0;t<e.length;t++)k=Wo(k,e[t]),t<e.length-1&&(R(k,!0),k={text:"",truncated:!1})}R(k,!1);const T=E+x,I=T>0&&E/T*100>=5;!function(e,t){if(p.Yd.has(e)&&p.Yd.delete(e),p.Yd.set(e,t),p.Yd.size<=100)return;const r=p.Yd.keys().next().value;void 0!==r&&p.Yd.delete(r)}(t,"utf8"===n.cacheEncoding&&C?"utf8bom":n.cacheEncoding);let A={text:"",truncated:m};if(A=qo(A,d,I),!o)return{content:A.text,totalLines:S,truncated:A.truncated,rangeApplied:!1};if(""===A.text)return{content:"",totalLines:S,truncated:!1,rangeApplied:!1};if(s){const e=r.limit??u;let t={text:"",truncated:b};return t=qo(t,y.slice(0,e),I),{content:t.text,totalLines:S,truncated:t.truncated,rangeApplied:!0}}if(c>=S)return{content:A.text,totalLines:S,truncated:A.truncated,rangeApplied:!1};let j={text:"",truncated:v};return j=qo(j,f,I),{content:j.text,totalLines:S,truncated:j.truncated,rangeApplied:!0}}class Ko{permissionsService;workspacePath;mcpStateAccessor;useStreamingRead;constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalReadExecutor.execute")),!1);const s=t.path,i=(0,p.o1)(s,this.workspacePath);if(await $o(e,"permissionsService.shouldBlockRead",3e3,(()=>this.permissionsService.shouldBlockRead(i))))return new Oo.sV({result:{case:"permissionDenied",value:new Oo.lW({path:i})}});void 0!==this.mcpStateAccessor&&Qr(e,this.mcpStateAccessor,i);try{const r=await $o(e,"stat",3e3,(()=>(0,n.stat)(i)));if(r.isDirectory())return new Oo.sV({result:{case:"invalidFile",value:new Oo.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Oo.sV({result:{case:"invalidFile",value:new Oo.cW({path:i,reason:"Path is neither a file nor a directory"})}});const s=(0,p.CM)(i),a=(0,p.JD)(i);if(s||a)return await this.readTerminalFile(e,i,r,t,a&&!s);const c=await $o(e,"getFormatForFile",3e3,(()=>(0,p.zV)(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,o.extname)(e).toLowerCase()}(i),d=(0,p.d8)(i);if(l){const t=await $o(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,n.readFile)(i);return jr(e)}));return new Oo.sV({result:{case:"success",value:new Oo.mE({path:i,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(u){const t=await $o(e,"readPdfBinary",3e3,(()=>(0,n.readFile)(i)));return new Oo.sV({result:{case:"success",value:new Oo.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){const t=await $o(e,"readBinaryFile",3e3,(()=>(0,n.readFile)(i)));return new Oo.sV({result:{case:"success",value:new Oo.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c.isBinaryFile)return Bo(i);{const n=this.useStreamingRead;if(n&&await $o(e,"useStreamingRead",3e3,(()=>n()))){const n=await $o(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=function(e,t,r){const n=function(e,t,r){return Go(r??p.Yd.get(e)??t.encoding)}(e,t,r),o=function(e){const t=Go(e);return"utf8bom"===t?"utf8":t}(n);return"utf8"===o?{kind:"strictUtf8",cacheEncoding:"utf8"}:Do.encodingExists(o)?{kind:"iconv",decoderEncoding:o,cacheEncoding:n}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,n.encodingHint);try{return await Jo(e,t,n,o)}catch(r){if(r instanceof Vo)return await Jo(e,t,n,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,i,c,t)));return new Oo.sV({result:{case:"success",value:new Oo.mE({path:i,output:{case:"content",value:n.content},totalLines:n.totalLines,fileSize:BigInt(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const o=await $o(e,"readText",3e3,(()=>(0,p.yR)(i,t.encodingHint))),s=await $o(e,"countLines",3e3,(()=>(0,p.lt)(o))),a=Ho(o,s,t);let l=a.content,u=!1;return l.length>jo.pZY&&(l=l.substring(0,jo.pZY),u=!0),new Oo.sV({result:{case:"success",value:new Oo.mE({path:i,output:{case:"content",value:l},totalLines:s,fileSize:BigInt(r.size),truncated:u,rangeApplied:a.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new Oo.sV({result:{case:"fileNotFound",value:new Oo.Ko({path:i})}}):"EACCES"===t.code||"EPERM"===t.code?new Oo.sV({result:{case:"permissionDenied",value:new Oo.lW({path:i})}}):new Oo.sV({result:{case:"error",value:new Oo.F_({path:i,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Mo(r)}}async readTerminalFile(e,t,r,o,s){const i=await $o(e,"readTerminalFile",3e3,(()=>(0,n.readFile)(t)));if(s&&(a=i,Uo.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(a,e)))))return Bo(t);var a;let c=function(e){const t=function(e){if(e.length<5||45!==e[0]||45!==e[1]||45!==e[2]||10!==e[3])return 0;const t=Buffer.from("\n---\n"),r=e.indexOf(t,4);return-1===r?0:r+t.length}(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=function(e,t){const r=e.length;if(r<2*Fo.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(Fo,r-Fo.length-1);return-1===o||o<n?r:function(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(10!==r&&(r<32||r>126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+Fo.length,r-4).toString("utf-8"))?o:r}(e,t),o=n<e.length?e.subarray(n).toString("utf-8"):"",s=e.subarray(t,n),i=function(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1<t;o+=2){const t=e[o],s=e[o+1];0===s&&Lo(t)&&r++,0===t&&Lo(s)&&n++}return r>=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}(s);let a;if("utf-16le"===i)a=s.toString("utf16le");else if("utf-16be"===i){const e=s.length-s.length%2,t=Buffer.from(s.subarray(0,e));t.swap16(),a=t.toString("utf16le")}else a=s.toString("utf-8");return 65279===a.charCodeAt(0)&&(a=a.slice(1)),r+a+o}(i).replaceAll("\r\n","\n");const l=(0,p.lt)(c),u=Ho(c,l,o);c=u.content;let d=!1;return c.length>jo.pZY&&(c=c.substring(0,jo.pZY),d=!0),new Oo.sV({result:{case:"success",value:new Oo.mE({path:t,output:{case:"content",value:c},totalLines:l,fileSize:BigInt(r.size),truncated:d,rangeApplied:u.rangeApplied})}})}}var Yo=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),Zo=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xo=(0,se.promisify)(_t.execFile);class Qo{activeRecording=null;artifactsDir;stagingDir;display;disablePolishedRendering;polishedRenderer;onRecordingStartedCallback=null;onRecordingStoppedCallback=null;recordingStoppedCallbackInvoked=!1;constructor(e){if(this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await e.inputEventLogger.stop()}catch{}if(!e.childProcess.killed&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await n.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await n.mkdir(this.stagingDir,{recursive:!0}),await n.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return o.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:Yo.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:Yo.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:Yo.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async pathExists(e){try{return await n.access(e),!0}catch{return!1}}async getUniqueArtifactVideoPath(e){const t=o.parse(e),r=t.name||"recording",n=t.ext||".mp4";let s=`${r}${n}`,i=2;for(;await this.pathExists(o.join(this.artifactsDir,s));)s=`${r}-${i}${n}`,i++;return o.join(this.artifactsDir,s)}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,s;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?s=e.filename:(n=e.reason,s=`${o.basename(r)}.mp4`)}else s=`${o.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(s),requestedFilePathRejectedReason:n}}static PROXY_TARGET_WIDTH=1920;static PROXY_TARGET_FPS=60;static PROXY_CRF=17;static PROXY_PRESET="veryfast";static PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1";async getVideoDurationMs(e){const{stdout:t}=await Xo("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await Xo("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e]),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e){const t=o.join(e,"recording"),r=o.join(t,"recording_full.mp4");return await this.polishedRenderer.renderRecordingSession({stagingSessionDir:e,outputVideoPath:r,fps:Qo.PROXY_TARGET_FPS,includeBrandTag:!0}),await n.access(r,n.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await Xo("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e]),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${Qo.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${Qo.PROXY_TARGET_FPS}fps`)}return Qo.PROXY_TARGET_FPS}static DEFAULT_REFRESH_RATE=60;async startFfmpegRecording(e,t){const r=o.join(t,"recording");await n.mkdir(r,{recursive:!0});const s=o.join(r,"recording_render_proxy_1080p.mp4");let i;try{i=(await Tt(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${Qo.DEFAULT_REFRESH_RATE}Hz`),i=Qo.DEFAULT_REFRESH_RATE}const a=["-video_size",e,"-framerate",String(i),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${Qo.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${Qo.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",Qo.PROXY_PRESET,"-crf",String(Qo.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",s],c=(0,_t.spawn)("ffmpeg",a,{stdio:["ignore","pipe","pipe"],detached:!0}),l=new Promise(((e,t)=>{let r="",n=!1;c.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);c.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),c.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);c.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),c.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:c,videoStartedPromise:l}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,_t.spawn)("ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:s,ffmpegStartedEpochMs:i,inputEvents:a,resolution:c,renderProxies:l}=e,u=o.join(t,"recording"),d=o.join(u,"recording-data.json"),p=i-s,h=a.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),m={version:3,durationMs:r,recordingStartEpochMs:s,ffmpegStartedEpochMs:i,eventToVideoOffsetMs:p,displayWidth:c.display.width,displayHeight:c.display.height,apiWidth:c.api.width,apiHeight:c.api.height,inputEvents:h,renderProxies:l??null};await n.writeFile(d,JSON.stringify(m,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(t.killed||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(e){clearTimeout(o),n(new Error(`Failed to send SIGTERM: ${e instanceof Error?e.message:String(e)}`))}}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`})}})}if(t.mode===Yo.$u.UNSPECIFIED)return new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case Yo.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){e=!0;try{await this.cleanupRecording(this.activeRecording),await n.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}this.activeRecording=null}let r=null,o=null,s=null;try{s=this.buildSessionDir(t.toolCallId||"recording"),await n.mkdir(s,{recursive:!0});const{resolutionString:i,resolution:a}=await Tt(this.display),{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(i,s);r=c;const u=function(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}(this.display);o=new Yt({displayNum:u,resolution:a}),await o.start();const d=o.getRecordingStartTime();let p;try{p=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}this.activeRecording={childProcess:r,sessionDir:s,startTime:d,inputEventLogger:o,resolution:a,ffmpegStartedEpochMs:p,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null},this.onRecordingStartedCallback&&this.onRecordingStartedCallback(o),r.once("exit",((e,t)=>{this.activeRecording&&(this.activeRecording.ffmpegDiedEarly=!0,this.activeRecording.ffmpegDiedTime=Date.now(),this.activeRecording.ffmpegExitCode=e,this.activeRecording.ffmpegExitSignal=t)}));const h=!!t.saveAsFilename;return new Yo.Tj({result:{case:"startSuccess",value:new Yo.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:h})}})}catch(e){if(o)try{await o.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return s&&await n.rm(s,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:e instanceof Error?e.message:String(e)})}})}}case Yo.$u.SAVE_RECORDING:{if(!this.activeRecording)return new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:"No active recording to save"})}});const e=this.activeRecording;try{const r=await e.inputEventLogger.stop(),s=e.inputEventLogger.getRecordingStartTime();this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e);const i=e.ffmpegStartedEpochMs??s,a=e.sessionDir,{finalVideoPath:c,requestedFilePathRejectedReason:l}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:a}),u=o.join(a,"recording"),d=o.join(u,"recording_render_proxy_1080p.mp4");try{await n.access(d,n.constants.R_OK)}catch{return this.activeRecording=null,new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:`Recording proxy not found at ${d}`})}})}const[p,h,m]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),f={profileVersion:Qo.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:h.width,height:h.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:h.width,height:h.height,fps:Qo.PROXY_TARGET_FPS,codec:"h264",profile:Qo.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};if(await this.saveRecordingDataPackage({sessionDir:a,durationMs:p,recordingStartEpochMs:s,ffmpegStartedEpochMs:i,inputEvents:r,resolution:e.resolution,renderProxies:f}),this.disablePolishedRendering)await n.copyFile(d,c);else{const e=await this.renderPolished(a);await n.rename(e,c)}return this.activeRecording=null,new Yo.Tj({result:{case:"saveSuccess",value:new Yo.ol({path:c,recordingDurationMs:Mt.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:l})}})}catch(t){return await this.cleanupRecording(e),this.invokeStoppedCallbackOnce(),this.activeRecording=null,new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:t instanceof Error?t.message:String(t)})}})}}case Yo.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:"No active recording to discard"})}});const e=this.activeRecording;try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await n.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new Yo.Tj({result:{case:"discardSuccess",value:new Yo.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;return this.activeRecording=null,new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:`Failed to discard recording: ${t instanceof Error?t.message:String(t)}. Session may remain at: ${r}`})}})}}default:{const e=t.mode;return new Yo.Tj({result:{case:"failure",value:new Yo.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{Zo(r)}}}var es=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");async function ts(e){const t=await(0,n.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=o.join(e,n.name),s={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(s.children=await ts(t)),r.push(s)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function rs(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...rs(t,e,s))}))}return n}async function ns(e){if(!await(0,n.access)(e,n.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await ts(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>rs(e,"",r===t.length-1))).join("\n")}async function os(e,t){return ns(o.join(e,"agent-notes",t))}async function ss(e){return ns(o.join(e,"agent-notes","shared"))}var is=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},as=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const cs=(0,c.h)("local-exec:request-context");async function ls(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{is(o,(0,c.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{as(o)}}async function us(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function ds(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,T.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,T.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}async function ps(e,t,r={}){const{projectDir:n,notesSessionId:o,metaAgentNotesEnabled:s,getSmartModeClassifierAutoModeEnabled:i,devForceNextSmartModeClassifierBlockToken:a,isWorkingDirHomeDir:c,getSandboxEnabled:l,getSandboxSupported:u,getNetworkAllowlistInfo:d,userTerminalHint:p,artifactsFolder:h,secretRedactionEnabled:m,getComputerUseSupported:f}=r,g=`${oe.default.platform()} ${oe.default.release()}`,v=(0,T.G6)(p),y=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),w=n,b=n?`${n}/terminals`:void 0,k=n&&!0!==s?`${n}/agent-notes/shared`:void 0,S=n&&o?`${n}/agent-notes/${o}`:void 0,E=n?`${n}/agent-transcripts`:void 0,x=!!l&&l(),_=u?.(),C=i?.();let P;if(d)try{P=await d()}catch{P=void 0}return new es.GE({osVersion:g,workspacePaths:t,shell:v,sandboxEnabled:x,projectFolder:w,terminalsFolder:b,agentSharedNotesFolder:k,agentConversationNotesFolder:S,agentTranscriptsFolder:E,timeZone:y,processWorkingDirectory:process.cwd(),artifactsFolder:h,...void 0!==C&&{smartModeClassifierAutoModeEnabled:C},...void 0!==a&&{devForceNextSmartModeClassifierBlockToken:a},...void 0!==m&&{secretRedactionEnabled:m},...void 0!==_&&{sandboxSupported:_},...void 0!==P?.hasDefaults&&{sandboxNetworkHasDefaults:P.hasDefaults},...P?.explicitEntries&&P.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:P.explicitEntries},...void 0!==f&&{computerUseSupported:f()},...void 0!==c&&{isWorkingDirHomeDir:c}})}const hs={type:"object",properties:{},additionalProperties:!1};function ms(e){const t=e?.trim();return t||void 0}function fs(e,t){const r=function(e){return ms(e.serverIdentifier)}(e);if(r)return r;const n=ms(e.serverName);return n?t.get(n)??n:void 0}function gs(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}class vs{mcpLease;constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(cs.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(cs.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r){const n=new Map;for(const t of e)n.has(t.providerIdentifier)||n.set(t.providerIdentifier,t.clientKey);const o=t.map((e=>fs(e,n))).filter((e=>Boolean(e)));return{servers:[...new Set([...e.map((e=>e.clientKey)),...o,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e)).map((([e])=>e))])].map((o=>{const s=e.filter((e=>e.clientKey===o));return{serverName:s[0]?.providerIdentifier??o,serverIdentifier:o,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>fs(e,n)===o)),status:r?.get(o)}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(cs.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>[t,gs(await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"}))))])));return new Map(n)}(e,this.mcpLease))}}class ys{mcpStateAccessor;constructor(e){this.mcpStateAccessor=e}async execute(e,t){return r=await this.mcpStateAccessor.getState(e),new Er._W({result:{case:"success",value:new Er.pv({servers:r.servers.map((e=>new Er.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new nr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?Mt.Value.fromJson(e.inputSchema):void 0}))),instructions:e.instructions,status:e.status})))})}});var r}}class ws{cursorRulesService;cloudRulesService;subagentsService;repositoryProvider;grepProvider;lsExecutor;mcpStateAccessor;gitExecutor;workspacePaths;getSandboxEnabled;getSandboxSupported;getNetworkAllowlistInfo;getSmartModeClassifierAutoModeEnabled;devForceNextSmartModeClassifierBlockToken;projectDir;isWorkingDirHomeDir;userTerminalHint;getMcpFileSystemOptions;mcpMetaToolEnabled;alwaysExposeVirtualMcpAuthTool;artifactsFolder;secretRedactionEnabled;attributionConfigProvider;isAttributionDisabledByAdmin;getAgentSkills;additionalRules;getComputerUseSupported;cachedWorkspaces=new Map;inFlightWorkspaceWarms=new Map;globalCache;globalCacheTraceId;cacheDebounceTimeout;fileWatcher;constructor(e,t,r,n,o,s,i,a,c,l={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.lsExecutor=s,this.mcpStateAccessor=i,this.gitExecutor=a,this.workspacePaths=c;const{projectDir:u,getSmartModeClassifierAutoModeEnabled:d,devForceNextSmartModeClassifierBlockToken:p,isWorkingDirHomeDir:h,createFileWatcher:m,warmRequestContext:f,getSandboxEnabled:g,getSandboxSupported:v,getNetworkAllowlistInfo:y,userTerminalHint:w,getMcpFileSystemOptions:b,mcpMetaToolEnabled:k,alwaysExposeVirtualMcpAuthTool:S,artifactsFolder:E,secretRedactionEnabled:x,attributionConfigProvider:_,isAttributionDisabledByAdmin:C,getAgentSkills:P,additionalRules:R,getComputerUseSupported:T}=l;this.projectDir=u,this.isWorkingDirHomeDir=h,this.getSandboxEnabled=g,this.getSandboxSupported=v,this.getNetworkAllowlistInfo=y,this.getSmartModeClassifierAutoModeEnabled=d,this.devForceNextSmartModeClassifierBlockToken=p,this.userTerminalHint=w,this.getMcpFileSystemOptions=b,this.mcpMetaToolEnabled=k??!1,this.alwaysExposeVirtualMcpAuthTool=S??!1,this.artifactsFolder=E,this.secretRedactionEnabled=x,this.attributionConfigProvider=_,this.isAttributionDisabledByAdmin=C,this.getAgentSkills=P,this.additionalRules=R??[],this.getComputerUseSupported=T,this.warmWorkspaceCaches(),!0===f&&this.rebuildGlobalCache(),void 0!==m&&(!0!==f&&this.rebuildAllCaches(),this.fileWatcher=m(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,c.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=is(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"getGitRepoPathForWorkspacePath"})).stdout.trim()}catch{return null}}(n.ctx,this.gitExecutor,t),s=o?await pe(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?he(s):void 0};this.cachedWorkspaces.set(t,i)}catch(e){r.error=e,r.hasError=!0}finally{as(r)}}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,c.q6)(),r=is(e,(0,c.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId,this.globalCache=this.computeGlobalCache(r.ctx)}catch(t){e.error=t,e.hasError=!0}finally{as(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=is(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,l,u,d]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),p=Math.round(performance.now()-o);return p>1e3&&cs.warn(r.ctx,"computeGlobalCache: slow",{totalMs:p,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{as(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0}async collectWorkspaceCaches(e){const t={stack:[],error:void 0,hasError:!1};try{const r=is(t,(0,c.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let n;if(this.grepProvider.getTrackedState)try{n=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{n=void 0}let o=!0;const s=(await Promise.all(this.workspacePaths.map((async e=>{const t=this.getWorkspaceCache(e);if(void 0===t)return o=!1,void this.ensureWorkspaceCacheWarm(r.ctx,e);const s=n?.[e];if(void 0!==s)return new es.DS({path:t.repoPath,status:s.gitStatus,branchName:s.gitBranchName,remoteUrl:t.remoteUrl});if(void 0===t.repoPath)return;const{status:i,branchName:a}=await async function(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(ls(e,t,r,n)),o(us(e,t,r,n))]);return{status:s,branchName:i}}(r.ctx,this.gitExecutor,t.repoPath,3e3);return new es.DS({path:t.repoPath,status:i,branchName:a,remoteUrl:t.remoteUrl})})))).filter((e=>void 0!==e));return{gitRepos:s,gitRepoInfoComplete:o}}catch(e){t.error=e,t.hasError=!0}finally{as(t)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=is(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),o=this.projectDir,s=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=is(e,(0,c.VI)(n.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),void 0===this.globalCache){const e=this.computeGlobalCache(n.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)}))}return this.globalCache}catch(t){e.error=t,e.hasError=!0}finally{as(e)}},i=performance.now(),a={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{a[e]=Math.round(performance.now()-r)}))},[u,d,p,{gitRepos:h,gitRepoInfoComplete:m},f,g,v,y,w]=await Promise.all([l("globalCache",s()),l("mcpState",this.mcpStateAccessor.getState(n.ctx)),l("env",ps(n.ctx,this.workspacePaths,{projectDir:o,notesSessionId:t.notesSessionId,metaAgentNotesEnabled:!1,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.artifactsFolder,secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported})),l("git",this.collectWorkspaceCaches(n.ctx)),l("conversationNotes",o&&t.notesSessionId?os(o,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",o?ss(o):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(n.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",this.getAgentSkills?this.getAgentSkills(n.ctx):Promise.resolve([]))]),b=performance.now()-i;for(const[e,t]of Object.entries(a))n.span.setAttribute(`requestContext.timing.${e}Ms`,t);n.span.setAttribute("requestContext.timing.totalMs",Math.round(b)),b>1e3&&cs.warn(n.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(b),...a});const k=this.mcpMetaToolEnabled?function(e,t){const r=e.servers.map((e=>{const r=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),n=e.tools.map((e=>new nr.E$({toolName:e.toolName,description:e.description,inputSchema:void 0!==e.inputSchema?Mt.Value.fromJson(e.inputSchema):void 0})));return!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||n.some((e=>e.toolName===Or))||n.push(new nr.E$({toolName:Or,description:"Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",inputSchema:Mt.Value.fromJson(hs)})),new nr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:r||void 0,tools:n})}));return new nr.U_({enabled:!0,mcpDescriptors:r})}(d,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool}):void 0,S=this.attributionConfigProvider?.get(),E=!y&&(S?.attribution?.attributeCommitsToAgent??!0),x=!y&&(S?.attribution?.attributePRsToAgent??!0),_=new es.bb({rules:u.rules,env:p,gitRepos:h,gitRepoInfoComplete:m,repositoryInfo:u.codebaseReference?[{relativeWorkspacePath:u.codebaseReference.relativeWorkspacePath,repoName:u.codebaseReference.repoName,repoOwner:u.codebaseReference.repoOwner,isTracked:u.codebaseReference.isTracked,isLocal:u.codebaseReference.isLocal,orthogonalTransformSeed:u.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:u.codebaseReference.pathEncryptionKey}]:[],tools:d.servers.flatMap((e=>e.tools)).map((e=>new nr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?Mt.Value.fromJson(e.inputSchema):void 0}))),conversationNotesListing:f,sharedNotesListing:g,mcpInstructions:d.servers.flatMap((e=>e.instructions)),customSubagents:u.customSubagents,mcpFileSystemOptions:v,mcpMetaToolOptions:k,supportsMcpAuth:!0,commitAttributionMessage:E?"enabled":void 0,prAttributionMessage:x?"enabled":void 0,agentSkills:w});return null!==u.cloudRule&&void 0!==u.cloudRule&&(_.cloudRule=u.cloudRule),_}catch(e){r.error=e,r.hasError=!0}finally{as(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=is(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=await this.computeCachedRequestContext(n.ctx,t);return new es._G({result:{case:"success",value:new es.yW({requestContext:e})}})}catch(e){return n.span.recordException(e),new es._G({result:{case:"error",value:new es.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{as(r)}}}function bs(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===u._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var ks=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Ss{permissionsService;coreExecutor;ignoreService;constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new u.W4({result:{case:"success",value:new u.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:O(e.sandboxPolicy)}):new u.W4({result:{case:"failure",value:new u.xC({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:O(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,i,l="",u="",d=null,p=!1;const h=o?{perRepo:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:h,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?l+=o.data:"stderr"===o.type?u+=o.data:"exit"===o.type&&(d=null!=o.code?0|o.code:null,n=o.outputLocation,p=o.aborted,i=yr(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,f={command:t.command,workingDirectory:r,exitCode:p?-1:d??-1,signal:p?"SIGTERM":"",stdout:l,stderr:u,executionTime:m,localExecutionTimeMs:i,sandboxPolicy:o,outputLocation:n};return this.buildResultFromExit(f)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new u.W4({result:{case:"timeout",value:new u.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:O(o)}):e.signal.aborted?new u.W4({result:{case:"rejected",value:new u.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:O(o)}):new u.W4({result:{case:"spawnError",value:new u.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:O(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?j(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(),l=bs(t),d=(0,p.o1)(i);if(!t.parsingResult)return new u.W4({result:{case:"spawnError",value:new u.mJ({command:o,workingDirectory:d,error:"Parsing result is required"})}});let h;if(t.skipApproval)h=s;else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:d,timeout:l,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:(0,a.oG)(t)},s);if("block"===e.kind)return"permissionsConfig"===e.reason.type&&e.reason.isReadonly?new u.W4({result:{case:"permissionDenied",value:new u.jn({command:o,workingDirectory:d,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new u.W4({result:{case:"rejected",value:new u.pZ({command:o,workingDirectory:d,reason:M(e.reason)})}});h=e.policy}if(k()&&(h=P(o,t.parsingResult)),h&&"insecure_none"!==h.type){const e=await this.ignoreService.getCursorIgnoreMapping();h={...h,ignoreMapping:e}}return this.executeWithPolicy(n,t,i,l,h)}catch(e){r.error=e,r.hasError=!0}finally{ks(r)}}}var Es=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class xs{permissionsService;constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new u.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new Es.e({allowlisted:n})}}class _s{shellStreamExecutor;constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new u.jK({status:u.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}var Cs=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ps=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rs=(0,c.h)("local-exec:shell-core"),Ts="win32"===process.platform;class Is{executor;workspacePath;projectDir;shellOutputBackpressureOptions;constructor(e,t,r,n){this.executor=e,this.workspacePath=t,this.projectDir=r,this.shellOutputBackpressureOptions=n}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Cs(r,(0,c.VI)(e.withName("ShellCoreExecutor.execute")),!1);const s=performance.now(),a=t.workingDirectory||await this.executor.getCwd(),l=(0,p.o1)(a,this.workspacePath);let u,d=0,h=0,m=!1,f=!1,g=!1;t.fileOutputThresholdBytes&&this.projectDir&&(u={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const v=t.signal,y=(0,T.CG)(t.sandboxPolicy??T.BM);t.sandboxPolicy&&(yield{type:"start",sandboxed:"workspace_readonly"===y||"workspace_readwrite"===y});const w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,p.sh)(t.conversationId)),this.projectDir&&(w.AGENT_TRANSCRIPTS=o.default.join(this.projectDir,p.O2)),t.askpassConfig&&!Ts&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let b=0,k="";for await(const r of this.executor.execute(e,t.command,{signal:v,workingDirectory:l,env:w,sandboxPolicy:t.sandboxPolicy,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,bufferOutputEvents:this.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.shellOutputBackpressureOptions?.outputLimiterOptions})){if(b=0,k="",("stdout"===r.type||"stderr"===r.type)&&(k=r.data.toString(),b=r.data.length,u))if(u.size+=b,u.lineCount+=k.split("\n").length-1,u.size>kr);else if(u.file)u.file.write(k);else if(u.buffer+=k,u.size>u.threshold){const e=o.default.join(this.projectDir,br);u.path=o.default.join(e,`${(0,St.randomUUID)()}.txt`),await(0,n.mkdir)(o.default.dirname(u.path),{recursive:!0}),u.file=(0,i.createWriteStream)(u.path),u.file.write(u.buffer),u.buffer=""}switch(r.type){case"stdout":m||(d+b>Xt?(m=!0,yield{type:"stdout_trimmed"}):(d+=b,yield{type:"stdout",data:k}));break;case"suppressed_output":g||(g=!0,yield{type:"stdout",data:T.Ls});break;case"stderr":f||(h+b>Xt?(f=!0,yield{type:"stderr_trimmed"}):(h+=b,yield{type:"stderr",data:k}));break;case"exit":{const e=Math.max(0,Math.round(performance.now()-s));let t;u?.file&&(await new Promise((e=>u.file.end(e))),t=new vt.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})),yield{type:"exit",code:r.code,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}}catch(e){r.error=e,r.hasError=!0}finally{Ps(r)}}async getCwd(){return this.executor.getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class As{innerExecutor;shellManager;constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Cs(r,(0,c.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Rs.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Ps(r)}}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class js{innerExecutor;askpassConfig;constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}var Os=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ds=(0,c.h)("local-exec:shell-stream");class Ms{iterator;timeoutMs;pendingPromise=null;stopReason;timer;stopResolve;stopPromise;constructor(e,t){this.iterator=e,this.timeoutMs=t,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===u.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:u.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:u.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}class Ns{permissionsService;coreExecutor;ignoreService;backgroundShellManager;activeForegroundExecutions=new Map;constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n}async forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e),r=t?.requestBackground();return r?new u.jK({status:u.iA.ACCEPTED,shellResult:r}):new u.jK({status:u.iA.NOT_FOUND})}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,c.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const n=t.command;let o=t.requestedSandboxPolicy?j(t.requestedSandboxPolicy):void 0;if(o&&"insecure_none"!==o.type){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}const s=t.workingDirectory||await this.coreExecutor.getCwd(),i=bs(t),l=(0,p.o1)(s),d=Date.now();if(!t.parsingResult)throw new Error("Parsing result is required");const h=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0},o);if("block"===h.kind)return"permissionsConfig"===h.reason.type?void(yield new u.FI({event:{case:"permissionDenied",value:new u.jn({command:n,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:h.reason.isReadonly??!1})}})):void(yield new u.FI({event:{case:"rejected",value:new u.pZ({command:n,workingDirectory:l,reason:M(h.reason)})}}));if(Ds.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:t.parsingResult?.executableCommands.length??0,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),t.skipApproval)Ds.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"});else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:l,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:(0,a.oG)(t)},o);if("block"===r.kind){if(Ds.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===r.reason.type)return void(yield new u.FI({event:{case:"permissionDenied",value:new u.jn({command:n,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const o=M(r.reason);return void(yield new u.FI({event:{case:"rejected",value:new u.pZ({command:n,workingDirectory:l,reason:o})}}))}o=r.policy,Ds.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:o.type})}if(k()&&(o=P(n,t.parsingResult),"insecure_none"!==o.type)){const e=await this.ignoreService.getCursorIgnoreMapping();o={...o,ignoreMapping:e}}yield new u.FI({event:{case:"start",value:new u.tD({sandboxPolicy:O(o)})}});const m=t.timeoutBehavior===u._d.BACKGROUND,f=m&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,v=m?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,w=o?{perRepo:o}:void 0,b=this.coreExecutor.execute(e,{command:n,workingDirectory:s,signal:v,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:w,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:f,showElapsedTime:y});let S;m||(S=setTimeout((()=>g.abort()),i));const E=m?new Ms(b[Symbol.asyncIterator](),i):null;let x,_,C,R="",T=!1;const I=t.toolCallId&&E?{requestBackground:()=>{if(E.requestBackground())return C=C??this.backgroundShellManager.generateShellId(),new u.W4({result:{case:"success",value:new u.QR({shellId:C,pid:_,command:n,workingDirectory:l,msToWait:yr(Date.now()-d),backgroundReason:u.Jg.USER_REQUEST,interleavedOutput:R})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I);const A=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)};let D;E&&e.signal&&e.signal.addEventListener("abort",(()=>{E.backgroundRequested||(g.abort(),E.abort())}),{once:!0});const N=t.hardTimeout;void 0!==N&&N>0&&(D=setTimeout((()=>{void 0!==C?this.backgroundShellManager.abort(C)||g.abort():(T=!0,g.abort(),E?.abort())}),N));const $=E?.iterate()??b;try{for await(const t of $)if("stdout"===t.type)R+=t.data,yield new u.FI({event:{case:"stdout",value:new u.o0({data:t.data})}});else if("stderr"===t.type)R+=t.data,yield new u.FI({event:{case:"stderr",value:new u.Db({data:t.data})}});else if("stdin_ready"===t.type)x=t.stdin,_=t.pid;else if("exit"===t.type){let r;t.aborted&&(r=e.signal?.aborted?u.Lv.USER_ABORT:E?.timedOut||g.signal.aborted?u.Lv.TIMEOUT:u.Lv.USER_ABORT),yield new u.FI({event:{case:"exit",value:new u.vb({code:(t.code??0)>>>0,cwd:await this.coreExecutor.getCwd(),outputLocation:t.outputLocation,aborted:t.aborted,abortReason:r,localExecutionTimeMs:yr(t.localExecutionTimeMs)})}})}}finally{clearTimeout(S),E?.backgroundRequested||clearTimeout(D),A()}if(E?.backgroundRequested&&!T){const r=C??this.backgroundShellManager.generateShellId();C=r;const o=E.backgroundReasonValue===u.Jg.USER_REQUEST?u.Jg.USER_REQUEST:u.Jg.TIMEOUT,s=o===u.Jg.USER_REQUEST?Date.now()-d:i;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:n,workingDirectory:l,toolCallId:t.toolCallId,sandboxPolicy:w,initialOutput:R,stdin:x,pid:_,abortController:g,eventIterator:E.getHandoffIterator(),startTime:d,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification}),yield new u.FI({event:{case:"backgrounded",value:new u.Y9({shellId:r,command:n,workingDirectory:l,pid:_,msToWait:y?s:void 0,reason:o})}})}else e.signal?.aborted&&void 0!==E?.stopReasonValue?(clearTimeout(D),yield new u.FI({event:{case:"exit",value:new u.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(),aborted:!0,abortReason:u.Lv.USER_ABORT})}})):clearTimeout(D)}catch(e){r.error=e,r.hasError=!0}finally{Os(r)}}}var $s=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class Ls{permissionsService;constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new $s.M({allowlisted:r})}}var Fs=r("node:constants");const Us=(0,o.join)((0,oe.homedir)(),".cursor","projects"),Bs=(0,o.join)((0,oe.homedir)(),".cursor","worktrees");function Hs(e){return lo(Us,e)&&e!==Us}function zs(e){return lo(Bs,e)&&e!==Bs}function Ws(e,t){const r=function(e){if(!lo(Us,e))return;if(e===Us)return;const t=(0,o.relative)(Us,e).split(o.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}var qs=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Gs=(0,c.h)("LocalWriteExecutor"),Vs=async(e,t,r,n)=>{const o=setTimeout((()=>{Gs.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};class Js{fileChangeTracker;permissionsService;pendingDecisionProvider;workspacePaths;workspacePath;worktreeMainPath;onWriteForAiTracking;constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,onWriteForAiTracking:i}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.onWriteForAiTracking=i}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,i=t.path,a=t.fileText,l=t.fileBytes.length>0?t.fileBytes:void 0,u=(0,p.o1)(i,this.workspacePath),d=Ws(u,["assets","agent-tools","swarm-agents"]);if((0,p.fl)({targetPath:u,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new wr.v3({result:{case:"error",value:new wr.QM({path:u,error:p.PS})}});let h,m=!1;try{(await(0,n.stat)(u)).size<=Qt?h=await Vs(s,"readText before write",3e3,(()=>(0,p.yR)(u,t.encodingHint))):m=!0}catch{}const f=await Vs(s,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(s,u,a)));if(f){const e=await Vs(s,"handleBlockReason",3e3,(()=>D(f,{onNeedsApproval:async(e,r)=>{const n="fileEdit"!==r?.type||r.isNewFile,o="fileEdit"===r?.type?r.diffString:a,s="fileEdit"===r?.type?r.blockReason:void 0,i=await this.pendingDecisionProvider.requestApproval({type:er.Write,details:{path:u,reason:e,isNewFile:n,diffString:o,before:h,after:a,blockReason:s},toolCallId:t.toolCallId});return i.approved?null:new wr.v3({result:{case:"rejected",value:new wr.en({path:u,reason:i.reason||""})}})},onUserRejected:e=>new wr.v3({result:{case:"rejected",value:new wr.en({path:u,reason:e||""})}}),onPermissionDenied:(e,t)=>new wr.v3({result:{case:"permissionDenied",value:new wr.U7({path:u,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const g=(0,o.dirname)(u);try{await Vs(s,"mkdir",3e3,(()=>(0,n.mkdir)(g,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new wr.v3({result:{case:"permissionDenied",value:new wr.U7({path:u,directory:g,operation:"create_directory",error:"Permission denied"})}}):new wr.v3({result:{case:"error",value:new wr.QM({path:u,error:e.message})}})}let v,y;if(void 0!==l)v=l,y=0;else{const e=await Vs(s,"getBufferForWrite",3e3,(()=>(0,p.Bh)(u,a,this.workspacePath,t.encodingHint)));v=e.buffer,y=e.lines}try{await Vs(s,"writeFile",3e3,(async()=>{let e;await(0,n.writeFile)(u,v,{flush:!0});try{e=await(0,n.open)((0,o.dirname)(u),Fs.default.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new wr.v3({result:{case:"permissionDenied",value:new wr.U7({path:u,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new wr.v3({result:{case:"noSpace",value:new wr.bM({path:u})}}):new wr.v3({result:{case:"error",value:new wr.QM({path:u,error:e.message})}})}if(this.fileChangeTracker&&void 0===l&&!d&&!m){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(u,h,a,e)}if(this.onWriteForAiTracking&&void 0===l&&!d){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:u,beforeContent:h,afterContent:a,metadata:e})}catch(e){Gs.warn(s,"onWriteForAiTracking failed (write succeeded)",{path:u,error:e instanceof Error?e.message:String(e)})}}const w=v.byteLength;let b;if(t.returnFileContentAfterWrite)try{b=await Vs(s,"readText after write",3e3,(()=>(0,p.yR)(u,t.encodingHint)))}catch{}return new wr.v3({result:{case:"success",value:new wr.j6({path:u,linesCreated:y,fileSize:w,...void 0!==b&&{fileContentAfterWrite:b}})}})}catch(e){r.error=e,r.hasError=!0}finally{qs(r)}}}class Ks extends a.h{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}backgroundShellExecutor;computerUseExecutor;pendingDecisionStore;fileChangeTracker;gitExecutor;ignoreService;grepProvider;permissionsService;workspacePaths;worktreeMainPath;diagnosticsProvider;mcpLease;mcpStateAccessor;cursorRulesService;cloudRulesService;subagentsService;repositoryProvider;projectDir;shellManager;_sandboxPolicyResolver;_defaultSandboxPolicy;_defaultSandboxPolicySources;mcpFileOutputThresholdBytes;backgroundShellFactory;backgroundWorkRegistry;wakeupOwnerConversationId;mcpElicitationFactory;createFileWatcher;sharedRequestContextExecutor;terminalExecutor;userTerminalHint;enableRecordScreen;recordScreenArtifactsDir;recordScreenDisplay;disableRecordScreenRendering;attributionConfigProvider;isAttributionDisabledByAdmin;getAgentSkills;getSmartModeClassifierAutoModeEnabled;devForceNextSmartModeClassifierBlockToken;mcpMetaToolEnabled;additionalRules;askpassConfig;recordScreenExecutor;constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,o.join)(e,".cursor/sandbox.json");try{const r=(0,i.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,T.$6)(n);return(0,T.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig;const s=this.terminalExecutor??(0,T.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let c;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,o.dirname)(e)));c=e.every((t=>t===e[0]))?e[0]:void 0}else c=t;let l=new Is(s,t??(0,oe.homedir)(),this.projectDir,e.shellOutputBackpressureOptions);e.shellCoreWrapper&&(l=e.shellCoreWrapper(l)),this.askpassConfig&&(l=new js(l,this.askpassConfig)),this.shellManager&&(l=new As(l,this.shellManager));const u=e.overrideShellExecutor??new Ss(this.permissionsService,l,this.ignoreService,this.pendingDecisionStore);this.register(a.qk,so(u));const d=e.overrideWriteExecutor??new Js(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:c,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking});this.register(a.Ln,so(d)),this.register(a.Rp,so(new rr(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,c,e.onDeleteForAiTracking))),this.register(a.IG,so(new lr)),this.register(a.jH,new To);const h=this.mcpStateAccessor??new vs(this.mcpLease);this.register(a.u8,so(new dn(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:h})));const m=so(e.overrideReadExecutor??new Ko(this.permissionsService,c,{mcpStateAccessor:h,useStreamingRead:e.useStreamingRead}));this.register(a._A,m),e.registerRedactedReadExecutor&&this.register(a.Mf,m);const f=new fn(this.permissionsService,this.ignoreService,c);this.register(a.bL,so(f)),this.register(a.T0,so(new Qn(this.permissionsService,c))),this.register(a.TZ,so(new Cn(u))),this.register(a.Pi,so(new Fn(this.permissionsService,d,c))),this.register(a.oh,so(new ro(d,c))),this.register(a.Rd,so(new Vn(this.permissionsService,c))),this.register(a.gh,so(new zn(this.permissionsService,c))),this.register(a.qN,so(new Yn(this.permissionsService,c))),this.register(a.w4,so(new ao(c,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(a.sO,so(new yt(e.getCanvasDiagnostics))),this.register(a.Yi,so(new Ur(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory))),this.register(a.rn,so(new Br(this.mcpLease))),this.register(a.ml,so(new Hr(this.mcpLease,c||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore))),this.register(a.pY,so(new ys(h))),this.register(a.MZ,so(this.sharedRequestContextExecutor??new ws(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,f,h,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,p.yn)(t,(0,oe.homedir)()),createFileWatcher:this.createFileWatcher,warmRequestContext:e.warmRequestContext,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:e.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,artifactsFolder:e.artifactsFolder,secretRedactionEnabled:e.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor}))),this.backgroundShellExecutor=new Z(this.permissionsService,l,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(a.Ok,so(this.backgroundShellExecutor));const g=new Ns(this.permissionsService,l,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(a.wv,function(e,t){const r=new oo.q({max:10,ttl:t?.ttl});return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=o.execId,i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new p.dV(a);r.set(s,c),yield*c.fork()}}}(g)),this.register(a.Gu,new xs(this.permissionsService)),this.register(a.OD,new Ao(this.permissionsService)),this.register(a.sC,new Ls(this.permissionsService));const v=new _s(g);this.register(a.PE,so(v));const y=!1===e.enableWriteBackgroundShellStdin?new no((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new no(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(a.TQ,so(y)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(a.iZ,so(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new Qo({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(a.pq,so(this.recordScreenExecutor))}}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function Ys(e){return e.replace(/\\/g,"/")}function Zs(e,t){for(const r of t){const t=Ys(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var Xs;function Qs(e,t){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return Xs.Plugin;const r=Ys(e.fullPath);return Zs(r,t.builtinDirs)?Xs.Builtin:Zs(r,t.userDirs)?Xs.UserHome:(Zs(r,t.workspaceDirs),Xs.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserHome=1]="UserHome",e[e.Workspace=2]="Workspace",e[e.Plugin=3]="Plugin"}(Xs||(Xs={}));var ei=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ti=(0,se.debuglog)("merged-agent-skills");class ri{services;getDisabledManagedSkillPaths;getPromptSortContext;static CHANGE_COALESCE_MS=1500;onChangeCallbacks=new Set;disposeChangeListeners;changeTimer;constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,c.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(ti("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),[s,i]=await Promise.all([Promise.all(n),Promise.resolve(this.getDisabledManagedSkillPaths()).catch((e=>(ti("getDisabledManagedSkillPaths rejected; fail-open: %s",e instanceof Error?e.message:String(e)),[])))]),a=s.flat(),l=new Set,u=[];for(const e of a){const t=Ye(e.fullPath);l.has(t)||(l.add(t),u.push(e))}let d=u;i.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,i))));const p=this.getPromptSortContext;return void 0!==p?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[je(e.userHomeDirectory).dirPath],r=De(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,o.join)(t,".cursor","rules"));for(const e of Oe(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,t)=>({skill:e,index:t,tier:Qs(e,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,p()):d}catch(e){t.error=e,t.hasError=!0}finally{ei(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),ri.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}const ni=(0,c.h)("skill-sync-manifest"),oi=".sync-manifest.json";async function si(e,t){try{const r=await(0,n.readFile)((0,o.join)(e,oi),"utf-8"),s=JSON.parse(r);return function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(s)?s:(ni.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||ni.warn(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ii(e,t,r){e.skills[t]={lastSyncedAt:r}}function ai(e,t){delete e.skills[t]}var ci=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const li=(0,c.h)("builtin-skills-sync");function ui(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function di(e){const t=te(e.content),r=ui(t.data)?t.data:{};return te.stringify(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ui(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function pi(e,t,r){const s=(0,o.join)(t,r.id),i=(0,o.join)(s,"SKILL.md"),a=r.fileContent;try{if(await(0,n.readFile)(i,"utf-8")===a)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||li.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,n.mkdir)(s,{recursive:!0}),await(0,n.writeFile)(i,a,"utf-8"),!0}async function hi(e,t){try{return(await(0,n.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||li.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function mi(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,c.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),l=(0,o.join)((0,oe.homedir)(),".cursor","skills-cursor");await(0,n.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([si(l,i),hi(i,l)]),p=u.lastInventoryAt;(void 0===p||a-p>=864e5)&&(await async function(e,t,r,n){try{const s=await Promise.all(r.map((async e=>{const r=(0,o.join)(t,e),[s,i]=await Promise.all([fi((0,o.join)(r,"SKILL.md")),"canvas"===e?fi((0,o.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:s,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));li.info(e,"managed_skills.startup_inventory",{skills_on_disk:s,manifest_present:Object.keys(n.skills).length>0})}catch(t){li.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const h=new Map;for(const e of t.managedSkills??[])(s=e.id)&&s===s.trim()&&!(s.includes("..")||s.includes("/")||s.includes("\\"))?h.set(e.id,e):li.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const m=new Set([...h.keys(),...d]);let f=0,g=0;const v=[];for(const e of m)try{const t=h.get(e),r=u.skills[e],s=r?a-r.lastSyncedAt:0,c=void 0!==r&&s>2592e5;if(t&&!1!==t.enabled)await pi(i,l,{id:e,fileContent:di(t)})?f++:g++,ii(u,e,a);else if(!1===t?.enabled||c){const s=!1===t?.enabled?"enabled_false":"grace_expired";await(0,n.rm)((0,o.join)(l,e),{recursive:!0,force:!0}),ai(u,e),v.push(e),li.info(i,"managed_skills.removed",{skill_id:e,reason:s,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null})}else r||ii(u,e,a)}catch(t){li.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,o.join)(e,".sync-manifest.json.tmp"),s=(0,o.join)(e,oi);await(0,n.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,n.rename)(r,s)}(l,u)}catch(e){li.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)})}return{synced:f,upToDate:g,removed:v}}catch(e){r.error=e,r.hasError=!0}finally{ci(r)}var s}async function fi(e){try{return await(0,n.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const gi=(0,c.h)("managed-skills-sync");async function vi(e,t){try{const r=await t.getManagedSkills()??[],n=await mi(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return gi.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}function yi(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class wi{pluginsService;constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...(0,ie.Iq)(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=yi(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var bi=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class ki{workspacePaths;userHomeDirectory;getSettings;marketplaceOptions;localPluginVariablesLookup;plugins=[];_loadFailures=[];loadPromise;loadedOnce=!1;pluginLogger;_extensionPlugins=new Map;_extensionPluginOriginalPaths=new Map;constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.pluginLogger=o??ie.Nz,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{let t=[];try{t=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const r=new Set(e.plugins.map((e=>e.installPath))),n=t.filter((e=>!r.has(e.installPath)));return this.plugins=[...e.plugins,...n],this._loadFailures=e.failures,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${n.length} extension), ${e.failures.length} failures`),this.plugins})).catch((async e=>{this.pluginLogger.log("error",`Failed to load plugins: ${e}`);try{const e=await this._reloadExtensionPlugins();this.plugins=[...e]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${e}`),this.plugins=[]}return this._loadFailures=[],this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,o.resolve)(e),s=await(0,n.realpath)(r);if(!(await(0,n.stat)(s)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${s}`);const i=oe.homedir();if(s.split(o.sep).filter(Boolean).length<3||s===i||"/"===s)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${s}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(s))throw new Error(`Plugin path ${s} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(s))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:s});const c=(0,o.basename)(s),l=await this._loadExtensionPluginContent(s,t);a.set(s,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:s}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${s} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const s=(0,o.resolve)(e);let i;try{i=await(0,n.realpath)(s)}catch{const e=this._extensionPluginOriginalPaths.get(t);i=e?.get(s)??s}const a=r.delete(i);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):a&&this._forgetExtensionPluginOriginalPath(t,i),a&&this.pluginLogger.log("info",`Unregistered extension plugin: ${i} (extension: ${t})`),a}async _loadExtensionPluginContent(e,t){const r=(0,o.basename)(e),n={name:r,localPath:e,extensionId:t},s=await(0,ie.Y_)(e,r,{name:r,version:"0.0.0"});return s.displayName&&(n.name=s.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==s.displayName&&{displayName:s.displayName},...void 0!==s.description&&{description:s.description},...void 0!==s.authorName&&{authorName:s.authorName},skills:s.skills,rules:s.rules,agents:s.agents,commands:s.commands,mcpConfig:s.mcpConfig??void 0,capabilities:s.capabilities,hooks:s.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${e}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const n=(0,c.q6)().withName("LocalPluginsService.load"),o=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,c.VI)(n),!1),performance.now()),s=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-o,{outcome:e})},i=this.getSettings(),a=(t=this.marketplaceOptions,r=this.userHomeDirectory,void 0===t?[]:(Array.isArray(t)?t:[t]).map((e=>({...e,userHomeDir:r})))),l=i.importThirdPartyPlugins,u=i.loadUserLocalPlugins??!0,d=i.loadUserSettingsPlugins??!1,p=i.loadCursorFirstParty??a.length>0;if(!(l||p||u||d))return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, user-local, and user-settings plugins are disabled"),{plugins:[],failures:[]};this.pluginLogger.increment("local_plugins_service.load.start",1);const h=this.workspacePaths[0]??void 0,m=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await(0,ie.wp)(h,{userHomeDir:this.userHomeDirectory,loadClaude:l,loadUserLocal:u,loadUserSettings:d,loadCursorFirstParty:p&&a.length>0,marketplaceSources:a.length>0?a.map((e=>({...e,onCursorError:m}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return s("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-o).toFixed(1)}ms`),e}catch(e){return s("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${e}`),{plugins:[],failures:[]}}}catch(t){e.error=t,e.hasError=!0}finally{bi(e)}var t,r}}var Si=r("../agent-core/dist/index.js");function Ei(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function xi(e){switch(e.code){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:e.code};case"ELOOP":return{status:"symlinkLoop",errno:e.code};default:return{status:"unknownError",errno:e.code??"UNKNOWN",message:e.message}}}async function _i(e,t){const r=(0,p.o1)(e,t);try{return Ei(await(0,n.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return Ei(r,r,xi(t));try{if((await(0,n.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,n.readlink)(r)}catch{}return Ei(r,r,{status:"danglingSymlink",symlinkTarget:e})}return Ei(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){const t=e;return"ENOENT"===t.code?async function(e){let t=(0,o.dirname)(e);const r=[(0,o.basename)(e)];for(;(0,o.dirname)(t)!==t;){try{const s=await(0,n.realpath)(t);return Ei((0,o.join)(s,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return Ei(e,e,xi(r))}r.unshift((0,o.basename)(t)),t=(0,o.dirname)(t)}return Ei(e,e,{status:"newFile"})}(r):Ei(r,r,xi(t))}}}function Ci(e){return"resolved"===e.status||"newFile"===e.status}function Pi(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}var Ri=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ti=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ii=(0,c.h)("permissions-service"),Ai=(0,Et.Pu)("local_exec.permissions.mcp_allowlist_check.result",{description:"Result of MCP allowlist checks at user and team levels per tool call.",labelNames:["allowlist_scope","outcome"]});function ji(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function Oi(e){return[...new Set(e)]}function Di(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Mi({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function Ni(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function $i(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Li(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText&&(0,T.Nl)(e.targetText)}async function Fi({targetText:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n,pathModule:o,tempPathOptions:s}){if(""!==o.parse(e).root&&!o.isAbsolute(e))return;const i=await n(e,t);if(Ci(i.resolution)){for(const e of r){const t=await n(e);if(Ci(t.resolution)&&Mi({basePath:t.resolvedPath,targetPath:i.resolvedPath,pathModule:o}))return"workspace-file"}return Gi(i.resolvedPath,s)?"tmp-file":void 0}}function Ui(e){return Oi(e.map((e=>e.trim())).filter(Boolean))}function Bi(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Hi(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function zi(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new u.r6({type:"word",value:e})));return new u.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Wi(e,t={}){return{type:e,...t}}function qi(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1],n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Gi(e,{platform:t,env:r,pathModule:n}){if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}return"darwin"===t?["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/"].some((t=>e.startsWith(t))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((t=>e.startsWith(t)))}function Vi(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,T.$b)(e.networkPolicy),n=(0,T.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,T._B)(e.networkPolicy),s=(0,T._B)(t.networkPolicy);return!(o&&n&&!s)&&("workspace_readonly"===e.type&&"workspace_readwrite"===t.type||e.type===t.type)}class Ji{command;requestedPolicy;state;matchForms;constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&Vi(t,r);this.state=o?"preapproved":"approvable";const s=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:s}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Vi(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Ki(e){return e?.type??"undefined"}class Yi{ignoreService;pendingDecisionStore;permissionsProvider;teamSettingsService;adminNetworkControlsEnabled;rootDirectories;perUserSandboxConfigPath;mcpAllowlistLog;constructor(e,t,r,n,s,i=!1,a){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=i,this.rootDirectories=Array.isArray(s)?s:[s??process.cwd()],this.perUserSandboxConfigPath=a?.perUserSandboxConfigPath??(0,o.join)((0,oe.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=a?.mcpAllowlistLog}async shouldBlockRead(e,{cursorIgnoreChecked:t=!1}={}){const r=(0,p.o1)(e),n=await ve(r);return null===n?{type:"unsafeResolution",message:ji("Read","path",r)}:await this.ignoreService.isRepoBlocked(n)?{type:"adminBlock",source:"Team repo blocklist"}:await this.isPathExplicitlyDenied("Read",r)?{type:"permissionsConfig"}:!Hs(n)&&!zs(n)&&(!t&&await this.ignoreService.isCursorIgnored(n)?{type:"cursorIgnore"}:(await this.isPathExplicitlyAllowed("Read",r),!1))}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Ri(n,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const s=await _i(t);if(!Ci(s.resolution))return{type:"unsafeResolution",message:Pi(s.originalPath,s.resolution)};const i=s.resolvedPath,a=i;if(await this.ignoreService.isRepoBlocked(a))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",i))return{type:"permissionsConfig"};const l=s.originalPath.split(o.sep).pop()?.toLowerCase()??"",u=i.split(o.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};const d=Hs(a),h=zs(a),m=!d&&!h&&await this.ignoreService.isCursorIgnored(a);if(d||h);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",i))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(i))return!1;const f=await this.getPermissions();if("workspace_readonly"===f.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===f.approvalMode)return!1;const g="win32"===process.platform||"darwin"===process.platform;for(const e of this.rootDirectories){const t=await _i(e);if(!Ci(t.resolution))continue;const r=t.resolvedPath;if(g?i.toLowerCase()===r.toLowerCase()||i.toLowerCase().startsWith(r.toLowerCase()+o.sep):i===r||i.startsWith(r+o.sep)){const e=(0,o.relative)(r,i).split(o.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const v=async()=>{let e=!1,t="";try{t=await(0,p.yR)(i),e=!1}catch{e=!0}let n="";if(e)n=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,Tn.YB)("a","b",e(t),e(r),"","",{context:2});n=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:n}};let y,w=!1;for(const e of this.rootDirectories){const t=await _i(e);if(!Ci(t.resolution))continue;const r=t.resolvedPath;if(i.toLowerCase().startsWith(r.toLowerCase())){w=!0,y=r;break}}const b=w?void 0:function(e){if(!zs(e))return;const t=(0,o.relative)(Bs,e).split(o.sep).filter(Boolean);return 0!==t.length?(0,o.join)(Bs,t[0]):void 0}(i);if(!w&&void 0===b){if(function(e){return Gi(e,{platform:process.platform,env:process.env,pathModule:o})}(i))return!1;if(Ws(i,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,oe.homedir)()}${o.sep}.cursor${o.sep}`;if(i.startsWith(e)){const e=i.split(o.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const k=y??b,S=i;let E=(0,o.relative)(k,S).split(o.sep);if(E=E.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&E.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await v();return{type:"needsApproval",approvalReason:`Protected config file: ${E[E.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,T.OK)(i,k)){const e=E[E.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await v();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}return await this.checkCursorFileProtection(E)||!1}catch(e){n.error=e,n.hasError=!0}finally{Ti(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await ve(t.workingDirectory);if(null===n){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:ji("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(n))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const o=(await this.getPermissions()).userConfiguredPolicy,s=r??o;return"workspace_readonly"===o.type&&"workspace_readonly"!==s.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,n){const s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory},n);if("block"===s.kind)return s;const i=await this.getPermissions(),c=i.approvalMode,l="unrestricted"===c,u=i.userConfiguredPolicy,d=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(Ii.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:c,userConfiguredPolicyType:Ki(u),requestedPolicyType:Ki(n),effectiveRequestedPolicyType:Ki(n??u),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:(0,a.S_)(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return Ii.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:c,userConfiguredPolicyType:Ki(u),requestedPolicyType:Ki(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??u);const h=r.parsingResult.executableCommands,m=r.parsingResult.hasRedirects,f=!0===r.parsingResult.allRedirectsAreDevNull,g=r.parsingResult.parsingFailed,v=r.classifierResult,y=r.smartModeApprovalReason,w=r.smartModeApprovalRequestId,b=void 0!==v&&!v.classificationFailed&&v.commands.length>0?v:void 0,k="allowlist"===c&&i.smartAllowlistEnabled?b?.commands:void 0,S=void 0!==k,E=k?k.map(zi):h,x=void 0!==k?k.map(Bi):E.map((e=>[e.fullText.trim()].filter(Boolean))),_=void 0!==b?b.commands.map(Bi):x;if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==u.type&&(n={...n,skipStatsigDefaults:u.skipStatsigDefaults??!0}),"insecure_none"!==u.type&&(0,T.$b)(u.networkPolicy)&&"insecure_none"!==n.type&&!(0,T._B)(n.networkPolicy)){const e=u.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}v&&Ii.info(e,"Smart allowlist: classifier result received",{classificationFailed:v.classificationFailed,suggestedSandboxMode:v.suggestedSandboxMode,commandCount:v.commands.length,suggestedAllowlistEntryCount:v.commands.filter((e=>e.suggestedAllowlistEntry)).length});let C=!1;const P=[],R=[];let I=[],A=[],j=[];const O=Ui(i.smartAllowlistDenylist??[]);if(O.length>0){A=[];const t=_.map((e=>e[0]??""));for(let e=0;e<_.length;e++){const r=_[e];if(r&&0!==r.length&&O.some((e=>Hi(r,e)))){const r=t[e];r&&A.push(r)}}A.length>0&&(Ii.info(e,"Command blocklist: commands require approval",{count:A.length}),P.push(`In blocklist: ${A.join(", ")}`))}if(S&&v){const t=x.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));Ii.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:O.length});const n=x.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;e<v.commands.length;e++){if(n[e])continue;const t=v.commands[e];t&&s.push(t)}if(I=Ui(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ui(o)}(e)))),j=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>I.includes(e))),I.length>0){const e=(0,p.To)(I,j),t=e.length>0?e.join(", "):I.join(", ");R.push(`Not in allowlist: ${t}`)}C=o&&0===A.length,C&&Ii.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const D="ask-every-time"===c||"insecure_none"===n.type&&"allowlist"===c?void 0:u,M=E.map(((e,t)=>new Ji(e,n,D,x[t])));if((0===E.length||g&&!S)&&!l){Ii.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:c,requestedPolicyType:Ki(n),userConfiguredPolicyType:Ki(u),isSmartAllowlistActive:S,parsingFailed:g,parserCommandCount:E.length,hasSmartModeApprovalReason:void 0!==y,hasSmartModeApprovalRequestId:void 0!==w});const o={type:er.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:y??(g?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:y,smartModeApprovalRequestId:w}},s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,M))return{kind:"block",reason:{type:"permissionsConfig"}};const N=await this.teamSettingsService.getAutoRunControls(),$={type:"insecure_none"};for(const e of M)await this.isInShellAllowlist(e)&&e.approveWithPolicy($),d&&N&&this.isInTeamAllowlist(N,e)&&e.approveWithPolicy($);for(const e of M)N&&this.isInTeamBlocklist(N,e)&&e.deny();const L=await this.teamSettingsService.getDeleteFileProtection();if(L)for(const e of M)"rm"===e.command.name&&e.deny();const F=this.buildShellApprovalDecisionFacts({commands:M,autoRunControls:N,shouldApplyTeamShellAllowlist:d,deleteProtectionEnabled:L,softDenylistedCommands:A});if("workspace_readonly"===u.type&&"workspace_readonly"!==n.type)return Ii.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const U=(0,a.S_)(r.hookApprovalRequirement),B=r.hookApprovalRequirement?.reason,H=U?void 0:this.getShellAutoApprovalPolicy({approvalMode:c,isUnrestricted:l,requestedPolicy:n,facts:F,preserveRequestedPolicyForAllowlistedCommands:S}),z=void 0!==H&&F.allCommandsAllowlisted&&"insecure_none"===H.type&&"allowlistEscalated"in H&&!0===H.allowlistEscalated;if(H&&(void 0===y||z)){S&&F.allCommandsPreapproved&&!F.allCommandsAllowlisted&&Ii.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(H);return Ii.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:c,requestedPolicyType:Ki(n),userConfiguredPolicyType:Ki(u),autoApprovalPolicyType:Ki(H),mergedPolicyType:Ki(t),isSmartAllowlistActive:S,smartModeApprovalBypassedByAllowlist:z,allCommandsRunnable:F.allCommandsRunnable,allCommandsAllowlisted:F.allCommandsAllowlisted,allCommandsPreapproved:F.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==y,commandCount:M.length}),{kind:"allow",policy:t}}const W=!(!m||f||g)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n=_i,pathModule:s=o,tempPathOptions:i={platform:process.platform,env:process.env,pathModule:s}}){if(!e.hasRedirects)return!0;const a=e.redirects;if(0===a.length)return!1;const c=e.executableCommands.length>1,l=Di();for(const e of a){if(Li(e))continue;const o=c?Di():l,{operator:a,targetText:d}=e,p=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=$i(d),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(u=t)&&"original-stderr"!==u&&"dev-null"!==u&&"workspace-file"!==u&&"tmp-file"!==u){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===a){const e=$i(d),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===d){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!Ni(a)||void 0===d){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const h=await Fi({targetText:d,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:n,pathModule:s,tempPathOptions:i});if(!h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,h)}var u;return!0}({parsingResult:r.parsingResult,workingDirectory:r.workingDirectory,rootDirectories:this.rootDirectories});let q=(S||(!m||f||W)&&!g)&&("allowlist"===c||"ask-every-time"===c)&&F.canAllowlistInPrompt;const G=[],V=void 0!==y,J=F.notInTeamAllowlist.length>0&&(F.hasSecurityDenies||F.hasSoftDenies||!F.allCommandsRunnable);if(void 0!==y&&G.push(y),U&&(V||G.push(B?`Hook requested approval: ${B}`:"Hook requested approval"),q=!1),P.length>0&&(V||G.push(...P),q=!1),!V)if(S&&R.length>0)G.push(...R);else if(F.unapprovedCommands.length>0){const e=this.generateAllowlistPatterns(F.unapprovedCommands.map((e=>e.command))),t=(0,p.To)(e),r=t.length>0?t.join(", "):F.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${r}`)}if(F.hasSecurityDenies&&(V||(F.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),F.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${F.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),q=!1),J){const t=F.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");Ii.info(e,"Shell permissions: commands not in team allowlist",{commandCount:F.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),q=!1}const K=G.join(" • "),Y=[];if(q){const e=void 0!==y?M.filter((e=>"allowlisted"!==e.state)):F.unapprovedCommands;Y.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const Z=S&&R.length>0,X=Z?I:Y,Q=Z&&j.length>0?j:void 0,ee="insecure_none"!==n.type&&"insecure_none"!==u.type,te="insecure_none"!==n.type,re=[void 0!==y?"smart_mode_approval":void 0,U?"hook_forces_prompt":void 0,P.length>0?"command_blocklist":void 0,S&&R.length>0?"smart_allowlist_miss":void 0,F.unapprovedCommands.length>0?"unapproved_commands":void 0,F.hasSecurityDenies?"security_denies":void 0,J?"team_allowlist_miss":void 0].filter((e=>void 0!==e));Ii.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:c,requestedPolicyType:Ki(n),userConfiguredPolicyType:Ki(u),isSandboxAvailable:ee,isSandboxEnabled:te,canAllowlist:q,isSmartAllowlistActive:S,hasSmartModeApprovalReason:void 0!==y,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:U,approvalReasonTypes:re,commandCount:M.length,unapprovedCommandCount:F.unapprovedCommands.length,deniedCommandCount:F.deniedCommands.length,notInTeamAllowlistCount:F.notInTeamAllowlist.length,notAllowedCommandCount:X.length,suggestedAllowlistEntryCount:Q?.length??0,allCommandsRunnable:F.allCommandsRunnable,allCommandsAllowlisted:F.allCommandsAllowlisted,allCommandsPreapproved:F.allCommandsPreapproved,hasSecurityDenies:F.hasSecurityDenies,hasSoftDenies:F.hasSoftDenies});const ne={type:er.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:K,isSandboxAvailable:"allowlist"===c&&ee,isSandboxEnabled:"allowlist"===c&&te,canAllowlist:q,notAllowedCommands:X,suggestedAllowlistEntries:Q,smartModeApprovalReason:y,smartModeApprovalRequestId:w}},oe=await this.pendingDecisionStore.requestApproval(ne);if(oe.approved){const e="unrestricted"===c?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:oe.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const i=r.classifierResult,a=void 0!==i&&!i.classificationFailed&&i.commands.length>0?i:void 0,c=(o.smartAllowlistEnabled??!1)&&void 0!==a;if(r.parsingResult.parsingFailed&&!c)return!1;const l=r.parsingResult.executableCommands,u=c?a.commands.map(zi):l;if(0===u.length)return!1;const d=c?a.commands.map(Bi):u.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==a?a.commands.map(Bi):d,h={type:"insecure_none"},m=u.map(((e,t)=>new Ji(e,h,void 0,d[t])));if(await this.hasHardDeny(n,m))return!1;const f=Ui(o.smartAllowlistDenylist??[]);if(f.length>0)for(const e of p)if(e&&0!==e.length&&f.some((t=>Hi(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const g=await this.teamSettingsService.getAutoRunControls();if(void 0!==g&&m.some((e=>this.isInTeamBlocklist(g,e))))return!1;for(const e of m){const t=await this.isInShellAllowlist(e),r=s&&void 0!==g&&this.isInTeamAllowlist(g,e);if(!t&&!r)return!1}return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=await this.foldPerUserFilePolicy(e),r=t.skipStatsigDefaults?t:await this.applyStatsigDefaults(t),n=await this.loadPerRepoFilePolicy(r.type),o=await this.buildTeamAdminPolicy(r.type),s=(0,T._B)(e.networkPolicy),{policy:i}=await(0,T.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:r,perRepo:n,teamAdmin:o});return s?{...i,networkPolicy:(0,T.T6)()}:i}async foldPerUserFilePolicy(e){const t=await(0,T.tv)(this.perUserSandboxConfigPath,(0,oe.homedir)());if(!t||"insecure_none"===t.type)return e;let r=(0,T.fZ)(t.networkPolicy,e.networkPolicy);r&&void 0!==e.networkPolicy?.default&&(r={...r,default:e.networkPolicy.default});const n=(0,T.s9)(t.additionalReadonlyPaths,e.additionalReadonlyPaths),o={...e,networkPolicy:r,additionalReadonlyPaths:n.length>0?n:void 0};if("workspace_readwrite"===e.type&&"workspace_readwrite"===t.type){const r=(0,T.s9)(t.additionalReadwritePaths,e.additionalReadwritePaths);return{...o,additionalReadwritePaths:r.length>0?r:void 0}}return o}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,T._B)(e.networkPolicy))return e;const r={default:"deny",allow:Oi(t.allowlist)};return{...e,networkPolicy:(0,T.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,T.tv)((0,o.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Wi(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict}):r:void 0}async buildTeamAdminPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return Wi(e,{networkPolicy:(0,T.Po)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=Oi(t.allowlist)),t.denylist.length>0&&(r.deny=Oi(t.denylist)),Wi(e,{networkPolicy:r})}async isInShellAllowlist(e){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=this.getEmptyShellAllowlistCandidates(t),o=await this.pendingDecisionStore.requestApproval({type:er.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qi(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qi(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){const t=await this.teamSettingsService.getDotCursorProtection();if(e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase()))&&t){const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:{type:"permissionsConfig"}}return null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","bash","npx"];for(const n of e)r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name);return[...new Set(t)]}matchesPathEntry(e,t,r){const n=new RegExp(`^\\s*${e}\\s*\\((.*)\\)\\s*$`),o=t.match(n);if(!o)return!1;const s=(o[1]??"").trim(),i=this.expandTilde(s);return this.matchGlob(i,r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}expandTilde(e){return"~"===e?(0,oe.homedir)():e.startsWith("~/")?(0,oe.homedir)()+e.slice(1):e}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}matchGlob(e,t){const r=`^${this.escapeRegExp(e.trim()).replace(/\\\*/g,".*")}$`;try{return new RegExp(r).test(t)}catch{return e.trim()===t}}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t){const r={stack:[],error:void 0,hasError:!1};try{Ri(r,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:n,toolName:o,providerIdentifier:s,args:i}=t,a=e=>{this.mcpAllowlistLog?.(e)};a(`[permissions-service] shouldBlockMcp: toolName="${o}", providerIdentifier="${s}"`);const l=await this.getPermissions(),u=await this.teamSettingsService.getMcpToolControls(),d=!0===u?.enabled;if(await this.isMcpExplicitlyDenied(e,s,o))return a(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${o}", providerIdentifier="${s}"`),{type:"permissionsConfig"};const p=t.smartModeApproval?.reason;if(void 0!==p)return"workspace_readonly"===l.userConfiguredPolicy.type&&"unrestricted"!==l.approvalMode?(a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${o}", providerIdentifier="${s}"`),{type:"permissionsConfig",isReadonly:!0}):(a(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${o}", providerIdentifier="${s}"`),!(d?this.isMcpInTeamAllowlist(u,{providerIdentifier:s,toolName:o}):await this.isMcpExplicitlyAllowed(e,s,o))&&{type:"needsApproval",approvalReason:p,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:s,args:i,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:p,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(d){const t=this.isMcpInTeamAllowlist(u,{providerIdentifier:s,toolName:o});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${o}", providerIdentifier="${s}"`),!1}else{const t=await this.isMcpExplicitlyAllowed(e,s,o);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${o}", providerIdentifier="${s}"`),!1}if("workspace_readonly"===l.userConfiguredPolicy.type&&"unrestricted"!==l.approvalMode)return a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${o}", providerIdentifier="${s}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===l.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return a(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${o}", providerIdentifier="${s}"`),!1;a(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${o}", providerIdentifier="${s}"`)}return a(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${o}", providerIdentifier="${s}", approvalMode="${l.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${o}`,approvalDetails:{type:"mcp",name:n,toolName:o,providerIdentifier:s,args:i,canAllowlist:!0}}}catch(e){r.error=e,r.hasError=!0}finally{Ti(r)}}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t;if(await this.isMcpExplicitlyDenied(r,n,o))return!1;const s=await this.teamSettingsService.getMcpToolControls();return!0===s?.enabled?!!this.isMcpInTeamAllowlist(s,{providerIdentifier:n,toolName:o}):await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=t.toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,p=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(p),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){Ai.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);if(!r)return!1;const n=r[1]?.trim()??"";return(0,Si.gR)(t,n)}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r}){return e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r})))}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var Zi=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const Xi=3e5;BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function Qi({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=(r.networkAllowlist??[]).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||(0,Si.kj)(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class ea{dashboardClient;constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new Zi.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new Zi.aYW({}))}}class ta{teamAdminSettingsProvider;defaultAllowlistProvider;options;settingsPromise;teamReposPromise;defaultAllowlistPromise;lastFetchTime=0;lastReposFetchTime=0;lastDefaultAllowlistFetchTime=0;lastFetchSucceeded=!0;constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.settingsPromise=this.fetchSettings()}invalidateCache(){this.lastFetchTime=0,this.lastDefaultAllowlistFetchTime=0,this.defaultAllowlistPromise=void 0}async fetchSettings(){this.lastFetchTime=Date.now();try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e}catch(e){return void(this.lastFetchSucceeded=!1)}}async getTeamAdminSettings(){return(Date.now()-this.lastFetchTime>Xi||void 0===await this.settingsPromise)&&(this.settingsPromise=this.fetchSettings()),this.settingsPromise}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(function(e,t){return!(0,Sr.Y)(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Sr.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=Qi({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?Qi({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;return await this.isMcpSettingsOverhaulEnabled()?(0,Sr._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1}):{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=await this.isMcpSettingsOverhaulEnabled(),r=e?.allowedMcpConfiguration;if(t)return{enabled:!0,mcpToolAllowlist:(0,Sr.FC)({autoRunControls:e?.autoRunControls,allowedMcpServers:r?.allowedMcpServers,isMcpSettingsOverhaulEnabled:!0}),allowUserOverride:!1}}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls;return{sandboxingDisabled:t?.sandboxing===Zi.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===Zi._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===Zi.i24.ALWAYS_DISABLED}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async getDefaultNetworkAllowlist(){const e=Date.now();return(!this.defaultAllowlistPromise||e-this.lastDefaultAllowlistFetchTime>Xi)&&(this.lastDefaultAllowlistFetchTime=e,this.defaultAllowlistPromise=this.fetchDefaultAllowlist()),this.defaultAllowlistPromise}async fetchDefaultAllowlist(){if(!this.defaultAllowlistProvider)return{allowlist:[],available:!0};try{return{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}}catch{return{allowlist:[],available:!1}}}async getTeamRepos(){const e=Date.now();return(!this.teamReposPromise||e-this.lastReposFetchTime>Xi)&&(this.teamReposPromise=this.fetchTeamRepos(),this.lastReposFetchTime=e),this.teamReposPromise}async fetchTeamRepos(){return this.teamAdminSettingsProvider.getTeamRepos()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}},"../mcp-agent-exec/dist/index.js"(e,t,r){r.d(t,{mz:()=>g,xz:()=>he,mF:()=>h,Q7:()=>ye,gT:()=>ge,uz:()=>Q,i9:()=>ee,bm:()=>Y,U$:()=>K,LK:()=>X,$b:()=>p,XV:()=>fe,_x:()=>d,ME:()=>n.ME,SW:()=>w,Y:()=>n.Y,Zj:()=>ve,FC:()=>n.FC,_N:()=>n._N});var n=r("../mcp-core/dist/index.js"),o=r("node:crypto?8af2"),s=r("node:fs/promises"),i=r("node:path"),a=r("../context/dist/index.js"),c=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class l extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class u extends Error{serverName;constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class d{disabledService;constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new l(t);return await o(e,r)}}class p{approvalService;constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,a.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new u(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{c(s)}}}class h{approvalsPath;cwd;approvalsPromise;constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,o.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,s.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,s.mkdir)(i.default.dirname(this.approvalsPath),{recursive:!0}),await(0,s.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var m=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},f=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class g{async load(e,t,r,n,o){const s=o(e,r);return new y(e,t,s,r)}}function v(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class y{serverName;clientPromise;config;toolsPromise;resourcesPromise;promptsPromise;clientPromiseTraceId;constructor(e,t,r,n){var o,s;this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=null===(s=null===(o=(0,a.fU)(e))||void 0===o?void 0:o.spanContext())||void 0===s?void 0:s.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=m(r,(0,a.VI)(e.withName("CachedMcpClient.getTools")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=v(this.toolsPromise);return void 0!==o?o:await this.toolsPromise}catch(e){r.error=e,r.hasError=!0}finally{f(r)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=m(s,(0,a.VI)(e.withName("CachedMcpClient.callTool")),!1),c=await this.getClient(i.ctx);if(null===c)throw new Error("Client is not ready");return c.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{f(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=m(t,(0,a.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{f(t)}}async getClient(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=m(r,(0,a.VI)(e.withName("CachedMcpClient.getClient")),!1);return n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined"),await this.clientPromise}catch(e){r.error=e,r.hasError=!0}finally{f(r)}}async listResources(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=m(r,(0,a.VI)(e.withName("CachedMcpClient.listResources")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=v(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:await this.resourcesPromise}}catch(e){r.error=e,r.hasError=!0}finally{f(r)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=m(r,(0,a.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{f(r)}}async listPrompts(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const n=m(r,(0,a.VI)(e.withName("CachedMcpClient.listPrompts")),!1);n.span.setAttribute("serverName",this.serverName),n.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const o=v(this.promptsPromise);return void 0!==o?o:await this.promptsPromise}catch(e){r.error=e,r.hasError=!0}finally{f(r)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=m(n,(0,a.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{f(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=m(t,(0,a.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{f(t)}}async close(){var e;try{const t=await this.clientPromise;await(null===(e=null==t?void 0:t.close)||void 0===e?void 0:e.call(t))}catch(e){}}}function w(e){var t,r;const n=e;if(!n.resource||"object"!=typeof n.resource)return n.uri?`Resource: ${n.uri}${n.name?` (${n.name})`:""}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`;{const e=n.resource;if("string"==typeof e.text)return e.text;if("string"!=typeof e.blob)return`Resource: ${null!==(r=e.uri)&&void 0!==r?r:"unknown"}${e.name?` (${e.name})`:""}`;try{return Buffer.from(e.blob,"base64").toString("utf8")}catch(r){return`[Binary resource: ${null!==(t=e.uri)&&void 0!==t?t:"unknown"}]`}}}var b=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js"),k=r("zod");const S=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function E(e,t){if("string"==typeof e)return function(e,t){return e.replace(S,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>E(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=E(o,t);return r}return e}const x=k.z.object({type:k.z.literal("stdio").optional(),command:k.z.string(),args:k.z.array(k.z.string()).optional(),env:k.z.record(k.z.string(),k.z.string()).optional(),cwd:k.z.string().optional()}),_=k.z.object({CLIENT_ID:k.z.string(),CLIENT_SECRET:k.z.string().optional(),scopes:k.z.array(k.z.string()).optional()}),C=k.z.object({caBundle:k.z.string().trim().min(1).max(131072)}).strict(),P=k.z.object({type:k.z.enum(["http","sse"]).optional(),url:k.z.string(),headers:k.z.record(k.z.string(),k.z.string()).optional(),auth:_.optional(),tls:C.optional()}),R=k.z.union([x,P]),T=k.z.object({mcpServers:k.z.record(k.z.string(),R)});async function I(e,t=e=>process.env[e]){try{const r=await(0,s.readFile)(e,"utf8"),n=E((0,b.qg)(r),t);return T.parse(n)}catch(e){return{mcpServers:{}}}}var A=r("node:os"),j=r("../utils/dist/index.js"),O=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js"),D=r("../constants/dist/index.js"),M=r("../proto/dist/generated/agent/v1/mcp_pb.js"),N=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),$=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),L=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),F=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),U=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),B=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"),H=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},z=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const W=["authorization_code","refresh_token"],q=["code"];class G{_codeVerifier;_lastRedirectUrl;_oauthState;_oauthAttemptId;_identifier;_redirectUrl;_clientMetadata;_scopes;_tokens;_clientInformation;_saveTokens;_prepareForRefresh;_releaseRefreshLeaseOnError;_invalidateCredentials;_saveClientInformation;constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,o.randomUUID)(),this._oauthState=function(e,t,r){const n=Object.assign({id:e,owner:t},r?{attemptId:r}:{});return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this._tokens}async saveTokens(e){this._tokens=e,await this._saveTokens(e)}async prepareForRefresh(){var e;await(null===(e=this._prepareForRefresh)||void 0===e?void 0:e.call(this))}async releaseRefreshLeaseOnError(e){var t;await(null===(t=this._releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(this,e))}async invalidateCredentials(e){var t;switch(e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0;break;default:return e}await(null===(t=this._invalidateCredentials)||void 0===t?void 0:t.call(this,e))}redirectToAuthorization(e){var t;(null===(t=this._scopes)||void 0===t?void 0:t.length)&&!e.searchParams.has("scope")&&e.searchParams.set("scope",this._scopes.join(" ")),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function V(e){var t;const{serverName:r,config:n,tokenStorage:o,authRedirectUrl:s}=e,i=function(e,t){if(e)return Object.assign(Object.assign({client_id:e.CLIENT_ID},e.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{}),{redirect_uris:(0,D.RJV)(t),grant_types:[...W],response_types:[...q],token_endpoint_auth_method:"none"})}(n.auth,s),a=function({storedClientInformation:e,staticClientInformation:t}){var r,n,o,s;return t?e&&e.client_id===t.client_id?Object.assign(Object.assign(Object.assign({},t),e),{client_secret:null!==(r=t.client_secret)&&void 0!==r?r:e.client_secret,redirect_uris:t.redirect_uris,grant_types:null!==(n=e.grant_types)&&void 0!==n?n:t.grant_types,response_types:null!==(o=e.response_types)&&void 0!==o?o:t.response_types,token_endpoint_auth_method:null!==(s=e.token_endpoint_auth_method)&&void 0!==s?s:t.token_endpoint_auth_method}):t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:i});return new G({identifier:r,redirectUrl:s,clientMetadata:{redirect_uris:(0,D.RJV)(s),token_endpoint_auth_method:"none",grant_types:[...W],response_types:[...q],client_name:"Cursor",logo_uri:D.G$s},scopes:null===(t=n.auth)||void 0===t?void 0:t.scopes,tokens:await o.loadTokens(),clientInformation:a,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>{var e,t;return null!==(t=null===(e=o.prepareForRefresh)||void 0===e?void 0:e.call(o))&&void 0!==t?t:Promise.resolve()},releaseRefreshLeaseOnError:e=>{var t,r;return null!==(r=null===(t=o.releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(o,e))&&void 0!==r?r:Promise.resolve()},invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e)})}class J{serverName;config;client;tools;stateValue;_authProvider;_sessionId;_currentElicitationProvider;_currentToolCallId;_currentToolName;_callToolLock=Promise.resolve();_oauthLifecycleLogger;_stateEnteredAtMs=Date.now();constructor(e,t,r){this.serverName=e,this.client=t,this.tools=new n.B1,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._sessionId=r.sessionId,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this.setupElicitationHandler()}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,o){if(!this._oauthLifecycleLogger)return;const s=this._stateKindLabel(e),i=this._stateKindLabel(t);if(s===i)return;const a=Date.now()-this._stateEnteredAtMs,c=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch(e){return}})();(0,n.VD)({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:Object.assign({identifier:this.serverName,from:s,to:i,cause:r,serverUrlHost:c,previousStateDurationMs:a},o)})}static createClient(){return new $.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}setupElicitationHandler(){this.client.setRequestHandler(B.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:e.params.requestedSchema});return{action:t.action,content:t.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,o,s,i,a,c){const l=new URL(t.url);s=null!=s?s:D.tl5;const u=await r.loadTokens(),d=await V({serverName:e,config:t,tokenStorage:r,authRedirectUrl:s}),p=null!=i?i:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=e=>void 0===p||void 0===a?p:(0,n.jI)({fetch:p,logger:a.logger,metadata:Object.assign(Object.assign({},a.metadata),{transportType:e})}),m=J.createClient(),f=r=>{var o,s,i;const a=null!==(i=null===(s=null===(o=d.lastRedirectUrl)||void 0===o?void 0:o.toString)||void 0===s?void 0:s.call(o))&&void 0!==i?i:"",u=new J(e,m,{oauthLifecycleLogger:c,initialState:{kind:"requires_authentication",url:a,callback:async t=>{try{if(!d.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");await(0,N.j2)(d,Object.assign({serverUrl:l.toString(),authorizationCode:t},void 0!==p?{fetchFn:p}:{})),c&&(0,n.VD)({logger:c,event:"mcp_oauth_callback_completion",metadata:Object.assign(Object.assign({identifier:e},(0,n.q2)(l.toString())),(0,n.tB)(d.tokens(),{expiresInIsFresh:!0}))}),u.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:d,sessionId:r,config:t});return u},g=async()=>{const r=new L.A(l,{authProvider:d,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:h("sse")});try{return await m.connect(r),new J(e,m,{initialState:{kind:"ready"},authProvider:d,config:t,oauthLifecycleLogger:c})}catch(t){if(t instanceof N.D_)return c&&(0,n.VD)({logger:c,event:"mcp_oauth_state_transition",metadata:Object.assign(Object.assign({identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(null==u?void 0:u.refresh_token)},(0,n.q2)(l.toString())),(0,n.X5)(t))}),f();throw t}};if("sse"===t.type)return g();const v=new U.j(l,{authProvider:d,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:h("streamableHttp")});try{return await m.connect(v),new J(e,m,{initialState:{kind:"ready"},authProvider:d,sessionId:v.sessionId,config:t,oauthLifecycleLogger:c})}catch(t){if(t instanceof N.D_)return c&&(0,n.VD)({logger:c,event:"mcp_oauth_state_transition",metadata:Object.assign(Object.assign({identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(null==u?void 0:u.refresh_token)},(0,n.q2)(l.toString())),(0,n.X5)(t))}),f(v.sessionId);if((0,n.PK)(t))return g();throw t}}static async fromCachedSession(e,t,r,o,s,i=D.tl5,a,c,l){const u=new URL(t.url),d=await V({serverName:e,config:t,tokenStorage:o,authRedirectUrl:i}),p=null!=a?a:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,h=new U.j(u,{authProvider:d,sessionId:r.sessionId,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=s?s:{})},fetch:void 0!==p&&void 0!==c?(0,n.jI)({fetch:p,logger:c.logger,metadata:Object.assign(Object.assign({},c.metadata),{transportType:"streamableHttp"})}):p}),m=J.createClient();return await m.connect(h),new J(e,m,{initialState:{kind:"ready"},authProvider:d,sessionId:h.sessionId,config:t,oauthLifecycleLogger:l})}get sessionId(){return this._sessionId}static async fromCommand(e,t,r,n,o){var s;const i={stack:[],error:void 0,hasError:!1};try{H(i,(0,a.VI)(e.withName("McpSdkClient.fromCommand")),!1);const c=new F.oQ(Object.assign({command:r.command,args:null!==(s=r.args)&&void 0!==s?s:[],env:n,cwd:r.cwd,stderr:"ignore"},(null==o?void 0:o.spawn)&&{spawn:o.spawn})),l=J.createClient();return await l.connect(c),new J(t,l,{initialState:{kind:"ready"},config:r})}catch(e){i.error=e,i.hasError=!0}finally{z(i)}}async close(){await this.client.close()}async getTools(e){var t,r,o;const s={stack:[],error:void 0,hasError:!1};try{if(H(s,(0,a.VI)(e.withName("McpSdkClient.getTools")),!1),"requires_authentication"===this.stateValue.kind)return[];try{return await this.tools.get((async()=>{let e;const t=[];for(;;){const r=await this.client.listTools({cursor:e});if(t.push(...r.tools.map((e=>Object.assign(Object.assign({},e),{inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),e=r.nextCursor,void 0===e)break}return t}))}catch(e){if(e instanceof N.D_&&"ready"===this.stateValue.kind){const s=this.stateValue,i=null!==(o=null===(r=null===(t=this._authProvider)||void 0===t?void 0:t.lastRedirectUrl)||void 0===r?void 0:r.toString())&&void 0!==o?o:"";this.stateValue={kind:"requires_authentication",url:i,callback:async e=>{}},this._logStateTransition(s,this.stateValue,"runtime_unauthorized",Object.assign({},(0,n.X5)(e))),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){s.error=e,s.hasError=!0}finally{z(s)}}async callTool(e,t,r,o,s){var i,c,l;const u={stack:[],error:void 0,hasError:!1};try{H(u,(0,a.VI)(e.withName("McpSdkClient.callTool")),!1).span.setAttribute("toolName",t);const d=this._callToolLock;let p;this._callToolLock=new Promise((e=>{p=e}));try{await d,this._currentToolCallId=o,this._currentToolName=t,this._currentElicitationProvider=s;try{const e=await this.client.callTool({name:t,arguments:r});return{content:e.content,isError:void 0!==e.error}}catch(e){if(e instanceof N.D_&&"ready"===this.stateValue.kind){const t=this.stateValue,r=null!==(l=null===(c=null===(i=this._authProvider)||void 0===i?void 0:i.lastRedirectUrl)||void 0===c?void 0:c.toString())&&void 0!==l?l:"";this.stateValue={kind:"requires_authentication",url:r,callback:async e=>{}},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",Object.assign({},(0,n.X5)(e))),this._stateEnteredAtMs=Date.now()}throw e}finally{this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{p()}}catch(e){u.error=e,u.hasError=!0}finally{z(u)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(H(t,(0,a.VI)(e.withName("McpSdkClient.getInstructions")),!1),"requires_authentication"===this.stateValue.kind)return;return await this.client.getInstructions()}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(H(t,(0,a.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();if(!(null==r?void 0:r.resources))return{resources:[]};let n;const o=[];for(;;){const e=await this.client.listResources({cursor:n});if(o.push(...e.resources),n=e.nextCursor,void 0===n)break}return{resources:o}}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return H(r,(0,a.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{z(r)}}async listPrompts(e){var t;const r={stack:[],error:void 0,hasError:!1};try{if(H(r,(0,a.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind)return[];if(!(null!==(t=this.client.getServerCapabilities())&&void 0!==t?t:{prompts:!1}).prompts)return[];const n=await this.client.listPrompts();return(null==n?void 0:n.prompts)?n.prompts.map((e=>{var t;return{name:e.name,description:e.description,arguments:null===(t=e.arguments)||void 0===t?void 0:t.map((e=>({name:e.name,description:e.description,required:e.required})))}})):[]}catch(e){r.error=e,r.hasError=!0}finally{z(r)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return H(n,(0,a.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{z(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return this.stateValue}updateState(e,t){const r=this.stateValue;this.stateValue=e,this._logStateTransition(r,e,null!=t?t:"explicit_update"),this._stateEnteredAtMs=Date.now()}}class K extends Error{toolName;availableTools;constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}class Y extends Error{serverName;availableServers;constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error;class Z{tools;constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new K(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>Object.assign(Object.assign({},t.definition),{name:e})))}}class X{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new Z({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class Q{manager;constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=H(t,(0,a.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=H(t,(0,a.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=H(t,(0,a.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){var n;for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(null===(n=null==t?void 0:t.close)||void 0===n?void 0:n.call(t))}catch(e){}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class ee{clients;elicitationFactory;changeListeners=new Set;constructor(e,t){this.clients=e,this.elicitationFactory=t}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{var t;try{await(null===(t=e.close)||void 0===t?void 0:t.call(e))}catch(e){}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=H(t,(0,a.VI)(e.withName("McpManager.getToolSet")),!1),n=await(0,j.PH)(Object.entries(this.clients),(([e,t])=>t.getTools(r.ctx).then((r=>r.map((r=>Object.assign(Object.assign({},r),{clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:4}),o=Array.from(n.values()).flat(),s={};for(const e of o)s[`${e.clientName}-${e.name}`]={definition:Object.assign(Object.assign({},e),{clientKey:e.clientKey,providerIdentifier:e.clientName,toolName:e.name}),execute:async(t,n,o)=>{const s=null==o?void 0:o.createProvider(e.clientName,e.name,n);return await e.client.callTool(r.ctx,e.name,t,n,s)}};return new Z(s)}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=H(t,(0,a.VI)(e.withName("McpManager.getInstructions")),!1),n=await(0,j.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new M.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:4});return Array.from(n.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{z(t)}}}function te(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class re{options;constructor(e){this.options=e,(0,n.VD)({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return Object.assign({identifier:this.options.identifier},this.options.serverUrl?{serverUrl:(0,n.q2)(this.options.serverUrl)}:{})}async loadTokens(){const e=await this.options.inner.loadTokens();return(0,n.VD)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,n.tB)(e))}),e}async saveTokens(e){await this.options.inner.saveTokens(e),(0,n.VD)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,n.tB)(e,{expiresInIsFresh:!0}))})}async prepareForRefresh(){var e,t;(0,n.VD)({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(null===(t=(e=this.options.inner).prepareForRefresh)||void 0===t?void 0:t.call(e))}async releaseRefreshLeaseOnError(e){var t,r;(0,n.VD)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:Object.assign(Object.assign({},this.baseMetadata),(0,n.X5)(e))}),await(null===(r=(t=this.options.inner).releaseRefreshLeaseOnError)||void 0===r?void 0:r.call(t,e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return(0,n.VD)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,n.O3)(e))}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),(0,n.VD)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,n.O3)(e))})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&((0,n.VD)({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:Object.assign(Object.assign({},this.baseMetadata),{scope:e})}),await this.options.inner.invalidateCredentials(e))}}class ne{storage;identifier;constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}}class oe{inner;constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){var t,r;await(null===(r=(t=this.inner).invalidateCredentials)||void 0===r?void 0:r.call(t,e))}}var se=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ie=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ae=(0,a.h)("DefinitionMcpLoader");function ce(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?i.default.join(A.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?i.default.resolve(null!=r?r:process.cwd(),t):t}function le(e){return"function"==typeof e.getMcpNetworkControlsConfig}function ue(e){var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0}function de(e){if(void 0!==e)return(0,o.createHash)("sha256").update((0,n.Fm)(e)).digest("hex")}class pe{configPath;configPromise;constructor(e){this.configPath=e,this.configPromise=I(e)}clearCache(){this.configPromise=I(this.configPath)}async getDefinitions(e,t=!0){const r=await this.configPromise;return Object.entries(r.mcpServers).map((([e,t])=>({identifier:e,serverConfig:t,configPath:this.configPath})))}}class he{source;tokenStorage;middlewares;options;clientCache=new Map;sandboxPolicyFingerprint;constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n}async load(e,t=!0){var r,n,o;const s={stack:[],error:void 0,hasError:!1};try{se(s,(0,a.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),null===(n=(r=this.source).clearCache)||void 0===n||n.call(r));const i=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,i);const c={};return await(0,j.PH)([...i],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,o=null!=n?n:await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,o),c[r.identifier]=o}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r){ae.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}(e,r,t)}}),{max:null!==(o=this.options.maxConcurrency)&&void 0!==o?o:Math.max(i.length,1)}),new ee(c,this.options.elicitationFactory)}catch(e){s.error=e,s.hasError=!0}finally{ie(s)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(le);if(!r)return;let o;try{o=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{var t,o;const s=null!==(o=await(null===(t=r.getMcpNetworkControlsConfig)||void 0===t?void 0:t.call(r,function(e){var t;return"url"in e?{url:e.url}:{command:[e.command,...null!==(t=e.args)&&void 0!==t?t:[]].join(" ")}}(e.serverConfig))))&&void 0!==o?o:{};return[e.identifier,(0,n.Fm)(s)]}))))}catch(e){return}const s=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=o,void 0!==s&&s!==o&&(ae.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,j.PH)(e,(async e=>{var t;try{await(null===(t=e.close)||void 0===t?void 0:t.call(e))}catch(e){}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{se(n,(0,a.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{ie(n)}}async loadDefinitionClient(e,t,o){var s,i;const c=null!==(s=t.authStorageKey)&&void 0!==s?s:t.identifier,l=new ne(this.tokenStorage,c),u=te(e,ae),d=new re({inner:l,logger:u,identifier:c,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),p=o?new oe(d):d;return async function(e,t,o,s,i={middlewares:[],configPath:""},c){const l={stack:[],error:void 0,hasError:!1};try{const{middlewares:u,configPath:d}=i,p=se(l,(0,a.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);let h=async(e,o)=>{const i={stack:[],error:void 0,hasError:!1};try{const l=se(i,(0,a.VI)(e.withName("loadServer.next")),!1);l.span.setAttribute("serverName",t);const d=l.ctx;if("command"in o){l.span.setAttribute("kind","command");const e=u.find(le);return await async function(e,t,o,s){var i,a,c;const l=o.cwd?ce({filePath:o.cwd}):void 0;let u,d;if(o.args&&o.args.length>0)u=ce({filePath:o.command,baseDir:l}),d=o.args.map((e=>ce({filePath:e,baseDir:l})));else{const e=(0,O.A)(o.command);u=ce({filePath:e[0],baseDir:l}),d=e.slice(1).map((e=>ce({filePath:e,baseDir:l})))}const p=null!==(a=o.env)&&void 0!==a?a:{},h=await(null===(i=null==s?void 0:s.getMcpNetworkControlsConfig)||void 0===i?void 0:i.call(s,{command:[o.command,...null!==(c=o.args)&&void 0!==c?c:[]].join(" ")})),m=(0,n.$H)(h);if(void 0!==m){const{buildMcpSandboxPolicy:o}=await Promise.resolve().then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:s,spawnInSandbox:i}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),a=null!=l?l:process.cwd(),c=await o(m,a);ae.info(e,function(e){var t,r,n,o,s,i,a;return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===(null===(t=e.networkControlsConfig)||void 0===t?void 0:t.enabled))}, mcpNetworkMode=${null!==(i=null===(r=e.networkControlsConfig)||void 0===r?void 0:r.mcpNetworkMode)&&void 0!==i?i:"unset"}, mcpNetworkAllowlistCount=${ue(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${ue(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${ue(null===(s=e.networkControlsConfig)||void 0===s?void 0:s.localAgentNetworkAllowlist)}, sandboxPolicyHash=${null!==(a=de(e.sandboxNetworkControlsConfig))&&void 0!==a?a:"none"}`}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:m}),function(e){var t,r,n,o,s;return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===(null===(t=e.networkControlsConfig)||void 0===t?void 0:t.enabled),mcpNetworkMode:null===(r=e.networkControlsConfig)||void 0===r?void 0:r.mcpNetworkMode,mcpNetworkAllowlistCount:ue(null===(n=e.networkControlsConfig)||void 0===n?void 0:n.mcpNetworkAllowlist),mcpNetworkDenylistCount:ue(null===(o=e.networkControlsConfig)||void 0===o?void 0:o.mcpNetworkDenylist),localAgentNetworkAllowlistCount:ue(null===(s=e.networkControlsConfig)||void 0===s?void 0:s.localAgentNetworkAllowlist),sandboxPolicyHash:de(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:h,sandboxNetworkControlsConfig:m}));try{return await J.fromCommand(e,t,{command:u,args:d,cwd:l},p,{spawn:(e,t,r)=>i(e,t,r,c)})}catch(e){if(e instanceof s)throw new n.c8(t,e);throw e}}return!0===(null==h?void 0:h.enabled)&&"no_sandbox"===h.mcpNetworkMode&&ae.info(e,`Starting local MCP server "${t}" without MCP sandboxing`),J.fromCommand(e,t,{command:u,args:d,cwd:l},p)}(d,t,o,e)}if("url"in o){l.span.setAttribute("kind","url");const e=null==c?void 0:c(t);return await async function(e,t,r,n,o){const s=te(e,ae),i=function(e,t){return{logger:{debug:(t,r)=>ae.debug(e,t,r),info:(t,r)=>ae.info(e,t,r),warn:(t,r)=>ae.warn(e,t,r),error:(t,r,n)=>ae.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t);return J.fromStreamableHttp(t,r,n,r.headers,o,void 0,i,s)}(d,t,o,s,e)}throw new Error(`Invalid server: ${JSON.stringify(o)}`)}catch(e){i.error=e,i.hasError=!0}finally{ie(i)}};for(const e of u){const r=h;h=async(n,o)=>await e.load(n,t,o,d,r)}return await h(p.ctx,o)}catch(e){l.error=e,l.hasError=!0}finally{ie(l)}}(e,t.identifier,t.serverConfig,p,{middlewares:this.middlewares,configPath:null!==(i=t.configPath)&&void 0!==i?i:""},this.options.authRedirectUrlGenerator)}handleDefinitionLoadError(e,t,r){var n,o;let s=!1;try{s="handled"===(null===(o=(n=this.options).onDefinitionLoadError)||void 0===o?void 0:o.call(n,e,t,r))}catch(r){ae.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return s||function(e){return e instanceof l||e instanceof u||e instanceof me}(r)}}class me extends Error{serverName;reason;constructor(e,t,r){super(null!=r?r:"teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}class fe{blockingService;constructor(e){this.blockingService=e}async getMcpNetworkControlsConfig(e){var t,r,n;return null!==(n=await(null===(r=(t=this.blockingService).getMcpNetworkControlsConfig)||void 0===r?void 0:r.call(t,e)))&&void 0!==n?n:{}}async load(e,t,r,n,o){var s,i,a,c,l;const u={command:"command"in r?[r.command,...null!==(a=r.args)&&void 0!==a?a:[]].join(" "):void 0,url:"url"in r?r.url:void 0},d=null!==(c=await(null===(i=(s=this.blockingService).getMcpServerBlockInfo)||void 0===i?void 0:i.call(s,u)))&&void 0!==c?c:{blocked:await this.blockingService.isServerBlocked(u)};if(d.blocked)throw new me(t,null!==(l=d.reason)&&void 0!==l?l:"teamPolicy",d.message);return o(e,r)}}class ge extends he{configPath;elicitationFactory;constructor(e,t,r=[],n,o){super(new pe(e),t,r,{authRedirectUrlGenerator:n,elicitationFactory:o}),this.configPath=e,this.elicitationFactory=o}static init(e,t,r=[]){return new ge(t,e,r)}}function ve(e){var t;return"stdio"===e.type&&e.command?{command:e.command,args:null!==(t=e.args)&&void 0!==t?t:[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth}:void 0}r("../mcp-agent-exec/dist/mcp-sandbox-policy.js");class ye{mcpAuthPath;static mcpAuthPromises=new Map;static saveLocks=new Map;mcpAuthPromise;constructor(e){this.mcpAuthPath=e;const t=ye.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,ye.mcpAuthPromises.set(e,t),t.catch((()=>{ye.mcpAuthPromises.get(e)===t&&ye.mcpAuthPromises.delete(e)}))}ye.saveLocks.has(e)||ye.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,s.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t))e[r]={tokens:n};return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?n.tokens:void 0,clientInfo:"clientInfo"in n?n.clientInfo:void 0});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){var t;return null===(t=(await this.mcpAuthPromise)[e])||void 0===t?void 0:t.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){var t;return null===(t=(await this.mcpAuthPromise)[e])||void 0===t?void 0:t.clientInfo}async withSaveLock(e){var t;const r=null!==(t=ye.saveLocks.get(this.mcpAuthPath))&&void 0!==t?t:Promise.resolve();let n;ye.saveLocks.set(this.mcpAuthPath,new Promise((e=>{n=e})));try{return await r,await e()}finally{n()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,s.mkdir)(i.dirname(this.mcpAuthPath),{recursive:!0}),await(0,s.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){r.d(t,{buildMcpSandboxPolicy:()=>n.Ic});var n=r("../mcp-core/dist/index.js")},"../mcp-core/dist/index.js"(e,t,r){r.d(t,{B1:()=>W,c8:()=>je,Ic:()=>Re,O3:()=>X,tB:()=>K,ME:()=>D,Fm:()=>Ae,jI:()=>xe,VD:()=>le,X5:()=>ae,$H:()=>L,Y:()=>B,PK:()=>Oe,FC:()=>z,_N:()=>$,q2:()=>V});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<o|BigInt(t)}return{version:4,value:r}}function c(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=a(n);if(!o)return;t.push(Number(o.value>>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){var t;return null!==(t=a(e))&&void 0!==t?t:function(e){const t=A(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<s|BigInt(t)),n)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),i=t.slice(r+2),a=c(o),l=c(i);if(!a||!l)return;const u=a.length+l.length;return u>7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<<s|BigInt(t)),n)}}(e)}function u(e,t){const r=A(e),n=A(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=l(t.slice(0,r)),o=l(e);if(!n||!o||n.version!==o.version)return!1;const s=Number(t.slice(r+1)),i=4===n.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}const d="Blocked by MCP Network Admin Server Controls";function p(e){return/\s/.test(e)}const h="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",m=new RegExp(`^(?:${h}\\.)*${h}$`),f=new RegExp(`^\\*\\.(?:${h}\\.)*${h}$`),g="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${g}(?:\\.${g}){3}$`),y=/^[0-9a-f:]+$/,w=new RegExp(`^(?:${g}(?:\\.${g}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function b(e){const t=A(e);return t.length>0&&t.length<=253&&m.test(t)}function k(e){const t=A(e);return v.test(t)||function(e){const t=A(e);if(!y.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch(e){return!1}}(t)}function S(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return S(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return S(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(b(t)||k(t))}(t.hostname)}catch(e){return!1}}(e);const t=A(e);return"*"===t||!!f.test(t)||(t.includes("/")?function(e){const t=A(e);if(!w.test(t))return!1;const[r]=t.split("/");return void 0!==r&&u(r,t)}(t):b(t)||k(t))}function _(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${A(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(p(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search,o=!S(e.protocol,e.port);if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{if(o)return;const t=E(e);if(!x(t))return;return t}}catch(e){return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}function C(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function P(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function R(e,t){return function(e,t,r){const n=T(t);if(!n)return!1;let o;try{o=new URL(e)}catch(e){return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&A(s)===A(i)&&(C(a=o.pathname,c=n.pathname)||C(P(a),P(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:C(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function T(e){const t=e.trim();if(0===t.length||p(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=j(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!A(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(A(r.hostname)!==A(o))return}return r}}function I(e,t){if(C(e,t))return!0;const r=j(t);return!!r&&u(r.hostname,e)}function A(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function j(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch(e){return}}function O(e){return(null!=(t=e.mcpNetworkAllowlist)?t:[]).flatMap((e=>{const t=_(e);return void 0===t?[]:[t]}));var t}function D(e,t){var r,n;if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!T(e))return{allowed:!1,message:null!==(r=t.blockMessage)&&void 0!==r?r:d};const o=O(t);return o.length>0&&o.some((t=>function(e,t){const r=T(t);if(!r)return!1;if(!e.includes("://"))return u(A(r.hostname),e);if(R(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||!S(t.protocol,t.port)||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch(e){return}}(e);return void 0!==n&&R(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:null!==(n=t.blockMessage)&&void 0!==n?n:d}}function M(e){const t=null==e?void 0:e.trim();return t&&t.length>0?t:void 0}function N(e,t,r){return void 0!==(null==r?void 0:r.command)&&void 0===r.url&&void 0===t&&!0===(null==e?void 0:e.allowUserOverrideMcpServers)}function $({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0}){const i=null==e?void 0:e.allowedMcpServers,a=function(e){var t;if(!0!==(null==e?void 0:e.allowUserOverrideMcpServers))return;const r=(null!==(t=e.deniedMcpServers)&&void 0!==t?t:[]).flatMap((e=>{const t=M(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(void 0!==r&&r.includes("*")){const e=_(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=_(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=_(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return _(new URL(e).hostname)}catch(e){return}}(t);return void 0===r?[]:[r]}));return r.length>0?r:void 0}(e),c=void 0===t?void 0:function(e,t){return null==e?void 0:e.find((e=>function(e,t){const r=M(e.command),n=M(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&C(r,t.command),s=void 0===n||void 0!==t.url&&I(n,t.url);return o&&s}(e,t)))}(i,t),l=N(e,c,t),u=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){var n,o;return void 0===r?(null!==(o=null===(n=null==e?void 0:e.allowedMcpServers)||void 0===n?void 0:n.length)&&void 0!==o?o:0)>0:void 0!==t||N(e,t,r)}({allowedMcpConfiguration:e,matchedServer:c,server:t})||(void 0===t||l)&&void 0!==a,d=void 0===t?s?null==i?void 0:i.flatMap((e=>{var t;return null!==(t=e.networkAllowlist)&&void 0!==t?t:[]})):void 0:l?[]:function(e,t,r){var n;return void 0===e?r:[...null!==(n=e.networkAllowlist)&&void 0!==n?n:[],...void 0!==M(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(c,t,o),p=void 0===t?void 0:function(e,t){var r,n;if(void 0!==M(null==e?void 0:e.command)&&void 0!==t.command&&void 0===t.url)return null!==(r="allow_all"===(n=null==e?void 0:e.networkMode)||"allowlist"===n||"deny_all"===n||"no_sandbox"===n?n:void 0)&&void 0!==r?r:"no_sandbox"}(c,t),h=void 0===t||l?a:void 0;return Object.assign(Object.assign(Object.assign(Object.assign({enabled:u,mcpNetworkAllowlist:d},void 0!==p?{mcpNetworkMode:p}:{}),void 0!==h?{mcpNetworkDenylist:h}:{}),void 0!==r?{localAgentNetworkAllowlist:r}:{}),void 0!==n?{blockMessage:n}:{})}function L(e){if(!0===(null==e?void 0:e.enabled)&&"no_sandbox"!==e.mcpNetworkMode)return e}function F(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function U(e){const t=null==e?void 0:e.trim();return void 0===t||0===t.length?void 0:t}function B(e,t,r){var n;if(void 0===t)return!0;if(!0===t.disableAll)return!1;const o=null!==(n=t.allowedMcpServers)&&void 0!==n?n:[];return 0===o.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){var n;const o=null!==(n=null==r?void 0:r.matchesServerUrlPattern)&&void 0!==n?n:I;return t.some((t=>{const r=F(t.command),n=U(t.serverUrl);if(void 0===r&&void 0===n)return!1;const s=void 0===r||void 0!==e.command&&C(r,e.command),i=void 0===n||void 0!==e.url&&o(n,e.url);return s&&i}))}(e,t,r)}(e,o,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){var n;const o=null!==(n=null==r?void 0:r.matchesServerUrlPattern)&&void 0!==n?n:I;return(null!=t?t:[]).some((t=>{const r=F(t.command),n=U(t.serverUrl);if(void 0===r&&void 0===n)return!1;const s=void 0===r||void 0!==e.command&&C(r,e.command),i=void 0===n||void 0!==e.url&&o(n,e.url);return s&&i}))}(e,t.deniedMcpServers,r)}function H(e){return(null!=e?e:[]).flatMap((e=>{var t,r;const n=null===(t=e.name)||void 0===t?void 0:t.trim();if(void 0===n||0===n.length)return[];const o=(null!==(r=e.toolAllowlist)&&void 0!==r?r:[]).map((e=>e.trim())).filter((e=>e.length>0));return 0===o.length?[`${n}:*`]:o.map((e=>`${n}:${e}`))}))}function z({autoRunControls:e,allowedMcpServers:t,isMcpSettingsOverhaulEnabled:r}){var n;const o=!0===(null==e?void 0:e.enabled)&&null!==(n=e.mcpToolAllowlist)&&void 0!==n?n:[];return s=r?[...H(t),...o]:[...o],[...new Set(s)];var s}class W{ttl;state;staleDirty=!1;refreshInFlight;refreshGeneration=0;constructor(e=864e5){this.ttl=e}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch(e){}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=await e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}function q(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function G(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch(e){return{host:null,origin:null,pathname:null}}}(e),n=!1!==(null==t?void 0:t.includePath);return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function V(e,t){return G(e,t)}var J=r("crypto");function K(e,t){const r=null==e?void 0:e.access_token,n="string"==typeof r?r.length:0,o=Boolean(null==e?void 0:e.refresh_token),s="number"==typeof(null==e?void 0:e.expires_in)&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:(null==t?void 0:t.expiresInIsFresh)&&null!==s?Date.now()+Math.round(1e3*s):null}}function Y(e){if(e)return(0,J.createHash)("sha256").update(e).digest("hex").slice(0,12)}function Z(e){if(e&&0!==e.length)return Y(JSON.stringify([...e].sort()))}function X(e){var t,r;return{clientIdHash:Y(null==e?void 0:e.client_id),clientSecretHash:Y(null==e?void 0:e.client_secret),redirectUrisHash:Z(null==e?void 0:e.redirect_uris),redirectUriCount:null!==(r=null===(t=null==e?void 0:e.redirect_uris)||void 0===t?void 0:t.length)&&void 0!==r?r:0}}function Q(e,t){let r=e;for(const e of t){if("object"!=typeof r||null===r||!(e in r))return;r=r[e]}return r}function ee(e,t){for(const r of t)if("string"==typeof Q(e,r.split(".")))return Q(e,r.split("."))}const te="[REDACTED]",re=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function ne(e){return e.replace(/((?:access_token|refresh_token|id_token|client_secret|authorization|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${te}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${te}`)}function oe(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function se(e,t){return oe(ne(e),null==t?void 0:t.maxLength)}function ie(e){if("string"==typeof e)return oe(ne(e));if(void 0!==e)try{const t=JSON.stringify(e,((e,t)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||re.test(t)}(e)?te:"string"==typeof t?ne(t):t));if(!t)return;return oe(t)}catch(e){return}}function ae(e){var t,r,n,o,s;const i=e instanceof Error?e.name:null!=e?typeof e:void 0,a=e instanceof Error?e.message:null!=e?String(e):void 0,c=void 0!==a?se(a):void 0,l=ee(e,["code","cause.code"]),u=null!==(t=function(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}(e))&&void 0!==t?t:ee(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),d=null!==(r=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=Q(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e))&&void 0!==r?r:function(e){var t;if(!e)return;const r=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)/),n=null!==(t=null==r?void 0:r[1])&&void 0!==t?t:null==r?void 0:r[2];if(!n)return;const o=Number.parseInt(n,10);return Number.isNaN(o)?void 0:o}(c),p=ie(null!==(s=null!==(o=null!==(n=Q(e,["response","body"]))&&void 0!==n?n:Q(e,["body"]))&&void 0!==o?o:Q(e,["data"]))&&void 0!==s?s:Q(e,["cause","body"])),h=function(e){var t,r;const n=null===(t=e.message)||void 0===t?void 0:t.toLowerCase(),o=null===(r=e.code)||void 0===r?void 0:r.toLowerCase();return(null==n?void 0:n.includes("timed out"))||(null==n?void 0:n.includes("timeout"))||(null==n?void 0:n.includes("etimedout"))||"etimedout"===o?"timeout":(null==n?void 0:n.includes("enotfound"))||(null==n?void 0:n.includes("eai_again"))||(null==n?void 0:n.includes("dns"))||"enotfound"===o||"eai_again"===o?"dns":(null==n?void 0:n.includes("certificate"))||(null==n?void 0:n.includes("tls"))||(null==n?void 0:n.includes("ssl"))?"tls":(null==n?void 0:n.includes("econnreset"))||(null==n?void 0:n.includes("connection reset"))||"econnreset"===o?"connection_reset":(null==n?void 0:n.includes("econnrefused"))||(null==n?void 0:n.includes("connection refused"))||"econnrefused"===o?"connection_refused":void 0}({message:c,code:l});return q({errorName:i,errorMessage:c,errorType:null!=e?typeof e:void 0,httpStatus:d,oauthErrorCode:u,errorResponseSummary:p,networkClassification:h,sdkErrorKind:u?"oauth_error":h?"auth_transport_error":c?"generic_error":void 0})}const ce={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function le(e){var t,r,n,o,s,i,a,c,l,u;const d=null!==(l=e.message)&&void 0!==l?l:ce[e.event],p={event:e.event,cursorMcp:{oauth:q(Object.assign({},e.metadata))}},h=null!==(u=e.level)&&void 0!==u?u:"info";"error"!==h?"warn"!==h?"debug"!==h?null===(c=(a=e.logger).info)||void 0===c||c.call(a,d,p):null===(i=(s=e.logger).debug)||void 0===i||i.call(s,d,p):null===(o=(n=e.logger).warn)||void 0===o||o.call(n,d,p):null===(r=(t=e.logger).error)||void 0===r||r.call(t,d,e.error,p)}const ue=4096;function de(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function pe(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function he(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function me(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function fe(e,t){var r,n,o,s,i;if(null==e)return{kind:"none",bytes:0,contentLength:me(t.get("content-length"))};if("string"==typeof e){const n=(new TextEncoder).encode(e).length;return{kind:"text",bytes:n,contentLength:null!==(r=me(t.get("content-length")))&&void 0!==r?r:n}}if(e instanceof URLSearchParams){const r=e.toString(),o=(new TextEncoder).encode(r).length;return{kind:"text",bytes:o,contentLength:null!==(n=me(t.get("content-length")))&&void 0!==n?n:o}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:null!==(o=me(t.get("content-length")))&&void 0!==o?o:e.size}:e instanceof ArrayBuffer?{kind:"binary",bytes:e.byteLength,contentLength:null!==(s=me(t.get("content-length")))&&void 0!==s?s:e.byteLength}:ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:null!==(i=me(t.get("content-length")))&&void 0!==i?i:e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:me(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:me(t.get("content-length"))}}function ge(e,t){var r;if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const n="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch(e){return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch(e){return}}}(t):t instanceof URLSearchParams&&null!==(r=t.get("grant_type"))&&void 0!==r?r:void 0;return n?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(n):void 0}function ve(e){var t,r,n,o;const{input:s,init:i}=e,a=G(pe(s)),c=function(e,t){const r=new Headers(de(e)?e.headers:void 0);return new Headers(null==t?void 0:t.headers).forEach(((e,t)=>{r.set(t,e)})),r}(s,i),l=he(c),u=c.get("content-type"),d=Y(null!==(t=c.get("mcp-session-id"))&&void 0!==t?t:void 0),p=c.get("authorization"),h=p&&null!==(r=p.split(/\s+/,1)[0])&&void 0!==r?r:null;return{method:(null!==(o=null!==(n=null==i?void 0:i.method)&&void 0!==n?n:de(s)?s.method:void 0)&&void 0!==o?o:"GET").toUpperCase(),url:a,headers:{names:l,count:l.length},contentType:u,body:fe(null==i?void 0:i.body,c),sessionIdHash:null!=d?d:null,authorizationScheme:h}}function ye(e,t){var r,n,o,s,i;const a=he(e.headers),c=me(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:a,count:a.length},contentType:e.headers.get("content-type"),body:Object.assign({kind:null===e.body?"none":"stream",bytes:null===e.body?0:c,contentLength:c},void 0!==t?{errorSummary:t}:{}),sessionIdHash:null!==(n=Y(null!==(r=e.headers.get("mcp-session-id"))&&void 0!==r?r:void 0))&&void 0!==n?n:null,wwwAuthenticateHash:null!==(s=Y(null!==(o=e.headers.get("www-authenticate"))&&void 0!==o?o:void 0))&&void 0!==s?s:null,mcpProtocolVersion:null!==(i=e.headers.get("mcp-protocol-version"))&&void 0!==i?i:null}}function we(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}async function be(e,t){try{const r=await e.clone().text();return r.length>t?r.slice(0,t):r}catch(e){return}}async function ke(e){if(!function(e,t){var r,n;const o=ve({input:e,init:t});if(void 0!==ge(o.contentType,null==t?void 0:t.body))return!0;const s=null!==(n=null===(r=o.url.path)||void 0===r?void 0:r.toLowerCase())&&void 0!==n?n:"";return s.endsWith("/token")||s.includes("/oauth/token")||s.includes("/connect/token")}(e.input,e.init))return;const t=await be(e.response,ue);if(void 0!==t)try{return ie(JSON.parse(t))}catch(e){return se(t,{maxLength:ue})}}async function Se(e){const t=await async function(e,t){var r,n;try{if(t.ok)return;const o=null!==(n=null===(r=t.headers.get("content-type"))||void 0===r?void 0:r.toLowerCase())&&void 0!==n?n:"";if(!o.includes("json")&&!o.includes("text"))return;const s=await be(t,ue);if(void 0===s)return;return function(e){if("/mcp"!==(t=G(pe(e.input)).path)&&!0!==(null==t?void 0:t.endsWith("/mcp")))return se(e.rawText,{maxLength:ue});var t;try{const t=JSON.parse(e.rawText);return"object"==typeof t&&null!==t?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?se(r.message,{maxLength:ue}):void 0;return void 0!==n||void 0!==o?JSON.stringify(Object.assign(Object.assign({},void 0!==n?{code:n}:{}),void 0!==o?{message:o}:{})):void 0}(t):void 0}catch(e){return}}({input:e,rawText:s})}catch(e){return}}(e.input,e.response);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await ke({input:e.input,response:e.response,init:e.init}):void 0}}function Ee(e,t,r){var n;try{e()}catch(e){null===(n=t.warn)||void 0===n||n.call(t,"MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function xe(e){const{fetch:t,logger:r,metadata:n,logSuccessfulExchanges:o=!0}=e;return async(e,s)=>{const i=Date.now();try{const a=await t(e,s),{responseErrorSummary:c,oauthTokenErrorBodySummary:l}=a.ok?{}:await Se({input:e,init:s,response:a});return!o&&a.ok||Ee((()=>{!function(e){var t,r;const{logger:n,response:o}=e,s=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=ve({input:t,init:r}),l=ge(c.contentType,null==r?void 0:r.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign({},s),{request:c,response:ye(n,i)}),void 0!==l?{oauth:{grantType:l}}:{}),void 0!==a?{oauthTokenErrorBodySummary:a}:{})}}}(e);o.ok?null===(t=n.info)||void 0===t||t.call(n,"MCP HTTP exchange completed",s):null===(r=n.warn)||void 0===r||r.call(n,"MCP HTTP exchange completed",s)}({logger:r,input:e,init:s,response:a,durationMs:Date.now()-i,metadata:n,responseErrorSummary:c,oauthTokenErrorBodySummary:l})}),r,"success"),a}catch(t){const o=function(e){var t,r;if(!e||"object"!=typeof e)return;const n=[e.response,null===(t=e.cause)||void 0===t?void 0:t.response];for(const e of n)if(e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status&&"headers"in e&&"function"==typeof(null===(r=e.headers)||void 0===r?void 0:r.get))return e}(t),{responseErrorSummary:a,oauthTokenErrorBodySummary:c}=o?await Se({input:e,init:s,response:o}):{};throw Ee((()=>{!function(e){var t;const{logger:r}=e;null===(t=r.warn)||void 0===t||t.call(r,"MCP HTTP exchange failed",function(e){var t;const{input:r,init:n,error:o,durationMs:s,metadata:i,responseFromError:a,responseErrorSummary:c,oauthTokenErrorBodySummary:l}=e,u=ae(o),d=ve({input:r,init:n}),p=ge(d.contentType,null==n?void 0:n.body),h=void 0!==a?ye(a,c):{status:null!==(t=u.httpStatus)&&void 0!==t?t:null,ok:null,headers:{names:[],count:0},contentType:null,body:Object.assign({kind:"none",bytes:null,contentLength:null},void 0!==c?{errorSummary:c}:{}),sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null};return{event:"mcp_http_exchange",outcome:"error",durationMs:s,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),{request:d,response:h}),void 0!==p?{oauth:{grantType:p}}:{}),void 0!==l?{oauthTokenErrorBodySummary:l}:{}),{error:we(u)})}}}(e))}({logger:r,input:e,init:s,error:t,durationMs:Date.now()-i,metadata:n,responseFromError:o,responseErrorSummary:a,oauthTokenErrorBodySummary:c})}),r,"failure"),t}}}new Set(["InvalidGrantError","InvalidRequestError"]),new Set(["SiblingAlreadyRefreshedError","OAuthRefreshTransientError","AbortError","TimeoutError","ServerError","TemporarilyUnavailableError"]);const _e=["0.0.0.0/0","::/0"];function Ce(e){const t=(null!=e?e:[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=_(e);return void 0===t?[]:[t]}));return{hasConfiguredEntries:t.length>0,hasInvalidEntries:r.length!==t.length,entries:r}}function Pe(e){const t=Ce(e.mcpNetworkAllowlist),r=Ce(e.mcpNetworkDenylist),n=e.mcpNetworkMode;if("deny_all"===n||r.entries.includes("*")||r.hasInvalidEntries)return{version:1,default:"deny"};if("allow_all"===n)return Object.assign({version:1,default:"deny",allow:[..._e]},r.entries.length>0?{deny:r.entries}:{});if("allowlist"===n||t.hasConfiguredEntries){const e=function(e){return e.entries.includes("*")?[..._e]:e.entries}(t);return e.length>0?Object.assign({version:1,default:"deny",allow:e},r.entries.length>0?{deny:r.entries}:{}):{version:1,default:"deny"}}return Object.assign({version:1,default:"deny",allow:[..._e]},r.entries.length>0?{deny:r.entries}:{})}async function Re(e,t){const{resolveSandboxPolicyForWorkspace:n}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),o={type:"workspace_readwrite",sandboxWorkspaceRoot:t,networkPolicy:Pe(e),networkPolicyStrict:!0},{policy:s}=await n(t,{perUser:o});return s}const Te=["0.0.0.0/0","::/0"];function Ie(e){const t=(null!=e?e:[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=_(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function Ae(e){const t=!0===e.enabled,r=Ie(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...Te];const t=Ie(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...Te]:t.entries;if(!function(e){var t;return(null!==(t=e.mcpNetworkAllowlist)&&void 0!==t?t:[]).some((e=>e.trim().length>0))}(e))return[...Te];const r=O(e);return r.includes("*")?[...Te]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class je extends Error{serverName;constructor(e,t){super(`MCP server "${e}" requires sandboxing because MCP Network Controls are enabled, but the sandbox is not supported on this platform or system. The server was not started.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}function Oe(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!(null==n?void 0:n[1]))return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){var t;if(!(e instanceof Error))return!1;const r=e,n=null===(t=e.cause)||void 0===t?void 0:t.code;return"ECONNREFUSED"===r.code||"ECONNREFUSED"===n||e.message.includes("ECONNREFUSED")}(e)}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,r("../constants/dist/index.js"),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]),new Set([429,502,503,504]),new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]),new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Error},"../shell-exec/dist/index.js"(e,t,r){r.d(t,{BM:()=>wt,Ls:()=>ct,SandboxUnsupportedError:()=>se,J:()=>u,St:()=>ae,Fn:()=>yt,oG:()=>Ge,Ko:()=>m,CG:()=>Ee,G6:()=>vt,_B:()=>F,OK:()=>M,$b:()=>L,Nl:()=>ut,K3:()=>ue,tv:()=>ht,fZ:()=>Pe,s9:()=>_e,T6:()=>B,Po:()=>U,$6:()=>pt,l7:()=>mt,Qd:()=>l,resolveSandboxPolicyForWorkspace:()=>Ie,spawnInSandbox:()=>ce});var n=r("node:path"),o=r("../utils/dist/index.js"),s=r("node:fs/promises"),i=r("node:os"),a=r("../context/dist/index.js");let c;function l(){const e=(0,o.Ef)("rg",[]).cmd;return"rg"!==e?e:void 0}function u(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");c=e}function d(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function p(e,t){const r=(0,n.dirname)(t);if(!r||"."===r)return e;const o=function(e){const t=d(e);return void 0!==t?e[t]??"":""}(e).split(n.delimiter).filter(Boolean);return function(e,t){const r=d(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...o.filter((e=>e!==r))].join(n.delimiter))}function h(e){return c&&(0,n.isAbsolute)(c)?{...p(e,c),CURSOR_RIPGREP_PATH:c}:e}function m(){if(!c)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return c}var f=r("node:child_process"),g=r("node:fs");function v(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;return n}const y=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function w(e){const t={...e};for(const e of y)delete t[e];return t}var b=r("node:crypto?8af2");let k;function S(){const e=(0,n.join)((0,i.tmpdir)(),"cursor-sandbox-cache",(k||(k=(0,b.randomBytes)(16).toString("hex")),k));return{NPM_CONFIG_CACHE:(0,n.join)(e,"npm"),PNPM_STORE_PATH:(0,n.join)(e,"pnpm-store"),GOCACHE:(0,n.join)(e,"go-build"),GOMODCACHE:(0,n.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,n.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,n.join)(e,"pip"),UV_CACHE_DIR:(0,n.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,n.join)(e,"bun"),YARN_CACHE_FOLDER:(0,n.join)(e,"yarn"),npm_config_devdir:(0,n.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,n.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,n.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,n.join)(e,"turbo"),GRADLE_USER_HOME:(0,n.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,n.join)(e,"conda"),POETRY_CACHE_DIR:(0,n.join)(e,"poetry"),GEM_SPEC_CACHE:(0,n.join)(e,"gem-specs"),BUNDLE_PATH:(0,n.join)(e,"bundle"),COMPOSER_HOME:(0,n.join)(e,"composer"),HOMEBREW_CACHE:(0,n.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,n.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,n.join)(e,"nx"),NUGET_PACKAGES:(0,n.join)(e,"nuget"),CCACHE_DIR:(0,n.join)(e,"ccache"),CP_HOME_DIR:(0,n.join)(e,"cocoapods")}}var E=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const x=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".ssh"}];function _(e){const t=x.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function C(e){const t=x.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}x.filter((e=>"git"===e.type)).map((e=>e.pattern)),x.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const P=[];let R=null,T=null;let I=null;const A=new Map;const j="win32"===process.platform||"darwin"===process.platform;function O(e,t){const r=t.endsWith(n.sep)?t.slice(0,-1):t;if(j){const t=e.toLowerCase(),o=r.toLowerCase();return t===o||t.startsWith(o+n.sep)}return e===r||e.startsWith(r+n.sep)}function D(e,t){const r=e.endsWith(n.sep)?e.slice(0,-1):e;return j?(0,n.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,n.relative)(r,t).replace(/\\/g,"/")}async function M(e,t){if(O(e,t)){const r=D(t,e);if((null===R&&(R=E({ignoreCase:!0}),R.add(x.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),R).ignores(r))return!0}const{isWorktree:r,gitDirParent:a}=await async function(e){const t=A.get(e);if(t)return t;const r=await(0,s.stat)((0,n.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return A.set(e,t),t}const i=await async function(e){try{const t=await(0,o.DP)("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,n.dirname)((0,n.resolve)(e,t.trim()))}catch{return null}}(e),a={isWorktree:!0,gitDirParent:i??e};return A.set(e,a),a}(t);if(O(e,a)){const t=D(a,e);if((null===T&&(T=E({ignoreCase:!0}),T.add(x.filter((e=>"git"===e.type)).map((e=>e.pattern)))),T).ignores(t))return!0}if(r&&O(e,t)&&".git"===D(t,e))return!0;for(const t of function(){if(null!==I)return I;const e=i.default.homedir(),t=[];for(const r of x)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,n.join)(e,r.pattern))}return I=t,t}())if(O(e,t))return!0;return!1}const N=new WeakMap;function $(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}function L(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function F(e){return void 0!==e&&"allow"===e.default}function U(){return{version:1,default:"deny"}}function B(){return{version:1,default:"allow"}}const H="darwin"===process.platform,z="linux"===process.platform,W=(0,a.h)("shell-exec:sandbox");function q(e){const t=b.randomBytes(8).toString("hex"),r=n.join(i.tmpdir(),`sandbox-policy-${t}`);return g.writeFileSync(r,e,{encoding:"utf-8",mode:384}),r}let G;function V(){return G}function J(e){"linux"===process.platform&&Object.assign(e,h(e))}let K=null,Y=null,Z=null,X=null;function Q(e){if(null!==K)return!!K;try{const t=V();return W.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(K=g.existsSync(t),K?W.info(e,`[checkBinaryAvailable] Binary path exists: ${K}`):(Y=new Error(`Sandbox binary not found at ${t}`),W.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!K):(Y=new Error("Sandbox binary path was not configured"),K=!1,W.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return Y=t,K=!1,W.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function ee(e){if(null!==X)return X;const t=e??(0,a.q6)();if(W.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Q(t)){const e=Y?.message||"Binary check failed";return Z=e,W.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),X=!1,X}if("win32"===process.platform)return Z="Windows sandbox helper only provides network proxy, not filesystem isolation",W.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),X=!1,X;if("darwin"===process.platform)return Z=null,W.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),X=!0,X;try{const e=process.cwd(),r={sandbox:{type:"workspace_readwrite",cwd:e,additionalReadwritePaths:[],networkAccess:!1,disableTmpWrite:!1,ignoreMapping:void 0}},n=String(V());W.info(t,`[isSandboxHelperSupported] Running preflight with binary: ${n}`),W.info(t,`[isSandboxHelperSupported] CWD: ${e}`);const o={...process.env};J(o);const s=q(JSON.stringify(r));return(0,f.execFileSync)(n,["--policy",s,"--preflight-only","--","/bin/true"],{stdio:["ignore","ignore","pipe"],timeout:15e3,env:o,shell:!1}),Z=null,W.info(t,"[isSandboxHelperSupported] Preflight succeeded, sandbox supported!"),X=!0,X}catch(e){const r=e,n=r.stderr?.toString?.()||"";return W.error(t,`[isSandboxHelperSupported] Preflight failed: ${r.message}`),W.error(t,`[isSandboxHelperSupported] Exit status: ${r?.status}`),n&&W.error(t,`[isSandboxHelperSupported] Stderr: ${n}`),"number"==typeof r?.status&&2===r.status?(Z=`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${n||"none"}`,X=!1,X):(Z=`Linux preflight failed: ${r.message||"unknown error"}. Exit status: ${r?.status}. stderr: ${n||"none"}`,X=!1,X)}}function te(e,t=[],r={},o){const s=(0,a.q6)();if(r.env=v(r.env),!Q(s))throw new Error(`Sandbox binary not available: ${Y?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,f.spawn)(e,t,r);if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),i=o.sandboxWorkspaceRoot??s;let a,c=e,l=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",l=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",l=["-c",`${e} ${t.join(" ")}`])),o.ignoreMapping&&(a=re(o.ignoreMapping));const u=function(e,t,r){const o=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},s=function(e){let t=n.resolve(e);for(;;){try{const e=n.join(t,".git");if(g.existsSync(e))return!0}catch{}const e=n.dirname(t);if(e===t)return!1;t=e}}(r),i=!z||s?t??{}:{},a={...o};for(const[e,t]of Object.entries(i))a[e]?a[e]=[...a[e],...t]:a[e]=t;if(0!==Object.keys(a).length)return re(a)}(o.additionalReadonlyPaths,o.writeProtectionMapping,i),d=L(o.networkPolicy),p="workspace_readonly"===o.type?{type:"workspace_readonly",cwd:i,additionalReadonlyPaths:u,networkAccess:d,ignoreMapping:a}:{type:"workspace_readwrite",cwd:i,additionalReadwritePaths:o.additionalReadwritePaths||[],additionalReadonlyPaths:u,networkAccess:d,disableTmpWrite:o.disableTmpWrite||!1,ignoreMapping:a},h=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!L(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),m={sandbox:p};void 0!==h&&(m.networkPolicy=h),!1===o.networkPolicyStrict&&(m.networkPolicyStrict=!1);const v=["--policy",q(JSON.stringify(m)),"--",c,...l],y={..."linux"===process.platform?w(process.env):process.env,..."linux"===process.platform&&r.env?w(r.env):r.env,CURSOR_SANDBOX:"native"};J(y);const b={cwd:r.cwd||s,env:y,stdio:r.stdio||["pipe","pipe","pipe"]};try{const e=new Date,t=(0,f.spawn)(String(V()),v,b);return H&&t.pid&&function(e,t){N.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${e}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function re(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?ne(t):t;o[e]=r;const n=oe(e);n!==e&&(o[n]=r)}return o}function ne(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function oe(e){try{return(0,g.realpathSync)(e)}catch{return e}}class se extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const ie="darwin"===process.platform;function ae(e){!function(e){m();const{sandboxBinaryPath:t}=e;G||(G=t)}(e)}function ce(e,t=[],r={},n){if(r.env=v(r.env),n.enableSharedBuildCache&&(r={...r,env:{...v(process.env),...S(),...r.env}}),"insecure_none"!==n.type){if(ee())return te(e,t,r,n);const o=Z;throw new se(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r){return(0,f.spawn)(e,t,r)}(e,t,r)}function le(e){return ie?async function(e){const t=N.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,f.execFile)("/usr/bin/log",s,((t,n,s)=>{if(t)return void e([{raw:t.message}]);const i=n.split(/\r?\n/).filter((e=>e.trim().length>0)),a=[];for(const e of i)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,i,c,l,u,d]=s,p=Number(i);a.push({timestamp:t.timestamp,processName:e.trim(),pid:p,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:$(p,r,o)});continue}const i=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(i){const e=Number(i[1]),s=i[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,i,l,u,d,p]=c,h=Number(i);a.push({timestamp:t.timestamp,processName:s.trim(),pid:h,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:p,duplicateCount:e,raw:n,relationship:$(h,r,o)})}else a.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}a.push({timestamp:t.timestamp,raw:n})}catch{}e(a)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function ue(e,t){if(ie)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return ee(t?.ctx)}var de;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(de||(de={}));const pe={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function he(e,t=[],r={},n,o){if(o?.aborted){const e=new Error("Operation was aborted");e.name="AbortError";const t=new(require("node:events").EventEmitter);return process.nextTick((()=>{t.emit("error",e)})),t}const s=ce(e,t,{...r,env:h(r.env??process.env)},n);if(o){const e=()=>{if(s.pid)try{if(r.detached)try{process.kill(-s.pid,"SIGTERM")}catch{s.kill("SIGTERM")}else s.kill("SIGTERM");const e=setTimeout((()=>{if(!s.killed&&s.pid)try{if(r.detached)try{process.kill(-s.pid,"SIGKILL")}catch{s.kill("SIGKILL")}else s.kill("SIGKILL")}catch(e){}}),1e3);s.once("exit",(()=>{clearTimeout(e)}))}catch(e){}};o.addEventListener("abort",e,{once:!0}),s.once("exit",(()=>{o.removeEventListener("abort",e)}))}return s}function me(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function fe(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}const ge="__CURSOR_BASH_STATE_START__",ve="__CURSOR_BASH_STATE_END__",ye=50,we=262144;class be{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??ye,this.maxBufferedBytes=t?.maxBufferedBytes??we}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o<e.length;o++){const s=e[o];s.type!==r?(t.push({type:r,data:Buffer.concat(n)}),r=s.type,n=[s.data]):n.push(s.data)}return t.push({type:r,data:Buffer.concat(n)}),t}(e))try{await this.writable.write(t)}catch{}}}function ke(e){if(!e.bufferOutputEvents){const t=(t,r)=>{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{t("stdout",e)})),e.stderr?.on("data",(e=>{t("stderr",e)})),{async waitForOutput(){},async flush(){}}}const t=new be(e.writable,e.outputLimiterOptions);let r;const n=Promise.all([Se(e.stdout,"stdout",t),Se(e.stderr,"stderr",t)]).then((()=>{})).catch((e=>{r=e}));return{async waitForOutput(){if(await n,void 0!==r)throw(e=r)instanceof Error?e:new Error(String(e));var e},async flush(){await t.flush()}}}async function Se(e,t,r){if(e)for await(const n of e)await r.push(t,n)}function Ee(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function xe(...e){return e.some((e=>!0===e))}function _e(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(Ce(e));return[...t]}function Ce(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Pe(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function Re(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e)){const e=r[t];if(e){const o=new Set(e);for(const e of n)o.has(e)&&o.delete(e),o.add(e);r[t]=[...o]}else r[t]=[...n]}return 0!==Object.keys(r).length?r:void 0}function Te(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ie(e,t){if(!t)return{policy:{type:"insecure_none"}};const r=await(0,s.stat)((0,n.join)(e,".git")).then((e=>e),(()=>null)),i=r?.isFile()??!1,a=null!==r;if("workspace_readwrite"===Ee(t)){let r=e;if(i){const s=await(0,o.DP)("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,n.resolve)(e,t.trim())),(()=>null));if(s){r=(0,n.dirname)(s);const o=t.perRepo,i=o?.ignoreMapping;t={...t,perRepo:{...o,type:"workspace_readwrite",additionalReadwritePaths:[...o?.additionalReadwritePaths??[],s],ignoreMapping:i,writeProtectionMapping:Re(o?.writeProtectionMapping,C(e))}}}}if(a)return Ae(t,{workspaceDir:e,gitDirParent:r})}return Ae(t,{workspaceDir:e})}function Ae(e,t){const r=function(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}(e);if(void 0===r)return De(e,t);switch(r){case"workspace_readwrite":return De(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=je(e,t),o={policy:Oe({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(e,t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={type:"insecure_none",allowlistEscalated:xe(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:Te(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:xe(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:Te(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},a=Object.fromEntries(Object.entries(i).filter((([e,t])=>void 0!==t)));a.type="insecure_none";const c={policy:a};return s&&(c.debug={fieldSources:{}}),c}(e,t);default:throw new Error(`Unknown policy type: ${r}`)}}function je(e,t){const r=t?.debug,{perUser:o,perRepo:s,teamAdmin:a}=e,c=t?.workspaceDir??process.cwd(),l=function(e){const t=function(){if(0!==P.length)return{version:1,deny:[...P]}}(),r=i.default.homedir(),o=[];for(const e of x)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":o.push(e.pattern);break;case"home":r.length>0&&o.push((0,n.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${t}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:o,writeProtectionMapping:_(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(c),u={},d=[o,s,a],p=["perUser","perRepo","teamAdmin","hardcoded"],h=(e,t)=>{r&&(u[e]=p[t]??"unknown")},m=xe(o?.disableTmpWrite,s?.disableTmpWrite,a?.disableTmpWrite);for(let e=d.length-1;e>=0;e--)if(!0===d[e]?.disableTmpWrite){h("disableTmpWrite",e);break}const f=xe(o?.networkPolicyStrict,s?.networkPolicyStrict,a?.networkPolicyStrict,l.networkPolicyStrict);l.networkPolicyStrict&&h("networkPolicyStrict",3);const g=_e(o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a?.additionalReadonlyPaths,l.additionalReadonlyPaths),v=g.length>0?g:void 0;let y=Pe(o?.networkPolicy,s?.networkPolicy,a?.networkPolicy,l.networkPolicy);const w=a?.networkPolicy?.allow;void 0!==w&&w.length>0&&void 0!==y&&(y={...y,allow:[...w]},r&&(u["networkPolicy.allow"]="teamAdmin (replace)"));const b=void 0!==(k=y)?k:{version:1,default:"deny"};var k;const S=Te(o?.debugOutputDir,s?.debugOutputDir,a?.debugOutputDir),E=xe(o?.captureDenies,s?.captureDenies,a?.captureDenies),C=Te(o?.enableSharedBuildCache,s?.enableSharedBuildCache,a?.enableSharedBuildCache),R=Re(o?.ignoreMapping,s?.ignoreMapping,a?.ignoreMapping,l.ignoreMapping),T=function(e){const t=x.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??c);return{disableTmpWrite:m||void 0,networkPolicyStrict:f,additionalReadonlyPaths:v,networkPolicy:b,debugOutputDir:S,captureDenies:E||void 0,enableSharedBuildCache:C,ignoreMapping:R,writeProtectionMapping:Re(o?.writeProtectionMapping,s?.writeProtectionMapping,a?.writeProtectionMapping,l.writeProtectionMapping,T),fieldSources:u}}function Oe(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function De(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=je(e,t),a=_e(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:Oe({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}const Me="win32"===process.platform;function Ne(e){return!Me&&!!e?.SUDO_ASKPASS}function $e(e){return Ne(e)?"alias sudo='sudo -A'; ":""}function Le(e){const t=[];let r=0;for(;r<e.length;){const n=0===r||"&&"===e.slice(Math.max(0,r-2),r)||"||"===e.slice(Math.max(0,r-2),r)||"|"===e[r-1]||";"===e[r-1],o=Math.max(0,r-10),s=e.slice(o,r),i=/(?:&&|\|\||[|;])\s*$/.test(s)||0===r&&/^\s*$/.test(s);if((n||i)&&"sudo"===e.slice(r,r+4)){const n=r+4;if(n>=e.length||/\s/.test(e[n])){let o=n;for(;o<e.length&&/\s/.test(e[o]);)o++;let s=!1;if(o<e.length&&"-"===e[o]){let t=o+1;for(;t<e.length&&/[^\s]/.test(e[t]);)t++;const r=e.slice(o,t);s=/^-[a-zA-Z]*A[a-zA-Z]*$/.test(r)}s?(t.push("sudo"),r=n):(t.push("sudo -A"),r=n);continue}}t.push(e[r]),r++}return t.join("")}var Fe=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Ue(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=(0,o.Ef)("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:(0,o.Ef)("bash",[]).cmd}function Be(e){if("win32"!==process.platform)return e;const t=n.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===n.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}class He{cwd;state;userTerminalHint;useFileStateTransport;constructor(e,t,r,n=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n}async getCwd(){return this.cwd}clone(e){return new He(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport)}async*execute(e,t,r){const c={stack:[],error:void 0,hasError:!1};try{const l=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(c,(0,a.VI)(e.withName("BashState.execute")),!1),u=r?.pipeStdin??!1,d=(0,o.Jt)(),p=r?.workingDirectory??this.cwd,h={...process.env,...pe,...r?.env};let m='builtin eval "$1"';u||(m+=" < /dev/null");const f=$e(h),g=this.useFileStateTransport;let v,y,w;if(g){v=await(0,s.mkdtemp)(n.default.join(i.default.tmpdir(),"cursor-bash-state-")),n.default.basename(v),y=n.default.join(v,"state-in"),w=n.default.join(v,"state-out"),await(0,s.writeFile)(y,this.state,"utf8"),await(0,s.writeFile)(w,"","utf8").catch((()=>{}));const e=Be(y),t=Be(w);h.CURSOR_STATE_INPUT_FILE=e,h.CURSOR_STATE_OUTPUT_FILE=t}const b=["-O","extglob","-c",`${g?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)"} && builtin shopt -s extglob && builtin eval -- "$snap" && { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${f}${m}; }; COMMAND_EXIT_CODE=$?; ${g?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4"}; builtin exit $COMMAND_EXIT_CODE`,"--",t],k=Ue(this.userTerminalHint);if(!k)throw new Error("Can't find Bash");const S=r?.sandboxWorkspaceRoot??p,E=(await Ie(S,r?.sandboxPolicy)).policy,x="insecure_none"!==E.type?{...E,sandboxWorkspaceRoot:S}:E;let _="";const C=async()=>{if(g){if(!w)return void(_=this.state);try{_=await(0,s.readFile)(w,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),_=this.state}}},P=async()=>{if(v)try{await(0,s.rm)(v,{recursive:!0,force:!0})}catch{}};let R;try{R=he(k,b,{env:h,stdio:[u?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:p,detached:!0},x,r?.signal)}catch(e){throw await P(),e}R.on("spawn",(async()=>{try{await d.write({type:"stdin_ready",stdin:R.stdin??void 0,pid:R.pid})}catch(e){}}));const T=ke({stdout:R.stdout,stderr:R.stderr,writable:d,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});R.on("error",(async e=>{await P(),d.throw(e)}));let I=null,A=null,j=!1;const O=async e=>{if(!j){if(j=!0,A&&(clearTimeout(A),A=null),(0,a.HF)(l.ctx,"exit"),e)try{await T.waitForOutput()}catch(e){return await P(),void d.throw(e instanceof Error?e:new Error(String(e)))}if(await T.flush(),!r?.signal?.aborted){await C();const e=`${ge}\n`,t=`${ve}\n`;if(_.startsWith(e)&&_.endsWith(t)){let t=_.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=me(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(x.captureDenies)try{const e=await le(R);e&&e.length>0&&await d.write({type:"sandbox_denies",events:e})}catch{}try{await d.write({type:"exit",code:I,data:"",aborted:r?.signal?.aborted??!1}),d.close()}catch{d.close()}await P()}};R.on("exit",((e,t)=>{I=e;const n=r?.closeTimeout??5e3;n>0&&(A=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),O(!1)}),n))})),R.on("close",(async()=>{await O(!0)}));const D=R.stdio[3],M=R.stdio[4];g||(D?.write(this.state),D?.end(),M?.on("data",(e=>{_+=e.toString()}))),yield*d}catch(e){c.error=e,c.hasError=!0}finally{Fe(c)}}}var ze=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class We{promise;constructor(e){this.promise=e}async getCwd(){return(await this.promise).getCwd()}clone(e){return new We(this.promise.then((t=>t.clone(e))))}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,a.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.promise;for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{ze(n)}}}var qe=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Ge(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=(0,o.Ef)("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=(0,o.Ef)("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=n.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,g.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}class Ve{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Ve(e??this.cwd,this.state)}async*execute(e,t,r){const c={stack:[],error:void 0,hasError:!1};try{const l=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(c,(0,a.VI)(e.withName("PowerShellState.execute")),!1),u=r?.pipeStdin??!1,d=r?.workingDirectory??this.cwd,p=(0,o.Jt)(),h={...process.env,...pe,...r?.env},m=Ne(h)?Le(t):t,f=i.tmpdir(),g=n.join(f,`ps-state-out-${(0,b.randomUUID)()}.txt`),v=((e,t,r,n)=>`\n${e}\n\nSet-Location '${t}'\n\n# Execute user command\n${r}\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n\n\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n\n Emit $PWD.Path\n #Log-Timing "working_dir"\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing "environment"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name "{0}" -Value "{1}"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing "finalize"\n}\n\nDump-PowerShellState -OutputFile "${n}"\n\nexit $COMMAND_EXIT_CODE\n`)(this.state,d,m,g),y=n.join(f,`ps-script-${(0,b.randomUUID)()}.ps1`);await async function(e,t){await s.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(y,v);const w=["-ExecutionPolicy","Bypass"];u||w.push("-NonInteractive"),w.push("-File",y);const k=Ge(),S="win32"===process.platform,E=r?.sandboxWorkspaceRoot??d,x=(await Ie(E,r?.sandboxPolicy)).policy,_=he(k,w,{env:h,stdio:[u?"pipe":"ignore","pipe","pipe"],cwd:d,detached:!S},"insecure_none"!==x.type?{...x,sandboxWorkspaceRoot:E}:x,r?.signal);_.on("spawn",(async()=>{try{await p.write({type:"stdin_ready",stdin:_.stdin??void 0,pid:_.pid})}catch(e){}}));const C=ke({stdout:_.stdout,stderr:_.stderr,writable:p,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),P=async()=>{try{const e=await s.readFile(g,"utf8"),{cwd:t,rest:r}=me(e);this.state=r,this.cwd=t.trim(),await(0,s.rm)(g).catch((()=>{}))}catch(e){}await(0,s.rm)(y).catch((()=>{}))};let R=null,T=null,I=!1;const A=async e=>{if(!I){if(I=!0,T&&(clearTimeout(T),T=null),(0,a.HF)(l.ctx,"exit"),e)try{await C.waitForOutput()}catch(e){return await P(),void p.throw(e instanceof Error?e:new Error(String(e)))}await C.flush();try{await p.write({type:"exit",code:R,data:"",aborted:r?.signal?.aborted??!1}),await P(),p.close()}catch(e){p.close()}}};_.on("exit",((e,t)=>{R=e;const n=r?.closeTimeout??5e3;n>0&&(T=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),A(!1)}),n))})),_.on("close",(async()=>{await A(!0)})),_.on("error",(e=>{P().catch((()=>{})),p.throw(e)})),yield*p}catch(e){c.error=e,c.hasError=!0}finally{qe(c)}}}var Je=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Ke{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new Ke(e??this.cwd,this.options)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,a.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),i=(0,o.Jt)(),c=r?.pipeStdin??!1,l={...process.env,...pe,...r?.env},u=Ne(l)?Le(t):t,d=r?.workingDirectory??this.cwd,p=r?.sandboxWorkspaceRoot??d,h=(await Ie(p,r?.sandboxPolicy)).policy,m="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:p}:h,f=he(this.options?.shell||process.env.SHELL||"/bin/sh",[...this.options?.shellArgs??[],"-c",u],{env:l,cwd:d,stdio:[c?"pipe":"ignore","pipe","pipe"]},m,r?.signal);f.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:f.stdin??void 0,pid:f.pid})}catch(e){}}));const g=ke({stdout:f.stdout,stderr:f.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});f.on("error",(e=>{i.throw(e)})),f.on("exit",(async e=>{if((0,a.HF)(s.ctx,"exit"),await g.flush(),m.captureDenies)try{const e=await le(f);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:e,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}})),yield*i}catch(e){n.error=e,n.hasError=!0}finally{Je(n)}}}const Ye="__CURSOR_ZSH_STATE_START__",Ze="__CURSOR_ZSH_STATE_END__";var Xe=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Qe(){const e=process.env.SHELL;return e?.includes("zsh")?e:(0,o.Ef)("zsh",[]).cmd}class et{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new et(e??this.cwd,this.state)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,a.VI)(e.withName("ZshState.execute")),!1),i=r?.pipeStdin??!1,c=(0,o.Jt)(),l=r?.workingDirectory??this.cwd,u={...process.env,...pe,...r?.env};let d='builtin eval "$1"';i||(d+=" < /dev/null");const p=["-c",`snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${$e(u)}${d}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],h=r?.sandboxWorkspaceRoot??l,m=(await Ie(h,r?.sandboxPolicy)).policy,f="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,g=he(Qe(),p,{env:u,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:l,detached:!0},f,r?.signal);let v="";g.on("spawn",(async()=>{try{await c.write({type:"stdin_ready",stdin:g.stdin??void 0,pid:g.pid})}catch(e){}}));const y=ke({stdout:g.stdout,stderr:g.stderr,writable:c,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});g.on("error",(e=>{c.throw(e)}));let w=null,b=null,k=!1;const S=async e=>{if(!k){if(k=!0,b&&(clearTimeout(b),b=null),(0,a.HF)(s.ctx,"exit"),e)try{await y.waitForOutput()}catch(e){return void c.throw(e instanceof Error?e:new Error(String(e)))}if(await y.flush(),!r?.signal?.aborted){const e=`${Ye}\n`,t=`${Ze}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=me(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(f.captureDenies)try{const e=await le(g);e&&e.length>0&&await c.write({type:"sandbox_denies",events:e})}catch{}try{await c.write({type:"exit",code:w,data:"",aborted:r?.signal?.aborted??!1}),c.close()}catch(e){c.close()}}};g.on("exit",((e,t)=>{w=e;const n=r?.closeTimeout??5e3;n>0&&(b=setTimeout((()=>{k||(console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Killing detached process group.`),function(e,t){if(e)try{process.kill(-e,t)}catch{return}}(g.pid,"SIGKILL"),S(!1))}),n))})),g.on("close",(async()=>{await S(!0)}));const E=g.stdio[3],x=g.stdio[4];E?.write(this.state),E?.end(),x?.on("data",(e=>{v+=e.toString()})),yield*c}catch(e){n.error=e,n.hasError=!0}finally{Xe(n)}}}const tt="__CURSOR_ZSH_STATE_LIGHT_VALID__",rt='#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state_light.zsh\n# dump_zsh_state_light\n# Or execute directly (captures a subshell\'s state):\n# ./dump_zsh_state_light.zsh\n\n# Lightweight version that skips function tracking for better performance\n\n# Define a function so sourcing won\'t alter caller state; emulate locally inside\nfunction dump_zsh_state_light() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=${EPOCHREALTIME}\n typeset step_start=${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf \'cursor_snap_%s=$(command base64 -d <<\'\'\'CURSOR_SNAP_EOF_%s\'\'\'\n\' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d \'\n\'\n builtin printf \'\nCURSOR_SNAP_EOF_%s\n\' "$var_name"\n builtin printf \')\n\'\n builtin printf \'eval "$cursor_snap_%s"\n\' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n # Emit validity marker so we can detect if dump_zsh_state_light completed\n _emit "__CURSOR_ZSH_STATE_LIGHT_VALID__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump (light) generated on $(command date +\'%Y-%m-%d %H:%M:%S %z\')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Environment variables (exported)\n # Filter out: proxy settings, sandbox vars, and sudo askpass vars (session-specific)\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE \'_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS\' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # \'cmd | head\' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE \'^(errreturn|nounset|pipefail)$\' | command awk \'{printf "builtin setopt %s 2>/dev/null || true\\n", $0}\' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # SKIP FUNCTIONS - this is the key difference for performance\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump (light)"\n _log_timing "finalize"\n}\n';var nt,ot,st=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function it(){const e=process.env.SHELL;return e?.includes("zsh")?e:(0,o.Ef)("zsh",[]).cmd}class at{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new at(e??this.cwd,this.state)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,a.VI)(e.withName("ZshLightState.execute")),!1),i=r?.pipeStdin??!1,c=(0,o.Jt)(),l=r?.workingDirectory??this.cwd,u={...process.env,...pe,...r?.env};let d='builtin eval "$1"';i||(d+=" < /dev/null");const p=$e(u),h=["-c",`snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; ${rt} builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${p}${d}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],m=r?.sandboxWorkspaceRoot??l,f=(await Ie(m,r?.sandboxPolicy)).policy,g="insecure_none"!==f.type?{...f,sandboxWorkspaceRoot:m}:f,v=he(it(),h,{env:u,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:l,detached:!0},g,r?.signal);let y="";v.on("spawn",(async()=>{try{await c.write({type:"stdin_ready",stdin:v.stdin??void 0,pid:v.pid})}catch(e){}}));const w=ke({stdout:v.stdout,stderr:v.stderr,writable:c,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});v.on("error",(e=>{c.throw(e)}));let b=null,k=null,S=!1;const E=async e=>{if(!S){if(S=!0,k&&(clearTimeout(k),k=null),(0,a.HF)(s.ctx,"exit"),e)try{await w.waitForOutput()}catch(e){return void c.throw(e instanceof Error?e:new Error(String(e)))}if(await w.flush(),!r?.signal?.aborted){const e=`${tt}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=me(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await le(v);e&&e.length>0&&await c.write({type:"sandbox_denies",events:e})}catch{}try{await c.write({type:"exit",code:b,data:"",aborted:r?.signal?.aborted??!1}),c.close()}catch(e){c.close()}}};v.on("exit",((e,t)=>{b=e;const n=r?.closeTimeout??5e3;n>0&&(k=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),E(!1)}),n))})),v.on("close",(async()=>{await E(!0)}));const x=v.stdio[3],_=v.stdio[4];x?.write(this.state),x?.end(),_?.on("data",(e=>{y+=e.toString()})),yield*c}catch(e){n.error=e,n.hasError=!0}finally{st(n)}}}r("node:perf_hooks?b4d9"),function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}(nt||(nt={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(ot||(ot={}));const ct="\n[This shell is producing too much output to stream. The command will still run.]\n",lt=new Set(["cat","grep"]);function ut(e){return lt.has(e)}function dt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function pt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:dt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}async function ht(e,t){const r=await async function(e,t){try{const r=await(0,s.readFile)(e,"utf-8"),n=JSON.parse(r),o=function(e){if("object"!=typeof e||null===e)return"Expected an object";const t=e;if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=t.networkPolicy;if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}(n);if(o)return{success:!1,error:`Invalid sandbox policy: ${o}`};let i=pt(n);return t&&(i=mt(i,t)),{success:!0,policy:i}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function mt(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,o.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r};const n=e.additionalReadwritePaths?.map((e=>(0,o.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadwritePaths:n}}function ft(e){try{return(0,o.Ef)(e,[]).cmd!==e}catch(e){return!1}}function gt(){if("win32"!==process.platform)return;if(!process.env.MSYSTEM)return;const e=process.env.EXEPATH;if(e)return function(e){const t=e.replace(/[\\/]+$/,""),r=n.default.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?n.default.win32.join(t,"bash.exe"):n.default.win32.join(t,"bin","bash.exe")}(e);const t=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"];for(const e of t)try{if((0,o.Ef)(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function vt(e){if(e===de.ZshLight)return de.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?gt():void 0,o=void 0!==n||/git.*bash\.exe$/i.test(t)||/program.*git.*bin.*bash\.exe$/i.test(t),s=!r||o;return t.includes("zsh")?de.Zsh:t.includes("bash")&&s?de.Bash:t.includes("pwsh")||t.includes("powershell")?de.PowerShell:n?de.Bash:r&&(ft("pwsh")||ft("powershell"))?de.PowerShell:ft("zsh")?de.Zsh:ft("bash")&&s?de.Bash:ft("pwsh")||ft("powershell")?de.PowerShell:de.Naive}function yt(e){let t=e;if(!e?.userTerminalHint){const r=gt();r&&(t={...e,userTerminalHint:r})}switch(vt(t?.userTerminalHint??"")){case de.Zsh:return new We(async function(e){const t={...process.env,...pe,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state.zsh\n# dump_zsh_state\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state.zsh\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:functions p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_ZSH_STATE_START__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Environment variables (exported)\n # Filter out: proxy settings, sandbox vars, and sudo askpass vars (session-specific)\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # Functions: dump all functions at once (much faster than individual processing)\n local all_functions\n all_functions=$(builtin typeset -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS_B64"\n _log_timing "functions"\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_zsh_state`],o=he(Qe(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let s="";o.stdout?.on("data",(e=>{s+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const i=fe(s,r),a=`${Ye}\n`,c=`${Ze}\n`;let l;i.startsWith(a)&&i.endsWith(c)?(l=i.slice(a.length),l=l.slice(0,-25)):l=`${process.cwd()}\n`;const{cwd:u,rest:d}=me(l);return new et(u,d)}(t));case de.Bash:return new We(async function(e){const t={...process.env,...pe,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Require base64 for safe encoding of emitted sections\n if ! command -v base64 >/dev/null 2>&1; then\n echo "Error: base64 command is required" >&2\n return 1\n fi\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # Environment variables (export statements)\n # Filter out: proxy settings, sandbox vars, and sudo askpass vars (session-specific)\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS_B64"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS_B64"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS_B64"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(builtin alias -p 2>/dev/null || true)\n _emit_encoded "$aliases" "ALIASES_B64"\n _log_timing "aliases"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],o=Ue(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const s=he(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal);let i="";s.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=fe(i,r),c=`${ge}\n`,l=`${ve}\n`;let u;a.startsWith(c)&&a.endsWith(l)?(u=a.slice(c.length),u=u.slice(0,-26)):u=`${process.cwd()}\n`;const{cwd:d,rest:p}=me(u),h="win32"===process.platform,m="win32"===process.platform?process.cwd():d;return new He(m,p,e?.userTerminalHint,h)}(t));case de.PowerShell:return new We(async function(){return new Ve(process.cwd(),"")}());case de.ZshLight:return new We(async function(e){const t={...process.env,...pe,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-o","extendedglob","-ilc",`${rt} builtin printf '${r}\\n'; dump_zsh_state_light`],o=he(it(),n,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let s="";o.stdout?.on("data",(e=>{s+=e.toString()})),await new Promise((e=>{o.on("close",(()=>{e(void 0)}))}));const i=fe(s,r),a=`${tt}\n`,c=i.startsWith(a)?i.slice(a.length):i,{cwd:l,rest:u}=me(c);return new at(l,u)}(t));default:return function(e){const t="win32"===process.platform,r=e?.shell??(t?Ge():void 0),n=process.cwd();return new Ke(n,{...e,shell:r})}(t)}}process.platform;const wt={perUser:{type:"insecure_none"}}}};