@cursor/bdk 0.2.3 → 0.2.4

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 (577) hide show
  1. package/dist/bin/agent-serve.js +9 -1
  2. package/dist/channels/slack/attachments.d.ts +2 -1
  3. package/dist/channels/slack/attachments.d.ts.map +1 -1
  4. package/dist/channels/slack/attachments.js +19 -9
  5. package/dist/channels/slack/dispatch.d.ts.map +1 -1
  6. package/dist/channels/slack/dispatch.js +26 -24
  7. package/dist/channels/slack/thread-context.d.ts +21 -11
  8. package/dist/channels/slack/thread-context.d.ts.map +1 -1
  9. package/dist/channels/slack/thread-context.js +75 -27
  10. package/dist/docs/404.html +2 -2
  11. package/dist/docs/assets/{app.BOIHhrKi.js → app.4kQ8Db_q.js} +4 -4
  12. package/dist/docs/assets/chunks/@localSearchIndexroot.CvuAJ0My.js +1 -0
  13. package/dist/docs/assets/chunks/{VPLocalSearchBox.D49zVZqM.js → VPLocalSearchBox.DY1RwB8Q.js} +1 -1
  14. package/dist/docs/assets/chunks/{arc.hmjb-sc4.js → arc.CxE_fSPK.js} +1 -1
  15. package/dist/docs/assets/chunks/{architectureDiagram-Q4EWVU46.CxEI1KqM.js → architectureDiagram-Q4EWVU46.CPX426ui.js} +1 -1
  16. package/dist/docs/assets/chunks/{baseUniq.DHHvBWoV.js → baseUniq.CB52JrKG.js} +1 -1
  17. package/dist/docs/assets/chunks/{blockDiagram-DXYQGD6D.DnXW-3bu.js → blockDiagram-DXYQGD6D.J0cNaQCL.js} +1 -1
  18. package/dist/docs/assets/chunks/{c4Diagram-AHTNJAMY.e-47O2jM.js → c4Diagram-AHTNJAMY.DJn3vEGT.js} +1 -1
  19. package/dist/docs/assets/chunks/channel.BoNycAoN.js +1 -0
  20. package/dist/docs/assets/chunks/{chunk-4BX2VUAB.3ry4pYXB.js → chunk-4BX2VUAB.Dao618F6.js} +1 -1
  21. package/dist/docs/assets/chunks/{chunk-4TB4RGXK.DGIZFRx6.js → chunk-4TB4RGXK.QW8Rhjai.js} +1 -1
  22. package/dist/docs/assets/chunks/{chunk-55IACEB6.DKBnqg9U.js → chunk-55IACEB6.DfRLLKF_.js} +1 -1
  23. package/dist/docs/assets/chunks/{chunk-EDXVE4YY.BIU8Ue5k.js → chunk-EDXVE4YY.CIV2ApKQ.js} +1 -1
  24. package/dist/docs/assets/chunks/{chunk-FMBD7UC4.DP-TFhjI.js → chunk-FMBD7UC4.BEheSuxp.js} +1 -1
  25. package/dist/docs/assets/chunks/{chunk-OYMX7WX6.Ux0OYj5v.js → chunk-OYMX7WX6.CUN88ENB.js} +1 -1
  26. package/dist/docs/assets/chunks/{chunk-QZHKN3VN.BzHMwYox.js → chunk-QZHKN3VN.CgqCs8b_.js} +1 -1
  27. package/dist/docs/assets/chunks/{chunk-YZCP3GAM.D4OGAsSP.js → chunk-YZCP3GAM.iCH0nnTJ.js} +1 -1
  28. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.C4x07Gkj.js +1 -0
  29. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.C4x07Gkj.js +1 -0
  30. package/dist/docs/assets/chunks/clone.Db22cH_-.js +1 -0
  31. package/dist/docs/assets/chunks/{cose-bilkent-S5V4N54A.Jq_7BUNx.js → cose-bilkent-S5V4N54A.BLcUxhWE.js} +1 -1
  32. package/dist/docs/assets/chunks/{dagre-KV5264BT.Di-skR2x.js → dagre-KV5264BT.Ep7LofOm.js} +1 -1
  33. package/dist/docs/assets/chunks/{diagram-5BDNPKRD.DeREHIdH.js → diagram-5BDNPKRD.Bzf4GSQ4.js} +1 -1
  34. package/dist/docs/assets/chunks/{diagram-G4DWMVQ6.C7Kcqxro.js → diagram-G4DWMVQ6.DD6Jh-eM.js} +1 -1
  35. package/dist/docs/assets/chunks/{diagram-MMDJMWI5.BK3eohyo.js → diagram-MMDJMWI5.oOIl8bWd.js} +1 -1
  36. package/dist/docs/assets/chunks/{diagram-TYMM5635.C6TyymXT.js → diagram-TYMM5635.DHs85Ade.js} +1 -1
  37. package/dist/docs/assets/chunks/{erDiagram-SMLLAGMA.DYGG-gGx.js → erDiagram-SMLLAGMA.BIb5ghCk.js} +1 -1
  38. package/dist/docs/assets/chunks/{flowDiagram-DWJPFMVM.C9nBcSV4.js → flowDiagram-DWJPFMVM.DV4paY9k.js} +1 -1
  39. package/dist/docs/assets/chunks/{ganttDiagram-T4ZO3ILL.wAg_ymsp.js → ganttDiagram-T4ZO3ILL.AyEKA6_v.js} +1 -1
  40. package/dist/docs/assets/chunks/{gitGraphDiagram-UUTBAWPF.B87j9Oeg.js → gitGraphDiagram-UUTBAWPF.BltiCDFo.js} +1 -1
  41. package/dist/docs/assets/chunks/{graph.CuFMj31w.js → graph.DzuEYGdC.js} +1 -1
  42. package/dist/docs/assets/chunks/{infoDiagram-42DDH7IO.P_mLGumP.js → infoDiagram-42DDH7IO.BV2l981J.js} +1 -1
  43. package/dist/docs/assets/chunks/{ishikawaDiagram-UXIWVN3A.DyuL_MsT.js → ishikawaDiagram-UXIWVN3A.BA4Izf-m.js} +1 -1
  44. package/dist/docs/assets/chunks/{journeyDiagram-VCZTEJTY.CtP09IoJ.js → journeyDiagram-VCZTEJTY.DjaFbFS3.js} +1 -1
  45. package/dist/docs/assets/chunks/{kanban-definition-6JOO6SKY.BoeSYPZo.js → kanban-definition-6JOO6SKY.CfTFieDs.js} +1 -1
  46. package/dist/docs/assets/chunks/{layout.B0lMMtNo.js → layout.DzfWqTBV.js} +1 -1
  47. package/dist/docs/assets/chunks/{linear.HxRBiAFX.js → linear.BO6mpulV.js} +1 -1
  48. package/dist/docs/assets/chunks/{min.BGlFFHwS.js → min.BGgTadgT.js} +1 -1
  49. package/dist/docs/assets/chunks/{mindmap-definition-QFDTVHPH.JyLBD9M8.js → mindmap-definition-QFDTVHPH.DPuIXVWY.js} +1 -1
  50. package/dist/docs/assets/chunks/{pieDiagram-DEJITSTG.DnSmNZF8.js → pieDiagram-DEJITSTG.BOnl3bBg.js} +1 -1
  51. package/dist/docs/assets/chunks/{quadrantDiagram-34T5L4WZ.CUCnbfCa.js → quadrantDiagram-34T5L4WZ.DNB6Ckdc.js} +1 -1
  52. package/dist/docs/assets/chunks/{requirementDiagram-MS252O5E.py0IVUn5.js → requirementDiagram-MS252O5E.D5-Qo7vb.js} +1 -1
  53. package/dist/docs/assets/chunks/{sankeyDiagram-XADWPNL6.Bkc-HWYp.js → sankeyDiagram-XADWPNL6.8t65cesf.js} +1 -1
  54. package/dist/docs/assets/chunks/{sequenceDiagram-FGHM5R23.Dqn8Mlv2.js → sequenceDiagram-FGHM5R23.CaG07BdS.js} +1 -1
  55. package/dist/docs/assets/chunks/{stateDiagram-FHFEXIEX.JikkoQUU.js → stateDiagram-FHFEXIEX.TKOweTB6.js} +1 -1
  56. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CuqmyQc4.js +1 -0
  57. package/dist/docs/assets/chunks/{theme.b6HQ6zG_.js → theme.Dx-JhpTB.js} +2 -2
  58. package/dist/docs/assets/chunks/{timeline-definition-GMOUNBTQ.BvpSXiBj.js → timeline-definition-GMOUNBTQ.fE53zQ2s.js} +1 -1
  59. package/dist/docs/assets/chunks/{vennDiagram-DHZGUBPP.CU7MVnZx.js → vennDiagram-DHZGUBPP.DJsZZaJg.js} +1 -1
  60. package/dist/docs/assets/chunks/{wardley-RL74JXVD.BKwC4ctG.js → wardley-RL74JXVD.844kyrjl.js} +1 -1
  61. package/dist/docs/assets/chunks/{wardleyDiagram-NUSXRM2D.BfaF6Uhe.js → wardleyDiagram-NUSXRM2D.CMZ-Ru_t.js} +1 -1
  62. package/dist/docs/assets/chunks/{xychartDiagram-5P7HB3ND.Bg5dcpj4.js → xychartDiagram-5P7HB3ND.XXrhBc7a.js} +1 -1
  63. package/dist/docs/assets/{deployment.md.BJ8i7Q6p.js → deployment.md.UhnJIMr-.js} +2 -2
  64. package/dist/docs/assets/{deployment.md.BJ8i7Q6p.lean.js → deployment.md.UhnJIMr-.lean.js} +1 -1
  65. package/dist/docs/assets/{guides_jev.md.BNDm14Gy.js → guides_jev.md.CRcgmjDb.js} +2 -2
  66. package/dist/docs/assets/{guides_jev.md.BNDm14Gy.lean.js → guides_jev.md.CRcgmjDb.lean.js} +1 -1
  67. package/dist/docs/assets/{reference_agent-config.md.DzGI777n.js → reference_agent-config.md.Cj5uBKp4.js} +1 -1
  68. package/dist/docs/assets/{reference_extensions.md.CPPrkWlJ.js → reference_extensions.md.pa2tN-e4.js} +4 -3
  69. package/dist/docs/assets/{reference_extensions.md.CPPrkWlJ.lean.js → reference_extensions.md.pa2tN-e4.lean.js} +1 -1
  70. package/dist/docs/building-with-agents.html +35 -35
  71. package/dist/docs/deployment.html +37 -37
  72. package/dist/docs/deployment.md +4 -1
  73. package/dist/docs/evals.html +35 -35
  74. package/dist/docs/guides/agent-to-agent.html +35 -35
  75. package/dist/docs/guides/bitbucket.html +35 -35
  76. package/dist/docs/guides/cloud-agents.html +35 -35
  77. package/dist/docs/guides/convert-automation.html +35 -35
  78. package/dist/docs/guides/github.html +35 -35
  79. package/dist/docs/guides/gitlab.html +35 -35
  80. package/dist/docs/guides/grokbot-agents.html +35 -35
  81. package/dist/docs/guides/hooks.html +35 -35
  82. package/dist/docs/guides/improve.html +35 -35
  83. package/dist/docs/guides/jev.html +37 -37
  84. package/dist/docs/guides/jev.md +7 -0
  85. package/dist/docs/guides/mcp-oauth.html +35 -35
  86. package/dist/docs/guides/opentelemetry.html +35 -35
  87. package/dist/docs/guides/slack.html +35 -35
  88. package/dist/docs/guides/webhooks.html +35 -35
  89. package/dist/docs/hashmap.json +1 -1
  90. package/dist/docs/hillclimbing.html +35 -35
  91. package/dist/docs/index.html +35 -35
  92. package/dist/docs/llms-full.txt +25 -2
  93. package/dist/docs/quickstart.html +35 -35
  94. package/dist/docs/reference/agent-config.html +37 -37
  95. package/dist/docs/reference/agent-config.md +1 -1
  96. package/dist/docs/reference/artifacts.html +35 -35
  97. package/dist/docs/reference/channels.html +35 -35
  98. package/dist/docs/reference/cli.html +35 -35
  99. package/dist/docs/reference/connections.html +35 -35
  100. package/dist/docs/reference/evals.html +35 -35
  101. package/dist/docs/reference/extensions.html +39 -38
  102. package/dist/docs/reference/extensions.md +13 -0
  103. package/dist/docs/reference/hooks.html +35 -35
  104. package/dist/docs/reference/http-api.html +35 -35
  105. package/dist/docs/reference/instructions.html +35 -35
  106. package/dist/docs/reference/playground.html +35 -35
  107. package/dist/docs/reference/project-layout.html +35 -35
  108. package/dist/docs/reference/prompt.html +35 -35
  109. package/dist/docs/reference/schedules.html +35 -35
  110. package/dist/docs/reference/sessions.html +35 -35
  111. package/dist/docs/reference/skills.html +35 -35
  112. package/dist/docs/reference/subagents.html +35 -35
  113. package/dist/docs/reference/tools.html +35 -35
  114. package/dist/docs/templates/agentic-owners.html +35 -35
  115. package/dist/docs/templates/security-reviewer.html +35 -35
  116. package/dist/docs/templates/thermo-quality-review.html +35 -35
  117. package/dist/docs/templates/thermo-review.html +35 -35
  118. package/dist/docs/templates/triage.html +35 -35
  119. package/dist/docs/troubleshooting.html +35 -35
  120. package/dist/extensions/jev/extension.d.ts +3 -0
  121. package/dist/extensions/jev/extension.d.ts.map +1 -1
  122. package/dist/extensions/jev/extension.js +10 -1
  123. package/dist/extensions/jev/lib/evaluate.d.ts +4 -0
  124. package/dist/extensions/jev/lib/evaluate.d.ts.map +1 -1
  125. package/dist/extensions/jev/lib/evaluate.js +6 -2
  126. package/dist/extensions.d.ts +4 -2
  127. package/dist/extensions.d.ts.map +1 -1
  128. package/dist/extensions.js +5 -2
  129. package/dist/internal/cli-deploy.d.ts.map +1 -1
  130. package/dist/internal/cli-deploy.js +19 -5
  131. package/dist/internal/discovery/agent-config.d.ts +6 -5
  132. package/dist/internal/discovery/agent-config.d.ts.map +1 -1
  133. package/dist/internal/discovery/agent-config.js +29 -28
  134. package/dist/internal/discovery/agent.js +1 -1
  135. package/dist/internal/discovery/extensions.d.ts.map +1 -1
  136. package/dist/internal/discovery/extensions.js +12 -0
  137. package/dist/internal/hosting.d.ts +8 -0
  138. package/dist/internal/hosting.d.ts.map +1 -1
  139. package/dist/internal/hosting.js +24 -0
  140. package/dist/types.d.ts +18 -2
  141. package/dist/types.d.ts.map +1 -1
  142. package/docs/deployment.md +4 -1
  143. package/docs/guides/jev.md +7 -0
  144. package/docs/reference/agent-config.md +1 -1
  145. package/docs/reference/extensions.md +13 -0
  146. package/package.json +1 -9
  147. package/dist/docs/assets/chunks/@localSearchIndexroot.D5L-b34G.js +0 -1
  148. package/dist/docs/assets/chunks/channel.BbOGaJQP.js +0 -1
  149. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.Db58HCb1.js +0 -1
  150. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.Db58HCb1.js +0 -1
  151. package/dist/docs/assets/chunks/clone.Co4MBflG.js +0 -1
  152. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CMsKhrW0.js +0 -1
  153. package/src/artifacts.ts +0 -68
  154. package/src/bin/agent-serve.ts +0 -1854
  155. package/src/channels/bitbucket/api.ts +0 -891
  156. package/src/channels/bitbucket/binding.ts +0 -417
  157. package/src/channels/bitbucket/bitbucket-channel.ts +0 -162
  158. package/src/channels/bitbucket/bitbucket-webhook.ts +0 -519
  159. package/src/channels/bitbucket/checks.ts +0 -146
  160. package/src/channels/bitbucket/cursor-account.ts +0 -106
  161. package/src/channels/bitbucket/defaults.ts +0 -100
  162. package/src/channels/bitbucket/events.ts +0 -74
  163. package/src/channels/bitbucket/index.ts +0 -51
  164. package/src/channels/bitbucket/replay.ts +0 -421
  165. package/src/channels/bitbucket/state.ts +0 -59
  166. package/src/channels/bitbucket/types.ts +0 -261
  167. package/src/channels/change-monitors/change-monitors-channel.ts +0 -63
  168. package/src/channels/change-monitors/index.ts +0 -8
  169. package/src/channels/change-monitors/types.ts +0 -42
  170. package/src/channels/checks.ts +0 -185
  171. package/src/channels/deployments/deployments-channel.ts +0 -224
  172. package/src/channels/deployments/index.ts +0 -25
  173. package/src/channels/deployments/types.ts +0 -92
  174. package/src/channels/github/api.ts +0 -526
  175. package/src/channels/github/auth.ts +0 -293
  176. package/src/channels/github/binding.ts +0 -233
  177. package/src/channels/github/checks.ts +0 -145
  178. package/src/channels/github/cursor-account.ts +0 -303
  179. package/src/channels/github/defaults.ts +0 -168
  180. package/src/channels/github/events.ts +0 -67
  181. package/src/channels/github/forward.ts +0 -359
  182. package/src/channels/github/github-channel.ts +0 -2334
  183. package/src/channels/github/index.ts +0 -54
  184. package/src/channels/github/progress.ts +0 -365
  185. package/src/channels/github/replay.ts +0 -372
  186. package/src/channels/github/state.ts +0 -124
  187. package/src/channels/github/types.ts +0 -590
  188. package/src/channels/gitlab/api.ts +0 -329
  189. package/src/channels/gitlab/binding.ts +0 -231
  190. package/src/channels/gitlab/checks.ts +0 -228
  191. package/src/channels/gitlab/cursor-account.ts +0 -105
  192. package/src/channels/gitlab/defaults.ts +0 -80
  193. package/src/channels/gitlab/events.ts +0 -37
  194. package/src/channels/gitlab/gitlab-channel.ts +0 -160
  195. package/src/channels/gitlab/gitlab-webhook.ts +0 -509
  196. package/src/channels/gitlab/index.ts +0 -44
  197. package/src/channels/gitlab/replay.ts +0 -328
  198. package/src/channels/gitlab/state.ts +0 -55
  199. package/src/channels/gitlab/types.ts +0 -247
  200. package/src/channels/issues/index.ts +0 -9
  201. package/src/channels/issues/issues-channel.ts +0 -45
  202. package/src/channels/issues/types.ts +0 -38
  203. package/src/channels/origin/api.ts +0 -507
  204. package/src/channels/origin/binding.ts +0 -114
  205. package/src/channels/origin/checks.ts +0 -250
  206. package/src/channels/origin/cursor-account.ts +0 -58
  207. package/src/channels/origin/defaults.ts +0 -140
  208. package/src/channels/origin/events.ts +0 -35
  209. package/src/channels/origin/index.ts +0 -35
  210. package/src/channels/origin/origin-channel.ts +0 -815
  211. package/src/channels/origin/origin-webhook.ts +0 -296
  212. package/src/channels/origin/reactions.ts +0 -72
  213. package/src/channels/origin/state.ts +0 -54
  214. package/src/channels/origin/types.ts +0 -295
  215. package/src/channels/slack/agentic-delivery.ts +0 -634
  216. package/src/channels/slack/agentic-posted.ts +0 -135
  217. package/src/channels/slack/agentic-signals.ts +0 -231
  218. package/src/channels/slack/api.ts +0 -761
  219. package/src/channels/slack/approvals.ts +0 -279
  220. package/src/channels/slack/assistant.ts +0 -76
  221. package/src/channels/slack/attachments.ts +0 -596
  222. package/src/channels/slack/auth.ts +0 -127
  223. package/src/channels/slack/blocks.ts +0 -131
  224. package/src/channels/slack/bot-mentions.ts +0 -318
  225. package/src/channels/slack/channel-watch.ts +0 -314
  226. package/src/channels/slack/cli-project.ts +0 -249
  227. package/src/channels/slack/code-fences.ts +0 -171
  228. package/src/channels/slack/constants.ts +0 -38
  229. package/src/channels/slack/credentials.ts +0 -88
  230. package/src/channels/slack/defaults.ts +0 -714
  231. package/src/channels/slack/dispatch.ts +0 -1060
  232. package/src/channels/slack/doctor.ts +0 -338
  233. package/src/channels/slack/eval-directive.ts +0 -306
  234. package/src/channels/slack/event-id-dedupe.ts +0 -30
  235. package/src/channels/slack/external-policy.ts +0 -75
  236. package/src/channels/slack/footer.ts +0 -106
  237. package/src/channels/slack/inbound.ts +0 -416
  238. package/src/channels/slack/index.ts +0 -53
  239. package/src/channels/slack/init.ts +0 -169
  240. package/src/channels/slack/interactive.ts +0 -406
  241. package/src/channels/slack/links.ts +0 -23
  242. package/src/channels/slack/live-delivery.ts +0 -489
  243. package/src/channels/slack/log.ts +0 -70
  244. package/src/channels/slack/manifest.ts +0 -240
  245. package/src/channels/slack/message-body.ts +0 -82
  246. package/src/channels/slack/nudge-carrier.ts +0 -224
  247. package/src/channels/slack/nudge-store.ts +0 -334
  248. package/src/channels/slack/paint-start.ts +0 -93
  249. package/src/channels/slack/placeholder.ts +0 -358
  250. package/src/channels/slack/pr-ref.ts +0 -74
  251. package/src/channels/slack/progress-delivery.ts +0 -138
  252. package/src/channels/slack/reasoning-card.ts +0 -125
  253. package/src/channels/slack/reasoning-chip.ts +0 -41
  254. package/src/channels/slack/recording-sink.ts +0 -167
  255. package/src/channels/slack/redact.ts +0 -6
  256. package/src/channels/slack/reply-options.ts +0 -279
  257. package/src/channels/slack/setup.ts +0 -125
  258. package/src/channels/slack/slack-channel.ts +0 -744
  259. package/src/channels/slack/socket-mode.ts +0 -140
  260. package/src/channels/slack/stop.ts +0 -25
  261. package/src/channels/slack/stream.ts +0 -66
  262. package/src/channels/slack/thread-context.ts +0 -485
  263. package/src/channels/slack/tool-approval-events.ts +0 -233
  264. package/src/channels/slack/tool-cards.ts +0 -198
  265. package/src/channels/slack/tool-chip.ts +0 -34
  266. package/src/channels/slack/types.ts +0 -787
  267. package/src/channels/slack/upload.ts +0 -137
  268. package/src/channels.ts +0 -543
  269. package/src/connections.ts +0 -153
  270. package/src/dashboard-session-url.ts +0 -30
  271. package/src/evals/assertions.ts +0 -688
  272. package/src/evals/expect.ts +0 -250
  273. package/src/evals/judge.ts +0 -329
  274. package/src/evals/loaders.ts +0 -111
  275. package/src/evals/matchers.ts +0 -223
  276. package/src/evals/reporters.ts +0 -257
  277. package/src/evals/results.ts +0 -130
  278. package/src/evals/run-facts.ts +0 -306
  279. package/src/evals.ts +0 -709
  280. package/src/extensions/cursor-cloud-agents/extension.ts +0 -131
  281. package/src/extensions/cursor-cloud-agents/lib/backend.ts +0 -386
  282. package/src/extensions/cursor-cloud-agents/lib/channels.ts +0 -11
  283. package/src/extensions/cursor-cloud-agents/lib/fleet.ts +0 -98
  284. package/src/extensions/cursor-cloud-agents/lib/inputs.ts +0 -5
  285. package/src/extensions/cursor-cloud-agents/lib/repos.ts +0 -80
  286. package/src/extensions/cursor-cloud-agents/lib/transcript.ts +0 -19
  287. package/src/extensions/cursor-cloud-agents/skills/handoff.md +0 -37
  288. package/src/extensions/cursor-cloud-agents/tools/cancel.ts +0 -21
  289. package/src/extensions/cursor-cloud-agents/tools/dump.ts +0 -47
  290. package/src/extensions/cursor-cloud-agents/tools/get.ts +0 -18
  291. package/src/extensions/cursor-cloud-agents/tools/launch.ts +0 -62
  292. package/src/extensions/cursor-cloud-agents/tools/list.ts +0 -31
  293. package/src/extensions/cursor-cloud-agents/tools/reply.ts +0 -36
  294. package/src/extensions/cursor-grokbot-agents/extension.ts +0 -132
  295. package/src/extensions/cursor-grokbot-agents/lib/agents.ts +0 -42
  296. package/src/extensions/cursor-grokbot-agents/lib/backend.ts +0 -208
  297. package/src/extensions/cursor-grokbot-agents/lib/contacts.ts +0 -74
  298. package/src/extensions/cursor-grokbot-agents/lib/conversation.ts +0 -260
  299. package/src/extensions/cursor-grokbot-agents/lib/inputs.ts +0 -21
  300. package/src/extensions/cursor-grokbot-agents/lib/lock.ts +0 -26
  301. package/src/extensions/cursor-grokbot-agents/skills/consult.md +0 -40
  302. package/src/extensions/cursor-grokbot-agents/tools/ask.ts +0 -32
  303. package/src/extensions/cursor-grokbot-agents/tools/check.ts +0 -25
  304. package/src/extensions/cursor-grokbot-agents/tools/interrupt.ts +0 -17
  305. package/src/extensions/cursor-grokbot-agents/tools/list.ts +0 -26
  306. package/src/extensions/improve/extension.ts +0 -69
  307. package/src/extensions/improve/skills/yourself.ts +0 -50
  308. package/src/extensions/jev/extension.ts +0 -95
  309. package/src/extensions/jev/lib/evaluate.ts +0 -266
  310. package/src/extensions/jev/skills/gated-write.md +0 -25
  311. package/src/extensions/jev/skills/questions.md +0 -33
  312. package/src/extensions/jev/tools/evaluate.ts +0 -82
  313. package/src/extensions/slack-communication/evals/harness.ts +0 -705
  314. package/src/extensions/slack-communication/evals/slack-communication.eval.ts +0 -830
  315. package/src/extensions/slack-communication/evals/slack-placeholder.eval.ts +0 -172
  316. package/src/extensions/slack-communication/extension.ts +0 -44
  317. package/src/extensions/slack-communication/skills/slack-voice.ts +0 -56
  318. package/src/extensions/slack-communication/tools/delete-message.ts +0 -33
  319. package/src/extensions/slack-communication/tools/edit-message.ts +0 -42
  320. package/src/extensions/slack-communication/tools/post-card.ts +0 -28
  321. package/src/extensions/slack-communication/tools/post-file.ts +0 -82
  322. package/src/extensions/slack-communication/tools/post-update.ts +0 -40
  323. package/src/extensions/slack-communication/tools/react.ts +0 -30
  324. package/src/extensions/slack-communication/tools/set-status.ts +0 -21
  325. package/src/extensions.ts +0 -179
  326. package/src/files-backends/agent-store-presigned-url.ts +0 -11
  327. package/src/files-backends/cursor-hosted.ts +0 -1212
  328. package/src/files-backends/local-fs.ts +0 -163
  329. package/src/files.ts +0 -293
  330. package/src/filesystem.ts +0 -2005
  331. package/src/hooks.ts +0 -30
  332. package/src/index.ts +0 -259
  333. package/src/internal/advertise-tools.ts +0 -370
  334. package/src/internal/approval-gate.ts +0 -103
  335. package/src/internal/artifacts-store.ts +0 -836
  336. package/src/internal/as-of.ts +0 -257
  337. package/src/internal/auth.ts +0 -46
  338. package/src/internal/authored-alias-hooks.ts +0 -138
  339. package/src/internal/authored-loaders.ts +0 -188
  340. package/src/internal/bounded-int.ts +0 -24
  341. package/src/internal/bounded.ts +0 -25
  342. package/src/internal/brand.ts +0 -28
  343. package/src/internal/browser-origin-guard.ts +0 -67
  344. package/src/internal/builtin-tools/artifacts.ts +0 -62
  345. package/src/internal/builtin-tools/index.ts +0 -53
  346. package/src/internal/builtin-tools/reminders.ts +0 -145
  347. package/src/internal/channel-dispatch.ts +0 -129
  348. package/src/internal/channel-route-dispatch.ts +0 -58
  349. package/src/internal/channel-state.ts +0 -83
  350. package/src/internal/chat-client.ts +0 -594
  351. package/src/internal/cli-ax.ts +0 -2318
  352. package/src/internal/cli-bitbucket.ts +0 -438
  353. package/src/internal/cli-convert-automation.ts +0 -335
  354. package/src/internal/cli-cursor.ts +0 -282
  355. package/src/internal/cli-deploy.ts +0 -2519
  356. package/src/internal/cli-docs.ts +0 -192
  357. package/src/internal/cli-github.ts +0 -806
  358. package/src/internal/cli-gitlab.ts +0 -452
  359. package/src/internal/cli-images.ts +0 -672
  360. package/src/internal/cli-manifest.ts +0 -56
  361. package/src/internal/cli-mcp-oauth.ts +0 -396
  362. package/src/internal/cli-mcp.ts +0 -808
  363. package/src/internal/cli-skills.ts +0 -98
  364. package/src/internal/cli-slack-manual.ts +0 -418
  365. package/src/internal/cli-slack.ts +0 -874
  366. package/src/internal/cloud-merge.ts +0 -51
  367. package/src/internal/cloud-turn-cost.ts +0 -159
  368. package/src/internal/connection-env.ts +0 -106
  369. package/src/internal/continuation-channel.ts +0 -233
  370. package/src/internal/continuation-identity.ts +0 -935
  371. package/src/internal/conversation-mirror.ts +0 -423
  372. package/src/internal/convert-automation/convert-workflow.ts +0 -1377
  373. package/src/internal/convert-automation/slug.ts +0 -29
  374. package/src/internal/convert-automation/types.ts +0 -212
  375. package/src/internal/cron.ts +0 -76
  376. package/src/internal/cursor/account-mcp.ts +0 -692
  377. package/src/internal/cursor/backend-client.ts +0 -984
  378. package/src/internal/cursor/bound-secret-file.ts +0 -101
  379. package/src/internal/cursor/credentials.ts +0 -560
  380. package/src/internal/cursor/cursor-api-transport.ts +0 -65
  381. package/src/internal/cursor/github-credentials.ts +0 -228
  382. package/src/internal/cursor/hosted-bound-secrets.ts +0 -71
  383. package/src/internal/cursor/hosted-deployment-secrets.ts +0 -100
  384. package/src/internal/cursor/hosted-store-secrets.ts +0 -152
  385. package/src/internal/cursor/session-token.ts +0 -111
  386. package/src/internal/cursor/store-api-client.ts +0 -323
  387. package/src/internal/cursor-account-mcp-auth.ts +0 -303
  388. package/src/internal/cursor-agent-template.ts +0 -50
  389. package/src/internal/cursor-deployment-relay.ts +0 -315
  390. package/src/internal/cursor-event-relay.ts +0 -675
  391. package/src/internal/cursor-relay-core.ts +0 -563
  392. package/src/internal/deferred-channel-session.ts +0 -61
  393. package/src/internal/deploy-client.ts +0 -1574
  394. package/src/internal/deploy-manifest.ts +0 -361
  395. package/src/internal/deploy-source.ts +0 -144
  396. package/src/internal/describe-error.ts +0 -32
  397. package/src/internal/dev-mode.ts +0 -20
  398. package/src/internal/discovery/agent-config.ts +0 -288
  399. package/src/internal/discovery/agent.ts +0 -381
  400. package/src/internal/discovery/channels.ts +0 -100
  401. package/src/internal/discovery/connections.ts +0 -516
  402. package/src/internal/discovery/context.ts +0 -38
  403. package/src/internal/discovery/cursor-plugin.ts +0 -628
  404. package/src/internal/discovery/extension-overlay.ts +0 -247
  405. package/src/internal/discovery/extensions.ts +0 -490
  406. package/src/internal/discovery/fs.ts +0 -103
  407. package/src/internal/discovery/hooks.ts +0 -63
  408. package/src/internal/discovery/info.ts +0 -174
  409. package/src/internal/discovery/instructions.ts +0 -98
  410. package/src/internal/discovery/modules.ts +0 -107
  411. package/src/internal/discovery/names.ts +0 -45
  412. package/src/internal/discovery/project.ts +0 -319
  413. package/src/internal/discovery/reminders.ts +0 -65
  414. package/src/internal/discovery/runtime.ts +0 -158
  415. package/src/internal/discovery/schedules.ts +0 -120
  416. package/src/internal/discovery/seed-files.ts +0 -34
  417. package/src/internal/discovery/services.ts +0 -151
  418. package/src/internal/discovery/skills.ts +0 -174
  419. package/src/internal/discovery/subagent.ts +0 -138
  420. package/src/internal/discovery/tools.ts +0 -170
  421. package/src/internal/discovery.ts +0 -27
  422. package/src/internal/distribution.ts +0 -126
  423. package/src/internal/docs-site.ts +0 -248
  424. package/src/internal/duration.ts +0 -37
  425. package/src/internal/env-file.ts +0 -83
  426. package/src/internal/eval-judge-model.ts +0 -142
  427. package/src/internal/eval-run-store.ts +0 -585
  428. package/src/internal/eval-runner.ts +0 -823
  429. package/src/internal/evals-client.ts +0 -475
  430. package/src/internal/event-log.ts +0 -342
  431. package/src/internal/event-mapper.ts +0 -811
  432. package/src/internal/expected-delivery-failure.ts +0 -34
  433. package/src/internal/factory-resource-channel.ts +0 -103
  434. package/src/internal/filesystem/errors.ts +0 -207
  435. package/src/internal/filesystem/format.ts +0 -253
  436. package/src/internal/filesystem/merge.ts +0 -192
  437. package/src/internal/filesystem/nearest.ts +0 -112
  438. package/src/internal/filesystem/scratch.ts +0 -239
  439. package/src/internal/filesystem/sdk-schemas.ts +0 -204
  440. package/src/internal/filesystem/tools.ts +0 -804
  441. package/src/internal/filesystem/walk.ts +0 -366
  442. package/src/internal/fixtures/units-server.ts +0 -52
  443. package/src/internal/framework-file-storage.ts +0 -357
  444. package/src/internal/framework-storage-selection.ts +0 -156
  445. package/src/internal/frontmatter.ts +0 -108
  446. package/src/internal/github-fanout.ts +0 -144
  447. package/src/internal/guest-network.ts +0 -391
  448. package/src/internal/handleAgentServeTrigger.ts +0 -286
  449. package/src/internal/host-files.ts +0 -341
  450. package/src/internal/host-kv.ts +0 -81
  451. package/src/internal/host-otel.ts +0 -231
  452. package/src/internal/host-platforms.ts +0 -170
  453. package/src/internal/hosted-admission-adapter.ts +0 -47
  454. package/src/internal/hosted-admission-context.ts +0 -37
  455. package/src/internal/hosted-catch-protocol.ts +0 -112
  456. package/src/internal/hosted-catch.ts +0 -179
  457. package/src/internal/hosted-delivery-protocol.ts +0 -824
  458. package/src/internal/hosted-delivery.ts +0 -1410
  459. package/src/internal/hosted-execution-diag.ts +0 -291
  460. package/src/internal/hosted-execution-flush.ts +0 -136
  461. package/src/internal/hosted-execution-latency.ts +0 -301
  462. package/src/internal/hosted-managed-automation.ts +0 -116
  463. package/src/internal/hosting.ts +0 -114
  464. package/src/internal/http-channel-define.ts +0 -25
  465. package/src/internal/http-channel.ts +0 -669
  466. package/src/internal/http-control-plane-session.ts +0 -110
  467. package/src/internal/ids.ts +0 -39
  468. package/src/internal/incoming-headers-to-fetch.ts +0 -45
  469. package/src/internal/init-interview.ts +0 -360
  470. package/src/internal/init-project.ts +0 -711
  471. package/src/internal/init-scaffold.ts +0 -182
  472. package/src/internal/inline-stdio-define-stub.ts +0 -4
  473. package/src/internal/inline-stdio-mcp.ts +0 -230
  474. package/src/internal/install-cursor-skills.ts +0 -604
  475. package/src/internal/is-record.ts +0 -3
  476. package/src/internal/json-schema.ts +0 -95
  477. package/src/internal/legacy-command-guard.ts +0 -66
  478. package/src/internal/listen-port.ts +0 -85
  479. package/src/internal/local-control-plane.ts +0 -442
  480. package/src/internal/local-env.ts +0 -59
  481. package/src/internal/local-ingress.ts +0 -90
  482. package/src/internal/log-ring.ts +0 -59
  483. package/src/internal/logs-client.ts +0 -477
  484. package/src/internal/map-pool.ts +0 -39
  485. package/src/internal/mcp-endpoint.ts +0 -747
  486. package/src/internal/mcp-host.ts +0 -509
  487. package/src/internal/mcp-oauth-on-demand.ts +0 -337
  488. package/src/internal/mcp-oauth-persist.ts +0 -118
  489. package/src/internal/mcp-oauth.ts +0 -549
  490. package/src/internal/net.ts +0 -29
  491. package/src/internal/open-browser.ts +0 -41
  492. package/src/internal/otel/attrs.ts +0 -16
  493. package/src/internal/otel/collector.ts +0 -937
  494. package/src/internal/otel/config.ts +0 -287
  495. package/src/internal/otel/http.ts +0 -122
  496. package/src/internal/otel/mcp.ts +0 -56
  497. package/src/internal/otel/propagation.ts +0 -17
  498. package/src/internal/otel/runtime.ts +0 -441
  499. package/src/internal/package-inline-stdio.ts +0 -114
  500. package/src/internal/peer-connections.ts +0 -96
  501. package/src/internal/platform-schedule-sync.ts +0 -75
  502. package/src/internal/platform-timers.ts +0 -365
  503. package/src/internal/playground/static.ts +0 -278
  504. package/src/internal/playground/toolchain.ts +0 -270
  505. package/src/internal/playground-proxy.ts +0 -564
  506. package/src/internal/process-memory-telemetry.ts +0 -334
  507. package/src/internal/project-layout.ts +0 -31
  508. package/src/internal/prompt-context.ts +0 -116
  509. package/src/internal/reminder-control-plane-protocol.ts +0 -482
  510. package/src/internal/reminder-runner.ts +0 -1559
  511. package/src/internal/reminder-schedule.ts +0 -104
  512. package/src/internal/reminder-store.ts +0 -176
  513. package/src/internal/request-error-status.ts +0 -95
  514. package/src/internal/request-headers.ts +0 -21
  515. package/src/internal/resolve-prod-target.ts +0 -334
  516. package/src/internal/resolved-connections.ts +0 -190
  517. package/src/internal/router.ts +0 -143
  518. package/src/internal/run-client.ts +0 -354
  519. package/src/internal/runtime-dispatch-runner.ts +0 -50
  520. package/src/internal/sanitize-mcp-tool-name.ts +0 -31
  521. package/src/internal/schedule-runner.ts +0 -154
  522. package/src/internal/scm/pr-url.ts +0 -245
  523. package/src/internal/sdk-runner.ts +0 -959
  524. package/src/internal/serve-restart.ts +0 -113
  525. package/src/internal/server.ts +0 -3147
  526. package/src/internal/session-cost.ts +0 -208
  527. package/src/internal/session-engine.ts +0 -5622
  528. package/src/internal/session-links.ts +0 -84
  529. package/src/internal/session-run-log.ts +0 -535
  530. package/src/internal/session-store.ts +0 -307
  531. package/src/internal/session-urls.ts +0 -32
  532. package/src/internal/sessions-client.ts +0 -239
  533. package/src/internal/skill-catalog.ts +0 -66
  534. package/src/internal/skills-sync.ts +0 -55
  535. package/src/internal/slack-provision-client.ts +0 -544
  536. package/src/internal/slack-thread-key.ts +0 -11
  537. package/src/internal/sleep.ts +0 -3
  538. package/src/internal/start-log-store.ts +0 -164
  539. package/src/internal/steering.ts +0 -17
  540. package/src/internal/storage-coordinator.ts +0 -800
  541. package/src/internal/storage-roles.ts +0 -86
  542. package/src/internal/storage.ts +0 -1
  543. package/src/internal/store-api-protocol.ts +0 -205
  544. package/src/internal/store-mirror.ts +0 -73
  545. package/src/internal/stream-progress.ts +0 -294
  546. package/src/internal/terminal-style.ts +0 -133
  547. package/src/internal/testing/factory-resource-fixtures.ts +0 -84
  548. package/src/internal/testing/scm-continuation-fixtures.ts +0 -285
  549. package/src/internal/tool-catalog.ts +0 -104
  550. package/src/internal/tool-policy.ts +0 -222
  551. package/src/internal/tool-result.ts +0 -50
  552. package/src/internal/trajectory.ts +0 -418
  553. package/src/internal/turn-cost.ts +0 -136
  554. package/src/internal/turn-governor.ts +0 -145
  555. package/src/internal/turn-lease-store.ts +0 -144
  556. package/src/internal/turn-outbox.ts +0 -77
  557. package/src/internal/update-check.ts +0 -517
  558. package/src/internal/v2-hosting.ts +0 -52
  559. package/src/internal/workspace-sync.ts +0 -114
  560. package/src/internal/workspace.ts +0 -505
  561. package/src/kv/memory-kv.ts +0 -94
  562. package/src/kv.ts +0 -18
  563. package/src/memory.ts +0 -487
  564. package/src/otel-public.ts +0 -24
  565. package/src/otel.ts +0 -320
  566. package/src/prompt.ts +0 -80
  567. package/src/reminders.ts +0 -65
  568. package/src/schedules.ts +0 -31
  569. package/src/skills.ts +0 -27
  570. package/src/storage-backends/cursor-hosted-v2.ts +0 -204
  571. package/src/storage-backends/cursor-hosted.ts +0 -388
  572. package/src/storage-backends/file-kv.ts +0 -276
  573. package/src/storage-protocol.ts +0 -261
  574. package/src/storage.ts +0 -408
  575. package/src/tools.ts +0 -166
  576. package/src/types.ts +0 -3776
  577. /package/dist/docs/assets/{reference_agent-config.md.DzGI777n.lean.js → reference_agent-config.md.Cj5uBKp4.lean.js} +0 -0
