@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
@@ -1,3147 +0,0 @@
1
- /**
2
- * The HTTP host: a plain node:http server that adapts requests to the Fetch
3
- * API, resolves route auth, and dispatches to the built-in HTTP channel
4
- * routes, custom channel routes (under `/v1/channels/<id>`), and the
5
- * server-level health / info / dev-dispatch routes.
6
- */
7
-
8
- import { Buffer } from "node:buffer";
9
- import { once } from "node:events";
10
- import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
11
- import type { AddressInfo } from "node:net";
12
- import { join } from "node:path";
13
- import {
14
- type BitbucketProxyTransport,
15
- CURSOR_BITBUCKET_REPOS_HEADER,
16
- } from "../channels/bitbucket/api.js";
17
- import {
18
- getBitbucketCursorAccountRuntime,
19
- resolveCursorBitbucketProxyUrl,
20
- } from "../channels/bitbucket/cursor-account.js";
21
- import {
22
- dispatchDeploymentEvent,
23
- getDeploymentsChannelOptions,
24
- } from "../channels/deployments/deployments-channel.js";
25
- import type { DeploymentsChannelOptions } from "../channels/deployments/types.js";
26
- import {
27
- type CursorAccountGithubTokenResolver,
28
- type CursorGithubRepoScope,
29
- createCursorAccountGithubTokenResolver,
30
- createCursorGithubProxyHostResolver,
31
- cursorGithubPermissionsForChannel,
32
- type GithubCursorAccountRuntime,
33
- getGithubCursorAccountRuntime,
34
- resolveCursorGithubCredentialScope,
35
- resolveCursorGithubPermissions,
36
- resolveCursorGithubProxyUrl,
37
- } from "../channels/github/cursor-account.js";
38
- import { findGitHubChannelTargets } from "../channels/github/forward.js";
39
- import {
40
- CURSOR_GITLAB_PROJECTS_HEADER,
41
- type GitLabProxyTransport,
42
- } from "../channels/gitlab/api.js";
43
- import {
44
- getGitLabCursorAccountRuntime,
45
- resolveCursorGitLabProxyUrl,
46
- } from "../channels/gitlab/cursor-account.js";
47
- import {
48
- getOriginCursorAccountRuntime,
49
- type OriginCursorAccountRuntime,
50
- parseCursorOriginRepoScope,
51
- } from "../channels/origin/cursor-account.js";
52
- import { findOriginChannelTargets } from "../channels/origin/origin-channel.js";
53
- import { appendSlackQuietHint } from "../channels/slack/agentic-posted.js";
54
- import { allowAll, bearerAuth, localDevStrict } from "../channels.js";
55
- import type {
56
- AgentProject,
57
- AgentServeHandle,
58
- ArtifactPage,
59
- AuthContext,
60
- AuthPolicy,
61
- ChannelHandlerArgs,
62
- ChannelStartArgs,
63
- MountedAgentInfo,
64
- ReminderInfo,
65
- ServeOptions,
66
- } from "../types.js";
67
- import {
68
- ARTIFACTS_PAGE_DEFAULT_LIMIT,
69
- ARTIFACTS_PAGE_MAX_LIMIT,
70
- InvalidArtifactCursorError,
71
- } from "./artifacts-store.js";
72
- import {
73
- type BrowserOriginGuardOptions,
74
- browserOriginGuardOptionsForPublicUrl,
75
- isTrustedBrowserMutation,
76
- } from "./browser-origin-guard.js";
77
- import { invokeChannelRoute } from "./channel-route-dispatch.js";
78
- import { selectConversationMirror } from "./conversation-mirror.js";
79
- import {
80
- type CursorAccountConnectionRef,
81
- CursorAccountMcpBridge,
82
- collectCursorAccountConnections,
83
- cursorAccountMcpPath,
84
- } from "./cursor/account-mcp.js";
85
- import { CursorBackendClient } from "./cursor/backend-client.js";
86
- import {
87
- cursorBackendUrl,
88
- cursorExternalApiUrl,
89
- type ResolvedApiKey,
90
- resolveApiKey,
91
- resolveApiKeySync,
92
- SIGN_IN_HINT,
93
- } from "./cursor/credentials.js";
94
- import { CursorGithubCredentialProvider } from "./cursor/github-credentials.js";
95
- import {
96
- DeploymentEventRelay,
97
- fanOutDeploymentEvent,
98
- mergeResolvedSubscriptions,
99
- type ResolvedSubscription,
100
- resolveDeploymentSubscriptions,
101
- } from "./cursor-deployment-relay.js";
102
- import {
103
- CursorEventRelay,
104
- type CursorScmSubscription,
105
- formatCursorScmDispatchOutcome,
106
- formatCursorScmEventLog,
107
- scmEventToGitHubPayload,
108
- scmMetadataToOriginPayload,
109
- } from "./cursor-event-relay.js";
110
- import { AGENT_SERVE_GENERATION_ENV_VAR } from "./cursor-relay-core.js";
111
- import { buildAgentDeployManifest } from "./deploy-manifest.js";
112
- import { formatDiagnostics, hasErrorDiagnostics, projectInfo } from "./discovery.js";
113
- import { packageVersion } from "./distribution.js";
114
- import { docsSiteExists, ensureDocsSiteBundle, renderDocsFile } from "./docs-site.js";
115
- import {
116
- EvalRunConflictError,
117
- EvalRunEmptyError,
118
- EvalRunNotRunningError,
119
- EvalRunStore,
120
- EvalRunUnknownError,
121
- } from "./eval-run-store.js";
122
- import { GUEST_NETWORK_PATH, guestNetworkReadinessResponse } from "./guest-network.js";
123
- import {
124
- collectGitHubTriggerTargets,
125
- collectOriginTriggerTargets,
126
- handleAgentServeTrigger,
127
- } from "./handleAgentServeTrigger.js";
128
- import { createHostPlatforms, warmupHostGitHubAuth } from "./host-platforms.js";
129
- import { registerHostedDeliveryRoute } from "./hosted-delivery.js";
130
- import type { HostedReminderFireDescriptorPayload } from "./hosted-delivery-protocol.js";
131
- import {
132
- HOSTED_DELIVERY_HEADER,
133
- HOSTED_GUEST_RETRY_TERMINAL,
134
- hostedGuestErrorResponse,
135
- } from "./hosted-delivery-protocol.js";
136
- import { hostedErrorMessageOnly, hostedErrorStackSnippet } from "./hosted-execution-diag.js";
137
- import { flushHostedExecutionProcessDeath } from "./hosted-execution-flush.js";
138
- import {
139
- buildHttpChannelRoutes,
140
- errorResponse,
141
- jsonResponse,
142
- readJsonObject,
143
- requireSessionOwner,
144
- } from "./http-channel.js";
145
- import { incomingHeadersToFetch, incomingRequestHost } from "./incoming-headers-to-fetch.js";
146
- import { DEFAULT_SERVE_PORT, listenHttpServer } from "./listen-port.js";
147
- import { createLocalControlPlane, type LocalControlPlane } from "./local-control-plane.js";
148
- import type { RouteLocalIngressContinuation } from "./local-ingress.js";
149
- import { createLogRing, type LogRing } from "./log-ring.js";
150
- import {
151
- createAgentMcpEndpoint,
152
- createToolMcpEndpoint,
153
- MCP_ENDPOINT_PATH,
154
- TOOL_MCP_ENDPOINT_PATH,
155
- } from "./mcp-endpoint.js";
156
- import { mcpOauthServeCallbackPath, mcpOauthServeCallbackUrl } from "./mcp-oauth-on-demand.js";
157
- import type { McpOauthSecretsTarget } from "./mcp-oauth-persist.js";
158
- import { isLoopbackAddress } from "./net.js";
159
- import { createOtelCollector, type OtelCollector } from "./otel/collector.js";
160
- import { pickAuthoredOtel, resolveOtelConfig } from "./otel/config.js";
161
- import { instrumentHttp } from "./otel/http.js";
162
- import { createOtelRuntime, forceFlushOtelRuntime, shutdownOtelRuntime } from "./otel/runtime.js";
163
- import { collectPeerConnections } from "./peer-connections.js";
164
- import {
165
- PLATFORM_SCHEDULE_CATALOG_FILENAME,
166
- syncHostedPlatformSchedules,
167
- } from "./platform-schedule-sync.js";
168
- import {
169
- createCursorHostedPlatformTimers,
170
- createCursorHostedReminderControlPlane,
171
- } from "./platform-timers.js";
172
- import {
173
- type AgentIndexEntry,
174
- renderAgentsIndexHtml,
175
- renderPlaygroundAsset,
176
- renderPlaygroundIndexHtml,
177
- } from "./playground/static.js";
178
- import {
179
- ensurePlaygroundBundle,
180
- playgroundDevBaseFromEnv,
181
- playgroundDevBasePath,
182
- startPlaygroundDevServer,
183
- } from "./playground/toolchain.js";
184
- import { collectMemoryHealthFields, sumEventLogStats } from "./process-memory-telemetry.js";
185
- import {
186
- claimFromDescriptor,
187
- type ReminderControlPlane,
188
- type ReminderFireDescriptor,
189
- } from "./reminder-control-plane-protocol.js";
190
- import {
191
- ReminderRunner,
192
- ReminderValidationError,
193
- rejectAnonymousReminderHandlers,
194
- UnknownReminderError,
195
- } from "./reminder-runner.js";
196
- import { mapThrownRequestError } from "./request-error-status.js";
197
- import {
198
- assertAccountConnectionsNotAnonymous,
199
- resolveMountConnections,
200
- validateMountConnectionsConfig,
201
- } from "./resolved-connections.js";
202
- import { Router, type ServerRouteContext } from "./router.js";
203
- import { RuntimeDispatchingRunner } from "./runtime-dispatch-runner.js";
204
- import { ScheduleRunner, UnknownScheduleError } from "./schedule-runner.js";
205
- import { type AgentRunner, CursorSdkRunner } from "./sdk-runner.js";
206
- import {
207
- HTTP_CHANNEL_ID,
208
- InvalidContinuationTokenError,
209
- SessionEngine,
210
- ToolInputError,
211
- ToolNotDirectlyCallableError,
212
- UnknownToolError,
213
- WorkspaceUnavailableError,
214
- } from "./session-engine.js";
215
- import {
216
- registerSessionRunFatalFlush,
217
- selectSessionRunLogStore,
218
- unregisterSessionRunFatalFlush,
219
- } from "./session-run-log.js";
220
- import { sessionUrlsForRequest } from "./session-urls.js";
221
- import { readSkillDetail, skillListEntry, UnknownSkillError } from "./skill-catalog.js";
222
- import { flushLocalStartLog, selectStartLogStore } from "./start-log-store.js";
223
- import { catalogDetailEntry, catalogListEntry } from "./tool-catalog.js";
224
-
225
- function memoryHealthFields(engines: readonly SessionEngine[]) {
226
- return collectMemoryHealthFields({
227
- eventLog: () => sumEventLogStats(engines.map(engine => engine.eventLogMemoryStats())),
228
- });
229
- }
230
-
231
- const MAX_BODY_BYTES = 32 * 1024 * 1024;
232
-
233
- /** One agent to serve: its slug (empty for single-agent mode) and project. */
234
- export interface AgentMount {
235
- slug: string;
236
- project: AgentProject;
237
- }
238
-
239
- interface MountedRuntime {
240
- slug: string;
241
- project: AgentProject;
242
- engine: SessionEngine;
243
- scheduleRunner: ScheduleRunner;
244
- reminderRunner: ReminderRunner;
245
- controlPlane?: LocalControlPlane;
246
- /**
247
- * Hosted (or local) reminder CP client for architecture v2 descriptor
248
- * execution. Undefined when the project is not on the CP protocol.
249
- */
250
- reminderControlPlane?: ReminderControlPlane;
251
- /** Playground eval batches (`/v1/dev/evals`); loopbackUrl set after listen. */
252
- evalRuns: EvalRunStore;
253
- }
254
-
255
- function localControlPlaneRoute(
256
- runtimes: readonly MountedRuntime[],
257
- ): RouteLocalIngressContinuation | undefined {
258
- for (const runtime of runtimes) {
259
- if (runtime.controlPlane !== undefined) {
260
- return input => runtime.controlPlane!.routeContinuation(input);
261
- }
262
- }
263
- return undefined;
264
- }
265
-
266
- function firstLocalControlPlane(
267
- runtimes: readonly MountedRuntime[],
268
- ): LocalControlPlane | undefined {
269
- return runtimes.find(runtime => runtime.controlPlane !== undefined)?.controlPlane;
270
- }
271
-
272
- function isV2Project(project: { agent: { architecture?: string } }): boolean {
273
- return project.agent.architecture === "v2";
274
- }
275
-
276
- /** Internal-only options for {@link startServer} (not on public `serve`). */
277
- export interface StartServerInternalOptions {
278
- /** Test seam: replace the Cursor SDK runner (integration tests). */
279
- runner?: AgentRunner;
280
- /** Test seam: bind the `--store` secrets client for on-demand MCP OAuth. */
281
- mcpOauthSecrets?: McpOauthSecretsTarget;
282
- /** Test seam: persist hosted-execution run logs without a live store. */
283
- sessionRunLog?: ReturnType<typeof selectSessionRunLogStore>;
284
- /** Test seam: persist the engine start.log tee without a live store. */
285
- startLogStore?: ReturnType<typeof selectStartLogStore>;
286
- }
287
-
288
- /**
289
- * Start an HTTP server hosting one or more agents. A single agent with an
290
- * empty slug serves at `/v1/*` and `/playground`; multiple agents each serve
291
- * under `/<slug>/v1/*` and `/<slug>/playground`, with an index at `/`.
292
- */
293
- export async function startServer(
294
- mounts: AgentMount[],
295
- options: ServeOptions & StartServerInternalOptions = {},
296
- ): Promise<AgentServeHandle> {
297
- if (mounts.length === 0) {
298
- throw new Error("startServer requires at least one agent mount");
299
- }
300
- const multi = mounts.length > 1 || mounts[0]?.slug !== "";
301
-
302
- for (const { slug, project } of mounts) {
303
- if (hasErrorDiagnostics(project)) {
304
- const label = slug === "" ? project.name : `${slug} (${project.name})`;
305
- throw new Error(
306
- `Refusing to serve agent ${label} — it has errors:\n${formatDiagnostics(
307
- project.diagnostics.filter(d => d.severity === "error"),
308
- )}`,
309
- );
310
- }
311
- }
312
-
313
- const logRing = createLogRing({ capacity: 2000 });
314
- const logger = logRing.wrap(options.logger ?? ((line: string) => console.log(line)));
315
- const dev = options.dev ?? false;
316
- const playground = options.playground ?? true;
317
- const hosted = options as {
318
- noControlPlane?: boolean;
319
- /** `--cursor-scm-proxy`: every cursorAccount SCM pack routes via the backend forwarder. */
320
- cursorScmProxy?: boolean;
321
- };
322
- const noControlPlane = hosted.noControlPlane === true;
323
- const scmProxyRequested = hosted.cursorScmProxy === true;
324
- const runSchedules = options.schedules ?? !dev;
325
- const runReminders = options.reminders ?? !dev;
326
-
327
- // CURSOR_AGENTKIT_VERSION is still the env the SDK reads when building
328
- // its client-version header (wire prefix remains `agentkit-`). Setting it
329
- // here makes the internal-only agentkit_enabled gate apply to every turn.
330
- process.env.CURSOR_AGENTKIT_VERSION ??= packageVersion();
331
-
332
- const authoredOtel = pickAuthoredOtel(
333
- mounts.map(m => ({
334
- slug: m.slug,
335
- name: m.project.name,
336
- otel: m.project.otel,
337
- })),
338
- );
339
- const resolveOtelExport = () =>
340
- resolveOtelConfig({
341
- authored: authoredOtel,
342
- serve: options.otel,
343
- });
344
- const otelRuntime = createOtelRuntime(resolveOtelExport(), logger, {
345
- resolveExport: resolveOtelExport,
346
- });
347
-
348
- const cursorGithubTargets = collectCursorGithubTargets(mounts);
349
- const cursorOriginTargets = collectCursorOriginTargets(mounts);
350
- const cursorGithubConfig = resolveCursorGithubEventConfig({
351
- configured: options.cursorEvents,
352
- targets: cursorGithubTargets,
353
- });
354
- const cursorOriginScope = resolveCursorOriginRepoScope({
355
- explicitRepos: options.cursorEvents?.repos ?? [],
356
- targets: cursorOriginTargets,
357
- });
358
- const effectiveCursorEvents =
359
- cursorGithubConfig.cursorEvents ??
360
- (cursorOriginScope === undefined ? undefined : { repos: [...cursorOriginScope.repos] });
361
-
362
- // One resolution for every Cursor credential consumer (SDK runner, account
363
- // MCP bridge, SCM event relay, GitHub credentials): explicit option →
364
- // CURSOR_API_KEY → CURSOR_API_KEY_FILE (or the hosted default path) →
365
- // CURSOR_SERVICE_ACCOUNT_KEY → stored `agent-sdk login`. SDK / GitHub /
366
- // account MCP re-read later; Slack and deployment-event relays capture
367
- // the key at start.
368
- const accountKey = await resolveApiKey(
369
- options.apiKey === undefined ? {} : { apiKey: options.apiKey },
370
- );
371
- // First present source wins (we define the order): option → env → file →
372
- // service account → stored login. Re-read so bind can drop env or file
373
- // onto a listening process.
374
- const liveCursorApiKey = (): string | undefined =>
375
- resolveApiKeySync(options.apiKey === undefined ? {} : { apiKey: options.apiKey })?.apiKey;
376
-
377
- // The SCM relay reads the event stream as the signed-in user, so
378
- // `cursorEvents` cannot work signed out. Require the credential before any
379
- // slow or stateful startup work (playground build, channel onStart, cron).
380
- // Not on a hosted v2 guest: under `--no-control-plane` with no v1 mount
381
- // this process never polls `/v0/scm-events` (the hosted control plane
382
- // owns ingest), and a persistent slot starts before its first credential
383
- // is bound, so demanding one here would refuse a guest that never needed it.
384
- const hostedControlPlaneOwnsIngest =
385
- noControlPlane && mounts.every(mount => isV2Project(mount.project));
386
- const cursorEventsAuth =
387
- effectiveCursorEvents === undefined || hostedControlPlaneOwnsIngest
388
- ? undefined
389
- : requireCursorEventsAuth(effectiveCursorEvents, accountKey);
390
-
391
- // Two architectures + local CP + cursor-events would register two
392
- // /v0/scm-events consumers (engine offset vs control-plane offset).
393
- // Fail before engines or relays start. `--no-control-plane` mixed is one
394
- // July consumer (v1 engine); hosted CP owns v2.
395
- assertSingleCursorEventsLane({
396
- noControlPlane,
397
- config: effectiveCursorEvents,
398
- auth: cursorEventsAuth,
399
- v1Mounts: mounts.filter(mount => !isV2Project(mount.project)),
400
- v2Mounts: mounts.filter(mount => isV2Project(mount.project)),
401
- githubRepos: cursorGithubConfig.cursorEvents?.repos ?? [],
402
- originRepos: cursorOriginScope?.repos ?? [],
403
- });
404
-
405
- let cursorGithubCredentials: CursorGithubCredentialProvider | undefined;
406
- // Proxy-wired GitHub token resolver for `ctx.host.github` when no startup
407
- // token mint runs (empty repo scope): host Octokit calls must route
408
- // through github-proxy exactly like channel Octokit calls.
409
- let hostGithubProxyResolver: CursorAccountGithubTokenResolver | undefined;
410
- if (cursorGithubTargets.length > 0) {
411
- const githubProxyRequested = scmProxyRequested;
412
- const needsGithubAuth = cursorGithubConfig.scope !== undefined || githubProxyRequested;
413
- if (needsGithubAuth) {
414
- const currentGithubApiKey = (): string | undefined => {
415
- const fromEvents = cursorEventsAuth?.apiKey.trim();
416
- if (fromEvents !== undefined && fromEvents !== "") {
417
- return fromEvents;
418
- }
419
- return liveCursorApiKey();
420
- };
421
- const githubApiKeyNow = currentGithubApiKey();
422
- if (githubApiKeyNow === undefined && options.allowAnonymous !== true) {
423
- throw new Error(
424
- "githubChannel({ cursorAccount: true }) could not resolve Cursor event authentication.",
425
- );
426
- }
427
- if (options.allowAnonymous === true) {
428
- if (options.allowAnonymousCursorGithub !== true) {
429
- throw new Error(
430
- "githubChannel({ cursorAccount: true }) cannot be served with --allow-anonymous because admitted callers could use the signed-in account's GitHub access. If every admitted caller is trusted (e.g. behind an SSO proxy), opt in with --allow-anonymous-cursor-github.",
431
- );
432
- }
433
- logger(
434
- "[agent-sdk] warning: --allow-anonymous-cursor-github — every admitted HTTP caller can drive sessions holding the signed-in account's repo-scoped GitHub credential; serve this only behind a trusted boundary (e.g. an SSO proxy)",
435
- );
436
- if (githubApiKeyNow === undefined) {
437
- logger(
438
- "[agent-sdk] GitHub auth: listening unsigned; credentials bind at task via CURSOR_API_KEY or CURSOR_API_KEY_FILE",
439
- );
440
- }
441
- }
442
- if (cursorGithubConfig.permissions === "contents-write") {
443
- logger(
444
- '[agent-sdk] warning: Cursor GitHub credentials include contents:write — the host holds a push-capable token shared with model-driven tools and untrusted webhook content; prefer permissions: "pr-write" unless this agent must push code',
445
- );
446
- }
447
- const githubAuthBaseUrl = cursorExternalApiUrl();
448
- const requireGithubApiKey = async (): Promise<string> => {
449
- const apiKey = currentGithubApiKey();
450
- if (apiKey === undefined) {
451
- throw new Error(
452
- `githubChannel({ cursorAccount: true }) has no Cursor credential yet. ${SIGN_IN_HINT}`,
453
- );
454
- }
455
- return apiKey;
456
- };
457
- const githubProxyUrl = githubProxyRequested
458
- ? resolveCursorGithubProxyUrl(githubAuthBaseUrl)
459
- : undefined;
460
- if (cursorGithubConfig.scope !== undefined && githubApiKeyNow !== undefined) {
461
- const provider = new CursorGithubCredentialProvider({
462
- client: new CursorBackendClient({
463
- backendUrl: githubAuthBaseUrl,
464
- apiKey: githubApiKeyNow,
465
- getApiKey: () => currentGithubApiKey() ?? "",
466
- logger,
467
- }),
468
- scope: cursorGithubConfig.scope,
469
- logger,
470
- });
471
- cursorGithubCredentials = provider;
472
- if (githubProxyUrl !== undefined) {
473
- // Proxy mode: channel Octokit calls carry the Cursor API key to the
474
- // backend forwarder, which swaps in the installation token server-side
475
- // and logs every call with per-deployment attribution. The provider
476
- // still runs so child `gh` processes get a `GH_TOKEN` lease (v1).
477
- const proxyTransport = {
478
- apiBaseUrl: githubProxyUrl,
479
- headers: {
480
- "x-cursor-github-repos": cursorGithubConfig.scope.repos.join(","),
481
- "x-cursor-github-permissions": cursorGithubConfig.permissions,
482
- },
483
- };
484
- for (const target of cursorGithubTargets) {
485
- target.accountRuntime.credentials.bind(requireGithubApiKey);
486
- target.accountRuntime.credentials.bindProxyTransport(proxyTransport);
487
- }
488
- logger(`[agent-sdk] GitHub auth: channel API calls route through ${githubProxyUrl}`);
489
- } else {
490
- for (const target of cursorGithubTargets) {
491
- target.accountRuntime.credentials.bind(() => provider.getToken());
492
- }
493
- }
494
- } else if (githubProxyUrl !== undefined) {
495
- // `cursorAccount: true` with no `--repo`: skip the startup token mint
496
- // (it requires a repo list) and let github-proxy take the repo from
497
- // each Octokit call. Hosted freeze bakes this flag into the template
498
- // so restore is GitHub-ready once Bind drops the key.
499
- const proxyTransport = {
500
- apiBaseUrl: githubProxyUrl,
501
- headers: {
502
- "x-cursor-github-permissions": cursorGithubConfig.permissions,
503
- },
504
- };
505
- for (const target of cursorGithubTargets) {
506
- target.accountRuntime.credentials.bind(requireGithubApiKey);
507
- target.accountRuntime.credentials.bindProxyTransport(proxyTransport);
508
- }
509
- // `ctx.host.github` gets the same proxy transport; without this it
510
- // would fall back to ambient auth (env token / `gh`) or an
511
- // unauthenticated Octokit, and every host GitHub call would 404.
512
- hostGithubProxyResolver = createCursorGithubProxyHostResolver({
513
- getApiKey: requireGithubApiKey,
514
- transport: proxyTransport,
515
- });
516
- logger(
517
- `[agent-sdk] GitHub auth: channel and host API calls route through ${githubProxyUrl} (repo scope per request)`,
518
- );
519
- }
520
- }
521
- }
522
- // GitLab `cursorAccount` channels: `ctx.gitlab` routes through the SCM
523
- // proxy in proxy mode. Without `--cursor-scm-proxy` the runtime stays
524
- // unbound and the handle falls back to direct `GITLAB_TOKEN` access.
525
- if (scmProxyRequested) {
526
- const gitlabProxyUrl = resolveCursorGitLabProxyUrl(cursorExternalApiUrl());
527
- let gitlabTargets = 0;
528
- for (const mount of mounts) {
529
- for (const channel of mount.project.channels) {
530
- const runtime = getGitLabCursorAccountRuntime(channel.definition);
531
- if (runtime === undefined) {
532
- continue;
533
- }
534
- gitlabTargets += 1;
535
- const transport: Omit<GitLabProxyTransport, "getApiKey"> = {
536
- apiBaseUrl: gitlabProxyUrl,
537
- ...(runtime.scope === undefined
538
- ? {}
539
- : {
540
- headers: {
541
- [CURSOR_GITLAB_PROJECTS_HEADER]: runtime.scope.projects.join(","),
542
- },
543
- }),
544
- };
545
- runtime.credentials.bind(async () => {
546
- const apiKey = liveCursorApiKey();
547
- if (apiKey === undefined) {
548
- throw new Error(
549
- `gitlabChannel({ cursorAccount }) has no Cursor credential yet. ${SIGN_IN_HINT}`,
550
- );
551
- }
552
- return apiKey;
553
- });
554
- runtime.credentials.bindProxyTransport(transport);
555
- }
556
- }
557
- if (gitlabTargets > 0) {
558
- logger(`[agent-sdk] GitLab auth: channel API calls route through ${gitlabProxyUrl}`);
559
- }
560
- // Bitbucket `cursorAccount` channels: same shape, `/v0/bitbucket-proxy`
561
- // with `x-cursor-bitbucket-repos` scope. The proxy picks Cloud 2.0 or
562
- // the DC host's 1.0 upstream per tenant; the pack picks the dialect
563
- // from the delivery payload.
564
- const bitbucketProxyUrl = resolveCursorBitbucketProxyUrl(cursorExternalApiUrl());
565
- let bitbucketTargets = 0;
566
- for (const mount of mounts) {
567
- for (const channel of mount.project.channels) {
568
- const runtime = getBitbucketCursorAccountRuntime(channel.definition);
569
- if (runtime === undefined) {
570
- continue;
571
- }
572
- bitbucketTargets += 1;
573
- const transport: Omit<BitbucketProxyTransport, "getApiKey"> = {
574
- apiBaseUrl: bitbucketProxyUrl,
575
- ...(runtime.scope === undefined
576
- ? {}
577
- : {
578
- headers: {
579
- [CURSOR_BITBUCKET_REPOS_HEADER]: runtime.scope.repos.join(","),
580
- },
581
- }),
582
- };
583
- runtime.credentials.bind(async () => {
584
- const apiKey = liveCursorApiKey();
585
- if (apiKey === undefined) {
586
- throw new Error(
587
- `bitbucketChannel({ cursorAccount }) has no Cursor credential yet. ${SIGN_IN_HINT}`,
588
- );
589
- }
590
- return apiKey;
591
- });
592
- runtime.credentials.bindProxyTransport(transport);
593
- }
594
- }
595
- if (bitbucketTargets > 0) {
596
- logger(`[agent-sdk] Bitbucket auth: channel API calls route through ${bitbucketProxyUrl}`);
597
- }
598
- }
599
- const resolvedCursorGithubCredentials = cursorGithubCredentials;
600
- const hostGithubToken =
601
- hostGithubProxyResolver ??
602
- (resolvedCursorGithubCredentials === undefined
603
- ? undefined
604
- : createCursorAccountGithubTokenResolver(() => resolvedCursorGithubCredentials.getToken()));
605
- const hostPlatforms = createHostPlatforms(
606
- hostGithubToken === undefined ? {} : { githubCredentials: { token: hostGithubToken } },
607
- );
608
-
609
- if (playground) {
610
- // Auto-build dist/playground when missing (monorepo / source checkout).
611
- // Published installs already ship the bundle; vite may be absent there.
612
- await ensurePlaygroundBundle(logger);
613
- }
614
- const docsSite = options.docs ?? true;
615
- if (docsSite) {
616
- // Same pattern for the documentation site at /docs.
617
- await ensureDocsSiteBundle(logger);
618
- }
619
- if (options.allowAnonymous === true) {
620
- logger(
621
- "[agent-sdk] warning: --allow-anonymous admits every HTTP caller as the same principal; use only on a trusted network (e.g. Tailscale) and prefer --bearer-token for shared hosts",
622
- );
623
- }
624
- // v2 hosted engines mirror the SDK conversation store to the deployment's
625
- // shared file storage so a fresh pod resumes threads instead of forking
626
- // them. Hosted serve is single-agent; a multi-mount serve (dev) has no
627
- // single agent name to mint keys under and does not mirror.
628
- const conversationMirror =
629
- mounts.length === 1 && mounts[0] !== undefined
630
- ? selectConversationMirror({ project: mounts[0].project, logger })
631
- : undefined;
632
- const sessionRunLog =
633
- options.sessionRunLog ??
634
- (mounts.length === 1 && mounts[0] !== undefined
635
- ? selectSessionRunLogStore({
636
- project: mounts[0].project,
637
- logger,
638
- snapshotLogs: () => logRing.since(),
639
- })
640
- : undefined);
641
- const startLogStore =
642
- options.startLogStore ??
643
- (mounts.length === 1 && mounts[0] !== undefined
644
- ? selectStartLogStore({
645
- project: mounts[0].project,
646
- logger,
647
- })
648
- : undefined);
649
- // The running claim stamps this before the turn; process-death flush
650
- // reuses it so the tee snapshot lands under the same ses_ key.
651
- let lastStartLogId: string | undefined;
652
- const flushStartLog = async (startLogId: string): Promise<void> => {
653
- lastStartLogId = startLogId;
654
- if (startLogStore === undefined) {
655
- return;
656
- }
657
- await flushLocalStartLog({ store: startLogStore, startLogId });
658
- };
659
- if (sessionRunLog !== undefined) {
660
- registerSessionRunFatalFlush(async error => {
661
- await flushHostedExecutionProcessDeath({
662
- flushProcessDeath: (reason, flushError) =>
663
- sessionRunLog.flushProcessDeath(reason, flushError),
664
- flushStartLog,
665
- startLogId: lastStartLogId,
666
- reason: "uncaught_exception",
667
- error,
668
- });
669
- });
670
- }
671
- const sdkRunner =
672
- options.runner ??
673
- new CursorSdkRunner({
674
- ...(options.apiKey === undefined || options.apiKey.trim() === ""
675
- ? {}
676
- : { apiKey: options.apiKey }),
677
- ...(conversationMirror === undefined ? {} : { conversationMirror }),
678
- logger,
679
- });
680
- // Grok Bot turns run on Cursor's hosted Grok Bot (Sand) harness through
681
- // the /v0/grokbot session API; the SDK side is a thin remote client. The
682
- // dispatching runner is only interposed when a mount needs it. An
683
- // injected test runner receives every turn, grokbot included.
684
- const hasGrokBotMounts = mounts.some(mount => mount.project.agent.runtime === "grokbot");
685
- // Fail closed like cursor-account GitHub/MCP: grokbot turns execute on the
686
- // signed-in account's hosted computer, so anonymous admission needs its
687
- // own opt-in.
688
- if (hasGrokBotMounts && options.allowAnonymous === true) {
689
- if (options.allowAnonymousGrokbot !== true) {
690
- throw new Error(
691
- 'runtime: "grokbot" cannot be served with --allow-anonymous because admitted callers could drive the signed-in account\'s hosted Grok Bot computer. If every admitted caller is trusted (e.g. behind an SSO proxy), opt in with --allow-anonymous-grokbot.',
692
- );
693
- }
694
- logger(
695
- "[agent-sdk] warning: --allow-anonymous-grokbot — every admitted HTTP caller can drive turns on the signed-in account's hosted Grok Bot computer; serve this only behind a trusted boundary (e.g. an SSO proxy)",
696
- );
697
- }
698
- let runner: AgentRunner = sdkRunner;
699
- if (hasGrokBotMounts && options.runner === undefined) {
700
- // Cursor-internal client, left out of the npm tarball (`files`); loaded
701
- // only when a mount needs it, so a published install fails here, before
702
- // listen, rather than on the first turn.
703
- const { GrokBotRunner } = await import("./grokbot/runner.js").catch(() => {
704
- throw new Error('runtime: "grokbot" is not available in the published @cursor/bdk package');
705
- });
706
- runner = new RuntimeDispatchingRunner({
707
- sdkRunner,
708
- grokbot: new GrokBotRunner({
709
- apiKey: options.apiKey,
710
- // `/v0/grokbot` lives on the external API (api.cursor.com), not
711
- // api2. Prefer that default over the account key's backendUrl.
712
- // Do not pass stored login as apiKey: that would pin it as an
713
- // option and beat a later CURSOR_API_KEY_FILE bind.
714
- backendUrl: cursorExternalApiUrl(),
715
- }),
716
- });
717
- logger("[agent-sdk] grokbot runtime: remote client (turns run on the hosted Grok Bot harness)");
718
- }
719
-
720
- const router = new Router();
721
- const runtimes: MountedRuntime[] = [];
722
- const channelStopHooks: Array<() => void | Promise<void>> = [];
723
- let githubAuthWarmed = false;
724
-
725
- // Validate peer MCP connections (defineConnection({ agent })) against the
726
- // mount set before anything starts: unknown slugs and self-references are
727
- // authoring errors. URLs resolve after listen, once the port is known.
728
- const peerRefsBySlug = collectPeerConnections(mounts);
729
-
730
- // Cursor account MCP connections (defineConnection({ cursorAccount: true }))
731
- // need a signed-in host: their tools execute on the Cursor backend with
732
- // the account's stored OAuth credentials. Fail fast at serve start instead
733
- // of at the first turn.
734
- const accountRefsBySlug = collectCursorAccountConnections(mounts);
735
- assertAccountConnectionsNotAnonymous({
736
- allowAnonymous: options.allowAnonymous,
737
- allowAnonymousCursorAccountMcp: options.allowAnonymousCursorAccountMcp,
738
- hasAccountConnections: accountRefsBySlug.size > 0,
739
- });
740
- if (
741
- options.allowAnonymous === true &&
742
- options.allowAnonymousCursorAccountMcp === true &&
743
- accountRefsBySlug.size > 0
744
- ) {
745
- logger(
746
- "[agent-sdk] warning: --allow-anonymous-cursor-account-mcp — every admitted HTTP caller can drive Cursor account MCP connectors; serve this only behind a trusted boundary (e.g. an SSO proxy or hosted alias token)",
747
- );
748
- }
749
- let accountBridge: CursorAccountMcpBridge | undefined;
750
- if (accountRefsBySlug.size > 0) {
751
- if (accountKey === undefined && options.allowAnonymous !== true) {
752
- throw new Error(
753
- `This project has Cursor account MCP connections (defineConnection({ cursorAccount: true })) but the host is not signed in to Cursor. ${SIGN_IN_HINT}`,
754
- );
755
- }
756
- if (accountKey === undefined) {
757
- logger(
758
- "[agent-sdk] Cursor account MCP: listening unsigned; credentials bind at task via CURSOR_API_KEY or CURSOR_API_KEY_FILE",
759
- );
760
- }
761
- accountBridge = new CursorAccountMcpBridge({
762
- client: new CursorBackendClient({
763
- backendUrl: accountKey?.backendUrl ?? cursorBackendUrl(),
764
- apiKey: accountKey?.apiKey ?? "",
765
- getApiKey: () => liveCursorApiKey() ?? "",
766
- logger,
767
- }),
768
- logger,
769
- // Cloud turns reach the bridge through the serve publicUrl; without
770
- // one, the bridge admits loopback callers only.
771
- allowRemoteCallers: options.publicUrl !== undefined,
772
- });
773
- }
774
-
775
- for (const { slug, project } of mounts) {
776
- // Each agent gets an isolated state root so their sessions never mix.
777
- const baseStateRoot = options.stateRoot ?? join(project.rootDir, ".agent-serve");
778
- const stateRoot = slug === "" ? baseStateRoot : join(baseStateRoot, slug);
779
- const otelCollector: OtelCollector | undefined =
780
- otelRuntime === undefined
781
- ? undefined
782
- : createOtelCollector(otelRuntime, project.name, logger);
783
- const engine = new SessionEngine({
784
- project,
785
- stateRoot,
786
- runner,
787
- logger,
788
- platforms: hostPlatforms,
789
- otel: otelCollector,
790
- otelMeter: otelRuntime?.meter,
791
- });
792
- engine.oauthCallbackHub.secrets = options.mcpOauthSecrets;
793
- engine.oauthCallbackHub.secretsBind = {
794
- slug: slug === "" ? undefined : slug,
795
- cloudToolsUrl: options.cloudToolsUrl,
796
- };
797
- engine.oauthCallbackHub.logger = logger;
798
- // Rehydrate sessions from the authored storage sink before any
799
- // channel or route can address them (continuation tokens must resolve).
800
- await engine.restoreStoredSessions();
801
-
802
- // Resolve a shared harness workspace in the background: on a large repo
803
- // that takes seconds, and a deployment coming online should absorb it
804
- // rather than whoever sends the first message. No-op unless the agent
805
- // pins `local.workspaceDir`.
806
- void engine.prewarmSharedWorkspace();
807
-
808
- if (!githubAuthWarmed) {
809
- // Soft ambient GitHub auth check before channel onStart (which may call
810
- // host.github). Missing auth is a warning only — serve still starts.
811
- await warmupHostGitHubAuth({
812
- logger,
813
- github: engine.host.github,
814
- ...(cursorGithubCredentials === undefined ? {} : { authSource: "cursor-account" }),
815
- });
816
- githubAuthWarmed = true;
817
- }
818
- const scheduleRunner = new ScheduleRunner(engine, project, logger);
819
- let reminderRunner!: ReminderRunner;
820
- const architecture = project.agent.architecture;
821
- const useReminderCpProtocol = architecture === "v2";
822
- const localControlPlane = noControlPlane
823
- ? undefined
824
- : await createLocalControlPlane({
825
- fireSchedule: name => scheduleRunner.dispatch(name),
826
- ...(useReminderCpProtocol
827
- ? {
828
- executeReminder: descriptor => reminderRunner.executeFire(descriptor),
829
- }
830
- : {
831
- fireReminder: (id, fireCount) =>
832
- reminderRunner.dispatch(id, {
833
- expectedFireCount: fireCount,
834
- }),
835
- }),
836
- stateDir: join(stateRoot, "control-plane"),
837
- armReminderClocks: runReminders,
838
- logger,
839
- });
840
- const timerClient = noControlPlane ? createCursorHostedPlatformTimers() : localControlPlane;
841
- const hostedReminderControlPlane =
842
- noControlPlane && useReminderCpProtocol
843
- ? createCursorHostedReminderControlPlane()
844
- : undefined;
845
- const reminderControlPlane = useReminderCpProtocol
846
- ? (localControlPlane ?? hostedReminderControlPlane)
847
- : undefined;
848
- reminderRunner = new ReminderRunner(engine, logger, timerClient, {
849
- namedHandlers: project.reminders ?? [],
850
- // Architecture v2 rejects anonymous run/until everywhere (local + hosted).
851
- rejectAnonymousHandlers: rejectAnonymousReminderHandlers({
852
- noControlPlane,
853
- architecture,
854
- }),
855
- architecture,
856
- controlPlane: reminderControlPlane,
857
- // Hosted admissions build their channel args with no request
858
- // principal (`buildChannelHandlerArgs` → `auth: null`), so a fire that
859
- // opens a session on a fresh pod uses the same one and a session
860
- // restored from durable storage still matches.
861
- hostedGuest: hostedReminderControlPlane === undefined ? undefined : { fireAuth: () => null },
862
- });
863
- const evalRuns = new EvalRunStore(
864
- project.rootDir,
865
- logger,
866
- // Playground eval history mirrors onto the defineStorage evals table.
867
- engine.storage?.evalRuns(),
868
- );
869
- // Eval history restores with the same startup step as sessions (reads
870
- // also hydrate lazily, but doing it here surfaces store problems at
871
- // boot and makes /v1/dev/evals complete from the first request).
872
- await evalRuns.hydrate();
873
- engine.setReminders({
874
- create: input => reminderRunner.create(input),
875
- list: filter => reminderRunner.list(filter),
876
- cancel: (id, reason) => reminderRunner.cancel(id, reason),
877
- cancelForContinuation: (token, reason) => reminderRunner.cancelForContinuation(token, reason),
878
- rekeyContinuation: (channelId, oldToken, newToken) =>
879
- reminderRunner.rekeyContinuation(channelId, oldToken, newToken),
880
- dispatch: id => reminderRunner.dispatch(id),
881
- });
882
- engine.setEvals({
883
- list: () => evalRuns.list(),
884
- get: runId => evalRuns.get(runId),
885
- listRunsWithActive: () => evalRuns.listRunsWithActive(),
886
- start: input => evalRuns.start(input),
887
- cancel: runId => evalRuns.cancel(runId),
888
- });
889
- const runtime: MountedRuntime = {
890
- slug,
891
- project,
892
- engine,
893
- scheduleRunner,
894
- reminderRunner,
895
- evalRuns,
896
- ...(localControlPlane === undefined ? {} : { controlPlane: localControlPlane }),
897
- ...(reminderControlPlane === undefined ? {} : { reminderControlPlane }),
898
- };
899
- runtimes.push(runtime);
900
- const accountRefs = accountRefsBySlug.get(slug);
901
- mountAgentRoutes(router, runtime, {
902
- dev,
903
- playground,
904
- noControlPlane,
905
- multi,
906
- logger,
907
- logRing,
908
- diagStateRoot: baseStateRoot,
909
- sessionRunLog,
910
- flushStartLog,
911
- flushOtel: () => forceFlushOtelRuntime(otelRuntime),
912
- ...(options.authToken === undefined ? {} : { authToken: options.authToken }),
913
- ...(options.allowAnonymous === true ? { allowAnonymous: true } : {}),
914
- ...(accountRefs !== undefined && accountBridge !== undefined
915
- ? { accountBridge, accountRefs }
916
- : {}),
917
- ...(sdkRunner instanceof CursorSdkRunner
918
- ? {
919
- evictSdkSession: (sessionId: string) => {
920
- sdkRunner.evictSession(sessionId);
921
- },
922
- }
923
- : {}),
924
- });
925
- for (const channel of project.channels) {
926
- const definition = channel.definition;
927
- if (definition.onStop !== undefined) {
928
- channelStopHooks.push(() => definition.onStop?.());
929
- }
930
- if (definition.onStart !== undefined) {
931
- const startArgs: ChannelStartArgs = {
932
- send: (message, sendOptions) => engine.send(channel.id, message, sendOptions),
933
- architecture: project.agent.architecture,
934
- getSession: sessionId => engine.getChannelSession(channel.id, sessionId),
935
- receive: (target, input) => engine.receive(target, input),
936
- callTool: (toolName, input, callOptions) => engine.callTool(toolName, input, callOptions),
937
- emitAssistantMessage: (sessionId, text) => engine.emitAssistantMessage(sessionId, text),
938
- host: engine.host,
939
- waitUntil: promise => {
940
- engine.trackBackground(promise);
941
- },
942
- resolveApproval: (sessionId, callId, decision, auth) =>
943
- engine.resolveApproval(sessionId, callId, decision, auth),
944
- resolveAuth: (sessionId, callId, decision, auth) =>
945
- engine.resolveAuth(sessionId, callId, decision, auth),
946
- hasContinuationSession: continuationToken =>
947
- engine.hasContinuationSession(channel.id, continuationToken),
948
- isContinuationBusy: continuationToken =>
949
- engine.isContinuationBusy(channel.id, continuationToken),
950
- getContinuationLastBotMessageTs: continuationToken =>
951
- engine.getContinuationLastBotMessageTs(channel.id, continuationToken),
952
- interruptContinuation: continuationToken =>
953
- engine.interruptContinuation(channel.id, continuationToken),
954
- logger,
955
- artifacts: engine.artifacts,
956
- };
957
- try {
958
- await definition.onStart(startArgs);
959
- } catch (error) {
960
- logger(
961
- `[agent-sdk] channel "${channel.id}" onStart failed: ${
962
- error instanceof Error ? (error.stack ?? error.message) : String(error)
963
- }`,
964
- );
965
- }
966
- }
967
- }
968
- if (timerClient !== undefined && runSchedules) {
969
- await syncHostedPlatformSchedules({
970
- timers: timerClient,
971
- schedules: project.schedules,
972
- catalogPath: join(stateRoot, PLATFORM_SCHEDULE_CATALOG_FILENAME),
973
- logger,
974
- });
975
- }
976
- if (timerClient !== undefined) {
977
- await reminderRunner.hydrate();
978
- }
979
- localControlPlane?.startClocks();
980
- }
981
-
982
- if (docsSite) {
983
- // The framework documentation site, mounted at /docs in both layouts
984
- // ("docs" is a reserved slug). Static, no secrets; unauthenticated like
985
- // the playground assets.
986
- router.add({
987
- method: "GET",
988
- pattern: "/docs",
989
- auth: "none",
990
- handler: () => renderDocsFile(""),
991
- });
992
- router.add({
993
- method: "GET",
994
- pattern: "/docs/*path",
995
- auth: "none",
996
- handler: (_request, ctx) => renderDocsFile(ctx.params.path ?? ""),
997
- });
998
- }
999
-
1000
- if (multi) {
1001
- // Host-level liveness for ALB / ECS health checks. Per-agent health stays
1002
- // at `/<slug>/v1/health`; without this, multi-mode has no `/v1/health`.
1003
- router.add({
1004
- method: "GET",
1005
- pattern: "/v1/health",
1006
- auth: "none",
1007
- handler: () =>
1008
- jsonResponse({
1009
- ok: true,
1010
- agents: runtimes.map(({ slug, project }) => ({
1011
- slug,
1012
- name: project.name,
1013
- })),
1014
- ...memoryHealthFields(runtimes.map(runtime => runtime.engine)),
1015
- }),
1016
- });
1017
- }
1018
-
1019
- // Orienting `/` for every layout (single empty-slug and multi).
1020
- // Lists playground links plus live routes (playground, health, docs).
1021
- if (playground) {
1022
- const entries = buildAgentIndexEntries(runtimes);
1023
- const indexHtml = renderAgentsIndexHtml(entries, {
1024
- docs: docsSite,
1025
- multi,
1026
- });
1027
- router.add({
1028
- method: "GET",
1029
- pattern: "/",
1030
- auth: "none",
1031
- handler: () =>
1032
- new Response(indexHtml, {
1033
- headers: { "content-type": "text/html; charset=utf-8" },
1034
- }),
1035
- });
1036
- if (multi) {
1037
- router.add({
1038
- method: "GET",
1039
- pattern: "/v1/agents",
1040
- auth: "none",
1041
- handler: () => jsonResponse({ agents: entries }),
1042
- });
1043
- }
1044
- }
1045
-
1046
- // Shared GitHub webhook ingress: one URL fans out to every mounted agent
1047
- // that declared a github channel. Signature verification is the caller's
1048
- // job (backend `/github_webhook` already verified); we only admit loopback
1049
- // so this route is not a public unsigned endpoint. Agents decide whether
1050
- // to run via their onPullRequest / onComment / … hooks.
1051
- const collectGitHubTargetsFrom = (selected: readonly MountedRuntime[]) =>
1052
- collectGitHubTriggerTargets({
1053
- mounts: selected.map(runtime => ({
1054
- slug: runtime.slug,
1055
- channels: runtime.project.channels,
1056
- buildHandlerArgs: channelId => buildChannelHandlerArgs({ runtime, channelId }),
1057
- })),
1058
- });
1059
- const collectOriginTargetsFrom = (selected: readonly MountedRuntime[]) =>
1060
- collectOriginTriggerTargets({
1061
- mounts: selected.map(runtime => ({
1062
- slug: runtime.slug,
1063
- channels: runtime.project.channels,
1064
- buildHandlerArgs: channelId => buildChannelHandlerArgs({ runtime, channelId }),
1065
- })),
1066
- });
1067
- const collectGitHubTargets = () => collectGitHubTargetsFrom(runtimes);
1068
- const v1Runtimes = runtimes.filter(runtime => !isV2Project(runtime.project));
1069
- const v2Runtimes = runtimes.filter(runtime => isV2Project(runtime.project));
1070
- const v1Mounts = mounts.filter(mount => !isV2Project(mount.project));
1071
- const v2Mounts = mounts.filter(mount => isV2Project(mount.project));
1072
- router.add({
1073
- method: "POST",
1074
- pattern: "/v1/webhooks/github",
1075
- auth: [localDevStrict()],
1076
- handler: async request => {
1077
- const bodyText = await request.text();
1078
- const routeContinuation = localControlPlaneRoute(runtimes);
1079
- const result = await handleAgentServeTrigger({
1080
- type: "github",
1081
- bodyText,
1082
- eventName: request.headers.get("x-github-event"),
1083
- deliveryId: request.headers.get("x-github-delivery") ?? undefined,
1084
- targets: collectGitHubTargets(),
1085
- ...(routeContinuation === undefined ? {} : { routeContinuation }),
1086
- });
1087
- const status = result.ok ? 202 : (result.targets[0]?.status ?? 500);
1088
- return jsonResponse(result, { status });
1089
- },
1090
- });
1091
-
1092
- for (const { slug, project } of mounts) {
1093
- validateMountConnectionsConfig({
1094
- slug,
1095
- project,
1096
- accountRefs: accountRefsBySlug.get(slug),
1097
- ...(options.publicUrl === undefined ? {} : { publicUrl: options.publicUrl }),
1098
- cloudToolsBridge: options.cloudToolsUrl !== undefined,
1099
- });
1100
- }
1101
-
1102
- await cursorGithubCredentials?.start();
1103
-
1104
- // Cursor SCM events: v1 stays on the engine poll. v2 ingest is local-CP
1105
- // only — hosted `--no-control-plane` skips the July poll (hosted CP wakes).
1106
- const routeContinuation = localControlPlaneRoute(runtimes);
1107
- const cursorEventsCommon = {
1108
- config: effectiveCursorEvents,
1109
- githubRepos: cursorGithubConfig.cursorEvents?.repos ?? [],
1110
- originRepos: cursorOriginScope?.repos ?? [],
1111
- stateRoot: options.stateRoot,
1112
- auth: cursorEventsAuth,
1113
- logger,
1114
- cursorAccountOnly:
1115
- options.cursorEvents === undefined &&
1116
- (cursorGithubTargets.length > 0 || cursorOriginTargets.length > 0),
1117
- };
1118
- const cursorEventRelay = startCursorEventRelay({
1119
- ...cursorEventsCommon,
1120
- mounts: v1Mounts,
1121
- collectGitHubTargets: () => collectGitHubTargetsFrom(v1Runtimes),
1122
- collectOriginTargets: () => collectOriginTargetsFrom(v1Runtimes),
1123
- lane: "engine",
1124
- skippedV2: v2Mounts.length > 0,
1125
- });
1126
- const controlPlaneScmRelay = startCursorEventRelay({
1127
- ...cursorEventsCommon,
1128
- mounts: v2Mounts,
1129
- collectGitHubTargets: () => collectGitHubTargetsFrom(v2Runtimes),
1130
- collectOriginTargets: () => collectOriginTargetsFrom(v2Runtimes),
1131
- ...(routeContinuation === undefined ? {} : { routeContinuation }),
1132
- lane: "control-plane",
1133
- start: false,
1134
- stateDirName: join("control-plane", "cursor-events"),
1135
- });
1136
- const localCp = firstLocalControlPlane(runtimes);
1137
- if (controlPlaneScmRelay !== undefined) {
1138
- if (localCp !== undefined) {
1139
- localCp.attachScmEvents(controlPlaneScmRelay);
1140
- } else {
1141
- logger(
1142
- "[agent-sdk] cursor-events: skipping v2 scm-events poll (--no-control-plane); hosted CP owns ingest",
1143
- );
1144
- }
1145
- } else if (hostedControlPlaneOwnsIngest && effectiveCursorEvents !== undefined) {
1146
- // No credential was required above, so no relay object was built; the
1147
- // outcome is the same skip.
1148
- logger(
1149
- "[agent-sdk] cursor-events: skipping v2 scm-events poll (--no-control-plane); hosted CP owns ingest",
1150
- );
1151
- }
1152
-
1153
- // Cursor deployment-events relay: automatic when a mounted agent authored
1154
- // `deploymentsChannel({ ... })`.
1155
- const cursorDeploymentRelay = startCursorDeploymentRelay({
1156
- options,
1157
- runtimes,
1158
- accountKey,
1159
- logger,
1160
- });
1161
-
1162
- // Trust --public-url's host when a reverse proxy rewrites Host.
1163
- const browserOriginGuard = browserOriginGuardOptionsForPublicUrl(options.publicUrl);
1164
- const server = createServer((req, res) => {
1165
- void instrumentHttp(otelRuntime, req, res, () =>
1166
- handleRequest(router, req, res, logger, browserOriginGuard),
1167
- );
1168
- });
1169
-
1170
- const host = options.host ?? "127.0.0.1";
1171
- const portWasExplicit = options.port !== undefined;
1172
- const requestedPort = options.port ?? DEFAULT_SERVE_PORT;
1173
- let boundPort: number;
1174
- try {
1175
- boundPort = await listenHttpServer({
1176
- server,
1177
- host,
1178
- port: requestedPort,
1179
- portWasExplicit,
1180
- logger,
1181
- });
1182
- } catch (error) {
1183
- await cursorDeploymentRelay?.stop();
1184
- await cursorEventRelay?.stop();
1185
- await controlPlaneScmRelay?.stop();
1186
- cursorGithubCredentials?.stop();
1187
- await shutdownOtelRuntime(otelRuntime);
1188
- throw error;
1189
- }
1190
- const address = server.address() as AddressInfo;
1191
- const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
1192
- const url = `http://${displayHost}:${boundPort}`;
1193
- const oauthOrigin = (options.publicUrl ?? url).replace(/\/$/, "");
1194
-
1195
- // Resolve peer + Cursor account MCP connections now that the listen port is
1196
- // known (see resolved-connections.ts for the URL/runtime rules).
1197
- for (const runtime of runtimes) {
1198
- const peerRefs = peerRefsBySlug.get(runtime.slug);
1199
- const accountRefs = accountRefsBySlug.get(runtime.slug);
1200
- const resolved = resolveMountConnections({
1201
- slug: runtime.slug,
1202
- project: runtime.project,
1203
- serverUrl: url,
1204
- ...(peerRefs === undefined ? {} : { peerRefs }),
1205
- ...(accountRefs !== undefined && accountBridge !== undefined
1206
- ? { accountRefs, accountBridge }
1207
- : {}),
1208
- ...(options.publicUrl === undefined ? {} : { publicUrl: options.publicUrl }),
1209
- ...(options.authToken === undefined ? {} : { authToken: options.authToken }),
1210
- cloudToolsBridge: options.cloudToolsUrl !== undefined,
1211
- logger,
1212
- });
1213
- if (resolved.length > 0) {
1214
- runtime.engine.setResolvedConnections(resolved);
1215
- }
1216
- const oauthBase = runtime.slug === "" ? "" : `/${runtime.slug}`;
1217
- runtime.engine.setMcpOauthCallbackUrl(mcpOauthServeCallbackUrl(oauthOrigin, oauthBase));
1218
- if (accountBridge !== undefined && accountRefs !== undefined) {
1219
- const bridge = accountBridge;
1220
- runtime.engine.setCursorAccountAuthProbe(async connection => {
1221
- const ref = accountRefs.find(entry => entry.name === connection);
1222
- if (ref === undefined) {
1223
- return undefined;
1224
- }
1225
- return await bridge.probeAuthUrl(ref);
1226
- });
1227
- }
1228
- const hasServerTools = runtime.project.agent.tools.some(tool => tool.execution === "server");
1229
- // Host-bridged connections ride the same endpoint as server tools, so
1230
- // the cloud tools connection is set whenever either needs it.
1231
- const bridgeableNames = runtime.engine.cloudBridgeableConnectionNames();
1232
- const cloudCapable =
1233
- runtime.project.agent.runtime === "cloud" || runtime.project.agent.cloud !== undefined;
1234
- if ((hasServerTools || bridgeableNames.length > 0) && cloudCapable) {
1235
- const basePath = runtime.slug === "" ? "" : `/${runtime.slug}`;
1236
- const publicToolsUrl =
1237
- options.cloudToolsUrl ??
1238
- (options.publicUrl === undefined
1239
- ? undefined
1240
- : `${options.publicUrl.replace(/\/$/, "")}${basePath}${TOOL_MCP_ENDPOINT_PATH}`);
1241
- if (publicToolsUrl === undefined) {
1242
- if (hasServerTools) {
1243
- logger(
1244
- `[agent-sdk] warning: agent "${runtime.project.name}" has server tools but no --public-url or --cloud-tools-url; cloud turns omit those tools.`,
1245
- );
1246
- }
1247
- } else {
1248
- const resolveCloudToolsHeaders =
1249
- options.cloudToolsUrl === undefined
1250
- ? undefined
1251
- : (): Record<string, string> | undefined => {
1252
- const apiKey = liveCursorApiKey();
1253
- return apiKey === undefined ? undefined : { authorization: `Bearer ${apiKey}` };
1254
- };
1255
- const headers =
1256
- options.cloudToolsUrl !== undefined
1257
- ? resolveCloudToolsHeaders?.()
1258
- : options.authToken === undefined
1259
- ? undefined
1260
- : { authorization: `Bearer ${options.authToken}` };
1261
- if (options.cloudToolsUrl !== undefined && headers === undefined) {
1262
- if (options.allowAnonymous !== true) {
1263
- throw new Error(
1264
- `Agent "${runtime.project.name}" needs a Cursor API key to authenticate --cloud-tools-url. ${SIGN_IN_HINT}`,
1265
- );
1266
- }
1267
- logger(
1268
- `[agent-sdk] --cloud-tools-url: listening unsigned; Bearer resolves after task-time credential binding`,
1269
- );
1270
- }
1271
- runtime.engine.setCloudServerToolsConnection(
1272
- {
1273
- type: "http",
1274
- url: publicToolsUrl,
1275
- ...(headers === undefined ? {} : { headers }),
1276
- },
1277
- resolveCloudToolsHeaders,
1278
- );
1279
- }
1280
- }
1281
- }
1282
-
1283
- const agents: MountedAgentInfo[] = runtimes.map(({ slug, project }) => ({
1284
- slug,
1285
- project,
1286
- url: slug === "" ? url : `${url}/${slug}`,
1287
- }));
1288
- for (const runtime of runtimes) {
1289
- runtime.evalRuns.loopbackUrl = runtime.slug === "" ? url : `${url}/${runtime.slug}`;
1290
- }
1291
- const runtimeBySlug = new Map(runtimes.map(r => [r.slug, r]));
1292
-
1293
- // --dev: spawn Vite HMR. Single-agent infers the slug base; multi-agent
1294
- // serves `/<slug>/playground` on the HMR origin (optional AGENT_SERVE_BASE
1295
- // pins one slug at the HMR root instead).
1296
- let playgroundDev: ReturnType<typeof startPlaygroundDevServer>;
1297
- if (playground && dev) {
1298
- const pinnedBase =
1299
- mounts.length === 1 ? playgroundDevBasePath(mounts) : playgroundDevBaseFromEnv();
1300
- const multiAgent = mounts.length > 1 && pinnedBase === undefined;
1301
- playgroundDev = startPlaygroundDevServer({
1302
- targetUrl: url,
1303
- basePath: pinnedBase,
1304
- multiAgent,
1305
- logger,
1306
- });
1307
- }
1308
-
1309
- const handle: AgentServeHandle = {
1310
- url,
1311
- port: address.port,
1312
- project: runtimes[0]?.project as AgentProject,
1313
- agents,
1314
- dispatchSchedule: (name, slug = runtimes[0]?.slug ?? "") => {
1315
- const runtime = runtimeBySlug.get(slug);
1316
- if (runtime === undefined) {
1317
- throw new Error(`Unknown agent slug "${slug}"`);
1318
- }
1319
- return runtime.scheduleRunner.dispatch(name);
1320
- },
1321
- createReminder: (input, slug = runtimes[0]?.slug ?? "") => {
1322
- const runtime = runtimeBySlug.get(slug);
1323
- if (runtime === undefined) {
1324
- throw new Error(`Unknown agent slug "${slug}"`);
1325
- }
1326
- return runtime.reminderRunner.create(input);
1327
- },
1328
- listReminders: (filter, slug = runtimes[0]?.slug ?? "") => {
1329
- const runtime = runtimeBySlug.get(slug);
1330
- if (runtime === undefined) {
1331
- throw new Error(`Unknown agent slug "${slug}"`);
1332
- }
1333
- return runtime.reminderRunner.list(filter);
1334
- },
1335
- cancelReminder: (id, options) => {
1336
- const slug = options?.slug ?? runtimes[0]?.slug ?? "";
1337
- const runtime = runtimeBySlug.get(slug);
1338
- if (runtime === undefined) {
1339
- throw new Error(`Unknown agent slug "${slug}"`);
1340
- }
1341
- return runtime.reminderRunner.cancel(id, options?.reason);
1342
- },
1343
- dispatchReminder: (id, slug = runtimes[0]?.slug ?? "") => {
1344
- const runtime = runtimeBySlug.get(slug);
1345
- if (runtime === undefined) {
1346
- throw new Error(`Unknown agent slug "${slug}"`);
1347
- }
1348
- return runtime.reminderRunner.dispatch(id);
1349
- },
1350
- callTool: (toolName, input, options) => {
1351
- const { slug, ...callOptions } = options ?? {};
1352
- const runtime = runtimeBySlug.get(slug ?? runtimes[0]?.slug ?? "");
1353
- if (runtime === undefined) {
1354
- throw new Error(`Unknown agent slug "${slug}"`);
1355
- }
1356
- return runtime.engine.callTool(toolName, input, callOptions);
1357
- },
1358
- close: async () => {
1359
- if (sessionRunLog !== undefined) {
1360
- await flushHostedExecutionProcessDeath({
1361
- flushProcessDeath: reason => sessionRunLog.flushProcessDeath(reason),
1362
- flushStartLog,
1363
- startLogId: lastStartLogId,
1364
- reason: "process_exit",
1365
- });
1366
- unregisterSessionRunFatalFlush();
1367
- }
1368
- playgroundDev?.stop();
1369
- await cursorDeploymentRelay?.stop();
1370
- await cursorEventRelay?.stop();
1371
- await controlPlaneScmRelay?.stop();
1372
- for (const runtime of runtimes) {
1373
- runtime.controlPlane?.stop();
1374
- runtime.scheduleRunner.stop();
1375
- runtime.reminderRunner.stop();
1376
- // Before the engines close their storage coordinators, so the
1377
- // interrupted-batch write can still reach the sink.
1378
- runtime.evalRuns.close();
1379
- }
1380
- for (const stop of channelStopHooks) {
1381
- try {
1382
- await stop();
1383
- } catch (error) {
1384
- logger(
1385
- `[agent-sdk] channel onStop failed: ${
1386
- error instanceof Error ? (error.stack ?? error.message) : String(error)
1387
- }`,
1388
- );
1389
- }
1390
- }
1391
- server.close();
1392
- server.closeAllConnections();
1393
- try {
1394
- await Promise.all(runtimes.map(runtime => runtime.engine.close()));
1395
- } finally {
1396
- cursorGithubCredentials?.stop();
1397
- await shutdownOtelRuntime(otelRuntime);
1398
- }
1399
- },
1400
- };
1401
- if (playgroundDev?.url !== undefined) {
1402
- handle.playgroundDevUrl = playgroundDev.url;
1403
- }
1404
- if (docsSite && docsSiteExists()) {
1405
- handle.docsUrl = `${handle.url}/docs`;
1406
- }
1407
- return handle;
1408
- }
1409
-
1410
- function mountAgentRoutes(
1411
- router: Router,
1412
- runtime: MountedRuntime,
1413
- args: {
1414
- dev: boolean;
1415
- playground: boolean;
1416
- noControlPlane?: boolean;
1417
- multi: boolean;
1418
- logger: (line: string) => void;
1419
- logRing: LogRing;
1420
- sessionRunLog?: ReturnType<typeof selectSessionRunLogStore>;
1421
- flushStartLog?: (startLogId: string) => Promise<void>;
1422
- flushOtel?: () => Promise<void>;
1423
- authToken?: string;
1424
- allowAnonymous?: boolean;
1425
- /** Cursor account bridge + this mount's account MCP connections, when authored. */
1426
- accountBridge?: CursorAccountMcpBridge;
1427
- accountRefs?: CursorAccountConnectionRef[];
1428
- /**
1429
- * Serve `--state-root`. Hosted-execution writes `hosted-execution.json`
1430
- * here so the Temporal host can read a stable path after the POST.
1431
- */
1432
- diagStateRoot?: string;
1433
- /**
1434
- * Drop the cached SDK agent handle after a hosted turn so hibernate
1435
- * cannot snapshot a frozen Connect/HTTP2 session. Injected test
1436
- * runners may omit this.
1437
- */
1438
- evictSdkSession?: (sessionId: string) => void;
1439
- },
1440
- ): void {
1441
- const { slug, project, engine, scheduleRunner, reminderRunner, reminderControlPlane } = runtime;
1442
- const { dev, playground, noControlPlane, multi, logger, logRing, sessionRunLog, flushStartLog } =
1443
- args;
1444
- // "" (single) -> "/v1/..."; "my-agent" (multi) -> "/my-agent/v1/...".
1445
- const base = slug === "" ? "" : `/${slug}`;
1446
-
1447
- // The Cursor account MCP bridge for this mount's account MCP connections:
1448
- // loopback-only + per-boot bearer secret, never on the public auth chain.
1449
- if (args.accountBridge !== undefined && args.accountRefs !== undefined) {
1450
- const bridge = args.accountBridge;
1451
- const refByName = new Map(args.accountRefs.map(ref => [ref.name, ref]));
1452
- router.add({
1453
- method: "POST",
1454
- pattern: `${base}${cursorAccountMcpPath(":connection")}`,
1455
- auth: [bridge.authPolicy()],
1456
- handler: (request, ctx) => {
1457
- const ref = refByName.get(ctx.params.connection ?? "");
1458
- if (ref === undefined) {
1459
- return errorResponse(
1460
- 404,
1461
- "not_found",
1462
- `No Cursor account MCP connection named "${ctx.params.connection ?? ""}" on this agent.`,
1463
- );
1464
- }
1465
- return bridge.handle(request, ref, appendSlackQuietHint);
1466
- },
1467
- });
1468
- }
1469
- const defaultAuth: AuthPolicy[] =
1470
- args.authToken !== undefined
1471
- ? [bearerAuth(args.authToken)]
1472
- : args.allowAnonymous === true
1473
- ? [allowAll()]
1474
- : [localDevStrict()];
1475
- const httpAuth = project.httpChannel.auth ?? defaultAuth;
1476
- // Temporal posts this marker on a direct pod port-token fetch. The alias
1477
- // proxy strips it, so webhook/playground tokens cannot present it.
1478
- const platformTimerFireAuth: AuthPolicy = request => {
1479
- if (request.headers.get("x-agent-serve-timed-work") === "1") {
1480
- return {
1481
- authenticator: "app",
1482
- principalId: "agent-serve:timed-work",
1483
- principalType: "runtime",
1484
- };
1485
- }
1486
- return null;
1487
- };
1488
- // A v2 mount served under `--no-control-plane` is a hosted v2 guest: the
1489
- // hosted control plane drives it through the hosted delivery route below.
1490
- // Session HTTP is a control-plane surface, so such a guest mounts no
1491
- // `/v1/session*` or `/v1/sessions` routes — session starts arrive as hosted
1492
- // admissions (`agentsdk.session` on the built-in http channel) and session
1493
- // reads come from the control plane's runs surface and durable storage.
1494
- // Local dev, self-hosted serve, and hosted v1 keep the engine mounts.
1495
- const hostedV2Guest = noControlPlane === true && isV2Project(project);
1496
- if (hostedV2Guest) {
1497
- registerHostedDeliveryRoute({
1498
- router,
1499
- base,
1500
- // The built-in http channel is not in `project.channels`; the control
1501
- // plane's session start (`agentsdk.session`) is delivered to it.
1502
- channels: [...project.channels, { id: HTTP_CHANNEL_ID, definition: project.httpChannel }],
1503
- buildHandlerArgs: (channelId, hostedSessionId) =>
1504
- buildChannelHandlerArgs({
1505
- runtime,
1506
- channelId,
1507
- hostedSessionId,
1508
- }),
1509
- fireReminder: (reminderId, fireCount) =>
1510
- reminderRunner.dispatch(reminderId, { expectedFireCount: fireCount }),
1511
- executeReminderDescriptor: async descriptor => {
1512
- if (reminderControlPlane === undefined) {
1513
- throw new Error("hosted reminder CP client is not configured");
1514
- }
1515
- const fireDescriptor = descriptor as unknown as ReminderFireDescriptor;
1516
- const outcome = await reminderRunner.executeFire(fireDescriptor);
1517
- // applyReminderOutcome is idempotent and internally retries transient
1518
- // CP failures. Handler execution is at-least-once across Temporal
1519
- // re-admission if apply ultimately fails.
1520
- const apply = await reminderControlPlane.applyReminderOutcome(
1521
- claimFromDescriptor(fireDescriptor),
1522
- outcome,
1523
- );
1524
- // Cancel/rekey winning the race is a successful no-op from the guest's
1525
- // perspective (fired work may have run; lifecycle authority stayed CP).
1526
- if (!apply.applied && apply.reason === "missing") {
1527
- return {
1528
- reminderId: descriptor.id,
1529
- outcome: "noop" as const,
1530
- reason: apply.reason,
1531
- };
1532
- }
1533
- return {
1534
- reminderId: descriptor.id,
1535
- outcome: "fired" as const,
1536
- };
1537
- },
1538
- drainSessionDurability: sessionId => engine.drainSessionDurability(sessionId),
1539
- flushOtel: args.flushOtel,
1540
- ...(args.diagStateRoot === undefined ? {} : { stateRoot: args.diagStateRoot }),
1541
- ...(sessionRunLog === undefined
1542
- ? {}
1543
- : {
1544
- persistSessionRun: async document => {
1545
- await sessionRunLog.persist(document);
1546
- },
1547
- flushStartLog,
1548
- }),
1549
- snapshotLogs: () => logRing.since(),
1550
- ...(args.evictSdkSession === undefined ? {} : { evictSdkSession: args.evictSdkSession }),
1551
- });
1552
- }
1553
- // Playground lists/opens Slack (and other channel) sessions across
1554
- // principals when `--dev` (loopback) or `--allow-anonymous` (trusted
1555
- // shared host, e.g. corp Okta ALB). Never when bearer / custom channel
1556
- // auth is set — those keep strict per-principal isolation.
1557
- const relaxSessionReadAuth =
1558
- args.authToken === undefined &&
1559
- project.httpChannel.auth === undefined &&
1560
- (dev || args.allowAnonymous === true);
1561
- const relaxSessionReadAuthBeyondLoopback = args.allowAnonymous === true;
1562
- // Separate from read-relax: playground Approve/Deny on Slack-owned parked
1563
- // tools (Slack principals never match local/anonymous HTTP auth).
1564
- const relaxSessionApprovalAuth = relaxSessionReadAuth;
1565
-
1566
- router.add({
1567
- method: "GET",
1568
- pattern: `${base}${mcpOauthServeCallbackPath()}`,
1569
- auth: "none",
1570
- handler: request => engine.oauthCallbackHub.handleCallback(request),
1571
- });
1572
-
1573
- router.add({
1574
- method: "GET",
1575
- pattern: `${base}/v1/health`,
1576
- auth: "none",
1577
- // Temporal consumes this response before promoting a newly deployed pod.
1578
- // Include the framework build there so deploy observability gets the
1579
- // version from the process that will serve turns, with no second request.
1580
- handler: () =>
1581
- jsonResponse({
1582
- ok: true,
1583
- name: project.name,
1584
- version: packageVersion(),
1585
- ...memoryHealthFields([engine]),
1586
- }),
1587
- });
1588
-
1589
- // TAS polls this after `/v1/health` and before the hosted POST. Auth none
1590
- // mirrors health: the engine is reachable only through the anyrun port
1591
- // proxy (network token) or the alias route.
1592
- router.add({
1593
- method: "GET",
1594
- pattern: `${base}${GUEST_NETWORK_PATH}`,
1595
- auth: "none",
1596
- handler: () => guestNetworkReadinessResponse(),
1597
- });
1598
-
1599
- // Bootstrap the SPA can't derive from its own URL (agent name, dev mode, and
1600
- // — in multi-agent mode — where the agents index lives).
1601
- router.add({
1602
- method: "GET",
1603
- pattern: `${base}/v1/meta`,
1604
- auth: "none",
1605
- handler: () =>
1606
- jsonResponse({
1607
- name: project.name,
1608
- dev,
1609
- basePath: base,
1610
- // Framework version, for SPA/engine skew observability now that the
1611
- // hosted playground shell is served centrally (backend deploys)
1612
- // while engines stay on their install-time version.
1613
- version: packageVersion(),
1614
- ...(multi ? { indexPath: "/" } : {}),
1615
- }),
1616
- });
1617
-
1618
- router.add({
1619
- method: "GET",
1620
- pattern: `${base}/v1/info`,
1621
- auth: httpAuth,
1622
- handler: () => jsonResponse(projectInfo(project)),
1623
- });
1624
-
1625
- // Hosted-only: the control plane's provision flow reads the deploy manifest
1626
- // from the running engine (same derivation as `july manifest`) right after
1627
- // the health probe, so every deploy surface — CLI, UI, redeploy — gets its
1628
- // declarations from the installed code without a client-side extraction
1629
- // step. `auth: "none"` mirrors `/v1/health`: hosted engines are reachable
1630
- // only through the anyrun port proxy (network token) or the alias route
1631
- // (alias token), and the route is not registered outside hosted mode, so
1632
- // self-hosted `july serve` never exposes the manifest unauthenticated.
1633
- if (process.env[AGENT_SERVE_GENERATION_ENV_VAR] !== undefined) {
1634
- router.add({
1635
- method: "GET",
1636
- pattern: `${base}/v1/manifest`,
1637
- auth: "none",
1638
- handler: () => jsonResponse(buildAgentDeployManifest(project)),
1639
- });
1640
- }
1641
-
1642
- // Playground Logs tab: recent ServeOptions.logger lines (channels, sessions,
1643
- // webhook capture). `after` is an exclusive index cursor for polling.
1644
- router.add({
1645
- method: "GET",
1646
- pattern: `${base}/v1/logs`,
1647
- auth: httpAuth,
1648
- handler: request => {
1649
- const url = new URL(request.url);
1650
- const afterRaw = url.searchParams.get("after");
1651
- const after = afterRaw === null || afterRaw === "" ? -1 : Number.parseInt(afterRaw, 10);
1652
- const cursor = Number.isFinite(after) ? after : -1;
1653
- const entries = logRing.since(cursor);
1654
- return jsonResponse({
1655
- entries,
1656
- nextAfter: entries.length === 0 ? cursor : (entries[entries.length - 1]?.index ?? cursor),
1657
- });
1658
- },
1659
- });
1660
-
1661
- // Session list is session surface: not mounted on a hosted v2 guest (the
1662
- // control plane owns session reads there; see hostedV2Guest above).
1663
- if (!hostedV2Guest) {
1664
- router.add({
1665
- method: "GET",
1666
- pattern: `${base}/v1/sessions`,
1667
- auth: httpAuth,
1668
- handler: async (request, ctx) => {
1669
- // Same gate as requireSessionOwner / relaxSessionReadAuth: never with
1670
- // bearer or custom channel auth (strict per-principal isolation).
1671
- // `--allow-anonymous` alone is a shared-principal trust boundary (corp
1672
- // Okta ALB); `--dev` alone stays loopback-only.
1673
- const includeAll =
1674
- relaxSessionReadAuth &&
1675
- (relaxSessionReadAuthBeyondLoopback ||
1676
- (typeof ctx.requestIp === "string" && isLoopbackAddress(ctx.requestIp)));
1677
- // `?latest=1` — only the newest visible session. Clients binding a
1678
- // default session (agsh) do not need the whole list, and on hosted
1679
- // storage the whole list is a database scan.
1680
- const latest = new URL(request.url).searchParams.get("latest");
1681
- const listed =
1682
- latest === "1" || latest === "true"
1683
- ? await engine.latestSessionWithSource(ctx.auth, { includeAll })
1684
- : await engine.listSessionsWithSource(ctx.auth, { includeAll });
1685
- return jsonResponse({
1686
- sessions: listed.sessions,
1687
- source: listed.source,
1688
- });
1689
- },
1690
- });
1691
- }
1692
-
1693
- // Durable artifacts (ctx.artifacts / tag_artifact), newest-updated first.
1694
- // Cursor-paginated: pass `pageToken` from the previous response's
1695
- // `nextPageToken`. A page can be short (even empty) with a nextPageToken
1696
- // when a sparse filter exhausted the per-call scan budget.
1697
- router.add({
1698
- method: "GET",
1699
- pattern: `${base}/v1/artifacts`,
1700
- auth: httpAuth,
1701
- handler: async (request, ctx) => {
1702
- const url = new URL(request.url);
1703
- const limitRaw = url.searchParams.get("limit");
1704
- let limit = ARTIFACTS_PAGE_DEFAULT_LIMIT;
1705
- if (limitRaw !== null && limitRaw !== "") {
1706
- const parsed = Number.parseInt(limitRaw, 10);
1707
- if (!Number.isInteger(parsed) || parsed < 1) {
1708
- return errorResponse(400, "invalid_request", "`limit` must be a positive integer.");
1709
- }
1710
- limit = Math.min(parsed, ARTIFACTS_PAGE_MAX_LIMIT);
1711
- }
1712
- const kind = url.searchParams.get("kind") ?? undefined;
1713
- const sessionId = url.searchParams.get("sessionId") ?? undefined;
1714
- const pageToken = url.searchParams.get("pageToken") ?? undefined;
1715
- // Same includeAll gate as /v1/sessions: never with bearer or custom
1716
- // channel auth (strict per-principal isolation); otherwise session
1717
- // ownership applies (see SessionEngine.pageArtifacts).
1718
- const includeAll =
1719
- relaxSessionReadAuth &&
1720
- (relaxSessionReadAuthBeyondLoopback ||
1721
- (typeof ctx.requestIp === "string" && isLoopbackAddress(ctx.requestIp)));
1722
- let page: ArtifactPage;
1723
- try {
1724
- page = await engine.pageArtifacts(ctx.auth, {
1725
- includeAll,
1726
- filter: { kind, sessionId },
1727
- limit,
1728
- cursor: pageToken,
1729
- });
1730
- } catch (error) {
1731
- if (error instanceof InvalidArtifactCursorError) {
1732
- return errorResponse(400, "invalid_request", "`pageToken` is not a valid page token.");
1733
- }
1734
- throw error;
1735
- }
1736
- return jsonResponse({
1737
- artifacts: page.records,
1738
- nextPageToken: page.nextCursor,
1739
- });
1740
- },
1741
- });
1742
-
1743
- // File/blob payload of one artifact (`tag({ contents })`).
1744
- router.add({
1745
- method: "GET",
1746
- pattern: `${base}/v1/artifacts/:id/content`,
1747
- auth: httpAuth,
1748
- handler: async (_request, ctx) => {
1749
- const includeAll =
1750
- relaxSessionReadAuth &&
1751
- (relaxSessionReadAuthBeyondLoopback ||
1752
- (typeof ctx.requestIp === "string" && isLoopbackAddress(ctx.requestIp)));
1753
- const found = await engine.getArtifactContent(ctx.auth, ctx.params.id ?? "", { includeAll });
1754
- if (found === undefined) {
1755
- return errorResponse(404, "not_found", "No such artifact, or it carries no content.");
1756
- }
1757
- // A view over bytes is a valid fetch body; the DOM lib types are
1758
- // narrower than the runtime.
1759
- // contentType is author/model-controlled and the playground shares
1760
- // this origin: force download, never render or sniff.
1761
- return new Response(found.body as unknown as BodyInit, {
1762
- headers: {
1763
- "content-type": found.record.content?.contentType ?? "application/octet-stream",
1764
- "content-disposition": "attachment",
1765
- "x-content-type-options": "nosniff",
1766
- },
1767
- });
1768
- },
1769
- });
1770
-
1771
- // The agent's MCP surface: peers and external MCP clients delegate to
1772
- // this agent (ask / check / call_tool) over streamable HTTP. Stateless —
1773
- // POST only; GET/DELETE get a spec-compliant 405 from the endpoint.
1774
- const mcpEndpoint = createAgentMcpEndpoint({ engine, logger });
1775
- for (const method of ["POST", "GET", "DELETE"] as const) {
1776
- router.add({
1777
- method,
1778
- pattern: `${base}${MCP_ENDPOINT_PATH}`,
1779
- auth: httpAuth,
1780
- handler: (request, ctx) => mcpEndpoint.handle(request, ctx.auth),
1781
- });
1782
- }
1783
-
1784
- const toolMcpEndpoint = createToolMcpEndpoint({ engine, logger });
1785
- for (const method of ["POST", "GET", "DELETE"] as const) {
1786
- router.add({
1787
- method,
1788
- pattern: `${base}${TOOL_MCP_ENDPOINT_PATH}`,
1789
- auth: defaultAuth,
1790
- handler: (request, ctx) => toolMcpEndpoint.handle(request, ctx.auth),
1791
- });
1792
- }
1793
-
1794
- // The live tool catalog: the session's tool namespace as a turn would
1795
- // assemble it — authored server tools plus advertised MCP passthroughs —
1796
- // under model-facing names. `/v1/info` stays the static authored
1797
- // manifest; this is the runtime view only the running deployment can
1798
- // answer. `session` / `continuationToken` query parameters bind the
1799
- // listing to a session identity (advertised inventories can be
1800
- // tenant-scoped and resolved per session).
1801
- const resolveCatalogBinding = async (
1802
- request: Request,
1803
- ctx: Pick<ServerRouteContext, "auth" | "requestIp">,
1804
- ): Promise<{ sessionId?: string; continuationToken?: string } | { errorResponse: Response }> => {
1805
- const url = new URL(request.url);
1806
- const sessionId = url.searchParams.get("session") ?? undefined;
1807
- const continuationToken = url.searchParams.get("continuationToken") ?? undefined;
1808
- if (sessionId !== undefined) {
1809
- const record = await engine.sessions.get(sessionId);
1810
- if (record === undefined) {
1811
- return {
1812
- errorResponse: errorResponse(404, "session_not_found", `Unknown session ${sessionId}.`),
1813
- };
1814
- }
1815
- const ownership = requireSessionOwner(record, ctx.auth, {
1816
- relax: relaxSessionReadAuth,
1817
- beyondLoopback: relaxSessionReadAuthBeyondLoopback,
1818
- requestIp: ctx.requestIp,
1819
- });
1820
- if (ownership !== undefined) {
1821
- return { errorResponse: ownership };
1822
- }
1823
- }
1824
- return { sessionId, continuationToken };
1825
- };
1826
-
1827
- router.add({
1828
- method: "GET",
1829
- pattern: `${base}/v1/tools`,
1830
- auth: httpAuth,
1831
- handler: async (request, ctx) => {
1832
- const binding = await resolveCatalogBinding(request, ctx);
1833
- if ("errorResponse" in binding) {
1834
- return binding.errorResponse;
1835
- }
1836
- try {
1837
- const catalog = await engine.listCatalogTools({
1838
- auth: ctx.auth,
1839
- ...binding,
1840
- });
1841
- return jsonResponse({
1842
- tools: catalog.tools.map(catalogListEntry),
1843
- // JSON.stringify drops the key when there is nothing to report.
1844
- connectionErrors:
1845
- catalog.connectionErrors.length === 0 ? undefined : catalog.connectionErrors,
1846
- });
1847
- } catch (error) {
1848
- if (error instanceof InvalidContinuationTokenError) {
1849
- return errorResponse(400, "invalid_continuation_token", error.message);
1850
- }
1851
- throw error;
1852
- }
1853
- },
1854
- });
1855
-
1856
- router.add({
1857
- method: "GET",
1858
- pattern: `${base}/v1/tools/:toolName`,
1859
- auth: httpAuth,
1860
- handler: async (request, ctx) => {
1861
- const toolName = ctx.params.toolName ?? "";
1862
- const binding = await resolveCatalogBinding(request, ctx);
1863
- if ("errorResponse" in binding) {
1864
- return binding.errorResponse;
1865
- }
1866
- try {
1867
- const described = await engine.describeCatalogTool(toolName, {
1868
- auth: ctx.auth,
1869
- ...binding,
1870
- });
1871
- if (described.tool === undefined) {
1872
- return jsonResponse(
1873
- {
1874
- ok: false,
1875
- error: "unknown_tool",
1876
- message: `Unknown tool "${toolName}".`,
1877
- availableTools: described.availableTools,
1878
- },
1879
- { status: 404 },
1880
- );
1881
- }
1882
- return jsonResponse(catalogDetailEntry(described.tool));
1883
- } catch (error) {
1884
- if (error instanceof InvalidContinuationTokenError) {
1885
- return errorResponse(400, "invalid_continuation_token", error.message);
1886
- }
1887
- throw error;
1888
- }
1889
- },
1890
- });
1891
-
1892
- // Deterministic tool invocation: run an authored server tool directly,
1893
- // without a model turn deciding to call it.
1894
- router.add({
1895
- method: "POST",
1896
- pattern: `${base}/v1/tools/:toolName`,
1897
- auth: httpAuth,
1898
- handler: async (request, ctx) => {
1899
- const toolName = ctx.params.toolName ?? "";
1900
- const body = await readJsonObject(request);
1901
- if (body === undefined) {
1902
- return errorResponse(
1903
- 400,
1904
- "invalid_request",
1905
- 'Expected a JSON object body, e.g. {"input": {...}}.',
1906
- );
1907
- }
1908
- if (body.sessionId !== undefined && typeof body.sessionId !== "string") {
1909
- return errorResponse(400, "invalid_request", "`sessionId` must be a string when provided.");
1910
- }
1911
- if (body.continuationToken !== undefined && typeof body.continuationToken !== "string") {
1912
- return errorResponse(
1913
- 400,
1914
- "invalid_request",
1915
- "`continuationToken` must be a string when provided.",
1916
- );
1917
- }
1918
- const continuationToken = body.continuationToken;
1919
- const sessionId = body.sessionId;
1920
- if (sessionId !== undefined) {
1921
- const record = await engine.sessions.get(sessionId);
1922
- if (record === undefined) {
1923
- return errorResponse(404, "session_not_found", `Unknown session ${sessionId}.`);
1924
- }
1925
- const ownership = requireSessionOwner(record, ctx.auth, {
1926
- relax: relaxSessionReadAuth,
1927
- beyondLoopback: relaxSessionReadAuthBeyondLoopback,
1928
- requestIp: ctx.requestIp,
1929
- });
1930
- if (ownership !== undefined) {
1931
- return ownership;
1932
- }
1933
- }
1934
- try {
1935
- const outcome = await engine.callTool(toolName, body.input ?? {}, {
1936
- auth: ctx.auth,
1937
- sessionId,
1938
- continuationToken,
1939
- });
1940
- return jsonResponse({ ok: !outcome.isError, ...outcome });
1941
- } catch (error) {
1942
- if (error instanceof UnknownToolError) {
1943
- return jsonResponse(
1944
- {
1945
- ok: false,
1946
- error: "unknown_tool",
1947
- message: error.message,
1948
- availableTools: error.availableToolNames,
1949
- },
1950
- { status: 404 },
1951
- );
1952
- }
1953
- if (error instanceof ToolNotDirectlyCallableError) {
1954
- return errorResponse(400, "tool_not_callable", error.message);
1955
- }
1956
- if (error instanceof ToolInputError) {
1957
- return errorResponse(400, "invalid_tool_input", error.message);
1958
- }
1959
- if (error instanceof InvalidContinuationTokenError) {
1960
- return errorResponse(400, "invalid_continuation_token", error.message);
1961
- }
1962
- if (error instanceof WorkspaceUnavailableError) {
1963
- return errorResponse(500, "workspace_unavailable", error.message);
1964
- }
1965
- throw error;
1966
- }
1967
- },
1968
- });
1969
-
1970
- // Deterministic skill reads: the body the harness would receive, plus
1971
- // resolved sibling files. Read-only, so plain GETs with no session binding.
1972
- router.add({
1973
- method: "GET",
1974
- pattern: `${base}/v1/skills`,
1975
- auth: httpAuth,
1976
- handler: async () =>
1977
- jsonResponse({
1978
- skills: project.agent.skills.map(skillListEntry),
1979
- }),
1980
- });
1981
-
1982
- router.add({
1983
- method: "GET",
1984
- pattern: `${base}/v1/skills/:skillName`,
1985
- auth: httpAuth,
1986
- handler: async (_request, ctx) => {
1987
- const skillName = ctx.params.skillName ?? "";
1988
- try {
1989
- return jsonResponse(await readSkillDetail(project.agent.skills, skillName));
1990
- } catch (error) {
1991
- if (error instanceof UnknownSkillError) {
1992
- return jsonResponse(
1993
- {
1994
- ok: false,
1995
- error: "unknown_skill",
1996
- message: error.message,
1997
- availableSkills: error.availableSkillNames,
1998
- },
1999
- { status: 404 },
2000
- );
2001
- }
2002
- throw error;
2003
- }
2004
- },
2005
- });
2006
-
2007
- if (playground) {
2008
- // Serve the built Vite SPA. `<base href>` is injected so the SPA's relative
2009
- // asset URLs resolve under this mount regardless of the trailing slash the
2010
- // browser lands on. Render per request so a mid-run `build:playground`
2011
- // is picked up without restarting. In dev, run `pnpm run dev:playground`
2012
- // (Vite + HMR) instead; it proxies `/v1` here.
2013
- router.add({
2014
- method: "GET",
2015
- pattern: `${base}/playground`,
2016
- auth: "none",
2017
- handler: () =>
2018
- new Response(renderPlaygroundIndexHtml(`${base}/playground/`), {
2019
- headers: { "content-type": "text/html; charset=utf-8" },
2020
- }),
2021
- });
2022
- router.add({
2023
- method: "GET",
2024
- pattern: `${base}/playground/assets/:file`,
2025
- auth: "none",
2026
- handler: (_request, ctx) => renderPlaygroundAsset(ctx.params.file ?? ""),
2027
- });
2028
- }
2029
-
2030
- // The built-in HTTP session channel (`/v1/session*`, including the
2031
- // session-scoped approvals/auths routes) is session surface: not mounted on
2032
- // a hosted v2 guest (see hostedV2Guest above). The `http` channel itself
2033
- // stays registered with the hosted delivery route, which is how the control
2034
- // plane's session starts reach it.
2035
- if (!hostedV2Guest) {
2036
- for (const route of buildHttpChannelRoutes({
2037
- engine,
2038
- config: project.httpChannel,
2039
- auth: httpAuth,
2040
- basePath: base,
2041
- // Dev playground lists every session (`includeAll`); allow opening them
2042
- // (see relaxSessionReadAuth above).
2043
- relaxSessionReadAuth,
2044
- relaxSessionReadAuthBeyondLoopback,
2045
- relaxSessionApprovalAuth,
2046
- })) {
2047
- router.add(route);
2048
- }
2049
- }
2050
-
2051
- // Playground eval list/run — available without `--dev` (corp / allow-anonymous).
2052
- // Schedule/reminder hand-dispatch stays `--dev` only below.
2053
- router.add({
2054
- method: "GET",
2055
- pattern: `${base}/v1/dev/evals`,
2056
- auth: httpAuth,
2057
- handler: async () => jsonResponse(await runtime.evalRuns.list()),
2058
- });
2059
- router.add({
2060
- method: "GET",
2061
- pattern: `${base}/v1/dev/evals/runs`,
2062
- auth: httpAuth,
2063
- handler: async () => {
2064
- return jsonResponse(await runtime.evalRuns.listRunsWithActive());
2065
- },
2066
- });
2067
- router.add({
2068
- method: "POST",
2069
- pattern: `${base}/v1/dev/evals/runs`,
2070
- auth: httpAuth,
2071
- handler: async request => {
2072
- const body = await readJsonObject(request);
2073
- const filterIds = asStringArray(body?.filterIds);
2074
- const tags = asStringArray(body?.tags);
2075
- const timeoutMs = asPositiveInt(body?.timeoutMs);
2076
- const verbose = body?.verbose === true;
2077
- const authHeader = request.headers.get("authorization");
2078
- const bearerToken = authHeader?.toLowerCase().startsWith("bearer ")
2079
- ? authHeader.slice("bearer ".length).trim()
2080
- : undefined;
2081
- try {
2082
- const snap = await runtime.evalRuns.start({
2083
- ...(filterIds === undefined ? {} : { filterIds }),
2084
- ...(tags === undefined ? {} : { tags }),
2085
- ...(bearerToken === undefined || bearerToken === "" ? {} : { bearerToken }),
2086
- ...(timeoutMs === undefined ? {} : { timeoutMs }),
2087
- ...(verbose ? { verbose: true } : {}),
2088
- });
2089
- return jsonResponse(snap, { status: 202 });
2090
- } catch (error) {
2091
- if (error instanceof EvalRunConflictError) {
2092
- return jsonResponse(
2093
- {
2094
- ok: false,
2095
- error: "eval_run_in_progress",
2096
- activeRunId: error.activeRunId,
2097
- },
2098
- { status: 409 },
2099
- );
2100
- }
2101
- if (error instanceof EvalRunEmptyError) {
2102
- return jsonResponse({ ok: false, error: "no_matching_evals" }, { status: 404 });
2103
- }
2104
- const message = error instanceof Error ? error.message : String(error);
2105
- return jsonResponse({ ok: false, error: "eval_start_failed", message }, { status: 400 });
2106
- }
2107
- },
2108
- });
2109
- router.add({
2110
- method: "GET",
2111
- pattern: `${base}/v1/dev/evals/runs/:runId`,
2112
- auth: httpAuth,
2113
- handler: async (_request, ctx) => {
2114
- const runId = ctx.params.runId ?? "";
2115
- const snap = await runtime.evalRuns.get(runId);
2116
- if (snap === undefined) {
2117
- return jsonResponse({ ok: false, error: "unknown_eval_run" }, { status: 404 });
2118
- }
2119
- return jsonResponse(snap);
2120
- },
2121
- });
2122
- router.add({
2123
- method: "POST",
2124
- pattern: `${base}/v1/dev/evals/runs/:runId/cancel`,
2125
- auth: httpAuth,
2126
- handler: async (_request, ctx) => {
2127
- const runId = ctx.params.runId ?? "";
2128
- try {
2129
- const snap = await runtime.evalRuns.cancel(runId);
2130
- return jsonResponse(snap);
2131
- } catch (error) {
2132
- if (error instanceof EvalRunUnknownError) {
2133
- return jsonResponse({ ok: false, error: "unknown_eval_run" }, { status: 404 });
2134
- }
2135
- if (error instanceof EvalRunNotRunningError) {
2136
- return jsonResponse(
2137
- {
2138
- ok: false,
2139
- error: "eval_run_not_running",
2140
- runId: error.runId,
2141
- status: error.status,
2142
- message: error.message,
2143
- },
2144
- { status: 409 },
2145
- );
2146
- }
2147
- const message = error instanceof Error ? error.message : String(error);
2148
- return jsonResponse({ ok: false, error: "eval_cancel_failed", message }, { status: 400 });
2149
- }
2150
- },
2151
- });
2152
-
2153
- if (noControlPlane === true) {
2154
- router.add({
2155
- method: "POST",
2156
- pattern: `${base}/v1/internal/schedules/:scheduleId/fire`,
2157
- auth: [platformTimerFireAuth],
2158
- handler: async (_request, ctx) => {
2159
- const scheduleId = ctx.params.scheduleId ?? "";
2160
- try {
2161
- const { sessionIds } = await scheduleRunner.dispatch(scheduleId);
2162
- return jsonResponse({ scheduleId, sessionIds });
2163
- } catch (error) {
2164
- if (error instanceof UnknownScheduleError) {
2165
- return jsonResponse(
2166
- {
2167
- ok: false,
2168
- error: "unknown_schedule",
2169
- availableScheduleIds: error.availableScheduleIds,
2170
- },
2171
- { status: 404 },
2172
- );
2173
- }
2174
- throw error;
2175
- }
2176
- },
2177
- });
2178
- router.add({
2179
- method: "POST",
2180
- pattern: `${base}/v1/internal/reminders/:reminderId/fire`,
2181
- auth: [platformTimerFireAuth],
2182
- handler: async (request, ctx) => {
2183
- const reminderId = ctx.params.reminderId ?? "";
2184
- const fireCountRaw = new URL(request.url).searchParams.get("fireCount");
2185
- const expectedFireCount = fireCountRaw === null ? undefined : Number(fireCountRaw);
2186
- try {
2187
- const result = await reminderRunner.dispatch(
2188
- reminderId,
2189
- expectedFireCount !== undefined && Number.isInteger(expectedFireCount)
2190
- ? { expectedFireCount }
2191
- : {},
2192
- );
2193
- return jsonResponse(result);
2194
- } catch (error) {
2195
- if (error instanceof UnknownReminderError) {
2196
- return jsonResponse(
2197
- {
2198
- ok: false,
2199
- error: "unknown_reminder",
2200
- availableReminderIds: error.availableReminderIds,
2201
- },
2202
- { status: 404 },
2203
- );
2204
- }
2205
- if (error instanceof ReminderValidationError) {
2206
- return jsonResponse(
2207
- { ok: false, error: "invalid_reminder", message: error.message },
2208
- { status: 400 },
2209
- );
2210
- }
2211
- throw error;
2212
- }
2213
- },
2214
- });
2215
- }
2216
-
2217
- if (dev) {
2218
- router.add({
2219
- method: "POST",
2220
- pattern: `${base}/v1/dev/schedules/:scheduleId`,
2221
- auth: httpAuth,
2222
- handler: async (_request, ctx) => {
2223
- const scheduleId = ctx.params.scheduleId ?? "";
2224
- try {
2225
- const { sessionIds } = await scheduleRunner.dispatch(scheduleId);
2226
- return jsonResponse({ scheduleId, sessionIds });
2227
- } catch (error) {
2228
- if (error instanceof UnknownScheduleError) {
2229
- return jsonResponse(
2230
- {
2231
- ok: false,
2232
- error: "unknown_schedule",
2233
- availableScheduleIds: error.availableScheduleIds,
2234
- },
2235
- { status: 404 },
2236
- );
2237
- }
2238
- throw error;
2239
- }
2240
- },
2241
- });
2242
- router.add({
2243
- method: "POST",
2244
- pattern: `${base}/v1/dev/reminders/:reminderId`,
2245
- auth: httpAuth,
2246
- handler: async (_request, ctx) => {
2247
- const reminderId = ctx.params.reminderId ?? "";
2248
- try {
2249
- const listed = await reminderRunner.list();
2250
- const reminder = listed.find(r => r.id === reminderId);
2251
- if (reminder === undefined) {
2252
- const ids = listed.map(r => r.id);
2253
- throw new UnknownReminderError(reminderId, ids);
2254
- }
2255
- const ownership = await assertReminderReadable({
2256
- engine,
2257
- reminder,
2258
- auth: ctx.auth,
2259
- requestIp: ctx.requestIp,
2260
- relax: relaxSessionReadAuth,
2261
- beyondLoopback: relaxSessionReadAuthBeyondLoopback,
2262
- });
2263
- if (ownership !== undefined) {
2264
- return ownership;
2265
- }
2266
- const result = await reminderRunner.dispatch(reminderId);
2267
- return jsonResponse(result);
2268
- } catch (error) {
2269
- if (error instanceof UnknownReminderError) {
2270
- return jsonResponse(
2271
- {
2272
- ok: false,
2273
- error: "unknown_reminder",
2274
- availableReminderIds: error.availableReminderIds,
2275
- },
2276
- { status: 404 },
2277
- );
2278
- }
2279
- if (error instanceof ReminderValidationError) {
2280
- return jsonResponse(
2281
- { ok: false, error: "invalid_reminder", message: error.message },
2282
- { status: 400 },
2283
- );
2284
- }
2285
- throw error;
2286
- }
2287
- },
2288
- });
2289
- router.add({
2290
- method: "GET",
2291
- pattern: `${base}/v1/dev/reminders`,
2292
- auth: httpAuth,
2293
- handler: async (_request, ctx) => {
2294
- const all = await reminderRunner.list();
2295
- const reminders: ReminderInfo[] = [];
2296
- for (const reminder of all) {
2297
- const denied = await assertReminderReadable({
2298
- engine,
2299
- reminder,
2300
- auth: ctx.auth,
2301
- requestIp: ctx.requestIp,
2302
- relax: relaxSessionReadAuth,
2303
- beyondLoopback: relaxSessionReadAuthBeyondLoopback,
2304
- });
2305
- if (denied === undefined) {
2306
- reminders.push(reminder);
2307
- }
2308
- }
2309
- return jsonResponse({ reminders });
2310
- },
2311
- });
2312
- }
2313
-
2314
- for (const channel of project.channels) {
2315
- const channelAuth = channel.definition.auth ?? defaultAuth;
2316
- for (const channelRoute of channel.definition.routes ?? []) {
2317
- router.add({
2318
- method: channelRoute.method,
2319
- pattern: `${base}/v1/channels/${channel.id}${channelRoute.path}`,
2320
- auth: channelAuth,
2321
- handler: (request, ctx) =>
2322
- invokeChannelRoute({
2323
- route: channelRoute,
2324
- request,
2325
- handlerArgs: buildChannelHandlerArgs({
2326
- runtime,
2327
- channelId: channel.id,
2328
- params: ctx.params,
2329
- requestIp: ctx.requestIp,
2330
- auth: ctx.auth,
2331
- }),
2332
- }),
2333
- });
2334
- }
2335
- }
2336
- }
2337
-
2338
- /** Cursor account credential + backend the SCM relay reads the stream with. */
2339
- interface CursorEventsAuth {
2340
- apiKey: string;
2341
- baseUrl: string;
2342
- }
2343
-
2344
- /**
2345
- * `cursorEvents` (`--cursor-events`) long-polls `/v0/scm-events` as the host's
2346
- * Cursor user, so a signed-out host has no way to receive deliveries. Fail the
2347
- * serve instead of starting with a relay that could never run.
2348
- */
2349
- function requireCursorEventsAuth(
2350
- config: NonNullable<ServeOptions["cursorEvents"]>,
2351
- accountKey: ResolvedApiKey | undefined,
2352
- ): CursorEventsAuth {
2353
- const apiKey = (config.apiKey ?? accountKey?.apiKey ?? "").trim();
2354
- if (apiKey === "") {
2355
- throw new Error(
2356
- `[agent-sdk] --cursor-events (serve({ cursorEvents })) requires a signed-in Cursor account: the SCM event stream is read as the host's user. ${SIGN_IN_HINT}`,
2357
- );
2358
- }
2359
- return {
2360
- apiKey,
2361
- // `/v0/scm-events/*` lives on the external API (api.cursor.com), not
2362
- // api2. Prefer that default over the account key's backendUrl, which
2363
- // follows cursorBackendUrl() (api2) when CURSOR_API_KEY is set.
2364
- baseUrl: config.baseUrl ?? cursorExternalApiUrl(),
2365
- };
2366
- }
2367
-
2368
- /**
2369
- * Opt-in Cursor SCM events relay. Credentials are already required by
2370
- * {@link requireCursorEventsAuth}; the remaining unusable configs (no repos,
2371
- * no github/origin channel) warn and leave the relay off — serve still starts.
2372
- *
2373
- * GitHub and Origin subscriptions are registered independently so mirrored
2374
- * `owner/name` slugs do not mix. `--cursor-events --repo` feeds GitHub
2375
- * channels; Origin is subscribed only when an `originChannel({ cursorAccount })`
2376
- * opted in.
2377
- */
2378
- function collectCursorEventSubscriptions(input: {
2379
- mounts: readonly AgentMount[];
2380
- githubRepos: readonly string[];
2381
- originRepos: readonly string[];
2382
- }): CursorScmSubscription[] {
2383
- const githubTargets = findGitHubChannelTargets(input.mounts);
2384
- const originTargets = findOriginChannelTargets(input.mounts);
2385
- const githubEvents = [...new Set(githubTargets.flatMap(target => target.events))];
2386
- const originEvents = [...new Set(originTargets.flatMap(target => target.events))];
2387
- const githubRepos = [...new Set(input.githubRepos.map(repo => repo.trim().toLowerCase()))].filter(
2388
- repo => repo.length > 0,
2389
- );
2390
- const originRepos = [...new Set(input.originRepos.map(repo => repo.trim().toLowerCase()))].filter(
2391
- repo => repo.length > 0,
2392
- );
2393
-
2394
- const subscriptions: CursorScmSubscription[] = [];
2395
- if (githubEvents.length > 0 && githubRepos.length > 0) {
2396
- for (const repo of githubRepos) {
2397
- subscriptions.push({
2398
- provider: "github",
2399
- repo,
2400
- events: githubEvents,
2401
- });
2402
- }
2403
- }
2404
- if (originEvents.length > 0 && originRepos.length > 0) {
2405
- for (const repo of originRepos) {
2406
- subscriptions.push({
2407
- provider: "origin",
2408
- repo,
2409
- events: originEvents,
2410
- });
2411
- }
2412
- }
2413
- return subscriptions;
2414
- }
2415
-
2416
- /**
2417
- * Local CP + `--cursor-events` + both architectures would start two
2418
- * consumers (different offset dirs). Refuse that at serve start.
2419
- * `--no-control-plane` is one July consumer — hosted CP owns v2.
2420
- */
2421
- function assertSingleCursorEventsLane(input: {
2422
- noControlPlane: boolean;
2423
- config: ServeOptions["cursorEvents"];
2424
- auth: CursorEventsAuth | undefined;
2425
- v1Mounts: readonly AgentMount[];
2426
- v2Mounts: readonly AgentMount[];
2427
- githubRepos: readonly string[];
2428
- originRepos: readonly string[];
2429
- }): void {
2430
- if (input.noControlPlane || input.config === undefined || input.auth === undefined) {
2431
- return;
2432
- }
2433
- const shared = {
2434
- githubRepos: input.githubRepos,
2435
- originRepos: input.originRepos,
2436
- };
2437
- if (
2438
- collectCursorEventSubscriptions({ mounts: input.v1Mounts, ...shared }).length === 0 ||
2439
- collectCursorEventSubscriptions({ mounts: input.v2Mounts, ...shared }).length === 0
2440
- ) {
2441
- return;
2442
- }
2443
- throw new Error(
2444
- "[agent-sdk] cursor-events: refusing to serve v1 and v2 github/origin agents in one process — they would open two /v0/scm-events consumers. Serve one architecture per process.",
2445
- );
2446
- }
2447
-
2448
- function startCursorEventRelay(input: {
2449
- config: ServeOptions["cursorEvents"];
2450
- githubRepos: readonly string[];
2451
- originRepos: readonly string[];
2452
- stateRoot: string | undefined;
2453
- mounts: AgentMount[];
2454
- auth: CursorEventsAuth | undefined;
2455
- logger: (line: string) => void;
2456
- collectGitHubTargets: () => ReturnType<typeof collectGitHubTriggerTargets>;
2457
- collectOriginTargets: () => ReturnType<typeof collectOriginTriggerTargets>;
2458
- routeContinuation?: RouteLocalIngressContinuation;
2459
- cursorAccountOnly: boolean;
2460
- /** Engine = v1 poll. Control-plane = v2 poll (started by local CP). */
2461
- lane: "engine" | "control-plane";
2462
- /** When the engine lane has no v1 targets, mention skipped v2 mounts. */
2463
- skippedV2?: boolean;
2464
- /** When false, return an unstarted relay (local CP calls start). */
2465
- start?: boolean;
2466
- /** Offset dir under stateRoot. Defaults to `cursor-events`. */
2467
- stateDirName?: string;
2468
- }): CursorEventRelay | undefined {
2469
- const { config, stateRoot, mounts, auth, logger } = input;
2470
- if (config === undefined || auth === undefined) {
2471
- return undefined;
2472
- }
2473
- const subscriptions = collectCursorEventSubscriptions({
2474
- mounts,
2475
- githubRepos: input.githubRepos,
2476
- originRepos: input.originRepos,
2477
- });
2478
- if (subscriptions.length === 0) {
2479
- if (input.lane === "engine" && input.skippedV2 === true) {
2480
- logger(
2481
- "[agent-sdk] cursor-events: no v1 github/origin targets; v2 ingest is control-plane only",
2482
- );
2483
- } else if (input.lane === "control-plane") {
2484
- return undefined;
2485
- } else if (
2486
- input.githubRepos.every(repo => repo.trim() === "") &&
2487
- input.originRepos.every(repo => repo.trim() === "")
2488
- ) {
2489
- logger(
2490
- "[agent-sdk] cursor-events: no repos configured (pass --repo owner/name); relay disabled",
2491
- );
2492
- } else {
2493
- logger(
2494
- "[agent-sdk] cursor-events: no mounted agent declares a github or origin channel; relay disabled",
2495
- );
2496
- }
2497
- return undefined;
2498
- }
2499
- const baseStateRoot =
2500
- stateRoot ?? join(mounts[0]?.project.rootDir ?? process.cwd(), ".agent-serve");
2501
- const relay = new CursorEventRelay({
2502
- baseUrl: auth.baseUrl,
2503
- apiKey: auth.apiKey,
2504
- subscriptions,
2505
- stateDir: join(baseStateRoot, input.stateDirName ?? "cursor-events"),
2506
- logger,
2507
- dispatch: async event => {
2508
- if (event.provider === "origin") {
2509
- const targets = input.collectOriginTargets().filter(target => {
2510
- const cursorAccount = target.options.cursorAccount;
2511
- if (
2512
- input.cursorAccountOnly &&
2513
- cursorAccount !== true &&
2514
- typeof cursorAccount !== "object"
2515
- ) {
2516
- return false;
2517
- }
2518
- return typeof cursorAccount !== "object"
2519
- ? true
2520
- : cursorAccount.repos.some(repo => repo.toLowerCase() === event.repo.toLowerCase());
2521
- });
2522
- const result = await handleAgentServeTrigger({
2523
- type: "origin",
2524
- bodyText: JSON.stringify(scmMetadataToOriginPayload(event)),
2525
- targets,
2526
- ...(input.routeContinuation === undefined
2527
- ? {}
2528
- : { routeContinuation: input.routeContinuation }),
2529
- });
2530
- logCursorScmDispatch(logger, event, result);
2531
- return;
2532
- }
2533
- if (event.provider !== "github") return;
2534
- const targets = input.collectGitHubTargets().filter(target => {
2535
- const cursorAccount = target.options.cursorAccount;
2536
- if (
2537
- input.cursorAccountOnly &&
2538
- cursorAccount !== true &&
2539
- typeof cursorAccount !== "object"
2540
- ) {
2541
- return false;
2542
- }
2543
- return typeof cursorAccount !== "object"
2544
- ? true
2545
- : cursorAccount.repos.some(repo => repo.toLowerCase() === event.repo.toLowerCase());
2546
- });
2547
- const result = await handleAgentServeTrigger({
2548
- type: "github",
2549
- bodyText: JSON.stringify(scmEventToGitHubPayload(event)),
2550
- eventName: event.eventName,
2551
- deliveryId: event.deliveryId,
2552
- targets,
2553
- ...(input.routeContinuation === undefined
2554
- ? {}
2555
- : { routeContinuation: input.routeContinuation }),
2556
- });
2557
- logCursorScmDispatch(logger, event, result);
2558
- },
2559
- });
2560
- if (input.start === false) {
2561
- return relay;
2562
- }
2563
- relay.start();
2564
- logger(
2565
- `[agent-sdk] cursor-events: relaying ${subscriptions.length} subscription(s) from ${auth.baseUrl}`,
2566
- );
2567
- return relay;
2568
- }
2569
-
2570
- function logCursorScmDispatch(
2571
- logger: (line: string) => void,
2572
- event: Parameters<typeof formatCursorScmEventLog>[0],
2573
- result: Awaited<ReturnType<typeof handleAgentServeTrigger>>,
2574
- ): void {
2575
- const outcomes = result.targets.map(target => formatCursorScmDispatchOutcome(target)).join(", ");
2576
- const rejected = result.targets.filter(target => target.status >= 400);
2577
- if (rejected.length > 0) {
2578
- logger(
2579
- `[agent-sdk] cursor-events: dropped ${formatCursorScmEventLog(event)} before hook: ${rejected.map(formatCursorScmDispatchOutcome).join(", ")}`,
2580
- );
2581
- }
2582
- logger(
2583
- `[agent-sdk] cursor-events: dispatched ${formatCursorScmEventLog(event)}${outcomes === "" ? "" : ` → ${outcomes}`}`,
2584
- );
2585
- }
2586
-
2587
- interface CursorGithubTarget {
2588
- slug: string;
2589
- channelId: string;
2590
- accountRuntime: GithubCursorAccountRuntime;
2591
- }
2592
-
2593
- function collectCursorGithubTargets(mounts: AgentMount[]): CursorGithubTarget[] {
2594
- const targets: CursorGithubTarget[] = [];
2595
- for (const mount of mounts) {
2596
- for (const channel of mount.project.channels) {
2597
- const accountRuntime = getGithubCursorAccountRuntime(channel.definition);
2598
- if (accountRuntime !== undefined) {
2599
- targets.push({
2600
- slug: mount.slug,
2601
- channelId: channel.id,
2602
- accountRuntime,
2603
- });
2604
- }
2605
- }
2606
- }
2607
- return targets;
2608
- }
2609
-
2610
- interface CursorGithubConfigResolution {
2611
- cursorEvents: ServeOptions["cursorEvents"];
2612
- scope: CursorGithubRepoScope | undefined;
2613
- permissions: CursorGithubRepoScope["permissions"];
2614
- }
2615
-
2616
- function cursorGithubPermissionsForTarget(
2617
- target: CursorGithubTarget,
2618
- ): CursorGithubRepoScope["permissions"] {
2619
- const authored =
2620
- typeof target.accountRuntime.options.cursorAccount === "object"
2621
- ? target.accountRuntime.options.cursorAccount.permissions
2622
- : undefined;
2623
- return (
2624
- target.accountRuntime.scope?.permissions ??
2625
- cursorGithubPermissionsForChannel(target.accountRuntime.options, authored)
2626
- );
2627
- }
2628
-
2629
- function resolveCursorGithubEventConfig(input: {
2630
- configured: ServeOptions["cursorEvents"];
2631
- targets: CursorGithubTarget[];
2632
- }): CursorGithubConfigResolution {
2633
- if (input.targets.length === 0) {
2634
- return {
2635
- cursorEvents: input.configured,
2636
- scope: undefined,
2637
- permissions: "pr-write",
2638
- };
2639
- }
2640
- const repos = [
2641
- ...(input.configured?.repos ?? []),
2642
- ...input.targets.flatMap(target => [...(target.accountRuntime.scope?.repos ?? [])]),
2643
- ];
2644
- const permissions = resolveCursorGithubPermissions(
2645
- input.targets.map(cursorGithubPermissionsForTarget),
2646
- );
2647
- const scope = resolveCursorGithubCredentialScope(repos, permissions);
2648
- if (scope === undefined) {
2649
- return {
2650
- cursorEvents: input.configured,
2651
- scope: undefined,
2652
- permissions,
2653
- };
2654
- }
2655
- return {
2656
- cursorEvents: {
2657
- ...input.configured,
2658
- repos: [...scope.repos],
2659
- },
2660
- scope,
2661
- permissions,
2662
- };
2663
- }
2664
-
2665
- interface CursorOriginTarget {
2666
- slug: string;
2667
- channelId: string;
2668
- accountRuntime: OriginCursorAccountRuntime;
2669
- }
2670
-
2671
- function collectCursorOriginTargets(mounts: AgentMount[]): CursorOriginTarget[] {
2672
- const targets: CursorOriginTarget[] = [];
2673
- for (const mount of mounts) {
2674
- for (const channel of mount.project.channels) {
2675
- const accountRuntime = getOriginCursorAccountRuntime(channel.definition);
2676
- if (accountRuntime !== undefined) {
2677
- targets.push({
2678
- slug: mount.slug,
2679
- channelId: channel.id,
2680
- accountRuntime,
2681
- });
2682
- }
2683
- }
2684
- }
2685
- return targets;
2686
- }
2687
-
2688
- /**
2689
- * Origin cursorAccount repos. `true` takes the host's explicit `--repo`
2690
- * list (not GitHub channel-declared repos). `{ repos }` is self-contained.
2691
- */
2692
- function resolveCursorOriginRepoScope(input: {
2693
- explicitRepos: readonly string[];
2694
- targets: CursorOriginTarget[];
2695
- }): ReturnType<typeof parseCursorOriginRepoScope> | undefined {
2696
- if (input.targets.length === 0) {
2697
- return undefined;
2698
- }
2699
- const wantsHostRepos = input.targets.some(
2700
- target => target.accountRuntime.options.cursorAccount === true,
2701
- );
2702
- const repos = [
2703
- ...(wantsHostRepos ? input.explicitRepos : []),
2704
- ...input.targets.flatMap(target => target.accountRuntime.scope?.repos ?? []),
2705
- ];
2706
- if (repos.length === 0) {
2707
- return undefined;
2708
- }
2709
- return parseCursorOriginRepoScope(repos);
2710
- }
2711
-
2712
- function buildAgentIndexEntries(runtimes: MountedRuntime[]): AgentIndexEntry[] {
2713
- return runtimes.map(({ slug, project }) => {
2714
- const hasSlack = project.channels.some(channel => channel.definition.meta?.kind === "slack");
2715
- return {
2716
- slug,
2717
- name: project.name,
2718
- model:
2719
- typeof project.agent.model === "string"
2720
- ? project.agent.model
2721
- : (project.agent.model?.id ?? ""),
2722
- tools: project.agent.tools.length,
2723
- channels: project.channels.length + 1,
2724
- slack: hasSlack ? { kind: "socket" as const } : undefined,
2725
- };
2726
- });
2727
- }
2728
-
2729
- interface CursorDeploymentTarget {
2730
- runtime: MountedRuntime;
2731
- channelId: string;
2732
- options: DeploymentsChannelOptions;
2733
- }
2734
-
2735
- /** Every mounted `deploymentsChannel`. Subscriptions are re-resolved live. */
2736
- function collectCursorDeploymentTargets(runtimes: MountedRuntime[]): CursorDeploymentTarget[] {
2737
- const targets: CursorDeploymentTarget[] = [];
2738
- for (const runtime of runtimes) {
2739
- for (const channel of runtime.project.channels) {
2740
- const options = getDeploymentsChannelOptions(channel.definition);
2741
- if (options === undefined) {
2742
- continue;
2743
- }
2744
- targets.push({
2745
- runtime,
2746
- channelId: channel.id,
2747
- options,
2748
- });
2749
- }
2750
- }
2751
- return targets;
2752
- }
2753
-
2754
- function liveDeploymentSubscriptionUnion(
2755
- targets: readonly CursorDeploymentTarget[],
2756
- ): ResolvedSubscription[] {
2757
- return mergeResolvedSubscriptions(
2758
- targets.map(target => resolveDeploymentSubscriptions(target.options)),
2759
- );
2760
- }
2761
-
2762
- /**
2763
- * Cursor deployment-events relay: automatic when a mounted agent authored
2764
- * `deploymentsChannel({ ... })`. One relay per process reads
2765
- * `/v0/deployment-events` for the union of every channel's deploy sources, and
2766
- * each event is routed to the channels that asked for it — the same ownership
2767
- * `startCursorEventRelay` has.
2768
- */
2769
- function startCursorDeploymentRelay(input: {
2770
- options: ServeOptions;
2771
- runtimes: MountedRuntime[];
2772
- accountKey: ResolvedApiKey | undefined;
2773
- logger: (line: string) => void;
2774
- }): DeploymentEventRelay | undefined {
2775
- const { options, runtimes, accountKey, logger } = input;
2776
- const targets = collectCursorDeploymentTargets(runtimes);
2777
- if (targets.length === 0) {
2778
- return undefined;
2779
- }
2780
- if (accountKey === undefined) {
2781
- if (input.options.allowAnonymous === true) {
2782
- logger(
2783
- "[agent-sdk] deployment-events: skipped while unsigned; long-poll relays need a key at start",
2784
- );
2785
- return undefined;
2786
- }
2787
- throw new Error(
2788
- `This project has channels subscribed to deployment events (deploymentsChannel({ ... })) but the host is not signed in to Cursor. ${SIGN_IN_HINT}`,
2789
- );
2790
- }
2791
- // Union is re-resolved on each heartbeat and fan-out so a channel that
2792
- // fills `deploySourceUris` after start registers the new URIs. This wire
2793
- // names every source, so a channel that omits the option registers nothing.
2794
- const initial = liveDeploymentSubscriptionUnion(targets);
2795
- if (initial.length === 0) {
2796
- logger(
2797
- `[agent-sdk] deployment-events: no deploy sources yet on ${targets
2798
- .map(target => `${target.runtime.slug || target.runtime.project.name}/${target.channelId}`)
2799
- .join(", ")}; the relay will register when a channel lists some`,
2800
- );
2801
- }
2802
- // Same host split as scm-events: `/v0/deployment-events/*` is on
2803
- // api.cursor.com, not api2.
2804
- const baseStateRoot =
2805
- options.stateRoot ?? join(targets[0].runtime.project.rootDir, ".agent-serve");
2806
- const relay = new DeploymentEventRelay({
2807
- baseUrl: cursorExternalApiUrl(),
2808
- apiKey: accountKey.apiKey,
2809
- stateDir: join(baseStateRoot, "deployment-events"),
2810
- subscriptions: () => liveDeploymentSubscriptionUnion(targets),
2811
- logger,
2812
- dispatch: async event =>
2813
- fanOutDeploymentEvent({
2814
- event,
2815
- logger,
2816
- targets: targets.map(target => ({
2817
- name: `${target.runtime.slug || target.runtime.project.name}/${target.channelId}`,
2818
- subscriptions: resolveDeploymentSubscriptions(target.options),
2819
- deliver: delivered =>
2820
- dispatchDeploymentEvent({
2821
- options: target.options,
2822
- event: delivered,
2823
- args: buildChannelHandlerArgs({
2824
- runtime: target.runtime,
2825
- channelId: target.channelId,
2826
- }),
2827
- }),
2828
- })),
2829
- }),
2830
- });
2831
- relay.start();
2832
- logger(
2833
- `[agent-sdk] deployment-events: relaying ${initial.length} deploy-source subscription(s) to ${targets.length} channel(s)`,
2834
- );
2835
- return relay;
2836
- }
2837
-
2838
- function buildChannelHandlerArgs(input: {
2839
- runtime: MountedRuntime;
2840
- channelId: string;
2841
- params?: Record<string, string>;
2842
- requestIp?: string | null;
2843
- auth?: AuthContext | null;
2844
- hostedSessionId?: string;
2845
- }): ChannelHandlerArgs {
2846
- const { runtime, channelId } = input;
2847
- const base = runtime.slug === "" ? "" : `/${runtime.slug}`;
2848
- const auth = input.auth ?? null;
2849
- return {
2850
- params: input.params ?? {},
2851
- requestIp: input.requestIp ?? null,
2852
- auth,
2853
- host: runtime.engine.host,
2854
- artifacts: runtime.engine.artifacts,
2855
- send: (message, sendOptions = {}) =>
2856
- runtime.engine.send(channelId, message, {
2857
- ...sendOptions,
2858
- auth: sendOptions.auth !== undefined ? sendOptions.auth : auth,
2859
- hostedSessionId: input.hostedSessionId,
2860
- }),
2861
- getSession: sessionId => runtime.engine.getChannelSession(channelId, sessionId),
2862
- receive: (target, inputReceive) => runtime.engine.receive(target, inputReceive),
2863
- callTool: (toolName, toolInput, callOptions) =>
2864
- runtime.engine.callTool(toolName, toolInput, callOptions),
2865
- waitUntil: promise => {
2866
- runtime.engine.trackBackground(promise);
2867
- },
2868
- sessionUrls: (req, sessionId) => sessionUrlsForRequest(req, base, sessionId),
2869
- hasContinuationSession: continuationToken =>
2870
- runtime.engine.hasContinuationSession(channelId, continuationToken),
2871
- isContinuationBusy: continuationToken =>
2872
- runtime.engine.isContinuationBusy(channelId, continuationToken),
2873
- getContinuationLastBotMessageTs: continuationToken =>
2874
- runtime.engine.getContinuationLastBotMessageTs(channelId, continuationToken),
2875
- interruptContinuation: continuationToken =>
2876
- runtime.engine.interruptContinuation(channelId, continuationToken),
2877
- };
2878
- }
2879
-
2880
- async function handleRequest(
2881
- router: Router,
2882
- req: IncomingMessage,
2883
- res: ServerResponse,
2884
- logger: (line: string) => void,
2885
- browserOriginGuard?: BrowserOriginGuardOptions,
2886
- ): Promise<void> {
2887
- let response: Response;
2888
- let hostedDeliveryRequest = false;
2889
- const method = req.method ?? "GET";
2890
- try {
2891
- const request = await toFetchRequest(req);
2892
- hostedDeliveryRequest = request.headers.get(HOSTED_DELIVERY_HEADER) === "1";
2893
- const requestErrorResponse = (status: number, error: string, message: string) =>
2894
- hostedDeliveryRequest
2895
- ? hostedGuestErrorResponse({
2896
- status,
2897
- error,
2898
- retry: HOSTED_GUEST_RETRY_TERMINAL,
2899
- message,
2900
- })
2901
- : errorResponse(status, error, message);
2902
- const url = new URL(request.url);
2903
- const match = router.match(request.method, url.pathname);
2904
- if (!isTrustedBrowserMutation(request, browserOriginGuard)) {
2905
- response = requestErrorResponse(
2906
- 403,
2907
- "forbidden_origin",
2908
- "Cross-origin browser mutations are not allowed.",
2909
- );
2910
- } else if (match === undefined) {
2911
- response = router.hasPath(url.pathname)
2912
- ? requestErrorResponse(
2913
- 405,
2914
- "method_not_allowed",
2915
- `${request.method} is not supported on ${url.pathname}.`,
2916
- )
2917
- : requestErrorResponse(404, "not_found", `No route for ${request.method} ${url.pathname}.`);
2918
- } else {
2919
- const requestIp = req.socket.remoteAddress ?? null;
2920
- let auth: AuthContext | null = null;
2921
- let unauthorized = false;
2922
- if (match.route.auth !== "none") {
2923
- auth = await resolveAuth(match.route.auth, request, requestIp);
2924
- unauthorized = auth === null;
2925
- }
2926
- response = unauthorized
2927
- ? requestErrorResponse(
2928
- 401,
2929
- "unauthorized",
2930
- "No auth policy admitted this request. In production, configure channel auth (e.g. bearerAuth) — the default localDevStrict() policy only admits loopback callers with a loopback Host.",
2931
- )
2932
- : await match.route.handler(request, {
2933
- params: match.params,
2934
- requestIp,
2935
- auth,
2936
- });
2937
- }
2938
- } catch (error) {
2939
- const mapped = mapThrownRequestError(error);
2940
- if (mapped !== undefined) {
2941
- response = hostedDeliveryRequest
2942
- ? hostedGuestErrorResponse({
2943
- status: mapped.status,
2944
- error: mapped.code,
2945
- retry: mapped.retry,
2946
- message: mapped.message,
2947
- })
2948
- : errorResponse(mapped.status, mapped.code, mapped.message);
2949
- } else {
2950
- logger(
2951
- `[agent-sdk] request failed: ${
2952
- error instanceof Error ? (error.stack ?? error.message) : String(error)
2953
- }`,
2954
- );
2955
- const snippet = hostedErrorStackSnippet(error);
2956
- const message = hostedDeliveryRequest
2957
- ? hostedErrorMessageOnly(error)
2958
- : snippet.length > 0
2959
- ? `Internal server error: ${snippet}`
2960
- : "Internal server error.";
2961
- response = hostedDeliveryRequest
2962
- ? hostedGuestErrorResponse({
2963
- status: 500,
2964
- error: "internal_error",
2965
- retry: HOSTED_GUEST_RETRY_TERMINAL,
2966
- message,
2967
- })
2968
- : errorResponse(500, "internal_error", message);
2969
- }
2970
- }
2971
-
2972
- try {
2973
- await writeFetchResponse(response, res, method);
2974
- } catch (error) {
2975
- logger(
2976
- `[agent-sdk] response write failed: ${
2977
- error instanceof Error ? error.message : String(error)
2978
- }`,
2979
- );
2980
- res.destroy();
2981
- }
2982
- }
2983
-
2984
- async function resolveAuth(
2985
- policies: AuthPolicy[],
2986
- request: Request,
2987
- requestIp: string | null,
2988
- ): Promise<AuthContext | null> {
2989
- for (const policy of policies) {
2990
- const result = await policy(request, { requestIp });
2991
- if (result !== null) {
2992
- return result;
2993
- }
2994
- }
2995
- return null;
2996
- }
2997
-
2998
- async function toFetchRequest(req: IncomingMessage): Promise<Request> {
2999
- const method = req.method ?? "GET";
3000
- const hostHeader = incomingRequestHost(req.headers);
3001
- const url = new URL(req.url ?? "/", `http://${hostHeader}`);
3002
- // Drop HTTP/2 pseudo-headers (`:method`, …) — Fetch `Headers` rejects them.
3003
- const headers = incomingHeadersToFetch(req.headers);
3004
-
3005
- if (method === "GET" || method === "HEAD") {
3006
- return new Request(url, { method, headers });
3007
- }
3008
- const body = await readBody(req);
3009
- // Buffer is a Uint8Array at runtime; TS's BodyInit wants ArrayBuffer-backed
3010
- // typed arrays, so re-view without copying.
3011
- return new Request(url, {
3012
- method,
3013
- headers,
3014
- body: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) as Uint8Array<ArrayBuffer>,
3015
- });
3016
- }
3017
-
3018
- async function readBody(req: IncomingMessage): Promise<Buffer> {
3019
- const chunks: Buffer[] = [];
3020
- let total = 0;
3021
- for await (const chunk of req) {
3022
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
3023
- total += buffer.length;
3024
- if (total > MAX_BODY_BYTES) {
3025
- throw new Error("Request body too large");
3026
- }
3027
- chunks.push(buffer);
3028
- }
3029
- return Buffer.concat(chunks);
3030
- }
3031
-
3032
- async function writeFetchResponse(
3033
- response: Response,
3034
- res: ServerResponse,
3035
- method = "GET",
3036
- ): Promise<void> {
3037
- const headers: Record<string, string> = {};
3038
- response.headers.forEach((value, key) => {
3039
- headers[key] = value;
3040
- });
3041
- res.writeHead(response.status, headers);
3042
-
3043
- // HEAD responses must not include a body (RFC 9110 §9.3.2). Cancel any
3044
- // handler-produced stream so long-lived GET handlers (e.g. session SSE)
3045
- // still unsubscribe when served via the HEAD→GET fallback.
3046
- if (method === "HEAD" || response.body === null) {
3047
- if (response.body !== null) {
3048
- void response.body.cancel().catch(() => {});
3049
- }
3050
- res.end();
3051
- return;
3052
- }
3053
-
3054
- const reader = response.body.getReader();
3055
- let clientGone = false;
3056
- const closed = new Promise<void>(resolve => {
3057
- res.once("close", () => {
3058
- if (!res.writableFinished) {
3059
- clientGone = true;
3060
- void reader.cancel().catch(() => {});
3061
- }
3062
- resolve();
3063
- });
3064
- });
3065
-
3066
- try {
3067
- while (!clientGone) {
3068
- const { done, value } = await reader.read();
3069
- if (done) {
3070
- break;
3071
- }
3072
- if (value !== undefined && value.length > 0) {
3073
- if (!res.write(value) && !clientGone) {
3074
- // Race against close so a vanished client can't wedge the loop
3075
- // waiting for a drain that will never come.
3076
- await Promise.race([once(res, "drain"), closed]);
3077
- }
3078
- }
3079
- }
3080
- } catch {
3081
- void reader.cancel().catch(() => {});
3082
- }
3083
- res.end();
3084
- }
3085
-
3086
- /**
3087
- * Dev reminder routes may only inspect/fire reminders whose bound session
3088
- * belongs to the caller (same principal), matching session read routes.
3089
- * Loopback `--dev` (and `--allow-anonymous`) can relax ownership like
3090
- * `GET /v1/sessions`.
3091
- */
3092
- function asStringArray(value: unknown): string[] | undefined {
3093
- if (!Array.isArray(value)) {
3094
- return undefined;
3095
- }
3096
- const out: string[] = [];
3097
- for (const item of value) {
3098
- if (typeof item === "string" && item.trim() !== "") {
3099
- out.push(item);
3100
- }
3101
- }
3102
- return out.length === 0 ? undefined : out;
3103
- }
3104
-
3105
- function asPositiveInt(value: unknown): number | undefined {
3106
- if (typeof value !== "number" || !Number.isFinite(value)) {
3107
- return undefined;
3108
- }
3109
- const n = Math.floor(value);
3110
- return n > 0 ? n : undefined;
3111
- }
3112
-
3113
- async function assertReminderReadable(input: {
3114
- engine: SessionEngine;
3115
- reminder: ReminderInfo;
3116
- auth: AuthContext | null;
3117
- requestIp?: string | null;
3118
- relax: boolean;
3119
- beyondLoopback: boolean;
3120
- }): Promise<Response | undefined> {
3121
- const existing = await input.engine.sessions.findByContinuation(
3122
- input.reminder.channelId,
3123
- input.reminder.continuationToken,
3124
- );
3125
- if (existing === undefined) {
3126
- // No live session — still gate on relax/loopback so a shared-dev caller
3127
- // cannot enumerate orphan reminder metadata across principals.
3128
- const relaxOwnership =
3129
- input.relax === true &&
3130
- (input.beyondLoopback === true ||
3131
- (typeof input.requestIp === "string" && isLoopbackAddress(input.requestIp)));
3132
- if (relaxOwnership) {
3133
- return undefined;
3134
- }
3135
- // Without a session principal to compare, deny non-relaxed callers.
3136
- return errorResponse(
3137
- 403,
3138
- "forbidden",
3139
- "This reminder is bound to a session that is not visible to the caller.",
3140
- );
3141
- }
3142
- return requireSessionOwner(existing, input.auth, {
3143
- relax: input.relax,
3144
- beyondLoopback: input.beyondLoopback,
3145
- requestIp: input.requestIp,
3146
- });
3147
- }