package/src/filesystem.ts DELETED
@@ -1,2005 +0,0 @@
1
- import { Buffer } from "node:buffer";
2
- import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
3
- import path from "node:path";
4
- import type { ToolName } from "@cursor/sdk";
5
- import { minimatch } from "minimatch";
6
- import { FileConflictError } from "./files.js";
7
- import {
8
- EditError,
9
- FileNotFoundError,
10
- InvalidGrepPatternError,
11
- isFileNotFoundError,
12
- isInvalidGrepPatternError,
13
- NoMountError,
14
- PathError,
15
- ReadOnlyMountError,
16
- remapPathError,
17
- WriteFailedError,
18
- } from "./internal/filesystem/errors.js";
19
- import { MEMORY_DIR_NAME } from "./memory.js";
20
-
21
- export {
22
- DeleteNotSupportedError,
23
- EditError,
24
- FileNotFoundError,
25
- InvalidGrepPatternError,
26
- isFileNotFoundError,
27
- isInvalidGrepPatternError,
28
- NoMountError,
29
- PathError,
30
- ReadOnlyMountError,
31
- WriteFailedError,
32
- } from "./internal/filesystem/errors.js";
33
-
34
- import { mergeSorted } from "./internal/filesystem/merge.js";
35
- import {
36
- isExcludedPath,
37
- listFilesFromPaths,
38
- mergeSortedByPath,
39
- statFromFilePaths,
40
- } from "./internal/filesystem/walk.js";
41
- import type { HostFilesApi, HostFilesScope } from "./types.js";
42
-
43
- /**
44
- * Status envelope used by walk helpers such as `lsFromList`.
45
- * FileSystem methods throw; they do not return this.
46
- * `@cursor/bdk` does not export it.
47
- */
48
- export type FileSystemResult<T> =
49
- | { status: "success"; value: T }
50
- | { status: "error"; error: { message: string } };
51
-
52
- /**
53
- * One file in a `list` / `glob` stream.
54
- *
55
- * `path` is an absolute posix path (`/src/a.ts`). No trailing slash
56
- * except `/`. `size` is optional byte length of the file contents.
57
- */
58
- export interface DirEntry {
59
- path: string;
60
- size?: number;
61
- }
62
-
63
- /**
64
- * Existence probe. `directory` means this path is a prefix of at
65
- * least one file (virtual trees infer directories) or a real
66
- * directory on disk. `missing` is a value, not an error.
67
- */
68
- export type FileInfo = { kind: "file" } | { kind: "directory" } | { kind: "missing" };
69
-
70
- /**
71
- * Native Grep `output_mode` envelope. Not a FileSystem method
72
- * result. The `grep` verb yields {@link GrepResult}; synthesis
73
- * shapes this union after draining the stream.
74
- */
75
- export type GrepUnionResult =
76
- | {
77
- type: "content";
78
- output: {
79
- matches: Array<{
80
- file: string;
81
- lineNumber?: number;
82
- line: string;
83
- beforeContext?: string[];
84
- afterContext?: string[];
85
- }>;
86
- totalMatches: number;
87
- };
88
- }
89
- | { type: "files"; output: { files: string[]; count: number } }
90
- | {
91
- type: "count";
92
- output: {
93
- counts: Array<{ file: string; count: number }>;
94
- total: number;
95
- };
96
- };
97
-
98
- /**
99
- * One content hit from `grep`. `path` is absolute posix.
100
- * `lineNumber` is 1-indexed. `line` is the full matching line,
101
- * without the trailing newline.
102
- */
103
- export interface GrepResult {
104
- path: string;
105
- lineNumber: number;
106
- line: string;
107
- }
108
-
109
- /**
110
- * Optional filters for {@link FileSystem.list}.
111
- *
112
- * `excludes` are ignore globs in the same language as native LS
113
- * `ignore`: a slash-free pattern matches at any depth, and a
114
- * directory match drops that tree. Implementations that can push
115
- * them to a backend should; others filter the yielded files.
116
- * Native LS still applies `ignore` after `list` so a mount that
117
- * ignores this argument still honors it.
118
- */
119
- export interface ListOptions {
120
- excludes?: readonly string[];
121
- /**
122
- * Optional result cap, lexicographic. Omitted means no
123
- * FileSystem-level cap. `0` yields nothing.
124
- */
125
- limit?: number;
126
- }
127
-
128
- /**
129
- * Optional filters for {@link FileSystem.glob}.
130
- *
131
- * `limit` is the same lexicographic cap as {@link ListOptions.limit}.
132
- */
133
- export interface GlobOptions {
134
- limit?: number;
135
- }
136
-
137
- /**
138
- * Default scan cap for synthesized LS / Glob and for Origin
139
- * `ListRepoPaths` from `/repo`. Smaller than Origin's 10k default
140
- * so a recursive listing does not materialize a huge response.
141
- */
142
- export const FILE_SYSTEM_SCAN_LIMIT = 1_000;
143
-
144
- /**
145
- * Content-search query. No `output_mode` or `offset` (those
146
- * belong to the native Grep tool).
147
- *
148
- * `pattern` is a JavaScript regular expression source. Invalid
149
- * source must throw {@link InvalidGrepPatternError} with message
150
- * `invalid grep pattern: ${pattern}`. `path` omitted / `""` /
151
- * `"/"` searches the whole tree; a file path searches that file
152
- * only. A slash-free `glob` (`*.ts`) matches the basename at any
153
- * depth under `path`.
154
- *
155
- * `excludes` are optional ignore globs (same language as
156
- * {@link ListOptions.excludes}). Implementations that can push
157
- * them to a backend should; others skip matching files. Native
158
- * Grep has no ignore field; this is FileSystem-only pushdown.
159
- *
160
- * `maxResults` is optional predicate pushdown: stop after this
161
- * many hits so a remote or large tree does not materialize a
162
- * full scan. Native Grep still applies `head_limit` / `offset`
163
- * after the merge. Omitted means no FileSystem-level cap.
164
- */
165
- export interface GrepQuery {
166
- pattern: string;
167
- path?: string;
168
- glob?: string;
169
- excludes?: readonly string[];
170
- caseInsensitive?: boolean;
171
- maxResults?: number;
172
- }
173
-
174
- /**
175
- * One semantic hit from `search`. `path` is absolute posix.
176
- * `score` is higher-is-better. Trees without an index yield
177
- * nothing; they do not invent lexical stand-ins.
178
- */
179
- export interface SearchResult {
180
- path: string;
181
- snippet: string;
182
- score: number;
183
- }
184
-
185
- /**
186
- * Semantic-search query. `targetDirectories` limits the scan
187
- * when an index exists; omitted means the whole tree.
188
- *
189
- * `maxResults` is optional predicate pushdown: stop after this
190
- * many hits so an index does not retrieve a large recall set.
191
- * Native SemanticSearch still applies `numResults` after the
192
- * merge. Omitted means no FileSystem-level cap.
193
- */
194
- export interface SearchQuery {
195
- query: string;
196
- targetDirectories?: string[];
197
- maxResults?: number;
198
- }
199
-
200
- /**
201
- * Exact, non-overlapping str-replace. `oldText` / `newText` are
202
- * literal strings, not regex. Splice must keep `$`, `$&`, `$1`
203
- * in `newText` as written (`String.prototype.replace` must not
204
- * be used).
205
- */
206
- export interface EditQuery {
207
- path: string;
208
- oldText: string;
209
- newText: string;
210
- replaceAll?: boolean;
211
- }
212
-
213
- /**
214
- * StrReplace success. `occurrencesModified` is the number of
215
- * non-overlapping replacements (1 unless `replaceAll`).
216
- */
217
- export interface EditResult {
218
- occurrencesModified: number;
219
- }
220
-
221
- /**
222
- * Path verbs for the tree the agent runs on.
223
- *
224
- * Every method is required. Trees without an index implement
225
- * `search` as an empty iterator. Methods do not fall back to the
226
- * host tree. Diagnostics are not a FileSystem concern.
227
- *
228
- * Paths are a single posix namespace rooted at `/`. Query paths
229
- * and yielded paths are absolute (`/src/a.ts`). No trailing
230
- * slash except `/`. `""`, `"/"`, and an omitted `prefix` / `dir`
231
- * / `path` (where optional) mean the root. Prefix tests are
232
- * path-segment: `/agent` matches `/agent/skills`, not
233
- * `/agent-tools`.
234
- *
235
- * Async iterators are already sorted. `unionFs` k-way merges
236
- * them and does not re-sort a source.
237
- *
238
- * - `list` / `glob`: lexicographic by `path`. Paths are unique.
239
- * - `grep`: by `path`, then `lineNumber` ascending. Keep every hit.
240
- * - `search`: by `score` descending, then `path` ascending.
241
- *
242
- * Native-tool pagination (`head_limit`, `offset`, `output_mode`,
243
- * `numResults`) stays on the synthesized tools. `grep` /
244
- * `search` take optional `maxResults` as predicate pushdown so
245
- * a tree can stop retrieving once the tool's cap is known.
246
- * Native `LS` is built from `list` + `stat`; there is no `ls`
247
- * method.
248
- *
249
- * Errors (authors must follow these, not invent parallel
250
- * spellings):
251
- *
252
- * - `list` / `stat` / `glob` must not throw for a missing path.
253
- * Missing is an empty iterator or `{ kind: "missing" }`.
254
- * - `read` / `write` / `delete` throw {@link PathError}
255
- * for recoverable failures. `error.message` is the string the
256
- * synthesized native tool shows the model. `error.path` is the
257
- * absolute posix path the composer remaps.
258
- * - `grep` throws for an invalid regex (and a missing host
259
- * search root). A missing virtual path yields nothing.
260
- * - `search` yields nothing when there is no index. An index
261
- * failure may throw.
262
- * - Missing-file message on `read` / `delete` is
263
- * `not found: ${path}` (normalized absolute posix).
264
- */
265
- export interface FileSystem {
266
- /**
267
- * Recursive file scan under `prefix`. Files only; directories
268
- * are inferred from path prefixes. A file is not under itself,
269
- * so listing a file path is empty. Empty is not "missing"
270
- * (`stat` answers that). Yields lexicographic unique
271
- * {@link DirEntry} rows. Omitted / `""` / `"/"` means the root.
272
- *
273
- * Errors: none. A missing or file-path prefix yields an empty
274
- * iterator. Do not throw.
275
- *
276
- * `options.excludes` / `options.limit` are optional pushdown.
277
- * See {@link ListOptions}.
278
- */
279
- list(prefix?: string, options?: ListOptions): AsyncIterable<DirEntry>;
280
- /**
281
- * Existence probe: exact file, a prefix that has files, or
282
- * missing. Does not throw. Native LS lists first and calls
283
- * this only when the iterator is empty.
284
- *
285
- * Errors: none. Unknown paths are `{ kind: "missing" }`.
286
- */
287
- stat(path: string): Promise<FileInfo>;
288
- /**
289
- * Same scan as `list`, filtered by `pattern` relative to
290
- * `dir`. Yields lexicographic unique {@link DirEntry} rows.
291
- * `dir` omitted / `""` / `"/"` means the tree root. Matching
292
- * is relative to `dir`, not basename-anywhere (`*.ts` under
293
- * `/src` is `/src/a.ts`, not `/src/nested/c.ts`).
294
- *
295
- * Errors: none. A missing `dir` or a pattern that matches
296
- * nothing yields an empty iterator. Do not throw for a bad
297
- * glob (it matches nothing).
298
- *
299
- * `options.limit` is optional result-cap pushdown. See
300
- * {@link GlobOptions}.
301
- */
302
- glob(pattern: string, dir?: string, options?: GlobOptions): AsyncIterable<DirEntry>;
303
- /**
304
- * Read the whole file. Text files return a string. Image
305
- * bytes (`jpeg` / `png` / `gif` / `webp`) return a
306
- * `Uint8Array` so native Read can base64 them into an image
307
- * content part. Native Read applies `offset` / `limit` and
308
- * numbers lines on text only.
309
- *
310
- * Errors (throw `Error`):
311
- * - Missing file, or a virtual directory with no file inode:
312
- * `not found: ${path}`.
313
- * - Host I/O (EISDIR, EACCES, …): the OS message, or the same
314
- * `not found: ${path}` fallback.
315
- * - `unionFs` with no mount: `no mount for path: ${path}`.
316
- */
317
- read(path: string): Promise<string | Uint8Array>;
318
- /**
319
- * Content matches. No output-mode or offset. Honor
320
- * `maxResults` when set. Yields {@link GrepResult} ordered
321
- * by path, then line number.
322
- *
323
- * Errors (throw `Error`):
324
- * - Invalid `pattern`: `invalid grep pattern: ${pattern}`.
325
- * - Host search root does not exist: the OS message, or
326
- * `not found: ${searchRoot}`. Native Grep turns the throw
327
- * into `{ status: "error" }`.
328
- *
329
- * A missing virtual `path` yields nothing (not an error).
330
- */
331
- grep(query: GrepQuery): AsyncIterable<GrepResult>;
332
- /**
333
- * Create or overwrite a file. Parents are created as needed.
334
- * Native Write formats `Wrote contents to ${path}` from the
335
- * path. The Write tool maps native `fileText` onto `contents`.
336
- *
337
- * Errors (throw `Error`):
338
- * - Host I/O: the OS message, or `write failed: ${path}`.
339
- * - `unionFs` with no mount: `no mount for path: ${path}`.
340
- * - A read-only mount may use `read-only mount` or
341
- * `read-only mount: ${path}`.
342
- *
343
- * Missing parents are not an error; create them. There is no
344
- * `not found` for `write`.
345
- */
346
- write(path: string, contents: string): Promise<void>;
347
- /**
348
- * Remove one file. Directories are not deleted; listing them
349
- * is empty and they have no inode of their own on a virtual
350
- * tree.
351
- *
352
- * Errors (throw `Error`):
353
- * - Missing file, or a virtual directory: `not found: ${path}`.
354
- * - Host I/O: the OS message, or `not found: ${path}`.
355
- * - `unionFs` with no mount: `no mount for path: ${path}`.
356
- */
357
- delete(path: string): Promise<void>;
358
- /**
359
- * Semantic hits. Trees without an index yield nothing (do
360
- * not register the host index). Honor `maxResults` when set.
361
- * Ordered by score descending, then path.
362
- *
363
- * Errors: none for a tree without an index (empty iterator).
364
- * An index that fails mid-scan may throw; native
365
- * SemanticSearch turns that into `{ status: "error" }` with
366
- * the thrown message or `search failed`.
367
- */
368
- search(query: SearchQuery): AsyncIterable<SearchResult>;
369
- }
370
-
371
- export const FILE_SYSTEM_TOOL_NAMES = [
372
- "Read",
373
- "LS",
374
- "Glob",
375
- "Grep",
376
- "Write",
377
- "StrReplace",
378
- "Delete",
379
- "SemanticSearch",
380
- ] as const;
381
-
382
- export type FileSystemToolName = (typeof FILE_SYSTEM_TOOL_NAMES)[number];
383
-
384
- const FILE_SYSTEM_TOOL_NAME_SET = new Set<string>(FILE_SYSTEM_TOOL_NAMES);
385
-
386
- const FILE_SYSTEM_TOOL_ALIASES: Readonly<Record<string, FileSystemToolName>> = {
387
- read: "Read",
388
- Read: "Read",
389
- ls: "LS",
390
- LS: "LS",
391
- glob: "Glob",
392
- Glob: "Glob",
393
- grep: "Grep",
394
- Grep: "Grep",
395
- write: "Write",
396
- Write: "Write",
397
- edit: "StrReplace",
398
- StrReplace: "StrReplace",
399
- delete: "Delete",
400
- Delete: "Delete",
401
- semSearch: "SemanticSearch",
402
- SemanticSearch: "SemanticSearch",
403
- };
404
-
405
- export function canonicalizeFileSystemToolName(name: string): FileSystemToolName | undefined {
406
- return FILE_SYSTEM_TOOL_ALIASES[name];
407
- }
408
-
409
- export function isFileSystemToolName(name: string): name is FileSystemToolName {
410
- return FILE_SYSTEM_TOOL_NAME_SET.has(name);
411
- }
412
-
413
- export function isFileSystemToolAlias(name: string): boolean {
414
- return canonicalizeFileSystemToolName(name) !== undefined;
415
- }
416
-
417
- /** Direct `callTool` names that mutate the tree and must wait on a busy turn. */
418
- export function isMutatingFileSystemTool(name: string): boolean {
419
- const canonical = canonicalizeFileSystemToolName(name);
420
- return canonical === "Write" || canonical === "StrReplace" || canonical === "Delete";
421
- }
422
-
423
- export function isFileSystemMethodPresent(root: FileSystem, method: keyof FileSystem): boolean {
424
- return typeof root[method] === "function";
425
- }
426
-
427
- const ADVERTISED_FILE_SYSTEM_TOOL_NAMES: FileSystemToolName[] = [
428
- "Read",
429
- "LS",
430
- "Glob",
431
- "Grep",
432
- "Write",
433
- "StrReplace",
434
- "Delete",
435
- "SemanticSearch",
436
- ];
437
-
438
- export function fileSystemToolNames(_root?: FileSystem): FileSystemToolName[] {
439
- return [...ADVERTISED_FILE_SYSTEM_TOOL_NAMES];
440
- }
441
-
442
- function fileSystemMethodForTool(name: FileSystemToolName): keyof FileSystem | undefined {
443
- switch (name) {
444
- case "Read":
445
- return "read";
446
- case "LS":
447
- return "list";
448
- case "Glob":
449
- return "glob";
450
- case "Grep":
451
- return "grep";
452
- case "Write":
453
- case "StrReplace":
454
- return "write";
455
- case "Delete":
456
- return "delete";
457
- case "SemanticSearch":
458
- return "search";
459
- }
460
- }
461
-
462
- function fileSystemSatisfiesFileTool(root: FileSystem, name: string): boolean {
463
- const canonical = canonicalizeFileSystemToolName(name);
464
- if (canonical === undefined) {
465
- return true;
466
- }
467
- const method = fileSystemMethodForTool(canonical);
468
- return method !== undefined && isFileSystemMethodPresent(root, method);
469
- }
470
-
471
- export class FileSystemConfigError extends Error {
472
- constructor(message: string) {
473
- super(message);
474
- this.name = "FileSystemConfigError";
475
- }
476
- }
477
-
478
- function allowlistHas(tools: readonly ToolName[], ...names: string[]): boolean {
479
- return tools.some(name => names.includes(name));
480
- }
481
-
482
- export function resolveRootHarnessAllowlist(tools?: readonly ToolName[]): ToolName[] {
483
- if (tools === undefined) {
484
- // File verbs are synthesized, including SemanticSearch from
485
- // `search`. Web tools are safe under the `/tmp` scratch
486
- // overlay. Todos are harness conversation state. Do not
487
- // unlock shell or task.
488
- return ["webSearch", "webFetch", "updateTodos", "readTodos", "mcp"];
489
- }
490
- if (allowlistHas(tools, "shell", "Shell")) {
491
- throw new FileSystemConfigError(
492
- '`root` cannot be combined with `tools` containing `"shell"`. ' +
493
- "Shell is not a FileSystem method and must not bind the host shell onto a virtual tree.",
494
- );
495
- }
496
- if (allowlistHas(tools, "task", "Task")) {
497
- throw new FileSystemConfigError(
498
- "`root` cannot list `task`: a child keeps the host toolset and " +
499
- "would read the real workspace. Sharing `root` with subagents " +
500
- "needs a Cursor SDK inherit, not an overridden Task tool.",
501
- );
502
- }
503
- if (allowlistHas(tools, "readLints", "ReadLints")) {
504
- throw new FileSystemConfigError(
505
- "`root` cannot list `readLints`: FileSystem has no diagnostics " +
506
- "verb, so the host language service would run against the real workspace.",
507
- );
508
- }
509
- const extras = tools.filter(name => !isFileSystemToolAlias(name));
510
- return withMcpGrant(extras);
511
- }
512
-
513
- export function resolveFileSystemTools(options: {
514
- root: FileSystem;
515
- tools?: readonly ToolName[];
516
- }): ToolName[] {
517
- const harness = resolveRootHarnessAllowlist(options.tools);
518
- if (options.tools === undefined) {
519
- return harness;
520
- }
521
- const implemented = fileSystemToolNames(options.root);
522
- const missing: string[] = [];
523
- for (const name of options.tools) {
524
- if (!fileSystemSatisfiesFileTool(options.root, name)) {
525
- missing.push(name);
526
- }
527
- }
528
- if (missing.length > 0) {
529
- throw new FileSystemConfigError(
530
- `\`tools\` names FileSystem method(s) that are not implemented: ${missing.join(", ")}. ` +
531
- `Implemented file tools: ${implemented.length > 0 ? implemented.join(", ") : "(none)"}.`,
532
- );
533
- }
534
- return harness;
535
- }
536
-
537
- export function withMcpGrant(tools: readonly ToolName[]): ToolName[] {
538
- return tools.includes("mcp") ? [...tools] : [...tools, "mcp"];
539
- }
540
-
541
- /**
542
- * Native Cursor SDK file tools replaced by synthesized FileSystem tools
543
- * on every local turn. SDK allowlist names (`edit`, not `Write`).
544
- */
545
- export const REPLACED_NATIVE_FILE_TOOLS: ToolName[] = [
546
- "read",
547
- "ls",
548
- "grep",
549
- "glob",
550
- "edit",
551
- "delete",
552
- ];
553
-
554
- /**
555
- * Host-default harness options: keep shell / webSearch / sandbox, but
556
- * hide the native file tools the synthesized FileSystem now owns.
557
- *
558
- * Omitted `tools` leaves the SDK default set and only excludes the
559
- * replaced natives. `[]` stays empty. A non-empty allowlist drops file
560
- * aliases (those ride synthesized tools) and grants `mcp`.
561
- */
562
- export function resolveHostHarnessToolOptions(tools?: readonly ToolName[]): {
563
- tools?: ToolName[];
564
- disallowedTools?: ToolName[];
565
- } {
566
- if (tools === undefined) {
567
- return { disallowedTools: [...REPLACED_NATIVE_FILE_TOOLS] };
568
- }
569
- if (tools.length === 0) {
570
- return { tools: [] };
571
- }
572
- return {
573
- tools: withMcpGrant(tools.filter(name => !isReplacedHostFileAlias(name))),
574
- };
575
- }
576
-
577
- /** File aliases host-default synthesizes. Native `semSearch` stays. */
578
- function isReplacedHostFileAlias(name: string): boolean {
579
- const canonical = canonicalizeFileSystemToolName(name);
580
- return canonical !== undefined && canonical !== "SemanticSearch";
581
- }
582
-
583
- export type GrepOutputMode = "content" | "files_with_matches" | "count";
584
-
585
- /** Decode a {@link FileSystem.read} result as UTF-8 text. */
586
- export function fileSystemText(content: string | Uint8Array): string {
587
- return typeof content === "string" ? content : Buffer.from(content).toString("utf8");
588
- }
589
-
590
- /**
591
- * Native Read image formats. Magic bytes first, then extension.
592
- * Returns undefined for text (and for any other binary).
593
- */
594
- export function detectImageMimeType(bytes: Uint8Array, filePath?: string): string | undefined {
595
- if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
596
- return "image/jpeg";
597
- }
598
- if (
599
- bytes.length >= 8 &&
600
- bytes[0] === 0x89 &&
601
- bytes[1] === 0x50 &&
602
- bytes[2] === 0x4e &&
603
- bytes[3] === 0x47
604
- ) {
605
- return "image/png";
606
- }
607
- if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) {
608
- return "image/gif";
609
- }
610
- if (
611
- bytes.length >= 12 &&
612
- bytes[0] === 0x52 &&
613
- bytes[1] === 0x49 &&
614
- bytes[2] === 0x46 &&
615
- bytes[3] === 0x46 &&
616
- bytes[8] === 0x57 &&
617
- bytes[9] === 0x45 &&
618
- bytes[10] === 0x42 &&
619
- bytes[11] === 0x50
620
- ) {
621
- return "image/webp";
622
- }
623
- if (filePath === undefined) {
624
- return undefined;
625
- }
626
- const lower = filePath.toLowerCase();
627
- if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) {
628
- return "image/jpeg";
629
- }
630
- if (lower.endsWith(".png")) {
631
- return "image/png";
632
- }
633
- if (lower.endsWith(".gif")) {
634
- return "image/gif";
635
- }
636
- if (lower.endsWith(".webp")) {
637
- return "image/webp";
638
- }
639
- return undefined;
640
- }
641
-
642
- export function fileSystemImage(
643
- content: string | Uint8Array,
644
- path: string,
645
- ): { mimeType: string; bytes: Uint8Array } | undefined {
646
- if (!(content instanceof Uint8Array)) {
647
- return undefined;
648
- }
649
- const mimeType = detectImageMimeType(content, path);
650
- if (mimeType === undefined) {
651
- return undefined;
652
- }
653
- return { mimeType, bytes: content };
654
- }
655
-
656
- function compileGrepPattern(pattern: string, caseInsensitive?: boolean, path = "/"): RegExp {
657
- try {
658
- return new RegExp(pattern, caseInsensitive === true ? "i" : undefined);
659
- } catch {
660
- throw new InvalidGrepPatternError(pattern, path);
661
- }
662
- }
663
-
664
- function* grepFileContent(args: {
665
- path: string;
666
- content: string;
667
- regex: RegExp;
668
- }): Generator<GrepResult> {
669
- const lines = args.content.split("\n");
670
- for (let i = 0; i < lines.length; i++) {
671
- const line = lines[i]!;
672
- if (args.regex.test(line)) {
673
- yield { path: args.path, lineNumber: i + 1, line };
674
- }
675
- }
676
- }
677
-
678
- function normalizeMaxResults(maxResults: number | undefined): number | undefined {
679
- if (maxResults === undefined || !Number.isFinite(maxResults)) {
680
- return undefined;
681
- }
682
- return Math.max(0, Math.floor(maxResults));
683
- }
684
-
685
- async function* limitResults<T>(
686
- source: AsyncIterable<T>,
687
- maxResults: number | undefined,
688
- ): AsyncGenerator<T> {
689
- const cap = normalizeMaxResults(maxResults);
690
- if (cap === 0) {
691
- return;
692
- }
693
- let n = 0;
694
- for await (const item of source) {
695
- yield item;
696
- n++;
697
- if (cap !== undefined && n >= cap) {
698
- return;
699
- }
700
- }
701
- }
702
-
703
- function grepPushdownLimit(
704
- query: GrepQuery,
705
- opts: { outputMode: GrepOutputMode; headLimit?: number; offset: number },
706
- ): number | undefined {
707
- // Count and files_with_matches paginate after grouping by file.
708
- // A line-level cap would hide later files once one file fills the window.
709
- if (opts.outputMode === "count" || opts.outputMode === "files_with_matches") {
710
- return query.maxResults;
711
- }
712
- const headLimit = opts.headLimit !== undefined && opts.headLimit > 0 ? opts.headLimit : undefined;
713
- if (headLimit === undefined) {
714
- return query.maxResults;
715
- }
716
- const toolCap = opts.offset + headLimit;
717
- return query.maxResults === undefined ? toolCap : Math.min(query.maxResults, toolCap);
718
- }
719
-
720
- function compareGrepResult(left: GrepResult, right: GrepResult): number {
721
- return left.path < right.path
722
- ? -1
723
- : left.path > right.path
724
- ? 1
725
- : left.lineNumber - right.lineNumber;
726
- }
727
-
728
- function compareSearchResult(left: SearchResult, right: SearchResult): number {
729
- if (right.score !== left.score) {
730
- return right.score - left.score;
731
- }
732
- return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
733
- }
734
-
735
- export async function collectGrepMatches(
736
- root: FileSystem,
737
- query: GrepQuery,
738
- opts: { outputMode: GrepOutputMode; headLimit?: number; offset?: number },
739
- ): Promise<GrepResult[]> {
740
- const matches: GrepResult[] = [];
741
- const offset = opts.offset !== undefined && opts.offset > 0 ? opts.offset : 0;
742
- const headLimit = opts.headLimit !== undefined && opts.headLimit > 0 ? opts.headLimit : undefined;
743
- const skippedFiles = new Set<string>();
744
- const acceptedFiles = new Set<string>();
745
- let skippedItems = 0;
746
- let takenItems = 0;
747
- const pushdown = grepPushdownLimit(query, {
748
- outputMode: opts.outputMode,
749
- offset,
750
- ...(opts.headLimit === undefined ? {} : { headLimit: opts.headLimit }),
751
- });
752
- const grepQuery = pushdown === undefined ? query : { ...query, maxResults: pushdown };
753
- for await (const match of root.grep(grepQuery)) {
754
- if (opts.outputMode === "content") {
755
- if (skippedItems < offset) {
756
- skippedItems++;
757
- continue;
758
- }
759
- matches.push(match);
760
- takenItems++;
761
- if (headLimit !== undefined && takenItems >= headLimit) {
762
- break;
763
- }
764
- continue;
765
- }
766
- if (skippedFiles.has(match.path)) {
767
- continue;
768
- }
769
- if (!acceptedFiles.has(match.path)) {
770
- if (skippedItems < offset) {
771
- skippedFiles.add(match.path);
772
- skippedItems++;
773
- continue;
774
- }
775
- if (headLimit !== undefined && takenItems >= headLimit) {
776
- break;
777
- }
778
- acceptedFiles.add(match.path);
779
- takenItems++;
780
- }
781
- matches.push(match);
782
- }
783
- return matches;
784
- }
785
-
786
- export type GrepContentHit = GrepResult & {
787
- beforeContext?: string[];
788
- afterContext?: string[];
789
- };
790
-
791
- export function shapeGrepUnion(
792
- matches: GrepContentHit[],
793
- outputMode: GrepOutputMode,
794
- ): GrepUnionResult {
795
- if (outputMode === "files_with_matches") {
796
- const files = [...new Set(matches.map(match => match.path))];
797
- return { type: "files", output: { files, count: files.length } };
798
- }
799
- if (outputMode === "count") {
800
- const counts = new Map<string, number>();
801
- for (const match of matches) {
802
- counts.set(match.path, (counts.get(match.path) ?? 0) + 1);
803
- }
804
- return {
805
- type: "count",
806
- output: {
807
- counts: [...counts].map(([file, count]) => ({ file, count })),
808
- total: matches.length,
809
- },
810
- };
811
- }
812
- return {
813
- type: "content",
814
- output: {
815
- matches: matches.map(match => ({
816
- file: match.path,
817
- lineNumber: match.lineNumber,
818
- line: match.line,
819
- ...(match.beforeContext === undefined ? {} : { beforeContext: match.beforeContext }),
820
- ...(match.afterContext === undefined ? {} : { afterContext: match.afterContext }),
821
- })),
822
- totalMatches: matches.length,
823
- },
824
- };
825
- }
826
-
827
- export function normalizeFsPath(input: string): string {
828
- const slashes = input.replace(/\\/g, "/");
829
- if (slashes === "") {
830
- return "/";
831
- }
832
- const withSlash = slashes.startsWith("/") ? slashes : `/${slashes}`;
833
- const resolved = path.posix.normalize(withSlash);
834
- if (resolved.length > 1 && resolved.endsWith("/")) {
835
- return resolved.slice(0, -1);
836
- }
837
- return resolved === "." || resolved === "" ? "/" : resolved;
838
- }
839
-
840
- /** Path-segment prefix: `/agent` matches `/agent/skills`, not `/agent-tools`. */
841
- export function pathHasSegmentPrefix(args: { path: string; prefix: string }): boolean {
842
- const p = normalizeFsPath(args.path);
843
- const pre = normalizeFsPath(args.prefix);
844
- if (pre === "/") {
845
- return true;
846
- }
847
- return p === pre || p.startsWith(`${pre}/`);
848
- }
849
-
850
- function matchGlob(relativePath: string, globPattern: string): boolean {
851
- return minimatch(relativePath, globPattern, { dot: true, nocase: false });
852
- }
853
-
854
- function pathMatchesGlob(
855
- filePath: string,
856
- dir: string,
857
- globPattern: string,
858
- options: { matchBasename?: boolean } = {},
859
- ): boolean {
860
- const posixFile = filePath.replace(/\\/g, "/");
861
- const posixDir = dir.replace(/\\/g, "/");
862
- const relative =
863
- posixDir === "/" || posixFile.startsWith(`${posixDir}/`)
864
- ? posixDir === "/"
865
- ? posixFile.replace(/^\//, "")
866
- : posixFile.slice(posixDir.length + 1)
867
- : posixFile.replace(/^\//, "");
868
- if (matchGlob(relative, globPattern) || matchGlob(posixFile.replace(/^\//, ""), globPattern)) {
869
- return true;
870
- }
871
- // Native grep `--glob '*.ts'` matches the basename at any depth.
872
- // Glob `*.ts` stays relative to `targetDirectory` and does not.
873
- if (options.matchBasename === true && !globPattern.includes("/")) {
874
- const slash = relative.lastIndexOf("/");
875
- const base = slash === -1 ? relative : relative.slice(slash + 1);
876
- return matchGlob(base, globPattern);
877
- }
878
- return false;
879
- }
880
-
881
- /**
882
- * Resolve a per-send `workspaceFiles` key onto the virtual `/` namespace.
883
- * Refuses paths that escape the root, and the reserved `memory` name.
884
- * Host-default workspaces symlink `memory/` to durable agent state, so a
885
- * seed under that name would write through the link.
886
- */
887
- export function virtualWorkspaceWritePath(relativePath: string): string {
888
- if (relativePath.includes("\0")) {
889
- throw new FileSystemConfigError(`Refusing to write outside the virtual root: ${relativePath}`);
890
- }
891
- const posix = relativePath.replaceAll("\\", "/");
892
- const base = "/virtual-root";
893
- const target = path.posix.normalize(path.posix.join(base, posix));
894
- if (target !== base && !target.startsWith(`${base}/`)) {
895
- throw new FileSystemConfigError(`Refusing to write outside the virtual root: ${relativePath}`);
896
- }
897
- const sliced = target.slice(base.length);
898
- const dest = sliced === "" ? "/" : sliced;
899
- if (
900
- pathHasSegmentPrefix({
901
- path: dest,
902
- prefix: `/${MEMORY_DIR_NAME}`,
903
- })
904
- ) {
905
- throw new FileSystemConfigError(
906
- `"${MEMORY_DIR_NAME}" is reserved for shared session memory; refusing to write ${relativePath}`,
907
- );
908
- }
909
- return dest;
910
- }
911
-
912
- export async function writeWorkspaceFilesToRoot(
913
- root: FileSystem,
914
- files: Record<string, string | { encoding: "base64"; data: string; mimeType?: string }>,
915
- ): Promise<void> {
916
- for (const [relativePath, contents] of Object.entries(files)) {
917
- // Refuse escapes, then write the sanitized relative dest so
918
- // `localFileSystem` joins against cwd and `tempFs` still normalizes
919
- // `a.txt` → `/a.txt`. Never forward an absolute host path.
920
- const dest = virtualWorkspaceWritePath(relativePath);
921
- const relativeDest = dest.replace(/^\//, "");
922
- if (relativeDest === "") {
923
- throw new FileSystemConfigError(`Refusing to write the virtual root: ${relativePath}`);
924
- }
925
- const fileText =
926
- typeof contents === "string"
927
- ? contents
928
- : Buffer.from(contents.data, "base64").toString("utf8");
929
- try {
930
- await root.write(relativeDest, fileText);
931
- } catch (error) {
932
- throw new FileSystemConfigError(
933
- `workspaceFiles failed to write ${relativePath}: ${
934
- error instanceof Error ? error.message : "write failed"
935
- }`,
936
- );
937
- }
938
- }
939
- }
940
-
941
- function replaceLiteral(args: {
942
- existing: string;
943
- oldText: string;
944
- newText: string;
945
- replaceAll: boolean;
946
- }): string {
947
- if (args.replaceAll) {
948
- return args.existing.split(args.oldText).join(args.newText);
949
- }
950
- const index = args.existing.indexOf(args.oldText);
951
- if (index === -1) {
952
- return args.existing;
953
- }
954
- return (
955
- args.existing.slice(0, index) + args.newText + args.existing.slice(index + args.oldText.length)
956
- );
957
- }
958
-
959
- function countNonOverlapping(haystack: string, needle: string): number {
960
- let count = 0;
961
- let from = 0;
962
- while (from <= haystack.length - needle.length) {
963
- const index = haystack.indexOf(needle, from);
964
- if (index === -1) {
965
- break;
966
- }
967
- count++;
968
- from = index + needle.length;
969
- }
970
- return count;
971
- }
972
-
973
- /**
974
- * Exact, non-overlapping str-replace. Uniqueness is the FileSystem
975
- * contract: more than one match fails unless `replaceAll`.
976
- */
977
- function applyExactEdit(args: {
978
- existing: string;
979
- oldText: string;
980
- newText: string;
981
- replaceAll: boolean;
982
- path: string;
983
- }): { contents: string; occurrencesModified: number } {
984
- if (args.oldText === "") {
985
- throw new EditError(args.path, "oldText is empty");
986
- }
987
- if (args.oldText === args.newText) {
988
- throw new EditError(args.path, "oldText and newText are exactly the same");
989
- }
990
- const occurrences = countNonOverlapping(args.existing, args.oldText);
991
- if (occurrences === 0) {
992
- throw new EditError(args.path, "The string to replace was not found in the file");
993
- }
994
- if (occurrences > 1 && !args.replaceAll) {
995
- throw new EditError(
996
- args.path,
997
- "The string to replace was found multiple times in the file. Use replace_all to replace all occurrences, or include more context to only edit one occurrence.",
998
- );
999
- }
1000
- return {
1001
- contents: replaceLiteral({
1002
- existing: args.existing,
1003
- oldText: args.oldText,
1004
- newText: args.newText,
1005
- replaceAll: args.replaceAll,
1006
- }),
1007
- occurrencesModified: occurrences,
1008
- };
1009
- }
1010
-
1011
- /**
1012
- * Exact str-replace as `read` + apply + `write`. Uniqueness is
1013
- * this helper's contract; FileSystem implementations do not
1014
- * implement edit. Native StrReplace calls this.
1015
- */
1016
- export async function strReplaceOnFileSystem(
1017
- root: Pick<FileSystem, "read" | "write">,
1018
- query: EditQuery,
1019
- ): Promise<EditResult> {
1020
- const existing = await root.read(query.path);
1021
- if (typeof existing !== "string") {
1022
- throw new EditError(query.path, `${query.path} is not text`);
1023
- }
1024
- const applied = applyExactEdit({
1025
- existing,
1026
- oldText: query.oldText,
1027
- newText: query.newText,
1028
- replaceAll: query.replaceAll === true,
1029
- path: query.path,
1030
- });
1031
- await root.write(query.path, applied.contents);
1032
- return { occurrencesModified: applied.occurrencesModified };
1033
- }
1034
-
1035
- /** Native Read offset/limit: 1-indexed, negative offset counts from the end. */
1036
- export function sliceReadContent(content: string, offset?: number, limit?: number): string {
1037
- if (offset === undefined && limit === undefined) {
1038
- return content;
1039
- }
1040
- const lines = content === "" ? [] : content.split("\n");
1041
- const total = lines.length;
1042
- const effectiveOffset = offset ?? 1;
1043
- const effectiveLimit = limit ?? (effectiveOffset < 0 ? Math.abs(effectiveOffset) : total);
1044
- const startIndex =
1045
- effectiveOffset < 0 ? Math.max(0, total + effectiveOffset) : Math.max(0, effectiveOffset - 1);
1046
- const endIndex = Math.min(total, startIndex + effectiveLimit);
1047
- return lines.slice(startIndex, endIndex).join("\n");
1048
- }
1049
-
1050
- async function* emptySearch(_query: SearchQuery): AsyncGenerator<SearchResult> {}
1051
-
1052
- async function* emptyStream(): AsyncGenerator<never> {}
1053
-
1054
- /**
1055
- * A FileSystem with no files. Use as an overlay leaf or a missing
1056
- * catalog so a miss stays {@link FileNotFoundError} instead of
1057
- * {@link NoMountError}. Writes and deletes throw
1058
- * {@link ReadOnlyMountError} — an empty tree is never a sink.
1059
- */
1060
- export function emptyFs(): FileSystem {
1061
- return {
1062
- list: () => emptyStream(),
1063
- glob: () => emptyStream(),
1064
- async *grep(query) {
1065
- compileGrepPattern(
1066
- query.pattern,
1067
- query.caseInsensitive,
1068
- query.path === undefined || query.path === "" ? "/" : normalizeFsPath(query.path),
1069
- );
1070
- yield* emptyStream();
1071
- },
1072
- search: emptySearch,
1073
- async stat(path) {
1074
- return statFromFilePaths([], path);
1075
- },
1076
- async read(path) {
1077
- throw new FileNotFoundError(normalizeFsPath(path));
1078
- },
1079
- async write(path) {
1080
- throw new ReadOnlyMountError(normalizeFsPath(path));
1081
- },
1082
- async delete(path) {
1083
- throw new ReadOnlyMountError(normalizeFsPath(path));
1084
- },
1085
- };
1086
- }
1087
-
1088
- /**
1089
- * In-memory FileSystem for tests and fixtures. Keys are absolute
1090
- * posix paths (`/a.txt`) and are normalized on ingest. Honors the
1091
- * {@link FileSystem} order and path contracts.
1092
- * `search` is empty. Creates `/agent-tools` on first scratch
1093
- * write the same way any other path is created.
1094
- */
1095
- export function tempFs(files: Record<string, string | Uint8Array> = {}): FileSystem {
1096
- const store = new Map<string, string | Uint8Array>();
1097
- for (const [path, content] of Object.entries(files)) {
1098
- store.set(normalizeFsPath(path), content);
1099
- }
1100
-
1101
- const listed = {
1102
- list(prefix?: string, options?: ListOptions) {
1103
- return listFilesFromPaths(
1104
- [...store.entries()].map(([filePath, content]) => ({
1105
- path: filePath,
1106
- size: typeof content === "string" ? content.length : content.byteLength,
1107
- })),
1108
- prefix,
1109
- options,
1110
- );
1111
- },
1112
- async stat(path: string) {
1113
- return statFromFilePaths(store.keys(), path);
1114
- },
1115
- };
1116
-
1117
- return {
1118
- list(prefix, options) {
1119
- return listed.list(prefix, options);
1120
- },
1121
- async stat(path) {
1122
- return listed.stat(path);
1123
- },
1124
- async read(inputPath) {
1125
- const path = normalizeFsPath(inputPath);
1126
- const content = store.get(path);
1127
- if (content === undefined) {
1128
- throw new FileNotFoundError(path);
1129
- }
1130
- return content;
1131
- },
1132
- async *grep(query) {
1133
- yield* limitResults(uncapped(), query.maxResults);
1134
- async function* uncapped() {
1135
- const regex = compileGrepPattern(
1136
- query.pattern,
1137
- query.caseInsensitive,
1138
- query.path === undefined || query.path === "" ? "/" : normalizeFsPath(query.path),
1139
- );
1140
- const scope =
1141
- query.path === undefined || query.path === "" ? "/" : normalizeFsPath(query.path);
1142
- const exact = store.get(scope);
1143
- if (scope !== "/" && exact !== undefined) {
1144
- if (
1145
- query.glob !== undefined &&
1146
- !pathMatchesGlob(scope, scope, query.glob, {
1147
- matchBasename: true,
1148
- })
1149
- ) {
1150
- return;
1151
- }
1152
- if (isExcludedPath(scope, query.excludes)) {
1153
- return;
1154
- }
1155
- yield* grepFileContent({
1156
- path: scope,
1157
- content: fileSystemText(exact),
1158
- regex,
1159
- });
1160
- return;
1161
- }
1162
- for await (const entry of listed.list(
1163
- scope === "/" ? undefined : scope,
1164
- query.excludes === undefined ? undefined : { excludes: query.excludes },
1165
- )) {
1166
- if (
1167
- query.glob !== undefined &&
1168
- !pathMatchesGlob(entry.path, scope, query.glob, {
1169
- matchBasename: true,
1170
- })
1171
- ) {
1172
- continue;
1173
- }
1174
- const content = store.get(entry.path);
1175
- if (content === undefined) {
1176
- continue;
1177
- }
1178
- yield* grepFileContent({
1179
- path: entry.path,
1180
- content: fileSystemText(content),
1181
- regex,
1182
- });
1183
- }
1184
- }
1185
- },
1186
- async *glob(pattern, dir, options) {
1187
- const scope = dir === undefined || dir === "" ? "/" : normalizeFsPath(dir);
1188
- yield* globFromList(listed.list(scope === "/" ? undefined : scope), {
1189
- pattern,
1190
- dir: scope,
1191
- ...(options?.limit === undefined ? {} : { limit: options.limit }),
1192
- });
1193
- },
1194
- async write(inputPath, contents) {
1195
- store.set(normalizeFsPath(inputPath), contents);
1196
- },
1197
- async delete(inputPath) {
1198
- const path = normalizeFsPath(inputPath);
1199
- if (!store.has(path)) {
1200
- throw new FileNotFoundError(path);
1201
- }
1202
- store.delete(path);
1203
- },
1204
- search: emptySearch,
1205
- };
1206
- }
1207
-
1208
- function fsErrorMessage(error: unknown, fallback: string): string {
1209
- return error instanceof Error ? error.message : fallback;
1210
- }
1211
-
1212
- function throwLocalReadError(error: unknown, filePath: string): never {
1213
- throw new FileNotFoundError(filePath, fsErrorMessage(error, `not found: ${filePath}`));
1214
- }
1215
-
1216
- function skipWalkDir(name: string): boolean {
1217
- return name === ".git" || name === "node_modules";
1218
- }
1219
-
1220
- async function walkLocalFiles(rootDir: string): Promise<string[]> {
1221
- const found: string[] = [];
1222
- const stack = [rootDir];
1223
- while (stack.length > 0) {
1224
- const current = stack.pop();
1225
- if (current === undefined) {
1226
- break;
1227
- }
1228
- let entries: Array<{
1229
- name: string;
1230
- isDirectory(): boolean;
1231
- isFile(): boolean;
1232
- }>;
1233
- try {
1234
- entries = await readdir(current, { withFileTypes: true });
1235
- } catch {
1236
- continue;
1237
- }
1238
- for (const entry of entries) {
1239
- const full = path.join(current, entry.name);
1240
- // Same as the pre-root host walk and native LS/Glob/Grep: Dirent
1241
- // isDirectory/isFile do not follow links, so workspace `memory/`
1242
- // and other symlinks are not enumerated. Exact-path read/stat still
1243
- // follow.
1244
- if (entry.isDirectory()) {
1245
- if (!skipWalkDir(entry.name)) {
1246
- stack.push(full);
1247
- }
1248
- } else if (entry.isFile()) {
1249
- found.push(full);
1250
- }
1251
- }
1252
- }
1253
- found.sort((left, right) => left.localeCompare(right));
1254
- return found;
1255
- }
1256
-
1257
- async function* listLocalFiles(rootDir: string): AsyncGenerator<DirEntry> {
1258
- for (const filePath of await walkLocalFiles(rootDir)) {
1259
- yield { path: filePath };
1260
- }
1261
- }
1262
-
1263
- /**
1264
- * Host-disk FileSystem. Relative paths resolve against `cwd`; absolute
1265
- * paths are used as-is — the same contract as Cursor SDK native file
1266
- * tools. `search` yields empty results (no host index).
1267
- *
1268
- * Internal. Not part of the public Agent SDK surface.
1269
- */
1270
- export function localFileSystem(options: { cwd: string }): FileSystem {
1271
- const cwd = path.resolve(options.cwd);
1272
-
1273
- const resolvePath = (input: string): string =>
1274
- path.isAbsolute(input) ? path.resolve(input) : path.resolve(cwd, input);
1275
-
1276
- return {
1277
- async *list(prefix, options) {
1278
- yield* limitResults(uncapped(), options?.limit);
1279
- async function* uncapped() {
1280
- const dirPath =
1281
- prefix === undefined || prefix === "" || prefix === "." ? cwd : resolvePath(prefix);
1282
- for await (const entry of listLocalFiles(dirPath)) {
1283
- if (!isExcludedPath(entry.path, options?.excludes)) {
1284
- yield entry;
1285
- }
1286
- }
1287
- }
1288
- },
1289
- async stat(probePath) {
1290
- const filePath = resolvePath(probePath);
1291
- try {
1292
- const info = await stat(filePath);
1293
- return { kind: info.isDirectory() ? "directory" : "file" } as const;
1294
- } catch {
1295
- return { kind: "missing" } as const;
1296
- }
1297
- },
1298
- async read(inputPath) {
1299
- const filePath = resolvePath(inputPath);
1300
- try {
1301
- const bytes = await readFile(filePath);
1302
- if (detectImageMimeType(bytes, filePath) !== undefined) {
1303
- return new Uint8Array(bytes);
1304
- }
1305
- return bytes.toString("utf8");
1306
- } catch (error) {
1307
- throwLocalReadError(error, filePath);
1308
- }
1309
- },
1310
- async *grep(query) {
1311
- yield* limitResults(uncapped(), query.maxResults);
1312
- async function* uncapped() {
1313
- const searchRoot = resolvePath(query.path ?? cwd);
1314
- const regex = compileGrepPattern(query.pattern, query.caseInsensitive, searchRoot);
1315
- let filesToSearch: string[];
1316
- try {
1317
- const info = await stat(searchRoot);
1318
- filesToSearch = info.isFile() ? [searchRoot] : await walkLocalFiles(searchRoot);
1319
- } catch (error) {
1320
- throwLocalReadError(error, searchRoot);
1321
- }
1322
- for (const filePath of filesToSearch) {
1323
- if (
1324
- query.glob !== undefined &&
1325
- !pathMatchesGlob(filePath, searchRoot, query.glob, {
1326
- matchBasename: true,
1327
- })
1328
- ) {
1329
- continue;
1330
- }
1331
- if (isExcludedPath(filePath, query.excludes)) {
1332
- continue;
1333
- }
1334
- let content: string;
1335
- try {
1336
- content = await readFile(filePath, "utf8");
1337
- } catch {
1338
- continue;
1339
- }
1340
- yield* grepFileContent({ path: filePath, content, regex });
1341
- }
1342
- }
1343
- },
1344
- async *glob(pattern, dir, options) {
1345
- const dirPath = dir === undefined || dir === "" || dir === "." ? cwd : resolvePath(dir);
1346
- yield* globFromList(listLocalFiles(dirPath), {
1347
- pattern,
1348
- dir: dirPath,
1349
- ...(options?.limit === undefined ? {} : { limit: options.limit }),
1350
- });
1351
- },
1352
- async write(inputPath, contents) {
1353
- const filePath = resolvePath(inputPath);
1354
- try {
1355
- await mkdir(path.dirname(filePath), { recursive: true });
1356
- await writeFile(filePath, contents, "utf8");
1357
- } catch (error) {
1358
- throw new WriteFailedError(filePath, fsErrorMessage(error, `write failed: ${filePath}`));
1359
- }
1360
- },
1361
- async delete(inputPath) {
1362
- const filePath = resolvePath(inputPath);
1363
- try {
1364
- await rm(filePath);
1365
- } catch (error) {
1366
- throwLocalReadError(error, filePath);
1367
- }
1368
- },
1369
- search: emptySearch,
1370
- };
1371
- }
1372
-
1373
- interface MountEntry {
1374
- prefix: string;
1375
- fs: FileSystem;
1376
- }
1377
-
1378
- function longestMount(path: string, mounts: MountEntry[]): MountEntry | undefined {
1379
- let best: MountEntry | undefined;
1380
- for (const mount of mounts) {
1381
- if (!pathHasSegmentPrefix({ path, prefix: mount.prefix })) {
1382
- continue;
1383
- }
1384
- if (best === undefined || mount.prefix.length > best.prefix.length) {
1385
- best = mount;
1386
- }
1387
- }
1388
- return best;
1389
- }
1390
-
1391
- /** Namespace path → child path. `/host/a.md` on `/host` is `/a.md`. */
1392
- function toChildPath(path: string, prefix: string): string {
1393
- if (prefix === "/") {
1394
- return path;
1395
- }
1396
- if (path === prefix) {
1397
- return "/";
1398
- }
1399
- if (path.startsWith(`${prefix}/`)) {
1400
- return path.slice(prefix.length);
1401
- }
1402
- return path;
1403
- }
1404
-
1405
- /** Child path → namespace path. `/a.md` on `/host` is `/host/a.md`. */
1406
- function toParentPath(path: string, prefix: string): string {
1407
- if (prefix === "/") {
1408
- return path;
1409
- }
1410
- if (path === "/" || path === "") {
1411
- return prefix;
1412
- }
1413
- return path.startsWith("/") ? `${prefix}${path}` : `${prefix}/${path}`;
1414
- }
1415
-
1416
- async function* mapMountEntries(
1417
- source: AsyncIterable<DirEntry>,
1418
- prefix: string,
1419
- ): AsyncIterable<DirEntry> {
1420
- try {
1421
- for await (const entry of source) {
1422
- yield { ...entry, path: toParentPath(entry.path, prefix) };
1423
- }
1424
- } catch (error) {
1425
- throw remapPathError(error, prefix);
1426
- }
1427
- }
1428
-
1429
- async function* mapMountGrep(
1430
- source: AsyncIterable<GrepResult>,
1431
- prefix: string,
1432
- ): AsyncIterable<GrepResult> {
1433
- try {
1434
- for await (const hit of source) {
1435
- yield { ...hit, path: toParentPath(hit.path, prefix) };
1436
- }
1437
- } catch (error) {
1438
- throw remapPathError(error, prefix);
1439
- }
1440
- }
1441
-
1442
- async function* mapMountSearch(
1443
- source: AsyncIterable<SearchResult>,
1444
- prefix: string,
1445
- ): AsyncIterable<SearchResult> {
1446
- try {
1447
- for await (const hit of source) {
1448
- yield { ...hit, path: toParentPath(hit.path, prefix) };
1449
- }
1450
- } catch (error) {
1451
- throw remapPathError(error, prefix);
1452
- }
1453
- }
1454
-
1455
- function childSearchQuery(query: SearchQuery, prefix: string): SearchQuery | undefined {
1456
- if (query.targetDirectories === undefined || query.targetDirectories.length === 0) {
1457
- return query;
1458
- }
1459
- const dirs: string[] = [];
1460
- for (const dir of query.targetDirectories) {
1461
- const normalized = normalizeFsPath(dir);
1462
- // `/` is every mount, the same way grep at `/` fans out.
1463
- if (normalized === "/") {
1464
- return { ...query, targetDirectories: undefined };
1465
- }
1466
- if (!pathHasSegmentPrefix({ path: normalized, prefix })) {
1467
- continue;
1468
- }
1469
- const child = toChildPath(normalized, prefix);
1470
- if (child === "/") {
1471
- return { ...query, targetDirectories: undefined };
1472
- }
1473
- dirs.push(child);
1474
- }
1475
- if (dirs.length === 0) {
1476
- return undefined;
1477
- }
1478
- return { ...query, targetDirectories: dirs };
1479
- }
1480
-
1481
- /**
1482
- * Longest-prefix compose, path-segment match. Every verb is
1483
- * defined. Does not synthesize `shell`. `/agent` is not a
1484
- * prefix of `/agent-tools`.
1485
- *
1486
- * The record keys are mount points. Each child is a FileSystem
1487
- * rooted at `/`. `unionFs` strips the prefix on the way in and
1488
- * re-prefixes yields (and error paths) on the way out:
1489
- * `unionFs({ "/host": hostFs(...) })` — the child never sees
1490
- * `/host`.
1491
- *
1492
- * A path with no mount:
1493
- * - `read` / `write` / `delete`: throw
1494
- * `no mount for path: ${path}`
1495
- * - `list` / `glob` / `grep`: empty iterator
1496
- * - `stat`: `{ kind: "missing" }` (`/` and exact mount prefixes
1497
- * are `{ kind: "directory" }`)
1498
- *
1499
- * Root `list` / `glob` / `grep` / `search` k-way merge already
1500
- * sorted sources. List and glob use `unique` so an earlier
1501
- * mount shadows a later one; grep and search keep every hit.
1502
- */
1503
- export function unionFs(mounts: Record<string, FileSystem>): FileSystem {
1504
- const entries: MountEntry[] = Object.entries(mounts).map(([prefix, fs]) => ({
1505
- prefix: normalizeFsPath(prefix),
1506
- fs,
1507
- }));
1508
- entries.sort((a, b) => b.prefix.length - a.prefix.length);
1509
-
1510
- const noMount = (path: string): never => {
1511
- throw new NoMountError(path);
1512
- };
1513
-
1514
- const forward = async <T>(
1515
- path: string,
1516
- run: (fs: FileSystem, childPath: string) => Promise<T>,
1517
- ): Promise<T> => {
1518
- const mount = longestMount(path, entries);
1519
- if (mount === undefined) {
1520
- return noMount(path);
1521
- }
1522
- const childPath = toChildPath(path, mount.prefix);
1523
- try {
1524
- return await run(mount.fs, childPath);
1525
- } catch (error) {
1526
- throw remapPathError(error, mount.prefix);
1527
- }
1528
- };
1529
-
1530
- const isRootPath = (value: string | undefined): boolean =>
1531
- value === undefined || value === "" || value === "/";
1532
-
1533
- return {
1534
- async *list(prefix, options) {
1535
- yield* limitResults(uncapped(), options?.limit);
1536
- async function* uncapped() {
1537
- if (isRootPath(prefix)) {
1538
- yield* mergeSortedByPath(
1539
- entries.map(mount => mapMountEntries(mount.fs.list(undefined, options), mount.prefix)),
1540
- { unique: true },
1541
- );
1542
- return;
1543
- }
1544
- const path = normalizeFsPath(prefix ?? "/");
1545
- const mount = longestMount(path, entries);
1546
- if (mount === undefined) {
1547
- return;
1548
- }
1549
- const childPath = toChildPath(path, mount.prefix);
1550
- yield* mapMountEntries(
1551
- mount.fs.list(childPath === "/" ? undefined : childPath, options),
1552
- mount.prefix,
1553
- );
1554
- }
1555
- },
1556
- async stat(path) {
1557
- const normalized = normalizeFsPath(path);
1558
- if (normalized === "/") {
1559
- return { kind: "directory" } as const;
1560
- }
1561
- if (entries.some(entry => entry.prefix === normalized)) {
1562
- return { kind: "directory" } as const;
1563
- }
1564
- const mount = longestMount(normalized, entries);
1565
- if (mount === undefined) {
1566
- return { kind: "missing" } as const;
1567
- }
1568
- return mount.fs.stat(toChildPath(normalized, mount.prefix));
1569
- },
1570
- async read(path) {
1571
- const normalized = normalizeFsPath(path);
1572
- return forward(normalized, (fs, childPath) => fs.read(childPath));
1573
- },
1574
- async write(path, contents) {
1575
- const normalized = normalizeFsPath(path);
1576
- return forward(normalized, (fs, childPath) => fs.write(childPath, contents));
1577
- },
1578
- async delete(path) {
1579
- const normalized = normalizeFsPath(path);
1580
- return forward(normalized, (fs, childPath) => fs.delete(childPath));
1581
- },
1582
- async *grep(query) {
1583
- yield* limitResults(uncapped(), query.maxResults);
1584
- async function* uncapped() {
1585
- const scope =
1586
- query.path === undefined || query.path === "" ? "/" : normalizeFsPath(query.path);
1587
- if (scope === "/") {
1588
- yield* mergeSorted(
1589
- entries.map(mount =>
1590
- mapMountGrep(mount.fs.grep({ ...query, path: undefined }), mount.prefix),
1591
- ),
1592
- { compare: compareGrepResult },
1593
- );
1594
- return;
1595
- }
1596
- const mount = longestMount(scope, entries);
1597
- if (mount === undefined) {
1598
- return;
1599
- }
1600
- const childPath = toChildPath(scope, mount.prefix);
1601
- yield* mapMountGrep(
1602
- mount.fs.grep({
1603
- ...query,
1604
- path: childPath === "/" ? undefined : childPath,
1605
- }),
1606
- mount.prefix,
1607
- );
1608
- }
1609
- },
1610
- async *search(query) {
1611
- yield* limitResults(uncapped(), query.maxResults);
1612
- async function* uncapped() {
1613
- const sources: AsyncIterable<SearchResult>[] = [];
1614
- for (const mount of entries) {
1615
- const childQuery = childSearchQuery(query, mount.prefix);
1616
- if (childQuery === undefined) {
1617
- continue;
1618
- }
1619
- sources.push(mapMountSearch(mount.fs.search(childQuery), mount.prefix));
1620
- }
1621
- yield* mergeSorted(sources, { compare: compareSearchResult });
1622
- }
1623
- },
1624
- async *glob(pattern, dir, options) {
1625
- yield* limitResults(uncapped(), options?.limit);
1626
- async function* uncapped() {
1627
- const scope = dir === undefined || dir === "" ? "/" : normalizeFsPath(dir);
1628
- if (scope === "/") {
1629
- yield* mergeSortedByPath(
1630
- entries.map(mount =>
1631
- mapMountEntries(mount.fs.glob(pattern, undefined, options), mount.prefix),
1632
- ),
1633
- { unique: true },
1634
- );
1635
- return;
1636
- }
1637
- const mount = longestMount(scope, entries);
1638
- if (mount === undefined) {
1639
- return;
1640
- }
1641
- const childPath = toChildPath(scope, mount.prefix);
1642
- yield* mapMountEntries(
1643
- mount.fs.glob(pattern, childPath === "/" ? undefined : childPath, options),
1644
- mount.prefix,
1645
- );
1646
- }
1647
- },
1648
- };
1649
- }
1650
-
1651
- async function collectLayerPaths(layer: FileSystem): Promise<string[]> {
1652
- const paths: string[] = [];
1653
- try {
1654
- for await (const entry of layer.list()) {
1655
- paths.push(entry.path);
1656
- }
1657
- } catch {
1658
- // A layer that cannot list also cannot own paths.
1659
- }
1660
- return paths;
1661
- }
1662
-
1663
- /**
1664
- * Same-root overlay: earlier layers win. Read-only.
1665
- *
1666
- * A downed layer costs its own files, not the overlay. Mutations
1667
- * throw `read-only mount` / `read-only mount: ${path}`. Empty
1668
- * `layers` throws `overlayFs needs at least one layer.`
1669
- */
1670
- export function overlayFs(layers: readonly FileSystem[]): FileSystem {
1671
- if (layers.length === 0) {
1672
- throw new Error("overlayFs needs at least one layer.");
1673
- }
1674
-
1675
- const walkLayers = async <T>(
1676
- collect: (layer: FileSystem) => AsyncIterable<T> | Promise<AsyncIterable<T>>,
1677
- ): Promise<{ streams: T[][]; failure: unknown; served: boolean }> => {
1678
- const streams: T[][] = [];
1679
- let failure: unknown;
1680
- let served = false;
1681
- for (const layer of layers) {
1682
- const collected: T[] = [];
1683
- try {
1684
- for await (const entry of await collect(layer)) {
1685
- collected.push(entry);
1686
- }
1687
- } catch (error) {
1688
- failure ??= error;
1689
- continue;
1690
- }
1691
- served = true;
1692
- streams.push(collected);
1693
- }
1694
- return { streams, failure, served };
1695
- };
1696
-
1697
- const collectOverlayHits = async <T extends { path: string }>(
1698
- queryFn: (layer: FileSystem) => AsyncIterable<T>,
1699
- rethrow?: (error: unknown) => boolean,
1700
- ): Promise<T[][]> => {
1701
- const streams: T[][] = [];
1702
- const shadowed = new Set<string>();
1703
- let failure: unknown;
1704
- let served = false;
1705
- for (const layer of layers) {
1706
- const collected: T[] = [];
1707
- try {
1708
- for await (const hit of queryFn(layer)) {
1709
- if (!shadowed.has(hit.path)) {
1710
- collected.push(hit);
1711
- }
1712
- }
1713
- served = true;
1714
- } catch (error) {
1715
- if (rethrow?.(error) === true) {
1716
- throw error;
1717
- }
1718
- failure ??= error;
1719
- continue;
1720
- }
1721
- streams.push(collected);
1722
- for (const path of await collectLayerPaths(layer)) {
1723
- shadowed.add(path);
1724
- }
1725
- }
1726
- if (!served && failure !== undefined) {
1727
- throw failure;
1728
- }
1729
- return streams;
1730
- };
1731
-
1732
- return {
1733
- async *list(prefix, options) {
1734
- const { streams, failure, served } = await walkLayers(layer => layer.list(prefix, options));
1735
- if (!served && failure !== undefined) {
1736
- throw failure;
1737
- }
1738
- yield* limitResults(mergeSortedByPath(streams, { unique: true }), options?.limit);
1739
- },
1740
- async stat(path) {
1741
- let failure: unknown;
1742
- let sawMissing = false;
1743
- for (const layer of layers) {
1744
- try {
1745
- const info = await layer.stat(path);
1746
- if (info.kind !== "missing") {
1747
- return info;
1748
- }
1749
- sawMissing = true;
1750
- } catch (error) {
1751
- failure ??= error;
1752
- }
1753
- }
1754
- if (!sawMissing && failure !== undefined) {
1755
- throw failure;
1756
- }
1757
- return { kind: "missing" } as const;
1758
- },
1759
- async *glob(pattern, dir, options) {
1760
- const { streams, failure, served } = await walkLayers(layer =>
1761
- layer.glob(pattern, dir, options),
1762
- );
1763
- if (!served && failure !== undefined) {
1764
- throw failure;
1765
- }
1766
- yield* limitResults(mergeSortedByPath(streams, { unique: true }), options?.limit);
1767
- },
1768
- async read(path) {
1769
- let failure: unknown;
1770
- for (const layer of layers) {
1771
- try {
1772
- return await layer.read(path);
1773
- } catch (error) {
1774
- if (isFileNotFoundError(error)) {
1775
- continue;
1776
- }
1777
- failure ??= error;
1778
- }
1779
- }
1780
- if (failure !== undefined) {
1781
- throw failure;
1782
- }
1783
- throw new FileNotFoundError(path);
1784
- },
1785
- async *grep(query) {
1786
- const { maxResults, ...uncappedQuery } = query;
1787
- yield* limitResults(
1788
- mergeSorted(
1789
- await collectOverlayHits(
1790
- layer => layer.grep(uncappedQuery),
1791
- error => isInvalidGrepPatternError(error),
1792
- ),
1793
- { compare: compareGrepResult },
1794
- ),
1795
- maxResults,
1796
- );
1797
- },
1798
- async write(path) {
1799
- throw new ReadOnlyMountError(path);
1800
- },
1801
- async delete(path) {
1802
- throw new ReadOnlyMountError(path);
1803
- },
1804
- async *search(query) {
1805
- const { maxResults, ...uncappedQuery } = query;
1806
- yield* limitResults(
1807
- mergeSorted(await collectOverlayHits(layer => layer.search(uncappedQuery)), {
1808
- compare: compareSearchResult,
1809
- }),
1810
- maxResults,
1811
- );
1812
- },
1813
- };
1814
- }
1815
-
1816
- function hostKey(path: string): string {
1817
- const normalized = normalizeFsPath(path);
1818
- return normalized === "/" ? "" : normalized.slice(1);
1819
- }
1820
-
1821
- function isHostConflict(error: unknown): boolean {
1822
- return (
1823
- error instanceof FileConflictError ||
1824
- (error instanceof Error &&
1825
- (error.name === "FileConflictError" || error.message.includes("lost a race")))
1826
- );
1827
- }
1828
-
1829
- /**
1830
- * `HostFilesApi` as a FileSystem rooted at `/`.
1831
- *
1832
- * Mount it with `unionFs({ "/host": hostFs(files, scope) })`. The
1833
- * child never sees `/host` — `unionFs` owns the prefix. `scope` is
1834
- * the HostFiles partition, not a path prefix. `search` is empty
1835
- * (HostFiles is not an index).
1836
- */
1837
- export function hostFs(files: HostFilesApi, scope: HostFilesScope): FileSystem {
1838
- const callOptions = { scope };
1839
- const readEtags = new Map<string, string>();
1840
-
1841
- const listed = {
1842
- async *list(prefix?: string, options?: ListOptions) {
1843
- const entries = await files.list(undefined, callOptions);
1844
- yield* listFilesFromPaths(
1845
- entries.map(entry => ({
1846
- path: normalizeFsPath(entry.path),
1847
- size: entry.size,
1848
- })),
1849
- prefix,
1850
- options,
1851
- );
1852
- },
1853
- async stat(path: string) {
1854
- const entries = await files.list(undefined, callOptions);
1855
- return statFromFilePaths(
1856
- entries.map(entry => normalizeFsPath(entry.path)),
1857
- path,
1858
- );
1859
- },
1860
- };
1861
-
1862
- const readText = async (inputPath: string): Promise<string> => {
1863
- const path = normalizeFsPath(inputPath);
1864
- const key = hostKey(path);
1865
- if (key === "") {
1866
- throw new FileNotFoundError(path);
1867
- }
1868
- const [content, stat] = await Promise.all([
1869
- files.read(key, callOptions),
1870
- files.stat(key, callOptions),
1871
- ]);
1872
- if (content === undefined) {
1873
- throw new FileNotFoundError(path);
1874
- }
1875
- if (stat?.etag !== undefined) {
1876
- readEtags.set(key, stat.etag);
1877
- }
1878
- return content;
1879
- };
1880
-
1881
- const writeHost = async (inputPath: string, contents: string): Promise<void> => {
1882
- const path = normalizeFsPath(inputPath);
1883
- const key = hostKey(path);
1884
- if (key === "") {
1885
- throw new FileNotFoundError(path);
1886
- }
1887
- try {
1888
- if (files.capabilities.conflictDetection) {
1889
- const etag = readEtags.get(key);
1890
- await files.write(key, contents, {
1891
- ...callOptions,
1892
- // No cached etag: unconditional create/overwrite. After a
1893
- // successful read or write, CAS on that etag.
1894
- ...(etag === undefined ? {} : { ifMatch: etag }),
1895
- });
1896
- } else {
1897
- await files.write(key, contents, callOptions);
1898
- }
1899
- } catch (error) {
1900
- if (isHostConflict(error)) {
1901
- throw new PathError(path, `${path} changed since you read it — read it again and rewrite.`);
1902
- }
1903
- throw error;
1904
- }
1905
- const stat = await files.stat(key, callOptions);
1906
- if (stat?.etag !== undefined) {
1907
- readEtags.set(key, stat.etag);
1908
- } else {
1909
- readEtags.delete(key);
1910
- }
1911
- };
1912
-
1913
- return {
1914
- list(prefix, options) {
1915
- return listed.list(prefix, options);
1916
- },
1917
- async stat(path) {
1918
- return listed.stat(path);
1919
- },
1920
- async read(path) {
1921
- return readText(path);
1922
- },
1923
- async *grep(query) {
1924
- yield* limitResults(uncapped(), query.maxResults);
1925
- async function* uncapped() {
1926
- const scopePath =
1927
- query.path === undefined || query.path === "" ? "/" : normalizeFsPath(query.path);
1928
- const regex = compileGrepPattern(query.pattern, query.caseInsensitive, scopePath);
1929
- const info = await listed.stat(scopePath);
1930
- if (scopePath !== "/" && info.kind === "file") {
1931
- if (
1932
- query.glob !== undefined &&
1933
- !pathMatchesGlob(scopePath, scopePath, query.glob, {
1934
- matchBasename: true,
1935
- })
1936
- ) {
1937
- return;
1938
- }
1939
- if (isExcludedPath(scopePath, query.excludes)) {
1940
- return;
1941
- }
1942
- yield* grepFileContent({
1943
- path: scopePath,
1944
- content: await readText(scopePath),
1945
- regex,
1946
- });
1947
- return;
1948
- }
1949
- for await (const entry of listed.list(
1950
- scopePath === "/" ? undefined : scopePath,
1951
- query.excludes === undefined ? undefined : { excludes: query.excludes },
1952
- )) {
1953
- if (
1954
- query.glob !== undefined &&
1955
- !pathMatchesGlob(entry.path, scopePath, query.glob, {
1956
- matchBasename: true,
1957
- })
1958
- ) {
1959
- continue;
1960
- }
1961
- yield* grepFileContent({
1962
- path: entry.path,
1963
- content: await readText(entry.path),
1964
- regex,
1965
- });
1966
- }
1967
- }
1968
- },
1969
- async *glob(pattern, dir, options) {
1970
- const dirPath = dir === undefined || dir === "" ? "/" : normalizeFsPath(dir);
1971
- yield* globFromList(listed.list(dirPath === "/" ? undefined : dirPath), {
1972
- pattern,
1973
- dir: dirPath,
1974
- ...(options?.limit === undefined ? {} : { limit: options.limit }),
1975
- });
1976
- },
1977
- async write(inputPath, contents) {
1978
- await writeHost(inputPath, contents);
1979
- },
1980
- async delete(inputPath) {
1981
- const path = normalizeFsPath(inputPath);
1982
- const key = hostKey(path);
1983
- if (key === "" || !(await files.exists(key, callOptions))) {
1984
- throw new FileNotFoundError(path);
1985
- }
1986
- await files.remove(key, callOptions);
1987
- readEtags.delete(key);
1988
- },
1989
- search: emptySearch,
1990
- };
1991
- }
1992
-
1993
- async function* globFromList(
1994
- source: AsyncIterable<DirEntry>,
1995
- options: { pattern: string; dir: string; limit?: number },
1996
- ): AsyncGenerator<DirEntry> {
1997
- yield* limitResults(uncapped(), options.limit);
1998
- async function* uncapped() {
1999
- for await (const entry of source) {
2000
- if (pathMatchesGlob(entry.path, options.dir, options.pattern)) {
2001
- yield entry;
2002
- }
2003
- }
2004
- }
2005
- }