@cursor/bdk 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (577) hide show
  1. package/dist/bin/agent-serve.js +9 -1
  2. package/dist/channels/slack/attachments.d.ts +2 -1
  3. package/dist/channels/slack/attachments.d.ts.map +1 -1
  4. package/dist/channels/slack/attachments.js +19 -9
  5. package/dist/channels/slack/dispatch.d.ts.map +1 -1
  6. package/dist/channels/slack/dispatch.js +26 -24
  7. package/dist/channels/slack/thread-context.d.ts +21 -11
  8. package/dist/channels/slack/thread-context.d.ts.map +1 -1
  9. package/dist/channels/slack/thread-context.js +75 -27
  10. package/dist/docs/404.html +2 -2
  11. package/dist/docs/assets/{app.BOIHhrKi.js → app.4kQ8Db_q.js} +4 -4
  12. package/dist/docs/assets/chunks/@localSearchIndexroot.CvuAJ0My.js +1 -0
  13. package/dist/docs/assets/chunks/{VPLocalSearchBox.D49zVZqM.js → VPLocalSearchBox.DY1RwB8Q.js} +1 -1
  14. package/dist/docs/assets/chunks/{arc.hmjb-sc4.js → arc.CxE_fSPK.js} +1 -1
  15. package/dist/docs/assets/chunks/{architectureDiagram-Q4EWVU46.CxEI1KqM.js → architectureDiagram-Q4EWVU46.CPX426ui.js} +1 -1
  16. package/dist/docs/assets/chunks/{baseUniq.DHHvBWoV.js → baseUniq.CB52JrKG.js} +1 -1
  17. package/dist/docs/assets/chunks/{blockDiagram-DXYQGD6D.DnXW-3bu.js → blockDiagram-DXYQGD6D.J0cNaQCL.js} +1 -1
  18. package/dist/docs/assets/chunks/{c4Diagram-AHTNJAMY.e-47O2jM.js → c4Diagram-AHTNJAMY.DJn3vEGT.js} +1 -1
  19. package/dist/docs/assets/chunks/channel.BoNycAoN.js +1 -0
  20. package/dist/docs/assets/chunks/{chunk-4BX2VUAB.3ry4pYXB.js → chunk-4BX2VUAB.Dao618F6.js} +1 -1
  21. package/dist/docs/assets/chunks/{chunk-4TB4RGXK.DGIZFRx6.js → chunk-4TB4RGXK.QW8Rhjai.js} +1 -1
  22. package/dist/docs/assets/chunks/{chunk-55IACEB6.DKBnqg9U.js → chunk-55IACEB6.DfRLLKF_.js} +1 -1
  23. package/dist/docs/assets/chunks/{chunk-EDXVE4YY.BIU8Ue5k.js → chunk-EDXVE4YY.CIV2ApKQ.js} +1 -1
  24. package/dist/docs/assets/chunks/{chunk-FMBD7UC4.DP-TFhjI.js → chunk-FMBD7UC4.BEheSuxp.js} +1 -1
  25. package/dist/docs/assets/chunks/{chunk-OYMX7WX6.Ux0OYj5v.js → chunk-OYMX7WX6.CUN88ENB.js} +1 -1
  26. package/dist/docs/assets/chunks/{chunk-QZHKN3VN.BzHMwYox.js → chunk-QZHKN3VN.CgqCs8b_.js} +1 -1
  27. package/dist/docs/assets/chunks/{chunk-YZCP3GAM.D4OGAsSP.js → chunk-YZCP3GAM.iCH0nnTJ.js} +1 -1
  28. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.C4x07Gkj.js +1 -0
  29. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.C4x07Gkj.js +1 -0
  30. package/dist/docs/assets/chunks/clone.Db22cH_-.js +1 -0
  31. package/dist/docs/assets/chunks/{cose-bilkent-S5V4N54A.Jq_7BUNx.js → cose-bilkent-S5V4N54A.BLcUxhWE.js} +1 -1
  32. package/dist/docs/assets/chunks/{dagre-KV5264BT.Di-skR2x.js → dagre-KV5264BT.Ep7LofOm.js} +1 -1
  33. package/dist/docs/assets/chunks/{diagram-5BDNPKRD.DeREHIdH.js → diagram-5BDNPKRD.Bzf4GSQ4.js} +1 -1
  34. package/dist/docs/assets/chunks/{diagram-G4DWMVQ6.C7Kcqxro.js → diagram-G4DWMVQ6.DD6Jh-eM.js} +1 -1
  35. package/dist/docs/assets/chunks/{diagram-MMDJMWI5.BK3eohyo.js → diagram-MMDJMWI5.oOIl8bWd.js} +1 -1
  36. package/dist/docs/assets/chunks/{diagram-TYMM5635.C6TyymXT.js → diagram-TYMM5635.DHs85Ade.js} +1 -1
  37. package/dist/docs/assets/chunks/{erDiagram-SMLLAGMA.DYGG-gGx.js → erDiagram-SMLLAGMA.BIb5ghCk.js} +1 -1
  38. package/dist/docs/assets/chunks/{flowDiagram-DWJPFMVM.C9nBcSV4.js → flowDiagram-DWJPFMVM.DV4paY9k.js} +1 -1
  39. package/dist/docs/assets/chunks/{ganttDiagram-T4ZO3ILL.wAg_ymsp.js → ganttDiagram-T4ZO3ILL.AyEKA6_v.js} +1 -1
  40. package/dist/docs/assets/chunks/{gitGraphDiagram-UUTBAWPF.B87j9Oeg.js → gitGraphDiagram-UUTBAWPF.BltiCDFo.js} +1 -1
  41. package/dist/docs/assets/chunks/{graph.CuFMj31w.js → graph.DzuEYGdC.js} +1 -1
  42. package/dist/docs/assets/chunks/{infoDiagram-42DDH7IO.P_mLGumP.js → infoDiagram-42DDH7IO.BV2l981J.js} +1 -1
  43. package/dist/docs/assets/chunks/{ishikawaDiagram-UXIWVN3A.DyuL_MsT.js → ishikawaDiagram-UXIWVN3A.BA4Izf-m.js} +1 -1
  44. package/dist/docs/assets/chunks/{journeyDiagram-VCZTEJTY.CtP09IoJ.js → journeyDiagram-VCZTEJTY.DjaFbFS3.js} +1 -1
  45. package/dist/docs/assets/chunks/{kanban-definition-6JOO6SKY.BoeSYPZo.js → kanban-definition-6JOO6SKY.CfTFieDs.js} +1 -1
  46. package/dist/docs/assets/chunks/{layout.B0lMMtNo.js → layout.DzfWqTBV.js} +1 -1
  47. package/dist/docs/assets/chunks/{linear.HxRBiAFX.js → linear.BO6mpulV.js} +1 -1
  48. package/dist/docs/assets/chunks/{min.BGlFFHwS.js → min.BGgTadgT.js} +1 -1
  49. package/dist/docs/assets/chunks/{mindmap-definition-QFDTVHPH.JyLBD9M8.js → mindmap-definition-QFDTVHPH.DPuIXVWY.js} +1 -1
  50. package/dist/docs/assets/chunks/{pieDiagram-DEJITSTG.DnSmNZF8.js → pieDiagram-DEJITSTG.BOnl3bBg.js} +1 -1
  51. package/dist/docs/assets/chunks/{quadrantDiagram-34T5L4WZ.CUCnbfCa.js → quadrantDiagram-34T5L4WZ.DNB6Ckdc.js} +1 -1
  52. package/dist/docs/assets/chunks/{requirementDiagram-MS252O5E.py0IVUn5.js → requirementDiagram-MS252O5E.D5-Qo7vb.js} +1 -1
  53. package/dist/docs/assets/chunks/{sankeyDiagram-XADWPNL6.Bkc-HWYp.js → sankeyDiagram-XADWPNL6.8t65cesf.js} +1 -1
  54. package/dist/docs/assets/chunks/{sequenceDiagram-FGHM5R23.Dqn8Mlv2.js → sequenceDiagram-FGHM5R23.CaG07BdS.js} +1 -1
  55. package/dist/docs/assets/chunks/{stateDiagram-FHFEXIEX.JikkoQUU.js → stateDiagram-FHFEXIEX.TKOweTB6.js} +1 -1
  56. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CuqmyQc4.js +1 -0
  57. package/dist/docs/assets/chunks/{theme.b6HQ6zG_.js → theme.Dx-JhpTB.js} +2 -2
  58. package/dist/docs/assets/chunks/{timeline-definition-GMOUNBTQ.BvpSXiBj.js → timeline-definition-GMOUNBTQ.fE53zQ2s.js} +1 -1
  59. package/dist/docs/assets/chunks/{vennDiagram-DHZGUBPP.CU7MVnZx.js → vennDiagram-DHZGUBPP.DJsZZaJg.js} +1 -1
  60. package/dist/docs/assets/chunks/{wardley-RL74JXVD.BKwC4ctG.js → wardley-RL74JXVD.844kyrjl.js} +1 -1
  61. package/dist/docs/assets/chunks/{wardleyDiagram-NUSXRM2D.BfaF6Uhe.js → wardleyDiagram-NUSXRM2D.CMZ-Ru_t.js} +1 -1
  62. package/dist/docs/assets/chunks/{xychartDiagram-5P7HB3ND.Bg5dcpj4.js → xychartDiagram-5P7HB3ND.XXrhBc7a.js} +1 -1
  63. package/dist/docs/assets/{deployment.md.BJ8i7Q6p.js → deployment.md.UhnJIMr-.js} +2 -2
  64. package/dist/docs/assets/{deployment.md.BJ8i7Q6p.lean.js → deployment.md.UhnJIMr-.lean.js} +1 -1
  65. package/dist/docs/assets/{guides_jev.md.BNDm14Gy.js → guides_jev.md.CRcgmjDb.js} +2 -2
  66. package/dist/docs/assets/{guides_jev.md.BNDm14Gy.lean.js → guides_jev.md.CRcgmjDb.lean.js} +1 -1
  67. package/dist/docs/assets/{reference_agent-config.md.DzGI777n.js → reference_agent-config.md.Cj5uBKp4.js} +1 -1
  68. package/dist/docs/assets/{reference_extensions.md.CPPrkWlJ.js → reference_extensions.md.pa2tN-e4.js} +4 -3
  69. package/dist/docs/assets/{reference_extensions.md.CPPrkWlJ.lean.js → reference_extensions.md.pa2tN-e4.lean.js} +1 -1
  70. package/dist/docs/building-with-agents.html +35 -35
  71. package/dist/docs/deployment.html +37 -37
  72. package/dist/docs/deployment.md +4 -1
  73. package/dist/docs/evals.html +35 -35
  74. package/dist/docs/guides/agent-to-agent.html +35 -35
  75. package/dist/docs/guides/bitbucket.html +35 -35
  76. package/dist/docs/guides/cloud-agents.html +35 -35
  77. package/dist/docs/guides/convert-automation.html +35 -35
  78. package/dist/docs/guides/github.html +35 -35
  79. package/dist/docs/guides/gitlab.html +35 -35
  80. package/dist/docs/guides/grokbot-agents.html +35 -35
  81. package/dist/docs/guides/hooks.html +35 -35
  82. package/dist/docs/guides/improve.html +35 -35
  83. package/dist/docs/guides/jev.html +37 -37
  84. package/dist/docs/guides/jev.md +7 -0
  85. package/dist/docs/guides/mcp-oauth.html +35 -35
  86. package/dist/docs/guides/opentelemetry.html +35 -35
  87. package/dist/docs/guides/slack.html +35 -35
  88. package/dist/docs/guides/webhooks.html +35 -35
  89. package/dist/docs/hashmap.json +1 -1
  90. package/dist/docs/hillclimbing.html +35 -35
  91. package/dist/docs/index.html +35 -35
  92. package/dist/docs/llms-full.txt +25 -2
  93. package/dist/docs/quickstart.html +35 -35
  94. package/dist/docs/reference/agent-config.html +37 -37
  95. package/dist/docs/reference/agent-config.md +1 -1
  96. package/dist/docs/reference/artifacts.html +35 -35
  97. package/dist/docs/reference/channels.html +35 -35
  98. package/dist/docs/reference/cli.html +35 -35
  99. package/dist/docs/reference/connections.html +35 -35
  100. package/dist/docs/reference/evals.html +35 -35
  101. package/dist/docs/reference/extensions.html +39 -38
  102. package/dist/docs/reference/extensions.md +13 -0
  103. package/dist/docs/reference/hooks.html +35 -35
  104. package/dist/docs/reference/http-api.html +35 -35
  105. package/dist/docs/reference/instructions.html +35 -35
  106. package/dist/docs/reference/playground.html +35 -35
  107. package/dist/docs/reference/project-layout.html +35 -35
  108. package/dist/docs/reference/prompt.html +35 -35
  109. package/dist/docs/reference/schedules.html +35 -35
  110. package/dist/docs/reference/sessions.html +35 -35
  111. package/dist/docs/reference/skills.html +35 -35
  112. package/dist/docs/reference/subagents.html +35 -35
  113. package/dist/docs/reference/tools.html +35 -35
  114. package/dist/docs/templates/agentic-owners.html +35 -35
  115. package/dist/docs/templates/security-reviewer.html +35 -35
  116. package/dist/docs/templates/thermo-quality-review.html +35 -35
  117. package/dist/docs/templates/thermo-review.html +35 -35
  118. package/dist/docs/templates/triage.html +35 -35
  119. package/dist/docs/troubleshooting.html +35 -35
  120. package/dist/extensions/jev/extension.d.ts +3 -0
  121. package/dist/extensions/jev/extension.d.ts.map +1 -1
  122. package/dist/extensions/jev/extension.js +10 -1
  123. package/dist/extensions/jev/lib/evaluate.d.ts +4 -0
  124. package/dist/extensions/jev/lib/evaluate.d.ts.map +1 -1
  125. package/dist/extensions/jev/lib/evaluate.js +6 -2
  126. package/dist/extensions.d.ts +4 -2
  127. package/dist/extensions.d.ts.map +1 -1
  128. package/dist/extensions.js +5 -2
  129. package/dist/internal/cli-deploy.d.ts.map +1 -1
  130. package/dist/internal/cli-deploy.js +19 -5
  131. package/dist/internal/discovery/agent-config.d.ts +6 -5
  132. package/dist/internal/discovery/agent-config.d.ts.map +1 -1
  133. package/dist/internal/discovery/agent-config.js +29 -28
  134. package/dist/internal/discovery/agent.js +1 -1
  135. package/dist/internal/discovery/extensions.d.ts.map +1 -1
  136. package/dist/internal/discovery/extensions.js +12 -0
  137. package/dist/internal/hosting.d.ts +8 -0
  138. package/dist/internal/hosting.d.ts.map +1 -1
  139. package/dist/internal/hosting.js +24 -0
  140. package/dist/types.d.ts +18 -2
  141. package/dist/types.d.ts.map +1 -1
  142. package/docs/deployment.md +4 -1
  143. package/docs/guides/jev.md +7 -0
  144. package/docs/reference/agent-config.md +1 -1
  145. package/docs/reference/extensions.md +13 -0
  146. package/package.json +1 -9
  147. package/dist/docs/assets/chunks/@localSearchIndexroot.D5L-b34G.js +0 -1
  148. package/dist/docs/assets/chunks/channel.BbOGaJQP.js +0 -1
  149. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.Db58HCb1.js +0 -1
  150. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.Db58HCb1.js +0 -1
  151. package/dist/docs/assets/chunks/clone.Co4MBflG.js +0 -1
  152. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CMsKhrW0.js +0 -1
  153. package/src/artifacts.ts +0 -68
  154. package/src/bin/agent-serve.ts +0 -1854
  155. package/src/channels/bitbucket/api.ts +0 -891
  156. package/src/channels/bitbucket/binding.ts +0 -417
  157. package/src/channels/bitbucket/bitbucket-channel.ts +0 -162
  158. package/src/channels/bitbucket/bitbucket-webhook.ts +0 -519
  159. package/src/channels/bitbucket/checks.ts +0 -146
  160. package/src/channels/bitbucket/cursor-account.ts +0 -106
  161. package/src/channels/bitbucket/defaults.ts +0 -100
  162. package/src/channels/bitbucket/events.ts +0 -74
  163. package/src/channels/bitbucket/index.ts +0 -51
  164. package/src/channels/bitbucket/replay.ts +0 -421
  165. package/src/channels/bitbucket/state.ts +0 -59
  166. package/src/channels/bitbucket/types.ts +0 -261
  167. package/src/channels/change-monitors/change-monitors-channel.ts +0 -63
  168. package/src/channels/change-monitors/index.ts +0 -8
  169. package/src/channels/change-monitors/types.ts +0 -42
  170. package/src/channels/checks.ts +0 -185
  171. package/src/channels/deployments/deployments-channel.ts +0 -224
  172. package/src/channels/deployments/index.ts +0 -25
  173. package/src/channels/deployments/types.ts +0 -92
  174. package/src/channels/github/api.ts +0 -526
  175. package/src/channels/github/auth.ts +0 -293
  176. package/src/channels/github/binding.ts +0 -233
  177. package/src/channels/github/checks.ts +0 -145
  178. package/src/channels/github/cursor-account.ts +0 -303
  179. package/src/channels/github/defaults.ts +0 -168
  180. package/src/channels/github/events.ts +0 -67
  181. package/src/channels/github/forward.ts +0 -359
  182. package/src/channels/github/github-channel.ts +0 -2334
  183. package/src/channels/github/index.ts +0 -54
  184. package/src/channels/github/progress.ts +0 -365
  185. package/src/channels/github/replay.ts +0 -372
  186. package/src/channels/github/state.ts +0 -124
  187. package/src/channels/github/types.ts +0 -590
  188. package/src/channels/gitlab/api.ts +0 -329
  189. package/src/channels/gitlab/binding.ts +0 -231
  190. package/src/channels/gitlab/checks.ts +0 -228
  191. package/src/channels/gitlab/cursor-account.ts +0 -105
  192. package/src/channels/gitlab/defaults.ts +0 -80
  193. package/src/channels/gitlab/events.ts +0 -37
  194. package/src/channels/gitlab/gitlab-channel.ts +0 -160
  195. package/src/channels/gitlab/gitlab-webhook.ts +0 -509
  196. package/src/channels/gitlab/index.ts +0 -44
  197. package/src/channels/gitlab/replay.ts +0 -328
  198. package/src/channels/gitlab/state.ts +0 -55
  199. package/src/channels/gitlab/types.ts +0 -247
  200. package/src/channels/issues/index.ts +0 -9
  201. package/src/channels/issues/issues-channel.ts +0 -45
  202. package/src/channels/issues/types.ts +0 -38
  203. package/src/channels/origin/api.ts +0 -507
  204. package/src/channels/origin/binding.ts +0 -114
  205. package/src/channels/origin/checks.ts +0 -250
  206. package/src/channels/origin/cursor-account.ts +0 -58
  207. package/src/channels/origin/defaults.ts +0 -140
  208. package/src/channels/origin/events.ts +0 -35
  209. package/src/channels/origin/index.ts +0 -35
  210. package/src/channels/origin/origin-channel.ts +0 -815
  211. package/src/channels/origin/origin-webhook.ts +0 -296
  212. package/src/channels/origin/reactions.ts +0 -72
  213. package/src/channels/origin/state.ts +0 -54
  214. package/src/channels/origin/types.ts +0 -295
  215. package/src/channels/slack/agentic-delivery.ts +0 -634
  216. package/src/channels/slack/agentic-posted.ts +0 -135
  217. package/src/channels/slack/agentic-signals.ts +0 -231
  218. package/src/channels/slack/api.ts +0 -761
  219. package/src/channels/slack/approvals.ts +0 -279
  220. package/src/channels/slack/assistant.ts +0 -76
  221. package/src/channels/slack/attachments.ts +0 -596
  222. package/src/channels/slack/auth.ts +0 -127
  223. package/src/channels/slack/blocks.ts +0 -131
  224. package/src/channels/slack/bot-mentions.ts +0 -318
  225. package/src/channels/slack/channel-watch.ts +0 -314
  226. package/src/channels/slack/cli-project.ts +0 -249
  227. package/src/channels/slack/code-fences.ts +0 -171
  228. package/src/channels/slack/constants.ts +0 -38
  229. package/src/channels/slack/credentials.ts +0 -88
  230. package/src/channels/slack/defaults.ts +0 -714
  231. package/src/channels/slack/dispatch.ts +0 -1060
  232. package/src/channels/slack/doctor.ts +0 -338
  233. package/src/channels/slack/eval-directive.ts +0 -306
  234. package/src/channels/slack/event-id-dedupe.ts +0 -30
  235. package/src/channels/slack/external-policy.ts +0 -75
  236. package/src/channels/slack/footer.ts +0 -106
  237. package/src/channels/slack/inbound.ts +0 -416
  238. package/src/channels/slack/index.ts +0 -53
  239. package/src/channels/slack/init.ts +0 -169
  240. package/src/channels/slack/interactive.ts +0 -406
  241. package/src/channels/slack/links.ts +0 -23
  242. package/src/channels/slack/live-delivery.ts +0 -489
  243. package/src/channels/slack/log.ts +0 -70
  244. package/src/channels/slack/manifest.ts +0 -240
  245. package/src/channels/slack/message-body.ts +0 -82
  246. package/src/channels/slack/nudge-carrier.ts +0 -224
  247. package/src/channels/slack/nudge-store.ts +0 -334
  248. package/src/channels/slack/paint-start.ts +0 -93
  249. package/src/channels/slack/placeholder.ts +0 -358
  250. package/src/channels/slack/pr-ref.ts +0 -74
  251. package/src/channels/slack/progress-delivery.ts +0 -138
  252. package/src/channels/slack/reasoning-card.ts +0 -125
  253. package/src/channels/slack/reasoning-chip.ts +0 -41
  254. package/src/channels/slack/recording-sink.ts +0 -167
  255. package/src/channels/slack/redact.ts +0 -6
  256. package/src/channels/slack/reply-options.ts +0 -279
  257. package/src/channels/slack/setup.ts +0 -125
  258. package/src/channels/slack/slack-channel.ts +0 -744
  259. package/src/channels/slack/socket-mode.ts +0 -140
  260. package/src/channels/slack/stop.ts +0 -25
  261. package/src/channels/slack/stream.ts +0 -66
  262. package/src/channels/slack/thread-context.ts +0 -485
  263. package/src/channels/slack/tool-approval-events.ts +0 -233
  264. package/src/channels/slack/tool-cards.ts +0 -198
  265. package/src/channels/slack/tool-chip.ts +0 -34
  266. package/src/channels/slack/types.ts +0 -787
  267. package/src/channels/slack/upload.ts +0 -137
  268. package/src/channels.ts +0 -543
  269. package/src/connections.ts +0 -153
  270. package/src/dashboard-session-url.ts +0 -30
  271. package/src/evals/assertions.ts +0 -688
  272. package/src/evals/expect.ts +0 -250
  273. package/src/evals/judge.ts +0 -329
  274. package/src/evals/loaders.ts +0 -111
  275. package/src/evals/matchers.ts +0 -223
  276. package/src/evals/reporters.ts +0 -257
  277. package/src/evals/results.ts +0 -130
  278. package/src/evals/run-facts.ts +0 -306
  279. package/src/evals.ts +0 -709
  280. package/src/extensions/cursor-cloud-agents/extension.ts +0 -131
  281. package/src/extensions/cursor-cloud-agents/lib/backend.ts +0 -386
  282. package/src/extensions/cursor-cloud-agents/lib/channels.ts +0 -11
  283. package/src/extensions/cursor-cloud-agents/lib/fleet.ts +0 -98
  284. package/src/extensions/cursor-cloud-agents/lib/inputs.ts +0 -5
  285. package/src/extensions/cursor-cloud-agents/lib/repos.ts +0 -80
  286. package/src/extensions/cursor-cloud-agents/lib/transcript.ts +0 -19
  287. package/src/extensions/cursor-cloud-agents/skills/handoff.md +0 -37
  288. package/src/extensions/cursor-cloud-agents/tools/cancel.ts +0 -21
  289. package/src/extensions/cursor-cloud-agents/tools/dump.ts +0 -47
  290. package/src/extensions/cursor-cloud-agents/tools/get.ts +0 -18
  291. package/src/extensions/cursor-cloud-agents/tools/launch.ts +0 -62
  292. package/src/extensions/cursor-cloud-agents/tools/list.ts +0 -31
  293. package/src/extensions/cursor-cloud-agents/tools/reply.ts +0 -36
  294. package/src/extensions/cursor-grokbot-agents/extension.ts +0 -132
  295. package/src/extensions/cursor-grokbot-agents/lib/agents.ts +0 -42
  296. package/src/extensions/cursor-grokbot-agents/lib/backend.ts +0 -208
  297. package/src/extensions/cursor-grokbot-agents/lib/contacts.ts +0 -74
  298. package/src/extensions/cursor-grokbot-agents/lib/conversation.ts +0 -260
  299. package/src/extensions/cursor-grokbot-agents/lib/inputs.ts +0 -21
  300. package/src/extensions/cursor-grokbot-agents/lib/lock.ts +0 -26
  301. package/src/extensions/cursor-grokbot-agents/skills/consult.md +0 -40
  302. package/src/extensions/cursor-grokbot-agents/tools/ask.ts +0 -32
  303. package/src/extensions/cursor-grokbot-agents/tools/check.ts +0 -25
  304. package/src/extensions/cursor-grokbot-agents/tools/interrupt.ts +0 -17
  305. package/src/extensions/cursor-grokbot-agents/tools/list.ts +0 -26
  306. package/src/extensions/improve/extension.ts +0 -69
  307. package/src/extensions/improve/skills/yourself.ts +0 -50
  308. package/src/extensions/jev/extension.ts +0 -95
  309. package/src/extensions/jev/lib/evaluate.ts +0 -266
  310. package/src/extensions/jev/skills/gated-write.md +0 -25
  311. package/src/extensions/jev/skills/questions.md +0 -33
  312. package/src/extensions/jev/tools/evaluate.ts +0 -82
  313. package/src/extensions/slack-communication/evals/harness.ts +0 -705
  314. package/src/extensions/slack-communication/evals/slack-communication.eval.ts +0 -830
  315. package/src/extensions/slack-communication/evals/slack-placeholder.eval.ts +0 -172
  316. package/src/extensions/slack-communication/extension.ts +0 -44
  317. package/src/extensions/slack-communication/skills/slack-voice.ts +0 -56
  318. package/src/extensions/slack-communication/tools/delete-message.ts +0 -33
  319. package/src/extensions/slack-communication/tools/edit-message.ts +0 -42
  320. package/src/extensions/slack-communication/tools/post-card.ts +0 -28
  321. package/src/extensions/slack-communication/tools/post-file.ts +0 -82
  322. package/src/extensions/slack-communication/tools/post-update.ts +0 -40
  323. package/src/extensions/slack-communication/tools/react.ts +0 -30
  324. package/src/extensions/slack-communication/tools/set-status.ts +0 -21
  325. package/src/extensions.ts +0 -179
  326. package/src/files-backends/agent-store-presigned-url.ts +0 -11
  327. package/src/files-backends/cursor-hosted.ts +0 -1212
  328. package/src/files-backends/local-fs.ts +0 -163
  329. package/src/files.ts +0 -293
  330. package/src/filesystem.ts +0 -2005
  331. package/src/hooks.ts +0 -30
  332. package/src/index.ts +0 -259
  333. package/src/internal/advertise-tools.ts +0 -370
  334. package/src/internal/approval-gate.ts +0 -103
  335. package/src/internal/artifacts-store.ts +0 -836
  336. package/src/internal/as-of.ts +0 -257
  337. package/src/internal/auth.ts +0 -46
  338. package/src/internal/authored-alias-hooks.ts +0 -138
  339. package/src/internal/authored-loaders.ts +0 -188
  340. package/src/internal/bounded-int.ts +0 -24
  341. package/src/internal/bounded.ts +0 -25
  342. package/src/internal/brand.ts +0 -28
  343. package/src/internal/browser-origin-guard.ts +0 -67
  344. package/src/internal/builtin-tools/artifacts.ts +0 -62
  345. package/src/internal/builtin-tools/index.ts +0 -53
  346. package/src/internal/builtin-tools/reminders.ts +0 -145
  347. package/src/internal/channel-dispatch.ts +0 -129
  348. package/src/internal/channel-route-dispatch.ts +0 -58
  349. package/src/internal/channel-state.ts +0 -83
  350. package/src/internal/chat-client.ts +0 -594
  351. package/src/internal/cli-ax.ts +0 -2318
  352. package/src/internal/cli-bitbucket.ts +0 -438
  353. package/src/internal/cli-convert-automation.ts +0 -335
  354. package/src/internal/cli-cursor.ts +0 -282
  355. package/src/internal/cli-deploy.ts +0 -2519
  356. package/src/internal/cli-docs.ts +0 -192
  357. package/src/internal/cli-github.ts +0 -806
  358. package/src/internal/cli-gitlab.ts +0 -452
  359. package/src/internal/cli-images.ts +0 -672
  360. package/src/internal/cli-manifest.ts +0 -56
  361. package/src/internal/cli-mcp-oauth.ts +0 -396
  362. package/src/internal/cli-mcp.ts +0 -808
  363. package/src/internal/cli-skills.ts +0 -98
  364. package/src/internal/cli-slack-manual.ts +0 -418
  365. package/src/internal/cli-slack.ts +0 -874
  366. package/src/internal/cloud-merge.ts +0 -51
  367. package/src/internal/cloud-turn-cost.ts +0 -159
  368. package/src/internal/connection-env.ts +0 -106
  369. package/src/internal/continuation-channel.ts +0 -233
  370. package/src/internal/continuation-identity.ts +0 -935
  371. package/src/internal/conversation-mirror.ts +0 -423
  372. package/src/internal/convert-automation/convert-workflow.ts +0 -1377
  373. package/src/internal/convert-automation/slug.ts +0 -29
  374. package/src/internal/convert-automation/types.ts +0 -212
  375. package/src/internal/cron.ts +0 -76
  376. package/src/internal/cursor/account-mcp.ts +0 -692
  377. package/src/internal/cursor/backend-client.ts +0 -984
  378. package/src/internal/cursor/bound-secret-file.ts +0 -101
  379. package/src/internal/cursor/credentials.ts +0 -560
  380. package/src/internal/cursor/cursor-api-transport.ts +0 -65
  381. package/src/internal/cursor/github-credentials.ts +0 -228
  382. package/src/internal/cursor/hosted-bound-secrets.ts +0 -71
  383. package/src/internal/cursor/hosted-deployment-secrets.ts +0 -100
  384. package/src/internal/cursor/hosted-store-secrets.ts +0 -152
  385. package/src/internal/cursor/session-token.ts +0 -111
  386. package/src/internal/cursor/store-api-client.ts +0 -323
  387. package/src/internal/cursor-account-mcp-auth.ts +0 -303
  388. package/src/internal/cursor-agent-template.ts +0 -50
  389. package/src/internal/cursor-deployment-relay.ts +0 -315
  390. package/src/internal/cursor-event-relay.ts +0 -675
  391. package/src/internal/cursor-relay-core.ts +0 -563
  392. package/src/internal/deferred-channel-session.ts +0 -61
  393. package/src/internal/deploy-client.ts +0 -1574
  394. package/src/internal/deploy-manifest.ts +0 -361
  395. package/src/internal/deploy-source.ts +0 -144
  396. package/src/internal/describe-error.ts +0 -32
  397. package/src/internal/dev-mode.ts +0 -20
  398. package/src/internal/discovery/agent-config.ts +0 -288
  399. package/src/internal/discovery/agent.ts +0 -381
  400. package/src/internal/discovery/channels.ts +0 -100
  401. package/src/internal/discovery/connections.ts +0 -516
  402. package/src/internal/discovery/context.ts +0 -38
  403. package/src/internal/discovery/cursor-plugin.ts +0 -628
  404. package/src/internal/discovery/extension-overlay.ts +0 -247
  405. package/src/internal/discovery/extensions.ts +0 -490
  406. package/src/internal/discovery/fs.ts +0 -103
  407. package/src/internal/discovery/hooks.ts +0 -63
  408. package/src/internal/discovery/info.ts +0 -174
  409. package/src/internal/discovery/instructions.ts +0 -98
  410. package/src/internal/discovery/modules.ts +0 -107
  411. package/src/internal/discovery/names.ts +0 -45
  412. package/src/internal/discovery/project.ts +0 -319
  413. package/src/internal/discovery/reminders.ts +0 -65
  414. package/src/internal/discovery/runtime.ts +0 -158
  415. package/src/internal/discovery/schedules.ts +0 -120
  416. package/src/internal/discovery/seed-files.ts +0 -34
  417. package/src/internal/discovery/services.ts +0 -151
  418. package/src/internal/discovery/skills.ts +0 -174
  419. package/src/internal/discovery/subagent.ts +0 -138
  420. package/src/internal/discovery/tools.ts +0 -170
  421. package/src/internal/discovery.ts +0 -27
  422. package/src/internal/distribution.ts +0 -126
  423. package/src/internal/docs-site.ts +0 -248
  424. package/src/internal/duration.ts +0 -37
  425. package/src/internal/env-file.ts +0 -83
  426. package/src/internal/eval-judge-model.ts +0 -142
  427. package/src/internal/eval-run-store.ts +0 -585
  428. package/src/internal/eval-runner.ts +0 -823
  429. package/src/internal/evals-client.ts +0 -475
  430. package/src/internal/event-log.ts +0 -342
  431. package/src/internal/event-mapper.ts +0 -811
  432. package/src/internal/expected-delivery-failure.ts +0 -34
  433. package/src/internal/factory-resource-channel.ts +0 -103
  434. package/src/internal/filesystem/errors.ts +0 -207
  435. package/src/internal/filesystem/format.ts +0 -253
  436. package/src/internal/filesystem/merge.ts +0 -192
  437. package/src/internal/filesystem/nearest.ts +0 -112
  438. package/src/internal/filesystem/scratch.ts +0 -239
  439. package/src/internal/filesystem/sdk-schemas.ts +0 -204
  440. package/src/internal/filesystem/tools.ts +0 -804
  441. package/src/internal/filesystem/walk.ts +0 -366
  442. package/src/internal/fixtures/units-server.ts +0 -52
  443. package/src/internal/framework-file-storage.ts +0 -357
  444. package/src/internal/framework-storage-selection.ts +0 -156
  445. package/src/internal/frontmatter.ts +0 -108
  446. package/src/internal/github-fanout.ts +0 -144
  447. package/src/internal/guest-network.ts +0 -391
  448. package/src/internal/handleAgentServeTrigger.ts +0 -286
  449. package/src/internal/host-files.ts +0 -341
  450. package/src/internal/host-kv.ts +0 -81
  451. package/src/internal/host-otel.ts +0 -231
  452. package/src/internal/host-platforms.ts +0 -170
  453. package/src/internal/hosted-admission-adapter.ts +0 -47
  454. package/src/internal/hosted-admission-context.ts +0 -37
  455. package/src/internal/hosted-catch-protocol.ts +0 -112
  456. package/src/internal/hosted-catch.ts +0 -179
  457. package/src/internal/hosted-delivery-protocol.ts +0 -824
  458. package/src/internal/hosted-delivery.ts +0 -1410
  459. package/src/internal/hosted-execution-diag.ts +0 -291
  460. package/src/internal/hosted-execution-flush.ts +0 -136
  461. package/src/internal/hosted-execution-latency.ts +0 -301
  462. package/src/internal/hosted-managed-automation.ts +0 -116
  463. package/src/internal/hosting.ts +0 -114
  464. package/src/internal/http-channel-define.ts +0 -25
  465. package/src/internal/http-channel.ts +0 -669
  466. package/src/internal/http-control-plane-session.ts +0 -110
  467. package/src/internal/ids.ts +0 -39
  468. package/src/internal/incoming-headers-to-fetch.ts +0 -45
  469. package/src/internal/init-interview.ts +0 -360
  470. package/src/internal/init-project.ts +0 -711
  471. package/src/internal/init-scaffold.ts +0 -182
  472. package/src/internal/inline-stdio-define-stub.ts +0 -4
  473. package/src/internal/inline-stdio-mcp.ts +0 -230
  474. package/src/internal/install-cursor-skills.ts +0 -604
  475. package/src/internal/is-record.ts +0 -3
  476. package/src/internal/json-schema.ts +0 -95
  477. package/src/internal/legacy-command-guard.ts +0 -66
  478. package/src/internal/listen-port.ts +0 -85
  479. package/src/internal/local-control-plane.ts +0 -442
  480. package/src/internal/local-env.ts +0 -59
  481. package/src/internal/local-ingress.ts +0 -90
  482. package/src/internal/log-ring.ts +0 -59
  483. package/src/internal/logs-client.ts +0 -477
  484. package/src/internal/map-pool.ts +0 -39
  485. package/src/internal/mcp-endpoint.ts +0 -747
  486. package/src/internal/mcp-host.ts +0 -509
  487. package/src/internal/mcp-oauth-on-demand.ts +0 -337
  488. package/src/internal/mcp-oauth-persist.ts +0 -118
  489. package/src/internal/mcp-oauth.ts +0 -549
  490. package/src/internal/net.ts +0 -29
  491. package/src/internal/open-browser.ts +0 -41
  492. package/src/internal/otel/attrs.ts +0 -16
  493. package/src/internal/otel/collector.ts +0 -937
  494. package/src/internal/otel/config.ts +0 -287
  495. package/src/internal/otel/http.ts +0 -122
  496. package/src/internal/otel/mcp.ts +0 -56
  497. package/src/internal/otel/propagation.ts +0 -17
  498. package/src/internal/otel/runtime.ts +0 -441
  499. package/src/internal/package-inline-stdio.ts +0 -114
  500. package/src/internal/peer-connections.ts +0 -96
  501. package/src/internal/platform-schedule-sync.ts +0 -75
  502. package/src/internal/platform-timers.ts +0 -365
  503. package/src/internal/playground/static.ts +0 -278
  504. package/src/internal/playground/toolchain.ts +0 -270
  505. package/src/internal/playground-proxy.ts +0 -564
  506. package/src/internal/process-memory-telemetry.ts +0 -334
  507. package/src/internal/project-layout.ts +0 -31
  508. package/src/internal/prompt-context.ts +0 -116
  509. package/src/internal/reminder-control-plane-protocol.ts +0 -482
  510. package/src/internal/reminder-runner.ts +0 -1559
  511. package/src/internal/reminder-schedule.ts +0 -104
  512. package/src/internal/reminder-store.ts +0 -176
  513. package/src/internal/request-error-status.ts +0 -95
  514. package/src/internal/request-headers.ts +0 -21
  515. package/src/internal/resolve-prod-target.ts +0 -334
  516. package/src/internal/resolved-connections.ts +0 -190
  517. package/src/internal/router.ts +0 -143
  518. package/src/internal/run-client.ts +0 -354
  519. package/src/internal/runtime-dispatch-runner.ts +0 -50
  520. package/src/internal/sanitize-mcp-tool-name.ts +0 -31
  521. package/src/internal/schedule-runner.ts +0 -154
  522. package/src/internal/scm/pr-url.ts +0 -245
  523. package/src/internal/sdk-runner.ts +0 -959
  524. package/src/internal/serve-restart.ts +0 -113
  525. package/src/internal/server.ts +0 -3147
  526. package/src/internal/session-cost.ts +0 -208
  527. package/src/internal/session-engine.ts +0 -5622
  528. package/src/internal/session-links.ts +0 -84
  529. package/src/internal/session-run-log.ts +0 -535
  530. package/src/internal/session-store.ts +0 -307
  531. package/src/internal/session-urls.ts +0 -32
  532. package/src/internal/sessions-client.ts +0 -239
  533. package/src/internal/skill-catalog.ts +0 -66
  534. package/src/internal/skills-sync.ts +0 -55
  535. package/src/internal/slack-provision-client.ts +0 -544
  536. package/src/internal/slack-thread-key.ts +0 -11
  537. package/src/internal/sleep.ts +0 -3
  538. package/src/internal/start-log-store.ts +0 -164
  539. package/src/internal/steering.ts +0 -17
  540. package/src/internal/storage-coordinator.ts +0 -800
  541. package/src/internal/storage-roles.ts +0 -86
  542. package/src/internal/storage.ts +0 -1
  543. package/src/internal/store-api-protocol.ts +0 -205
  544. package/src/internal/store-mirror.ts +0 -73
  545. package/src/internal/stream-progress.ts +0 -294
  546. package/src/internal/terminal-style.ts +0 -133
  547. package/src/internal/testing/factory-resource-fixtures.ts +0 -84
  548. package/src/internal/testing/scm-continuation-fixtures.ts +0 -285
  549. package/src/internal/tool-catalog.ts +0 -104
  550. package/src/internal/tool-policy.ts +0 -222
  551. package/src/internal/tool-result.ts +0 -50
  552. package/src/internal/trajectory.ts +0 -418
  553. package/src/internal/turn-cost.ts +0 -136
  554. package/src/internal/turn-governor.ts +0 -145
  555. package/src/internal/turn-lease-store.ts +0 -144
  556. package/src/internal/turn-outbox.ts +0 -77
  557. package/src/internal/update-check.ts +0 -517
  558. package/src/internal/v2-hosting.ts +0 -52
  559. package/src/internal/workspace-sync.ts +0 -114
  560. package/src/internal/workspace.ts +0 -505
  561. package/src/kv/memory-kv.ts +0 -94
  562. package/src/kv.ts +0 -18
  563. package/src/memory.ts +0 -487
  564. package/src/otel-public.ts +0 -24
  565. package/src/otel.ts +0 -320
  566. package/src/prompt.ts +0 -80
  567. package/src/reminders.ts +0 -65
  568. package/src/schedules.ts +0 -31
  569. package/src/skills.ts +0 -27
  570. package/src/storage-backends/cursor-hosted-v2.ts +0 -204
  571. package/src/storage-backends/cursor-hosted.ts +0 -388
  572. package/src/storage-backends/file-kv.ts +0 -276
  573. package/src/storage-protocol.ts +0 -261
  574. package/src/storage.ts +0 -408
  575. package/src/tools.ts +0 -166
  576. package/src/types.ts +0 -3776
  577. /package/dist/docs/assets/{reference_agent-config.md.DzGI777n.lean.js → reference_agent-config.md.Cj5uBKp4.lean.js} +0 -0
package/src/types.ts DELETED
@@ -1,3776 +0,0 @@
1
- /**
2
- * Public types for @cursor/bdk.
3
- *
4
- * The framework is filesystem-first: customers author an agent as files under
5
- * an `agent/` directory (markdown for prose, TypeScript for typed behavior),
6
- * and the framework discovers those files, compiles them into an
7
- * {@link AgentProject}, and serves the agent over channels using the Cursor
8
- * SDK as the execution harness.
9
- */
10
-
11
- import type { InteractionUpdate, SDKCustomTool, ToolName } from "@cursor/sdk";
12
- import type { z } from "zod";
13
- import type { FileSystem } from "./filesystem.js";
14
- import type {
15
- ContinuationClaim,
16
- ContinuationIdentity,
17
- MailboxContinuation,
18
- } from "./internal/continuation-identity.js";
19
- import type { OtelConfig, OtelDefinition } from "./otel.js";
20
- import type { StorageDefinition } from "./storage.js";
21
-
22
- // ============================================================================
23
- // JSON
24
- // ============================================================================
25
-
26
- export type JsonPrimitive = string | number | boolean | null;
27
- export type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;
28
- export type JsonObject = { [key: string]: JsonValue };
29
-
30
- /** A plain JSON Schema object (already-serialized tool input schema). */
31
- export type JsonSchemaObject = Record<string, unknown>;
32
-
33
- // ============================================================================
34
- // Definition branding
35
- // ============================================================================
36
-
37
- /**
38
- * Discriminates the `define*` helper that produced a module's default export
39
- * so discovery can validate that a file landed in the right authored slot.
40
- */
41
- export type DefinitionKind =
42
- | "agent"
43
- | "instructions"
44
- | "tool"
45
- | "skill"
46
- | "extension"
47
- | "disabled-tool"
48
- | "disabled-connection"
49
- | "disabled"
50
- | "connection"
51
- | "channel"
52
- | "http-channel"
53
- | "schedule"
54
- | "reminder"
55
- | "hook"
56
- | "eval"
57
- | "storage"
58
- | "artifacts"
59
- | "otel";
60
-
61
- export interface BrandedDefinition<K extends DefinitionKind> {
62
- readonly __agentServe: K;
63
- }
64
-
65
- // ============================================================================
66
- // Agent config (agent.ts)
67
- // ============================================================================
68
-
69
- /**
70
- * A Cursor model selection. Either a bare model id (`"gpt-5.2"`) or an id
71
- * with model parameters, mirroring the Cursor SDK's `ModelSelection`.
72
- */
73
- export type ModelSetting =
74
- | string
75
- | {
76
- id: string;
77
- params?: Array<{ id: string; value: string }>;
78
- };
79
-
80
- /**
81
- * Model used when the root agent omits `model` (local Cursor agents have no
82
- * harness-level default of their own).
83
- */
84
- export const DEFAULT_MODEL: ModelSetting = {
85
- id: "grok-4.5",
86
- params: [
87
- { id: "effort", value: "high" },
88
- { id: "fast", value: "true" },
89
- ],
90
- };
91
-
92
- /** Runtime selector. New public agents use the default local runtime. */
93
- export type AgentRuntime = "local" | "cloud" | "grokbot";
94
-
95
- /** Options used when launching Cursor cloud agents. */
96
- export interface AgentCloudOptions {
97
- env?:
98
- | { type: "cloud"; name?: string }
99
- | { type: "pool"; name?: string }
100
- | { type: "machine"; name?: string };
101
- repos?: Array<{
102
- url: string;
103
- startingRef?: string;
104
- prUrl?: string;
105
- }>;
106
- workOnCurrentBranch?: boolean;
107
- autoCreatePR?: boolean;
108
- skipReviewerRequest?: boolean;
109
- /**
110
- * Per-session env vars injected into the cloud agent's shell.
111
- * When set, the cloud API mints the SDK agent id (persisted as
112
- * {@link SessionRecord.sdkAgentId}).
113
- */
114
- envVars?: Record<string, string>;
115
- }
116
-
117
- /** Safe `/v1/info` projection of {@link AgentCloudOptions}; secret values are omitted. */
118
- export type AgentCloudPublicInfo = Omit<AgentCloudOptions, "envVars"> & {
119
- envVarsConfigured?: boolean;
120
- };
121
-
122
- function redactHttpUrlCredentials(url: string): string {
123
- try {
124
- const parsed = new URL(url);
125
- if (parsed.username !== "" || parsed.password !== "") {
126
- parsed.username = "";
127
- parsed.password = "";
128
- }
129
- return parsed.toString();
130
- } catch {
131
- return url.replace(/^(https?:\/\/)[^@/]+@/i, "$1");
132
- }
133
- }
134
-
135
- export function toPublicCloudInfo(cloud: AgentCloudOptions): AgentCloudPublicInfo {
136
- const { envVars, repos, ...rest } = cloud;
137
- const hasEnvVars = envVars !== undefined && Object.keys(envVars).length > 0;
138
- return {
139
- ...rest,
140
- ...(repos !== undefined
141
- ? {
142
- repos: repos.map(repo => ({
143
- ...repo,
144
- url: redactHttpUrlCredentials(repo.url),
145
- ...(repo.prUrl !== undefined ? { prUrl: redactHttpUrlCredentials(repo.prUrl) } : {}),
146
- })),
147
- }
148
- : {}),
149
- ...(hasEnvVars ? { envVarsConfigured: true } : {}),
150
- };
151
- }
152
-
153
- /**
154
- * Session-scoped facts a `root` factory needs and does not otherwise
155
- * have at `defineAgent` time. The factory returns a handle: each
156
- * method must observe the current binding. Do not snapshot the tree.
157
- */
158
- export interface RootContext {
159
- sessionId: string;
160
- agentName?: string;
161
- continuationKey?: string;
162
- host?: { files: HostFilesApi; reminders?: ReminderHostApi; kv?: HostKvApi };
163
- }
164
-
165
- /** Input to `defineAgent` (authored at `agent/agent.ts`). */
166
- export interface AgentConfig {
167
- /**
168
- * Cursor model to run the agent on. Defaults to {@link DEFAULT_MODEL} on
169
- * the root agent when omitted. Subagents omit it to inherit the parent's
170
- * model.
171
- */
172
- model?: ModelSetting;
173
- /**
174
- * Models to try, in order, when {@link model} is rejected before the
175
- * turn produces any output: catalog refusal ("Cannot use this model")
176
- * or a capacity error (`resource_exhausted` / `[unavailable]`). The
177
- * rejection is usually inside agent creation, before authored tools
178
- * run, so a fallback list on the agent is the only retry that can save
179
- * the turn. Each entry is the same shape as {@link model}.
180
- */
181
- fallbacks?: readonly ModelSetting[];
182
- /**
183
- * What this agent is for. Required on subagents: the parent model reads it
184
- * to decide when to delegate. Optional (documentation only) on the root.
185
- */
186
- description?: string;
187
- /** Display name override. Defaults to the package name / directory name. */
188
- name?: string;
189
- /**
190
- * Inline instructions. Prefer `instructions.md` next to `agent.ts`; this
191
- * exists for subagents and generated configs.
192
- */
193
- instructions?: string;
194
- /**
195
- * Execution runtime. Defaults to `"local"`. Compatibility strings
196
- * `"cloud"` and `"grokbot"` remain for agents that already ship; they
197
- * are not a product surface. New agents omit this field.
198
- */
199
- runtime?: AgentRuntime;
200
- /**
201
- * The FileSystem the model can see. Omit it and the root is the host
202
- * disk. A static handle (`tempFs`, `unionFs`, ...) is that object on
203
- * every session — writes are shared. Pass `(ctx) => …` and return a
204
- * new handle per session when you want isolation. A factory that
205
- * returns the same object still shares. Incompatible with
206
- * {@link local} `cwd` / `workspaceDir` / `sandbox` and with
207
- * {@link runtime} `"cloud"`.
208
- */
209
- root?: FileSystem | ((ctx: RootContext) => FileSystem | Promise<FileSystem>);
210
- /**
211
- * Cloud attach defaults merged under per-session
212
- * {@link SendMessageOptions.cloud}. Used by existing agents that still
213
- * set {@link runtime} `"cloud"` and by hybrid channel/tool handoffs.
214
- * In-process `agent/tools` run on local turns only.
215
- */
216
- cloud?: AgentCloudOptions;
217
- /** Local harness defaults. */
218
- local?: AgentLocalOptions;
219
- /**
220
- * Managed-hosting declarations (`agent-sdk deploy` onto Cursor's
221
- * agent-serve hosting). The manifest is the source of truth: deploy reads
222
- * it and sends it with the deployment request. Ignored by local serving.
223
- */
224
- hosting?: AgentHostingOptions;
225
- /**
226
- * Engine-wide turn admission limits. See {@link AgentConcurrencyOptions}.
227
- */
228
- concurrency?: AgentConcurrencyOptions;
229
- /**
230
- * Framework-provided model-facing tools, opted in per capability. See
231
- * {@link BuiltinToolsConfig}.
232
- */
233
- builtinTools?: BuiltinToolsConfig;
234
- /**
235
- * Allowlist of built-in harness tools offered to the model
236
- * (`AgentOptions.tools` on the SDK). Opt-in by design: unset keeps the
237
- * model's full standard toolset, and once set the agent gets exactly
238
- * what it names — nothing more, `[]` meaning no native built-in tools.
239
- * There is deliberately no exclusion form: an agent that restricts
240
- * tools states what it keeps, so tools the platform adds later stay
241
- * off until someone opts in.
242
- *
243
- * `"mcp"` is always granted alongside a configured allowlist. It is
244
- * transport, not capability: this kit's own server tools reach the
245
- * model over the SDK custom-tool MCP path, so omitting it would
246
- * silently strand `agent/tools/`. What MCP actually exposes stays
247
- * governed by the second layer — the tools you author, the connections
248
- * you declare, and the harness cwd's ambient `.cursor` config (point
249
- * `local.cwd` outside checkouts whose MCP servers the agent must not
250
- * see, and `local.sandbox` makes MCP calls fail closed).
251
- *
252
- * Names use the SDK's public tool vocabulary (`"shell"`, `"read"`,
253
- * `"edit"`, `"grep"`, `"glob"`, `"ls"`, `"task"`, ...). `"shell"` is a
254
- * capability group that also grants shell stdin writes — and is what
255
- * `execution: "agent"` tool scripts run through, so an allowlist
256
- * without it strands them (discovery warns). `"task"` gates subagents.
257
- * Unknown names fail the turn (`ConfigurationError` at `Agent.create`).
258
- *
259
- * This is not a security boundary against the serve host: like
260
- * `local.sandbox`, it only shapes what the model can call.
261
- */
262
- tools?: ToolName[];
263
- /**
264
- * Hosted architecture. Defaults to `"v2"`. Set `"v1"` to stay on the
265
- * resident-engine architecture.
266
- */
267
- architecture?: AgentArchitecture;
268
- /**
269
- * Persistent hosting for `architecture: "v2"`.
270
- *
271
- * Default (`false`): each session boots a pod from the release snapshot;
272
- * framework and author state are mirrored to Cursor stores because pod
273
- * disks are disposable.
274
- *
275
- * `true`: one long-lived pod per deployment runs each deployed version as
276
- * a container over one state directory on the pod's disk. Nothing is
277
- * mirrored: that directory is the durable copy. A redeploy starts the new
278
- * version beside the old one on the same state, then drains the old one.
279
- */
280
- persistent?: boolean;
281
- }
282
-
283
- /** Hosted architecture on {@link AgentConfig.architecture}. */
284
- export type AgentArchitecture = "v1" | "v2";
285
-
286
- /**
287
- * Built-in tools on {@link AgentConfig.builtinTools}. Each enabled
288
- * capability materializes as ordinary server tools at discovery time, so
289
- * turns, direct calls, `info`, and the playground treat them like authored
290
- * tools. Authored tools with the same name win with a warning.
291
- */
292
- export interface BuiltinToolsConfig {
293
- /**
294
- * Reminder tools bound to the current conversation, over
295
- * {@link HostContext.reminders}: `reminders_create`, `reminders_list`,
296
- * and `reminders_cancel` (the name the framework's reminder fire prompt
297
- * tells the model to call when a stop condition is met). Sessions
298
- * without a continuation key cannot arm reminders.
299
- */
300
- reminders?: boolean;
301
- }
302
-
303
- /**
304
- * Turn admission limits on {@link AgentConfig.concurrency}.
305
- *
306
- * ```ts
307
- * export default defineAgent({
308
- * // At most 3 sessions run a model turn at once; the rest queue FIFO.
309
- * concurrency: { maxRunningTurns: 3 },
310
- * });
311
- * ```
312
- */
313
- export interface AgentConcurrencyOptions {
314
- /**
315
- * Max model turns running at once across **all** of this agent's
316
- * sessions. When every slot is busy, newly admitted turns queue FIFO
317
- * (surfaced as a durable `turn.queued` event and `queued: true` on
318
- * `GET /v1/sessions`) instead of failing; each queued turn starts as
319
- * soon as a slot frees. Positive integer, hard-capped at
320
- * {@link MAX_RUNNING_TURNS_LIMIT}. Omit for unlimited.
321
- *
322
- * A queued turn still counts as `running` for busy semantics
323
- * (follow-ups preempt it; direct write-effect tool calls get
324
- * `SessionBusyError`),
325
- * and a follow-up that preempts a queued turn re-queues at the back.
326
- */
327
- maxRunningTurns?: number;
328
- }
329
-
330
- /**
331
- * Hard ceiling for {@link AgentConcurrencyOptions.maxRunningTurns}.
332
- * Matches the eval harness ceiling: each running turn issues model
333
- * provider requests, so unbounded parallelism is never meaningful.
334
- */
335
- export const MAX_RUNNING_TURNS_LIMIT = 200;
336
-
337
- /**
338
- * Managed-hosting block on {@link AgentConfig.hosting}.
339
- */
340
- export interface AgentHostingOptions {
341
- /**
342
- * Domains the deployed engine pod may reach (egress allowlist), e.g.
343
- * `"api.example.com"` or `"*.example.com"` (single leading wildcard).
344
- * Lowercase hostnames with at least two labels and an alphabetic TLD;
345
- * max 64. A `"host:port"` entry (e.g. `"clickhouse.example.com:9440"`)
346
- * opens raw TCP to that host's addresses, for wire protocols the proxy
347
- * cannot read a TLS hostname from.
348
- * `agent-sdk deploy` sends these as `egressAllowedDomains`
349
- * (unioned with any `--allow-domain` flags). Only valid on repo-backed
350
- * deployments. Deployment-scoped like {@link secretNames}: not capped by
351
- * the team's Cloud Agent egress allowlist. The platform still merges a
352
- * bootstrap set (npm, Slack, Cursor API) at provision time.
353
- */
354
- egressDomains?: string[];
355
- /**
356
- * Secret names this agent expects at runtime (declarative documentation;
357
- * values are never authored in files). `agent-sdk deploy` warns when a
358
- * declared name is not set on the deployment — set values with
359
- * `agent-sdk secrets set <slug> NAME`.
360
- */
361
- secretNames?: string[];
362
- /**
363
- * Name of a container image the team pushed with
364
- * `agent-sdk images push <local-image> --name <name>`; the deployed agent
365
- * runs inside it instead of the platform's default `node:22` image. The
366
- * image must be `linux/amd64` and provide `bash`, `node` (>= 22.13) and
367
- * `npm` on `PATH`. Requires `architecture: "v2"`; today only
368
- * `persistent: true` agents honor it. Deploy pins the image bytes it saw
369
- * (sha256); pushing the same name again takes effect on the next deploy.
370
- */
371
- image?: string;
372
- }
373
-
374
- /**
375
- * Local runtime options on {@link AgentConfig.local}.
376
- */
377
- export interface AgentLocalOptions {
378
- /**
379
- * Default local harness cwd parent. Absolute, or relative to the agent
380
- * project root. Each session uses `<cwd>/<sessionId>` unless a per-send
381
- * {@link SendMessageOptions.workspaceDir} overrides it.
382
- *
383
- * When omitted, a project nested in another git repo (a monorepo package)
384
- * defaults to `~/.cache/agent-serve/<dir>` so Cursor does not load the
385
- * enclosing checkout's AGENTS.md, rules, skills, or MCP servers. A
386
- * standalone git root keeps the in-project session workspace. Point this
387
- * at a checkout when the agent must inherit that tree.
388
- */
389
- cwd?: string;
390
- /**
391
- * One harness cwd shared by every session, for agents that work inside an
392
- * existing checkout. Absolute, or relative to the agent project root.
393
- * Takes precedence over {@link cwd}; a per-send
394
- * {@link SendMessageOptions.workspaceDir} still wins over both.
395
- *
396
- * The SDK keys its local executor — Cursor rules, skills, MCP, the ignore
397
- * mappings — on the harness cwd, so a shared directory resolves the
398
- * workspace once per serve process instead of once per session. With
399
- * `cwd`'s `<cwd>/<sessionId>` layout that cache never hits, and on a large
400
- * repo each session pays the full scan again.
401
- *
402
- * Sessions are no longer isolated from each other on disk: they share a
403
- * working tree, and a file one turn writes is visible to the next. Agent
404
- * scaffold (`AGENTS.md`, skills, tool scripts) is kept out of the shared
405
- * directory and delivered inline instead, so pointing this at a repo does
406
- * not write Agent SDK files into it — but `workspaceFiles` still lands in
407
- * the harness cwd, as it does for a per-send override.
408
- */
409
- workspaceDir?: string;
410
- /**
411
- * Run the harness inside Cursor's local sandbox (`sandboxOptions.enabled`
412
- * on the SDK). Off by default, matching the SDK: shell then auto-approves
413
- * and inherits the serve process environment — including any credentials
414
- * the host holds.
415
- *
416
- * Turn this on for agents whose turns read untrusted input (webhook
417
- * payloads, PR diffs, inbound chat). It is a real tool boundary rather
418
- * than a prompt-level one, so it still holds when the model is steered
419
- * into ignoring its instructions.
420
- */
421
- sandbox?: boolean;
422
- }
423
-
424
- export type AgentConfigDefinition = AgentConfig & BrandedDefinition<"agent">;
425
-
426
- /** Input to `defineInstructions` (authored at `agent/instructions.ts`). */
427
- export interface InstructionsConfig {
428
- markdown: string;
429
- }
430
-
431
- export type InstructionsDefinition = InstructionsConfig & BrandedDefinition<"instructions">;
432
-
433
- // ============================================================================
434
- // Tools (agent/tools/*.ts)
435
- // ============================================================================
436
-
437
- export type ToolResultContent =
438
- | { type: "text"; text: string }
439
- | { type: "image"; data: string; mimeType?: string };
440
-
441
- /**
442
- * JSON-ish value a tool may return. Unlike {@link JsonValue} this permits
443
- * `undefined` leaves (and thus optional object properties), because the
444
- * result is JSON-serialized before it reaches the model and `undefined`
445
- * fields are simply dropped — so authored tools can return objects shaped by
446
- * optional fields without fighting the type system.
447
- */
448
- export type ToolResultValue =
449
- | string
450
- | number
451
- | boolean
452
- | null
453
- | undefined
454
- | ToolResultValue[]
455
- | readonly ToolResultValue[]
456
- | { [key: string]: ToolResultValue };
457
-
458
- /**
459
- * What a tool's `execute` may return. Strings are passed to the model
460
- * verbatim, JSON values are serialized, and the envelope form carries rich
461
- * content and an error flag.
462
- */
463
- export type ToolExecuteResult =
464
- | ToolResultValue
465
- | {
466
- content: ToolResultContent[];
467
- isError?: boolean;
468
- /**
469
- * Structured result for tools that declare an `outputSchema`: MCP
470
- * clients require `structuredContent` on calls to schema-declaring
471
- * tools. Plain-object returns get it filled in automatically; the
472
- * envelope form (needed for images or `isError`) sets it here.
473
- */
474
- structuredContent?: JsonObject;
475
- };
476
-
477
- /** Repo-agnostic GitHub client on the agent-serve host. */
478
- export interface HostGitHubClient {
479
- getOctokit(): Promise<import("@octokit/rest").Octokit>;
480
- }
481
-
482
- /** Bot-token Slack Web API client on the agent-serve host. */
483
- export interface HostSlackClient {
484
- getClient(): Promise<import("@slack/web-api").WebClient>;
485
- }
486
-
487
- /** Host-side handle for calling an MCP connection from a server tool or channel handler. */
488
- export interface HostMcpRegistry {
489
- /** MCP connection names (filenames under `agent/mcp-connections/`). */
490
- names(): string[];
491
- listTools(connectionName: string): Promise<HostMcpToolInfo[]>;
492
- callTool(
493
- connectionName: string,
494
- toolName: string,
495
- args?: Record<string, unknown>,
496
- ): Promise<HostMcpCallResult>;
497
- }
498
-
499
- /**
500
- * MCP spec tool annotations (`Tool.annotations`, 2025-03-26 revision).
501
- *
502
- * A closed type on purpose: these are exactly the fields listing-time
503
- * bounding keeps, so the type matches what a reader can ever see — and the
504
- * hints are behavioral, so a misspelled or wrong-typed key must not
505
- * masquerade as a declaration.
506
- */
507
- export interface McpToolAnnotations {
508
- /** Human-readable display name for the tool, length-capped at listing. */
509
- title?: string;
510
- /** The tool does not modify its environment. */
511
- readOnlyHint?: boolean;
512
- /** The tool may perform destructive updates (meaningful when not read-only). */
513
- destructiveHint?: boolean;
514
- /** Repeated calls with the same arguments have no additional effect. */
515
- idempotentHint?: boolean;
516
- /** The tool may interact with an open world of external entities. */
517
- openWorldHint?: boolean;
518
- }
519
-
520
- export interface HostMcpToolInfo {
521
- name: string;
522
- description?: string;
523
- inputSchema?: JsonObject;
524
- outputSchema?: JsonObject;
525
- /**
526
- * MCP spec tool annotations, bounded at listing time to the
527
- * {@link McpToolAnnotations} fields. Untrusted server hints — consumers
528
- * that classify on them must fail closed when absent, and absent is
529
- * exactly what a server that declares nothing produces.
530
- */
531
- annotations?: McpToolAnnotations;
532
- }
533
-
534
- export interface HostMcpCallResult {
535
- content: Array<
536
- | { type: "text"; text: string }
537
- | { type: "image"; data: string; mimeType?: string }
538
- | { type: string; [key: string]: unknown }
539
- >;
540
- isError?: boolean;
541
- structuredContent?: JsonObject;
542
- }
543
-
544
- /**
545
- * Durable Slack follow-up nudge + ask-claim API attached to {@link HostContext}.
546
- * Used for mid-turn inject, boundary resume skip, and delayed-parent dedupe.
547
- */
548
- export interface SlackNudgeHostApi {
549
- append(input: {
550
- continuationKey: string;
551
- sourceTs: string;
552
- text: string;
553
- author?: string;
554
- }): Promise<boolean>;
555
- /** Drain pending nudges and return a `<slack_followup>` block, if any. */
556
- drainFormatted(continuationKey: string): Promise<string | undefined>;
557
- clear(continuationKey: string): Promise<void>;
558
- hasUndelivered(continuationKey: string): Promise<boolean>;
559
- isDelivered(continuationKey: string, sourceTs: string): Promise<boolean>;
560
- /** Claim `channelId:message.ts` exactly once (false = already seen). */
561
- tryClaimAsk(channelId: string, messageTs: string): Promise<boolean>;
562
- /** Release a claim after a failed send so Slack redelivery can retry. */
563
- releaseAsk(channelId: string, messageTs: string): Promise<void>;
564
- }
565
-
566
- /**
567
- * Shared host services available on every tool / hook / channel / schedule
568
- * surface. Channel packs attach this as `ctx.host` so handlers can tap
569
- * GitHub, Slack, or MCP without the pack depending on another platform.
570
- */
571
- export interface HostContext {
572
- /**
573
- * Authored MCP connections (`agent/mcp-connections/*` and
574
- * `agent/host-connections/*`). Call a specific MCP tool deterministically
575
- * without going through the agent loop.
576
- */
577
- mcp: HostMcpRegistry;
578
- /**
579
- * Host GitHub client (PAT / env / `gh auth` / App). Prefer webhook
580
- * `ctx.github` (installation-scoped) when handling a GitHub delivery.
581
- */
582
- github: HostGitHubClient;
583
- /** Host Slack Web API client (`SLACK_BOT_TOKEN` / channel envPrefix). */
584
- slack: HostSlackClient;
585
- /**
586
- * Per-session reminders (create / list / cancel / dispatch). Present once
587
- * the serve host has attached a {@link ReminderRunner}.
588
- */
589
- reminders?: ReminderHostApi;
590
- /**
591
- * Slack ask-dedupe / nudge helpers. Always present on a live
592
- * {@link SessionEngine} host. A busy Slack thread's follow-ups queue here
593
- * and reach the running agent at its next tool boundary, via the workspace
594
- * carrier hook; whatever the carrier does not reach in time still drains
595
- * into the boundary turn, deduped by source ts.
596
- */
597
- slackNudges?: SlackNudgeHostApi;
598
- /**
599
- * Playground eval batches (`/v1/dev/evals*`). Present once the serve host
600
- * has attached an {@link import("./evals.js").HostEvalsApi}. Used by the
601
- * built-in Slack `eval` directive and available to tools/handlers.
602
- */
603
- evals?: import("./evals.js").HostEvalsApi;
604
- /**
605
- * Author-facing durable JSON KV (`agentkit/v1/{agent}/kv/…`). Backed by
606
- * `agent/storage.ts` (`defineStorage`) when authored; otherwise files
607
- * under `--state-root/kv`. Prefer this over ad-hoc files under the
608
- * project tree so state survives host replacement.
609
- */
610
- kv: HostKvApi;
611
- /**
612
- * Author-facing durable files (`agentkit/v1/{agent}/files/…`). On
613
- * Cursor-managed hosting they live in the deployment's durable store;
614
- * otherwise under `--state-root/files`. Use this for file-shaped state —
615
- * evidence, reports, hand-offs to a delegated run — that must outlive the
616
- * process.
617
- */
618
- files: HostFilesApi;
619
- /**
620
- * Author-facing OpenTelemetry metrics and session tags. Always present.
621
- * Counters and histograms no-op when no meter is running. `setAttributes`
622
- * still tags the open session when a collector is attached.
623
- */
624
- otel: HostOtelApi;
625
- }
626
-
627
- /** Host-facing JSON key-value API attached to {@link HostContext.kv}. */
628
- export interface HostKvApi {
629
- /** Read one value. Miss → `undefined`. */
630
- get(key: string): Promise<JsonValue | undefined>;
631
- /** Write or replace one value. */
632
- put(key: string, value: JsonValue): Promise<void>;
633
- /** Remove one key. No-op when missing. */
634
- delete(key: string): Promise<void>;
635
- }
636
-
637
- /** A value plus its opaque version token, as returned by CAS-capable reads. */
638
- export interface KvVersionedEntry {
639
- value: JsonValue;
640
- /**
641
- * Opaque per-key token that changes on every successful write. Callers
642
- * must not parse it — backends mint whatever is cheap for them (a
643
- * counter, a UUID, an `updated_at`/`xmin` pair, …).
644
- */
645
- version: string;
646
- }
647
-
648
- /**
649
- * Outcome of a conditional write. On conflict the backend returns the
650
- * entry it observed (`undefined` when the key is absent), so a CAS retry
651
- * loop gets its re-read for free instead of paying a second round trip.
652
- */
653
- export type KvCasResult =
654
- | { ok: true; version: string }
655
- | { ok: false; current: KvVersionedEntry | undefined };
656
-
657
- /**
658
- * Conditional-write superset of {@link HostKvApi}. Version-token CAS was
659
- * chosen over compare-value: every candidate backend can mint a cheap
660
- * opaque token (counter, UUID, row version), while compare-value would
661
- * force deep JSON equality with key-order pitfalls on each of them. The
662
- * agent-facing `host.kv` stays plain {@link HostKvApi}; storage backends
663
- * supply CAS via the optional `cas` group on `defineStorage`.
664
- */
665
- export interface HostKvCasApi extends HostKvApi {
666
- /** Read one value with its version token. Miss → `undefined`. */
667
- getWithVersion(key: string): Promise<KvVersionedEntry | undefined>;
668
- /** Create the key only when absent. Conflict returns the existing entry. */
669
- putIfAbsent(key: string, value: JsonValue): Promise<KvCasResult>;
670
- /**
671
- * Replace the value only when the key still carries `expectedVersion`.
672
- * Conflict (version moved, or key deleted) returns the current entry.
673
- */
674
- putIfVersion(key: string, value: JsonValue, expectedVersion: string): Promise<KvCasResult>;
675
- /** All keys under a prefix, in ascending key order. */
676
- listKeys(prefix: string): Promise<string[]>;
677
- }
678
-
679
- /**
680
- * Runtime probe: does this KV implement the CAS superset? Only for
681
- * stores of unknown provenance — e.g. a caller-supplied {@link HostKvApi}
682
- * object whose static type does not carry the CAS methods. A
683
- * `defineStorage` backend declares CAS through its `cas` group instead
684
- * and never needs probing.
685
- */
686
- export function supportsKvCas(kv: HostKvApi): kv is HostKvCasApi {
687
- const candidate = kv as Partial<HostKvCasApi>;
688
- return (
689
- typeof candidate.getWithVersion === "function" &&
690
- typeof candidate.putIfAbsent === "function" &&
691
- typeof candidate.putIfVersion === "function" &&
692
- typeof candidate.listKeys === "function"
693
- );
694
- }
695
-
696
- /**
697
- * Which set of files a call addresses.
698
- *
699
- * `"session"` (the default) is private to one session. `"deployment"` is shared
700
- * by every session of the agent and survives redeploys; `partition` subdivides
701
- * it for author-chosen groupings such as a pull request or a customer.
702
- */
703
- export type HostFilesScope =
704
- | "session"
705
- | "deployment"
706
- | { kind: "session"; sessionId?: string }
707
- | { kind: "deployment"; partition?: string };
708
-
709
- /** Scope selector shared by every {@link HostFilesApi} call. */
710
- export interface HostFilesCallOptions {
711
- scope?: HostFilesScope;
712
- }
713
-
714
- /** One entry from {@link HostFilesApi.list}. */
715
- export interface HostFileEntry {
716
- /** Path within the scope, as authors address it. */
717
- path: string;
718
- size: number;
719
- /** Last-modified epoch ms, when the sink tracks one. */
720
- mtimeMs?: number;
721
- }
722
-
723
- /** Result of {@link HostFilesApi.stat}. */
724
- export interface HostFileStat {
725
- size: number;
726
- mtimeMs?: number;
727
- /** Opaque version tag; pass back as `ifMatch` to make a write conditional. */
728
- etag?: string;
729
- }
730
-
731
- /**
732
- * What the configured sink actually supports. Read these instead of assuming:
733
- * the same authored code runs against local disk, an Agent Store, and whatever
734
- * a customer plugged in, and those differ in ways that change correctness.
735
- */
736
- export interface HostFilesCapabilities {
737
- /**
738
- * Conditional writes are enforced, so a lost race raises
739
- * `FileConflictError` instead of silently clobbering. False means
740
- * last-writer-wins.
741
- */
742
- conflictDetection: boolean;
743
- /**
744
- * Files have a real local path ({@link HostFilesApi.materializedPath}) the
745
- * harness can open with ordinary file tools. False means the model cannot
746
- * reach them directly — only authored handler code (tools, hooks) can,
747
- * through this API.
748
- */
749
- materialized: boolean;
750
- /** Largest value the sink accepts, when it declares a limit. */
751
- maxBytes?: number;
752
- }
753
-
754
- /**
755
- * Durable files attached to {@link HostContext.files}.
756
- *
757
- * Deliberately not a filesystem: no handles, no seeking, no rename, no
758
- * directories, no errno. Paths are addresses within a {@link HostFilesScope},
759
- * never filesystem paths — {@link materializedPath} is the one place a real
760
- * path appears, and it is `undefined` whenever the sink keeps no local copy.
761
- */
762
- export interface HostFilesApi {
763
- /** What the configured sink supports. */
764
- readonly capabilities: HostFilesCapabilities;
765
-
766
- /** Bind `"session"`-scoped calls to `sessionId`. */
767
- forSession(sessionId: string): HostFilesApi;
768
-
769
- /** Read as text. Miss → `undefined`. */
770
- read(
771
- path: string,
772
- options?: HostFilesCallOptions & { encoding?: BufferEncoding },
773
- ): Promise<string | undefined>;
774
-
775
- /** Read as bytes. Miss → `undefined`. */
776
- readBytes(path: string, options?: HostFilesCallOptions): Promise<Uint8Array | undefined>;
777
-
778
- /**
779
- * Write or replace. Pass `ifMatch` with a {@link HostFileStat.etag} to make
780
- * the write conditional, or `null` to require that it does not exist —
781
- * enforced only when {@link HostFilesCapabilities.conflictDetection} is set.
782
- */
783
- write(
784
- path: string,
785
- data: string | Uint8Array,
786
- options?: HostFilesCallOptions & { ifMatch?: string | null },
787
- ): Promise<void>;
788
-
789
- /** Remove one path. No-op when missing. */
790
- remove(path: string, options?: HostFilesCallOptions): Promise<void>;
791
-
792
- /** Entries whose path starts with `prefix` (all when omitted), in path order. */
793
- list(prefix?: string, options?: HostFilesCallOptions): Promise<HostFileEntry[]>;
794
-
795
- exists(path: string, options?: HostFilesCallOptions): Promise<boolean>;
796
-
797
- stat(path: string, options?: HostFilesCallOptions): Promise<HostFileStat | undefined>;
798
-
799
- /**
800
- * Absolute local path the harness can read, or `undefined` when the sink
801
- * keeps no local copy. Never use it as an identity — pass paths and scopes
802
- * to the other calls so the same code works against a sink that has none.
803
- */
804
- materializedPath(path: string, options?: HostFilesCallOptions): string | undefined;
805
- }
806
-
807
- /** Attribute bag accepted by {@link HostOtelApi}. `undefined` values are dropped. */
808
- export type HostOtelAttributes = Record<string, string | number | boolean | undefined>;
809
-
810
- /**
811
- * Author-facing OpenTelemetry surface on {@link HostContext.otel}.
812
- *
813
- * Metrics and tags only — no custom spans, and no raw OTel `Meter` /
814
- * `Tracer`. First-party names (`cursor.token.usage`, …) and join keys
815
- * (`cursor.conversation.id`, `agent_sdk.session_id`, `agent_sdk.agent`,
816
- * …) are reserved.
817
- */
818
- export interface HostOtelApi {
819
- /** True when a meter is running and `increment` / `record` export. */
820
- readonly enabled: boolean;
821
-
822
- /**
823
- * Merge tags onto this host binding. On a session-bound host they join
824
- * open turn/tool spans and later first-party metrics. Unbound tags
825
- * stay on this host instance only.
826
- */
827
- setAttributes(attributes: HostOtelAttributes): void;
828
-
829
- /** Add 1 to a counter. */
830
- increment(name: string, attributes?: HostOtelAttributes): void;
831
- /** Add `value` to a counter. */
832
- increment(name: string, value: number, attributes?: HostOtelAttributes): void;
833
-
834
- /** Record one histogram observation. */
835
- record(name: string, value: number, attributes?: HostOtelAttributes): void;
836
- }
837
-
838
- /** Runtime context handed to a tool's `execute`. */
839
- export interface ToolContext {
840
- /** Correlates with `actions.requested` / `actions.completed` stream events. */
841
- toolCallId?: string;
842
- /** The session this tool call runs inside. */
843
- session: SessionInfo;
844
- /** Absolute path of the session's materialized workspace directory. */
845
- workspaceDir: string;
846
- /**
847
- * Absolute path of the agent's durable state root (shared across every
848
- * session of this agent).
849
- */
850
- stateRoot: string;
851
- /** Shared host services (MCP / GitHub / Slack). */
852
- host: HostContext;
853
- /**
854
- * Start or resume a session on any channel (cross-channel handoff).
855
- * Same semantics as a channel route's `send`, with an explicit channel id.
856
- * `auth` defaults to this tool call's session principal (like HTTP
857
- * channel `send`); pass explicitly to override.
858
- */
859
- send(channelId: string, message: string, options?: SendMessageOptions): Promise<ChannelSession>;
860
- /** Look up a session on a channel (e.g. refresh `sdkAgentId` after a turn). */
861
- getSession(channelId: string, sessionId: string): Promise<ChannelSession | null>;
862
- /**
863
- * Durable artifacts, bound to this tool call's session: `tag` auto-fills
864
- * `sessionId` (and `turnId` when known).
865
- */
866
- artifacts: ArtifactsApi;
867
- /**
868
- * Append a session event onto this call's in-flight turn. Same shape as a
869
- * Task subagent stream (`parentCallId`, `subagent.called` /
870
- * `subagent.completed`). Omitted for scratch `callTool` with no session.
871
- */
872
- emit?: (payload: SessionEventPayload) => void;
873
- /** The session's frozen `asOf`, or the wall clock. Use instead of `Date.now()`. */
874
- now(): Date;
875
- /**
876
- * The session's frozen instant (ISO-8601), when it has one. Present exactly
877
- * when this is an `asOf` session. A tool that reaches other tools itself —
878
- * the script sandbox — reads it to apply the same forward-time guard to the
879
- * calls it makes, which do not pass back through the host's gate.
880
- */
881
- asOf?: string;
882
- }
883
-
884
- /**
885
- * Where a tool's body runs.
886
- *
887
- * - `"server"` (default): in-process on the agent-serve host via Cursor SDK
888
- * custom tools. Only available when the agent {@link AgentConfig.runtime}
889
- * is `"local"`.
890
- * - `"agent"` — materialized into the session workspace as a shell
891
- * script the Cursor agent invokes. Requires
892
- * {@link ToolConfig.script}; `execute` is not used.
893
- */
894
- export type ToolExecution = "server" | "agent";
895
-
896
- /**
897
- * Whether a server tool call must pause for human approval before
898
- * `execute` runs. Boolean always gates; a predicate decides per call from
899
- * validated input only (no {@link ToolContext} — runs before the gate).
900
- */
901
- export type ToolNeedsApproval<TInput> = boolean | ((input: TInput) => boolean | Promise<boolean>);
902
-
903
- /**
904
- * Whether invoking a tool can change anything outside this session.
905
- *
906
- * `"read"` cannot, by construction — a query, a file read, a listing.
907
- * `"write"` changes something a person or another agent will later see: an
908
- * external system (a comment, a message, a ticket) or shared storage another
909
- * session reads back.
910
- *
911
- * This is what {@link SendMessageOptions.dryRun} enforces. In a dry-run
912
- * session a write is answered by the host and never executed, while reads run
913
- * for real — so an agent can be run against real data to see what it *would*
914
- * have done.
915
- *
916
- * A tool that declares nothing is treated as a write: a dry run promises
917
- * "nothing outside this session changed", which it cannot promise about a tool
918
- * it knows nothing about. An unannotated tool is therefore useless in a dry
919
- * run.
920
- */
921
- export type ToolEffect = "read" | "write";
922
-
923
- /** Authored `defineConnection({ effects })` — one effect or a set. */
924
- export type ConnectionEffects = ToolEffect | readonly ToolEffect[];
925
-
926
- const TOOL_EFFECTS: readonly ToolEffect[] = ["read", "write"];
927
-
928
- export function isToolEffect(value: unknown): value is ToolEffect {
929
- return value === "read" || value === "write";
930
- }
931
-
932
- /**
933
- * Normalize authored {@link ConnectionConfig.effects} to a unique list.
934
- * Invalid values are left for discovery to reject — this only collapses
935
- * `"read"` / `["read"]` / duplicates.
936
- */
937
- export function normalizeConnectionEffects(effects: ConnectionEffects): ToolEffect[] {
938
- const list = typeof effects === "string" ? [effects] : [...effects];
939
- const unique: ToolEffect[] = [];
940
- for (const effect of TOOL_EFFECTS) {
941
- if (list.includes(effect)) {
942
- unique.push(effect);
943
- }
944
- }
945
- return unique;
946
- }
947
-
948
- /**
949
- * Trim, drop blanks, and unique-preserve authored
950
- * {@link ConnectionConfig.tools} name lists. Invalid shapes are left
951
- * for discovery.
952
- */
953
- export function normalizeConnectionTools(tools: readonly string[]): string[] {
954
- const unique: string[] = [];
955
- const seen = new Set<string>();
956
- for (const raw of tools) {
957
- const name = raw.trim();
958
- if (name === "" || seen.has(name)) {
959
- continue;
960
- }
961
- seen.add(name);
962
- unique.push(name);
963
- }
964
- return unique;
965
- }
966
-
967
- /** True when `toolName` passes the connection's `tools` / `disallowedTools` filter. */
968
- export function connectionAllowsTool(
969
- filter: {
970
- tools?: readonly string[];
971
- disallowedTools?: readonly string[];
972
- },
973
- toolName: string,
974
- ): boolean {
975
- if (filter.tools !== undefined && !filter.tools.includes(toolName)) {
976
- return false;
977
- }
978
- return filter.disallowedTools === undefined || !filter.disallowedTools.includes(toolName);
979
- }
980
-
981
- /**
982
- * A tool's declared {@link ToolEffect} — fixed, or decided per call from
983
- * validated input for tools that read or write depending on their arguments
984
- * (an HTTP request keyed on method, a SQL tool keyed on statement).
985
- */
986
- export type ToolEffectDeclaration<TInput> = ToolEffect | ((input: TInput) => ToolEffect);
987
-
988
- export interface ToolConfig<TInput> {
989
- description: string;
990
- /**
991
- * Where the tool body runs. Defaults to `"server"` (in-process on the
992
- * agent-serve process). Use `"agent"` to materialize a workspace script
993
- * the Cursor agent invokes instead.
994
- */
995
- execution?: ToolExecution;
996
- /**
997
- * Zod schema (validated before `execute` runs) or a plain JSON Schema
998
- * object (forwarded to the model as-is, unvalidated). Omit to accept any
999
- * JSON object.
1000
- */
1001
- inputSchema?: z.ZodType<TInput> | JsonSchemaObject;
1002
- /**
1003
- * JSON Schema for the tool's structured output (`Tool.outputSchema` from
1004
- * the MCP spec), as a zod schema (converted, never validated against) or a
1005
- * plain JSON Schema object. Advertised when declared and omitted
1006
- * otherwise — results are not validated against it.
1007
- */
1008
- outputSchema?: z.ZodTypeAny | JsonSchemaObject;
1009
- /**
1010
- * When true (or when the predicate returns true), the host parks the
1011
- * in-flight tool call until a human approves or denies via
1012
- * `POST /v1/session/:sessionId/approvals/:callId`. Only supported for
1013
- * `execution: "server"` tools on the local runtime.
1014
- */
1015
- needsApproval?: ToolNeedsApproval<TInput>;
1016
- /**
1017
- * Whether this tool changes anything outside the session. Undeclared means
1018
- * write, so a dry run stubs it — see {@link ToolEffect}.
1019
- */
1020
- effect?: ToolEffectDeclaration<TInput>;
1021
- /**
1022
- * Input properties that carry time bounds. In a session created with
1023
- * {@link SendMessageOptions.asOf}, every named argument must be an
1024
- * absolute ISO-8601 instant with a timezone, no later than the session's
1025
- * frozen instant — a call that omits one, or supplies a relative or later
1026
- * value, is refused so the model retries with absolute bounds. Names must
1027
- * exist in {@link inputSchema}; a session with `asOf` refuses to start
1028
- * otherwise, because a misspelled name would silently check nothing.
1029
- * Ignored in sessions without `asOf`.
1030
- */
1031
- timeArgs?: readonly string[];
1032
- /**
1033
- * What a write tool returns in a dry-run session instead of executing.
1034
- *
1035
- * Omit for a tool whose result the caller only acknowledges. Supply one when
1036
- * the result is read structurally — a caller that uses `result.revision`
1037
- * breaks on a bare string — so a dry run stays on the same path production
1038
- * takes. Ignored unless {@link effect} resolves to `"write"`.
1039
- */
1040
- dryRunResult?: ToolExecuteResult | ((input: TInput) => ToolExecuteResult);
1041
- /**
1042
- * In-process implementation. Required when {@link execution} is
1043
- * `"server"` (the default); ignored for `"agent"` tools.
1044
- */
1045
- execute?: (input: TInput, ctx: ToolContext) => ToolExecuteResult | Promise<ToolExecuteResult>;
1046
- /**
1047
- * Agent tools: shell script body written into the session workspace.
1048
- * Receives a JSON object on stdin and should print the result on
1049
- * stdout. Required when {@link execution} is `"agent"`.
1050
- */
1051
- script?: string;
1052
- }
1053
-
1054
- /** Discovered tool definition with erased input generics. */
1055
- export interface ToolDefinition extends BrandedDefinition<"tool"> {
1056
- readonly description: string;
1057
- readonly execution?: ToolExecution;
1058
- readonly inputSchema?: z.ZodTypeAny | JsonSchemaObject;
1059
- readonly outputSchema?: z.ZodTypeAny | JsonSchemaObject;
1060
- readonly needsApproval?: ToolNeedsApproval<never>;
1061
- readonly effect?: ToolEffectDeclaration<never>;
1062
- readonly timeArgs?: readonly string[];
1063
- readonly dryRunResult?: ToolExecuteResult | ((input: never) => ToolExecuteResult);
1064
- readonly execute?: (
1065
- input: never,
1066
- ctx: ToolContext,
1067
- ) => ToolExecuteResult | Promise<ToolExecuteResult>;
1068
- readonly script?: string;
1069
- }
1070
-
1071
- // ============================================================================
1072
- // Skills (agent/skills/*)
1073
- // ============================================================================
1074
-
1075
- /** Input to `defineSkill` (authored at `agent/skills/<name>.ts`). */
1076
- export interface SkillConfig {
1077
- /** Routing hint advertised to the model in the skills catalog. */
1078
- description?: string;
1079
- /** The skill body (becomes `SKILL.md`). */
1080
- markdown: string;
1081
- /** Package-relative sibling files, e.g. `references/checklist.md`. */
1082
- files?: Record<string, string>;
1083
- }
1084
-
1085
- export type SkillDefinition = SkillConfig & BrandedDefinition<"skill">;
1086
-
1087
- // ============================================================================
1088
- // Extensions (agent/extensions/<ns>.ts | agent/extensions/<ns>/extension.ts)
1089
- // ============================================================================
1090
-
1091
- /**
1092
- * Input to `defineExtension`, the `extension.ts` at the root of an
1093
- * agent-shaped tree (`tools/`, `skills/`, `lib/`).
1094
- */
1095
- export interface ExtensionOptions<TConfig, TInput = TConfig> {
1096
- /** The tree's directory; pass `import.meta.dirname`. */
1097
- root: string;
1098
- /** What the extension adds; shown by `info`. */
1099
- description?: string;
1100
- /** Mount configuration schema. A consumer's settings are validated at mount. */
1101
- config?: z.ZodType<TConfig, z.ZodTypeDef, TInput>;
1102
- /** Choose which contribution groups this mount includes. */
1103
- contributions?: (config: TConfig) => ExtensionContributionSelection;
1104
- }
1105
-
1106
- /** Contribution groups a configured extension mount may include or omit. */
1107
- export interface ExtensionContributionSelection {
1108
- /** Include tools from the extension tree. Defaults to true. */
1109
- tools?: boolean;
1110
- /** Include skills from the extension tree. Defaults to true. */
1111
- skills?: boolean;
1112
- }
1113
-
1114
- /**
1115
- * What `extension.ts` default-exports. A consumer calls it from
1116
- * `agent/extensions/<ns>.ts` to mount the extension with a configuration;
1117
- * the extension's own modules import it to read that configuration.
1118
- */
1119
- export interface Extension<TConfig = undefined, TInput = TConfig> extends ExtensionDeclaration {
1120
- (...args: undefined extends TInput ? [config?: TInput] : [config: TInput]): ExtensionMount;
1121
- /** The mounted configuration (schema defaults applied); throws before the mount. */
1122
- readonly config: TConfig;
1123
- }
1124
-
1125
- /** The mount-independent part of an {@link Extension}: an agent-shaped tree. */
1126
- export interface ExtensionDeclaration {
1127
- readonly root: string;
1128
- readonly description: string | undefined;
1129
- }
1130
-
1131
- /** A Cursor plugin directory declared by `cursorPlugin`. */
1132
- export interface CursorPluginDeclaration extends ExtensionDeclaration {
1133
- readonly layout: "cursor-plugin";
1134
- readonly variables: Record<string, string>;
1135
- }
1136
-
1137
- /** What `agent/extensions/<ns>.ts` default-exports. */
1138
- export interface ExtensionMount extends BrandedDefinition<"extension"> {
1139
- readonly extension: ExtensionDeclaration | CursorPluginDeclaration;
1140
- readonly config: unknown;
1141
- readonly contributions?: ExtensionContributionSelection;
1142
- }
1143
-
1144
- /** `cursorPlugin({ ... })`: mount a Cursor plugin directory as an extension. */
1145
- export interface CursorPluginOptions {
1146
- /**
1147
- * The plugin directory: the one holding `.cursor-plugin/plugin.json`
1148
- * (or `.claude-plugin/plugin.json` / `plugin.json`). A relative path
1149
- * resolves against the project root.
1150
- */
1151
- path: string;
1152
- /**
1153
- * Values for the `${NAME}` placeholders in the plugin's MCP config, the
1154
- * variables a Cursor install prompts for. Names the mount omits fall back
1155
- * to `process.env`; a placeholder nothing resolves fails discovery.
1156
- */
1157
- variables?: Record<string, string>;
1158
- }
1159
-
1160
- /**
1161
- * `export default disableTool()` in a directory mount's `tools/<name>.ts`
1162
- * removes the extension's `<ns>__<name>`.
1163
- */
1164
- export type DisabledToolDefinition = BrandedDefinition<"disabled-tool">;
1165
-
1166
- /**
1167
- * `export default disableConnection()` in a directory mount's
1168
- * `mcp-connections/<server>.ts` removes the extension's `<ns>__<server>`.
1169
- */
1170
- export type DisabledConnectionDefinition = BrandedDefinition<"disabled-connection">;
1171
-
1172
- /**
1173
- * `export default disable()` / `disableSkill()` / `disableHook()` /
1174
- * `disableChannel()` / `disableSchedule()` / `disableSubagent()` /
1175
- * `disableInstructions()` / `disableArtifacts()` in a directory mount
1176
- * removes that contribution from the matching overlay slot.
1177
- */
1178
- export type DisabledDefinition = BrandedDefinition<"disabled">;
1179
-
1180
- /** One mounted extension and the names it contributed. */
1181
- export interface DiscoveredExtension {
1182
- /** Mount namespace: the filename stem or directory name under `agent/extensions/`. */
1183
- name: string;
1184
- description?: string;
1185
- /** Composed tool names (`<ns>__<name>`), overrides applied. */
1186
- tools: string[];
1187
- /** Composed skill names (`<ns>__<name>`), overrides applied. */
1188
- skills: string[];
1189
- /** Composed MCP connection names (`<ns>__<server>`). */
1190
- connections: string[];
1191
- /** Composed host MCP connection names (`<ns>__<server>`). */
1192
- hostConnections: string[];
1193
- /** Composed subagent names (`<ns>__<id>`). */
1194
- subagents: string[];
1195
- /** Composed hook names (`<ns>__<name>`). */
1196
- hooks: string[];
1197
- /** Composed channel ids (`<ns>__<id>`). */
1198
- channels: string[];
1199
- /** Composed schedule names (`<ns>__<name>`). */
1200
- schedules: string[];
1201
- /** Whether the mount contributed an instructions fragment. */
1202
- instructions: boolean;
1203
- /** Workspace seed paths the mount contributed. */
1204
- seedFiles: string[];
1205
- /** Composed artifact kind names (`<ns>__<kind>`). */
1206
- artifactKinds: string[];
1207
- }
1208
-
1209
- // ============================================================================
1210
- // MCP connections (agent/mcp-connections/*.ts)
1211
- // ============================================================================
1212
-
1213
- /**
1214
- * Transport for an MCP connection, mirroring the Cursor SDK's
1215
- * `McpServerConfig` shapes — plus two agent-serve variants that stay
1216
- * symbolic until the server starts:
1217
- *
1218
- * - `agent` addresses a **peer agent** mounted on the same serve host by
1219
- * slug; it resolves to that agent's MCP endpoint (`/<slug>/v1/mcp`).
1220
- * - `cursorAccount` exposes the **Cursor account's MCP connectors** (the
1221
- * HTTP/SSE servers the operator already authorized in Cursor). It
1222
- * resolves to a bridge on this host that executes every tool **on the
1223
- * Cursor backend** with the account's stored OAuth credentials — tokens
1224
- * never reach this host.
1225
- *
1226
- * Credentials belong in `headers` (http/sse) and `env` (stdio) as `${NAME}`
1227
- * templates, which the transport keeps verbatim and expands from the
1228
- * environment each time a client opens. Reading `process.env` in the
1229
- * connection module instead pins whatever the variable held when discovery
1230
- * imported it, which on Cursor hosting is nothing: the platform binds a
1231
- * deployment's secrets per request, long after that import.
1232
- */
1233
- export type ConnectionTransport =
1234
- | {
1235
- type?: "stdio";
1236
- command: string;
1237
- args?: string[];
1238
- env?: Record<string, string>;
1239
- cwd?: string;
1240
- }
1241
- | {
1242
- type?: "http" | "sse";
1243
- url: string;
1244
- headers?: Record<string, string>;
1245
- /** Host PKCE OAuth; `agent-sdk mcp oauth <name>`. No Authorization header. */
1246
- oauth?: true;
1247
- }
1248
- | {
1249
- /** Slug of a peer agent mounted on the same serve host. */
1250
- agent: string;
1251
- }
1252
- | {
1253
- /** Expose the Cursor account's MCP connectors (backend-executed). */
1254
- cursorAccount: true;
1255
- /**
1256
- * Restrict to these connector names after discovery normalization.
1257
- * Authored configs may also pass `"*"` / `["*"]` (see
1258
- * {@link ConnectionConfig}); those normalize to `undefined` (= all).
1259
- */
1260
- servers?: string[];
1261
- };
1262
-
1263
- /** True for the peer-agent transport variant (`{ agent: "<slug>" }`). */
1264
- export function isPeerConnectionTransport(
1265
- transport: ConnectionTransport,
1266
- ): transport is { agent: string } {
1267
- return "agent" in transport;
1268
- }
1269
-
1270
- /** True for the Cursor account transport variant (`{ cursorAccount: true }`). */
1271
- export function isCursorAccountTransport(
1272
- transport: ConnectionTransport,
1273
- ): transport is { cursorAccount: true; servers?: string[] } {
1274
- return "cursorAccount" in transport && transport.cursorAccount === true;
1275
- }
1276
-
1277
- /**
1278
- * Normalize an authored Cursor account `servers` filter.
1279
- *
1280
- * `undefined`, `"*"`, and `["*"]` (after trim) all mean every connected
1281
- * HTTP/SSE server on the account. Returns a concrete allowlist, or
1282
- * `undefined` for all. Does not validate emptiness, blank entries, or a
1283
- * mixed `"*"` + names list — discovery owns those diagnostics.
1284
- */
1285
- export function normalizeCursorAccountServers(
1286
- servers: string[] | "*" | undefined,
1287
- ): string[] | undefined {
1288
- if (servers === undefined || servers === "*") {
1289
- return undefined;
1290
- }
1291
- const trimmed = servers.map(server => server.trim());
1292
- if (trimmed.length === 1 && trimmed[0] === "*") {
1293
- return undefined;
1294
- }
1295
- return [...servers];
1296
- }
1297
-
1298
- /** True when an authored allowlist mixes `"*"` with other connector names. */
1299
- export function cursorAccountServersHasMixedWildcard(servers: string[] | "*" | undefined): boolean {
1300
- if (servers === undefined || servers === "*") {
1301
- return false;
1302
- }
1303
- const trimmed = servers.map(server => server.trim());
1304
- return trimmed.includes("*") && trimmed.some(server => server !== "*");
1305
- }
1306
-
1307
- /**
1308
- * True for an HTTP/SSE transport authorized with host PKCE OAuth
1309
- * (`defineConnection({ url, oauth: true })`). The tokens live on the serve
1310
- * host (`mcp-auth.json` / `MCP_OAUTH_*`), so only host-side MCP clients can
1311
- * use them.
1312
- */
1313
- export function isHostOauthConnectionTransport(
1314
- transport: ConnectionTransport,
1315
- ): transport is Extract<ConnectionTransport, { url: string }> & {
1316
- oauth: true;
1317
- } {
1318
- return "url" in transport && transport.oauth === true;
1319
- }
1320
-
1321
- /**
1322
- * True for transports that stay symbolic at discovery time and are resolved
1323
- * by the serve host once it is listening (peers and the Cursor account
1324
- * bridge). Symbolic transports never reach the SDK or the host MCP registry
1325
- * unresolved.
1326
- */
1327
- export function isSymbolicConnectionTransport(transport: ConnectionTransport): boolean {
1328
- return isPeerConnectionTransport(transport) || isCursorAccountTransport(transport);
1329
- }
1330
-
1331
- /** One TypeScript tool on `defineConnection({ tools })`. */
1332
- export type InlineStdioToolConfig = {
1333
- description: string;
1334
- inputSchema?: z.ZodTypeAny | JsonSchemaObject;
1335
- /** Output JSON Schema (zod converted, never validated); advertised when declared. */
1336
- outputSchema?: z.ZodTypeAny | JsonSchemaObject;
1337
- execute: (input: JsonObject) => unknown | Promise<unknown>;
1338
- };
1339
-
1340
- /** `defineConnection({ tools })`. TypeScript in; stdio MCP out. */
1341
- export type InlineStdioConnectionConfig = {
1342
- tools: Record<string, InlineStdioToolConfig>;
1343
- };
1344
-
1345
- /**
1346
- * Authored MCP connection config (`defineConnection(...)`).
1347
- *
1348
- * For Cursor account connections, `servers` may be omitted, `"*"`, or
1349
- * `["*"]` to forward every connected HTTP/SSE connector; a concrete
1350
- * `string[]` allowlists by connector name. Discovery normalizes the
1351
- * wildcard forms to an unfiltered {@link ConnectionTransport}.
1352
- *
1353
- * `{ tools }` authors TypeScript handlers. Discovery packages them into a
1354
- * stdio MCP server the agent environment can spawn.
1355
- */
1356
- export type ConnectionConfig = (
1357
- | ((
1358
- | Exclude<ConnectionTransport, { cursorAccount: true }>
1359
- | {
1360
- cursorAccount: true;
1361
- /**
1362
- * Which account connectors to expose.
1363
- *
1364
- * - Omit, pass `"*"`, or pass `["*"]` to forward **every** connected
1365
- * HTTP/SSE server on the account (no per-connector allowlist).
1366
- * - Pass connector names as they appear in the Cursor account's MCP
1367
- * config (e.g. `["Linear", "Notion"]`) to restrict the set.
1368
- */
1369
- servers?: string[] | "*";
1370
- }
1371
- ) & {
1372
- /**
1373
- * Tool-name allowlist. Same shape as {@link AgentConfig.tools}:
1374
- * when set, only these MCP tool names (the server's `tools/list`
1375
- * names) are advertised and callable through `host.mcp`. Names
1376
- * the server does not list are omitted, not guessed.
1377
- *
1378
- * A list of names is an allowlist. An object of handlers authors
1379
- * TypeScript tools ({@link InlineStdioConnectionConfig}).
1380
- *
1381
- * On a model-visible connection this requires {@link advertiseTools}:
1382
- * an attached server would still expose every tool. On
1383
- * `host-connections/` it restricts `host.mcp` alone.
1384
- *
1385
- * Combines with {@link disallowedTools} as deny-wins.
1386
- */
1387
- tools?: readonly string[];
1388
- })
1389
- | InlineStdioConnectionConfig
1390
- ) & {
1391
- /** Documentation only; shown in `info` output. */
1392
- description?: string;
1393
- /**
1394
- * Per-session auth: called at turn-build time with the session's
1395
- * {@link SessionInfo}, returning headers merged over the transport's
1396
- * static `headers` for that session's use of this connection. This is
1397
- * how a multi-tenant agent injects the caller's identity — it derives
1398
- * who the session is for host-side and mints a tenant-scoped
1399
- * credential; the model never sees a tenant parameter and can never
1400
- * choose the tenant.
1401
- *
1402
- * Derive the identity from durable session facts — `session.auth`,
1403
- * `session.id`, or your channel's own session state. Do **not** key it
1404
- * off `session.continuationKey`: it is a channel routing key, and channels
1405
- * may re-key it independently of the authenticated principal.
1406
- *
1407
- * Works attached or advertised. Advertised connections
1408
- * ({@link advertiseTools}) open per-operation clients with the
1409
- * evaluated headers. Attached connections ride the turn's SDK
1410
- * `mcpServers`, passed on every send rather than pinned on the cached
1411
- * per-session agent handle, so every turn — follow-ups, reminder
1412
- * wakes — runs on headers evaluated for that turn. The cost: when any
1413
- * attached connection has `auth`, *all* of the agent's attached
1414
- * connections are configured per send, so the harness opens fresh MCP
1415
- * clients for them each turn (stdio servers respawn per turn — avoid
1416
- * pairing an auth'd connection with a stateful stdio server), and
1417
- * workspace prewarm omits auth'd connections rather than attaching
1418
- * them without an identity.
1419
- *
1420
- * HTTP/SSE transports only, not combinable with `oauth: true`
1421
- * (discovery rejects both). A callback that throws fails the turn: a
1422
- * turn never silently runs without the connection's identity.
1423
- * `host.mcp` calls from server tools keep the static headers only.
1424
- */
1425
- auth?: ConnectionAuthProvider;
1426
- /**
1427
- * Advertise this connection's tools by name instead of leaving them
1428
- * behind the MCP meta-tools: at turn-build time the engine lists the
1429
- * connection's tools and synthesizes a named 1:1 passthrough server
1430
- * tool per entry — the server's own names, descriptions, and live
1431
- * schemas — merged into the authored `agent/tools/` catalog. The raw
1432
- * connection is then not attached to the model (it stays available on
1433
- * `host.mcp`), so each tool appears exactly once.
1434
- *
1435
- * Fail-closed: a `listTools` failure, an invalid tool name, or a name
1436
- * collision (with an authored tool or another advertised connection)
1437
- * fails the turn — a turn never silently runs with a shrunken toolset.
1438
- * The listing runs once per turn; point this at endpoints that can
1439
- * answer `tools/list` cheaply. Tools whose MCP `annotations.title` is
1440
- * `do-not-call` are omitted (vendor host-UI / MCP Apps helpers).
1441
- */
1442
- advertiseTools?: boolean;
1443
- /**
1444
- * With {@link advertiseTools}, a `listTools` or `auth` failure skips this
1445
- * connection (zero tools from it) instead of failing the turn. Other
1446
- * advertised connections still fail closed. Requires `advertiseTools`.
1447
- */
1448
- optional?: boolean;
1449
- /**
1450
- * Intended effects of tools this connection serves. When set, only
1451
- * tools whose classified effect is in this set are advertised — a
1452
- * connection that wants reads never puts a write, or a tool nothing
1453
- * classified, in the model's toolset.
1454
- *
1455
- * Classification is the same fail-closed read of MCP annotations the
1456
- * dry-run gate uses (`readOnlyHint` / `destructiveHint`). A tool the
1457
- * server does not classify is omitted, not guessed. Servers that leave
1458
- * tools unannotated stay empty here until they annotate or a trusted
1459
- * listing injects a known-read hint.
1460
- *
1461
- * Requires {@link advertiseTools}: this filters the named passthroughs
1462
- * the model sees. A single value (`"read"`) and an array (`["read"]`)
1463
- * are the same.
1464
- */
1465
- effects?: ConnectionEffects;
1466
- /**
1467
- * Tool-name denylist. Same shape as the Cursor SDK's
1468
- * `disallowedTools`: when set, these MCP tool names are omitted from
1469
- * the advertised set and rejected on `host.mcp`. Combines with
1470
- * {@link ConnectionConfig.tools} as deny-wins.
1471
- *
1472
- * On a model-visible connection this requires {@link advertiseTools}.
1473
- * On `host-connections/` it restricts `host.mcp` alone.
1474
- */
1475
- disallowedTools?: readonly string[];
1476
- };
1477
-
1478
- /**
1479
- * Per-session connection auth on {@link ConnectionConfig.auth}: session →
1480
- * headers merged over the transport's static headers for that session's
1481
- * turns. See the field docs for the fail-closed semantics.
1482
- */
1483
- export type ConnectionAuthProvider = (
1484
- session: SessionInfo,
1485
- ) => ConnectionAuthResult | Promise<ConnectionAuthResult>;
1486
-
1487
- /** What a {@link ConnectionAuthProvider} returns. */
1488
- export type ConnectionAuthResult = {
1489
- headers: Record<string, string>;
1490
- };
1491
-
1492
- /** True when the connection authors tools instead of a spawn/URL/peer. */
1493
- export function isInlineStdioConnection(
1494
- connection: ConnectionConfig,
1495
- ): connection is InlineStdioConnectionConfig & {
1496
- description?: string;
1497
- } {
1498
- return (
1499
- "tools" in connection && connection.tools !== undefined && !Array.isArray(connection.tools)
1500
- );
1501
- }
1502
-
1503
- /**
1504
- * An MCP connection is available to the agent (SDK `mcpServers`), host
1505
- * (`ctx.host.mcp`), and channel/schedule handlers.
1506
- */
1507
- export type ConnectionDefinition = ConnectionConfig & BrandedDefinition<"connection">;
1508
-
1509
- // ============================================================================
1510
- // Auth
1511
- // ============================================================================
1512
-
1513
- /** Who initiated a session (or an authenticated channel request). */
1514
- export interface AuthContext {
1515
- /** Which policy authenticated the caller, e.g. `"local-dev"`. */
1516
- authenticator: string;
1517
- principalId: string;
1518
- principalType: "user" | "service" | "runtime";
1519
- attributes?: Record<string, string>;
1520
- }
1521
-
1522
- export interface AuthRequestInfo {
1523
- /** Client IP, or null when the host cannot provide it. */
1524
- requestIp: string | null;
1525
- }
1526
-
1527
- /**
1528
- * A route auth policy. Return an {@link AuthContext} to admit the request,
1529
- * or null to pass to the next policy in the chain. A request is rejected
1530
- * with 401 when every policy in the chain returns null.
1531
- */
1532
- export type AuthPolicy = (
1533
- request: Request,
1534
- info: AuthRequestInfo,
1535
- ) => AuthContext | null | Promise<AuthContext | null>;
1536
-
1537
- // ============================================================================
1538
- // Session events (the NDJSON stream vocabulary)
1539
- // ============================================================================
1540
-
1541
- export interface SessionEventEnvelope {
1542
- /** Monotonic per-session event index; reconnect with `?startIndex=`. */
1543
- index: number;
1544
- sessionId: string;
1545
- /** Present on turn-scoped events. */
1546
- turnId?: string;
1547
- /** ISO-8601 timestamp. */
1548
- at: string;
1549
- }
1550
-
1551
- export interface ActionCall {
1552
- callId: string;
1553
- toolName: string;
1554
- args?: unknown;
1555
- /**
1556
- * When set, this tool call belongs to a nested subagent turn whose
1557
- * parent `task` tool call id is `parentCallId`.
1558
- */
1559
- parentCallId?: string;
1560
- /**
1561
- * Model generation that requested this call. Every tool from one
1562
- * `runStep` shares the same id (the step's invocation id).
1563
- */
1564
- modelCallId?: string;
1565
- }
1566
-
1567
- /** One tool result inside an {@link SessionEventPayload} `actions.completed` batch. */
1568
- export interface ActionResult {
1569
- callId: string;
1570
- toolName: string;
1571
- output?: unknown;
1572
- isError: boolean;
1573
- stubbed?: true;
1574
- parentCallId?: string;
1575
- modelCallId?: string;
1576
- }
1577
-
1578
- /** Human decision for a parked {@link ToolConfig.needsApproval} tool call. */
1579
- export type ApprovalDecision = "approve" | "deny";
1580
-
1581
- /** Durable record of a tool call waiting on human approval. */
1582
- export interface PendingApproval {
1583
- callId: string;
1584
- turnId: string;
1585
- toolName: string;
1586
- args: unknown;
1587
- requestedAt: string;
1588
- }
1589
-
1590
- /** Durable record of a tool call waiting on MCP authorization. */
1591
- export interface PendingAuth {
1592
- callId: string;
1593
- turnId: string;
1594
- toolName: string;
1595
- connection: string;
1596
- authUrl: string;
1597
- requestedAt: string;
1598
- }
1599
-
1600
- export type SessionEventPayload =
1601
- | { type: "session.started"; data: { channelId: string; dryRun?: boolean } }
1602
- | {
1603
- /** Cursor SDK agent id is known (cloud: `bc-…`; local: session id). */
1604
- type: "agent.bound";
1605
- data: { sdkAgentId: string; url?: string };
1606
- }
1607
- | { type: "message.received"; data: { text: string } }
1608
- | {
1609
- /**
1610
- * The turn was admitted while every {@link AgentConcurrencyOptions.maxRunningTurns}
1611
- * slot was busy; it waits FIFO and `turn.started` follows once a slot
1612
- * frees. `position` is 1-based among waiting turns at enqueue time.
1613
- */
1614
- type: "turn.queued";
1615
- data: { position: number; maxRunningTurns: number };
1616
- }
1617
- | { type: "turn.started"; data: Record<string, never> }
1618
- | { type: "step.started"; data: { stepId: number } }
1619
- | { type: "step.completed"; data: { stepId: number; durationMs: number } }
1620
- | {
1621
- type: "reasoning.appended";
1622
- data: { delta: string; text: string; parentCallId?: string };
1623
- }
1624
- | {
1625
- type: "reasoning.completed";
1626
- data: { durationMs?: number; parentCallId?: string };
1627
- }
1628
- | {
1629
- type: "message.appended";
1630
- data: { delta: string; text: string; parentCallId?: string };
1631
- }
1632
- | {
1633
- type: "message.completed";
1634
- data: {
1635
- text: string;
1636
- finishReason: "stop" | "tool_call";
1637
- parentCallId?: string;
1638
- };
1639
- }
1640
- | {
1641
- type: "actions.requested";
1642
- data: {
1643
- calls: ActionCall[];
1644
- parentCallId?: string;
1645
- /**
1646
- * Same id as {@link ActionCall.modelCallId} on every call.
1647
- * One envelope per model step (a single tool is a batch of one)
1648
- * once that step has finished listing tools.
1649
- */
1650
- modelCallId?: string;
1651
- };
1652
- }
1653
- | {
1654
- /**
1655
- * A server tool with {@link ToolConfig.needsApproval} is parked until
1656
- * a human resolves it. The turn stays running; send follow-ups
1657
- * after `session.waiting` as usual.
1658
- */
1659
- type: "action.approval_requested";
1660
- data: {
1661
- callId: string;
1662
- toolName: string;
1663
- args?: unknown;
1664
- parentCallId?: string;
1665
- };
1666
- }
1667
- | {
1668
- type: "action.approval_resolved";
1669
- data: {
1670
- callId: string;
1671
- toolName: string;
1672
- decision: ApprovalDecision;
1673
- by?: string;
1674
- parentCallId?: string;
1675
- };
1676
- }
1677
- | {
1678
- /**
1679
- * A host MCP call/list needs OAuth. The turn stays running until
1680
- * the human completes the `authUrl` and the runtime retries.
1681
- */
1682
- type: "action.auth_requested";
1683
- data: {
1684
- callId: string;
1685
- toolName: string;
1686
- connection: string;
1687
- authUrl: string;
1688
- parentCallId?: string;
1689
- };
1690
- }
1691
- | {
1692
- type: "action.auth_resolved";
1693
- data: {
1694
- callId: string;
1695
- toolName: string;
1696
- connection: string;
1697
- decision: ApprovalDecision;
1698
- by?: string;
1699
- parentCallId?: string;
1700
- };
1701
- }
1702
- | {
1703
- type: "action.result";
1704
- data: {
1705
- callId: string;
1706
- toolName: string;
1707
- output?: unknown;
1708
- isError: boolean;
1709
- /**
1710
- * The tool never ran: a write answered by the host in a `dryRun`
1711
- * session. `actions.requested` still carries the arguments the model
1712
- * chose, so this is the marker that separates "what it would have
1713
- * done" from a real effect when reading a trajectory.
1714
- */
1715
- stubbed?: true;
1716
- parentCallId?: string;
1717
- /** Same id as the matching {@link ActionCall.modelCallId}. */
1718
- modelCallId?: string;
1719
- };
1720
- }
1721
- | {
1722
- /**
1723
- * Every result for one {@link SessionEventPayload} `actions.requested`
1724
- * batch. Pair these two events; `action.result` stays the live
1725
- * per-call envelope for chips and spans.
1726
- */
1727
- type: "actions.completed";
1728
- data: {
1729
- results: ActionResult[];
1730
- parentCallId?: string;
1731
- modelCallId?: string;
1732
- };
1733
- }
1734
- | {
1735
- /**
1736
- * A dry-run call was refused because nothing classifies the tool's
1737
- * effect: the MCP server sent no readOnlyHint/destructiveHint and no
1738
- * server-side classification exists for it. The per-run count of these
1739
- * is the coverage signal — how much of a backtest was actually
1740
- * runnable, reported rather than assumed.
1741
- */
1742
- type: "action.effect_unclassified";
1743
- data: { callId: string; toolName: string; connection?: string };
1744
- }
1745
- | {
1746
- type: "subagent.called";
1747
- data: { callId: string; name?: string; description?: string };
1748
- }
1749
- | { type: "subagent.completed"; data: { callId: string; name?: string } }
1750
- | {
1751
- /** An artifact was tagged for this session (see {@link ArtifactsApi.tag}). */
1752
- type: "artifact.tagged";
1753
- data: {
1754
- id: string;
1755
- kind: string;
1756
- key?: string;
1757
- title?: string;
1758
- data: JsonValue;
1759
- source: ArtifactSource;
1760
- };
1761
- }
1762
- | {
1763
- type: "turn.completed";
1764
- data: {
1765
- result?: string;
1766
- usage?: TurnUsage;
1767
- cost?: TurnCost;
1768
- };
1769
- }
1770
- | {
1771
- /**
1772
- * The harness accepted the turn and named the run. Emitted once the
1773
- * send lands, so a channel can show the request id while the turn is
1774
- * still going rather than after it. Quote it verbatim when correlating
1775
- * with backend logs — never abbreviated.
1776
- */
1777
- type: "turn.bound";
1778
- data: { requestId: string };
1779
- }
1780
- | {
1781
- type: "turn.failed";
1782
- data: {
1783
- message: string;
1784
- /** Machine-readable terminal status. Omitted on legacy stored events. */
1785
- status?: "error" | "cancelled";
1786
- };
1787
- }
1788
- | {
1789
- /**
1790
- * A Slack follow-up queued mid-turn reached the running agent: the
1791
- * workspace carrier moved it from `pending/` to `delivered/` at a tool
1792
- * boundary. Channels use this to reposition a live progress message
1793
- * below the follow-up, which Slack cannot do any other way.
1794
- */
1795
- type: "nudge.delivered";
1796
- data: Record<string, never>;
1797
- }
1798
- | { type: "session.waiting"; data: Record<string, never> }
1799
- | { type: "session.completed"; data: Record<string, never> }
1800
- | { type: "session.failed"; data: { message: string } };
1801
-
1802
- export type SessionEvent = SessionEventEnvelope & SessionEventPayload;
1803
- export type SessionEventType = SessionEventPayload["type"];
1804
-
1805
- export interface TurnUsage {
1806
- inputTokens: number;
1807
- outputTokens: number;
1808
- cacheReadTokens: number;
1809
- cacheWriteTokens: number;
1810
- reasoningTokens?: number;
1811
- }
1812
-
1813
- /**
1814
- * Dollar cost of one turn's token usage (one agent loop pass).
1815
- * Recorded on `turn.completed` events so traces, the playground, and the
1816
- * CLI can aggregate spend. Computed by
1817
- * `POST /v1/models/estimate-cost` — billed usage events when available
1818
- * (credits, discounts, CTF), otherwise live catalog pricing.
1819
- */
1820
- export interface TurnCost {
1821
- /** Charged total for the turn, in USD. */
1822
- totalUsd: number;
1823
- inputUsd: number;
1824
- outputUsd: number;
1825
- cacheReadUsd: number;
1826
- cacheWriteUsd: number;
1827
- /** Model id the cost was priced against. */
1828
- model: string;
1829
- /** `"usage"` is billed events; `"catalog"` is live list pricing. */
1830
- source: "usage" | "catalog";
1831
- rawCostCents?: number;
1832
- chargedCents?: number;
1833
- }
1834
-
1835
- // ============================================================================
1836
- // Sessions
1837
- // ============================================================================
1838
-
1839
- export type SessionMode = "chat" | "task";
1840
-
1841
- /**
1842
- * Why the session exists. `"eval"` is regression traffic (`defineEval` /
1843
- * `agent-sdk eval` / playground Evals). Default `"live"`.
1844
- */
1845
- export type SessionPurpose = "live" | "eval";
1846
-
1847
- /** Read-only view of a session, handed to tools, hooks, and channel events. */
1848
- export interface SessionInfo {
1849
- id: string;
1850
- channelId: string;
1851
- mode: SessionMode;
1852
- /** Omit / `"live"` for production traffic; `"eval"` for eval harness sessions. */
1853
- purpose?: SessionPurpose;
1854
- /** True when write-classified tool calls are answered by the host. */
1855
- dryRun?: boolean;
1856
- /** Frozen instant this session reads at; absent means the wall clock. */
1857
- asOf?: string;
1858
- auth: AuthContext | null;
1859
- title?: string;
1860
- /**
1861
- * Channel-local continuation key when the session is addressable for
1862
- * follow-ups / reminders. Null when the session is not re-keyable.
1863
- */
1864
- continuationKey?: string | null;
1865
- /**
1866
- * Cursor SDK agent id once bound (hosted ids start with `bc-`; local
1867
- * turns use the session id). Hosted ids are minted during the first
1868
- * send, so read this from a fresh `getSession()` handle after a turn
1869
- * completes — unless the session was created with a seeded
1870
- * {@link SendMessageOptions.sdkAgentId}.
1871
- */
1872
- sdkAgentId?: string;
1873
- }
1874
-
1875
- /** Persisted session record (stored at `sessions/<id>/session.json`). */
1876
- export interface SessionRecord {
1877
- sessionId: string;
1878
- channelId: string;
1879
- mode: SessionMode;
1880
- /**
1881
- * `"eval"` for harness sessions. Older records omit this (treated as
1882
- * `"live"`).
1883
- */
1884
- purpose?: SessionPurpose;
1885
- /** Frozen at create from {@link SendMessageOptions.dryRun}. */
1886
- dryRun?: boolean;
1887
- /** Frozen at create from {@link SendMessageOptions.asOf}. */
1888
- asOf?: string;
1889
- /** Channel-local continuation key; null when the session is not addressable. */
1890
- continuationKey: string | null;
1891
- /**
1892
- * Rotating HTTP follow-up credential for a channel-owned session.
1893
- * Omitted until HTTP accepts the first follow-up.
1894
- */
1895
- httpContinuationKey?: string;
1896
- auth: AuthContext | null;
1897
- title?: string;
1898
- channelState?: JsonValue;
1899
- /** Cursor SDK agent id for this session. */
1900
- sdkAgentId?: string;
1901
- /**
1902
- * When set, local harness turns use this directory as `cwd` (e.g. a PR
1903
- * worktree). Session scaffold files still land under the session workspace.
1904
- */
1905
- workspaceOverride?: string;
1906
- /**
1907
- * One-shot files for the next turn (see
1908
- * {@link SendMessageOptions.workspaceFiles}). Cleared after apply.
1909
- */
1910
- pendingWorkspaceFiles?: Record<
1911
- string,
1912
- string | { encoding: "base64"; data: string; mimeType?: string }
1913
- >;
1914
- /**
1915
- * One-shot vision images for the next turn (see
1916
- * {@link SendMessageOptions.images}). Cleared after apply.
1917
- */
1918
- pendingImages?: Array<{ data: string; mimeType: string }>;
1919
- /**
1920
- * Per-session cloud attach options captured at session creation, merged
1921
- * over the agent's static `cloud` config on every turn of this session.
1922
- */
1923
- cloudOverride?: AgentCloudOptions;
1924
- /**
1925
- * Server-tool calls parked for human approval. Cleared when resolved
1926
- * or when the host process restarts without a live waiter (the in-flight
1927
- * SDK tool callback cannot be resumed after process restart).
1928
- */
1929
- pendingApprovals?: PendingApproval[];
1930
- /**
1931
- * Server-tool MCP calls parked for host or Cursor-account OAuth.
1932
- * Cleared when resolved or when the host restarts without a live waiter.
1933
- */
1934
- pendingAuths?: PendingAuth[];
1935
- turnCount: number;
1936
- createdAt: string;
1937
- updatedAt: string;
1938
- }
1939
-
1940
- export interface TurnOutcome {
1941
- status: "finished" | "error" | "cancelled";
1942
- result?: string;
1943
- errorMessage?: string;
1944
- /** Stable machine-readable runner code when the failure supplied one. */
1945
- errorCode?: string;
1946
- /** Why a cancelled turn stopped, when the engine observed the boundary. */
1947
- cancellationReason?: "signal" | "runner";
1948
- usage?: TurnUsage;
1949
- /** Cost of {@link usage} from the Cloud Agents cost endpoint. */
1950
- cost?: TurnCost;
1951
- }
1952
-
1953
- /**
1954
- * Session metadata returned by `GET /v1/sessions` (and consumed by the
1955
- * bundled playground). Includes the current wire-format continuation token:
1956
- * the listing is a testing/observability surface for callers already
1957
- * admitted by the route auth chain.
1958
- */
1959
- export interface SessionSummary {
1960
- sessionId: string;
1961
- channelId: string;
1962
- mode: SessionMode;
1963
- title?: string;
1964
- turnCount: number;
1965
- /** True while a turn is executing right now (including queued turns). */
1966
- running: boolean;
1967
- /**
1968
- * True while the session's admitted turn is waiting for a
1969
- * {@link AgentConcurrencyOptions.maxRunningTurns} slot (subset of
1970
- * {@link running}). Omitted when the agent has no turn limit.
1971
- */
1972
- queued?: boolean;
1973
- createdAt: string;
1974
- updatedAt: string;
1975
- /** True when write-classified tool calls are answered by the host. */
1976
- dryRun?: boolean;
1977
- /** Active wire token for HTTP follow-ups, or null when not addressable. */
1978
- continuationToken: string | null;
1979
- /**
1980
- * Conversation permalink (Slack thread, else GitHub PR).
1981
- */
1982
- externalUrl?: string;
1983
- /** GitHub PR when the session is about one. */
1984
- prUrl?: string;
1985
- }
1986
-
1987
- /**
1988
- * Where `GET /v1/sessions` loaded rows from.
1989
- * - `cursor-hosted` — durable Bugbot `agent_serve_kv` via `cursorHostedStorage`
1990
- * - `local` — the serve process `--state-root` session store
1991
- */
1992
- export type SessionListSource = "cursor-hosted" | "local";
1993
-
1994
- /**
1995
- * A session handle scoped to the channel that owns it. This is what channel
1996
- * route handlers get back from `send()` / `getSession()`.
1997
- */
1998
- export interface ChannelSession {
1999
- readonly id: string;
2000
- /** Channel-local continuation key currently addressing this session. */
2001
- readonly continuationToken: string | null;
2002
- /** True when this `send()` created the session. */
2003
- readonly isNew: boolean;
2004
- /**
2005
- * True when `admission: "coalesce"` enqueued this message behind an
2006
- * in-flight turn instead of starting immediately (Slack busy path).
2007
- */
2008
- readonly coalesced?: boolean;
2009
- readonly info: SessionInfo;
2010
- /**
2011
- * Replay recorded events from `startIndex`, then follow live (NDJSON).
2012
- * A handle from `send()` defaults `startIndex` to this admission so a
2013
- * resumed continuation does not replay earlier turns.
2014
- */
2015
- getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<Uint8Array>>;
2016
- /**
2017
- * Resolves after the currently running turn reaches a terminal event and
2018
- * handlers already queued for that session have settled.
2019
- */
2020
- waitForCompletion(): Promise<TurnOutcome>;
2021
- /** Re-key the session's channel-local continuation token. */
2022
- setContinuationToken(token: string | null): Promise<void>;
2023
- }
2024
-
2025
- export interface SendMessageOptions {
2026
- /**
2027
- * Who is sending; flows to `session.auth` on newly created sessions.
2028
- * On HTTP channel routes, defaults to the request principal from
2029
- * {@link ChannelHandlerArgs.auth}. Pass explicitly to override (e.g.
2030
- * `null` or a Slack-derived principal).
2031
- */
2032
- auth?: AuthContext | null;
2033
- /**
2034
- * Channel-local continuation token. When it addresses an existing session
2035
- * the message is a follow-up; otherwise a new session is created keyed by
2036
- * this token. Omit to always create a fresh session.
2037
- *
2038
- * `/v2` selectors refuse this field — pass {@link mailboxContinuation} or
2039
- * a structured {@link claim} instead.
2040
- */
2041
- continuationToken?: string;
2042
- /**
2043
- * v2 mailbox stamp from the control plane (hosted verified ingress or
2044
- * the local CP). Channel adapters do not extract. Ignored on v1.
2045
- */
2046
- mailboxContinuation?: MailboxContinuation;
2047
- /**
2048
- * v2 host join. Never a concatenated `pr:owner/repo#N` string — the
2049
- * registry mints `cont:` bytes from this claim.
2050
- */
2051
- claim?: ContinuationClaim;
2052
- /** Initial channel state for newly created sessions. */
2053
- state?: JsonValue;
2054
- /**
2055
- * On resume (continuation hit), shallow-merge into the existing session
2056
- * channel state before the turn starts. Null / undefined values in the
2057
- * patch do not overwrite existing keys, so sticky fields (stream ts,
2058
- * progress banner comment id, …) survive while wake-derived fields
2059
- * (`headSha`, refs) refresh. Ignored on create; pass {@link state} there.
2060
- */
2061
- refreshState?: JsonValue;
2062
- /** Session display title (applied when creating a new session). */
2063
- title?: string;
2064
- /**
2065
- * Session purpose at create time. `"eval"` marks regression traffic so
2066
- * hooks and telemetry can tell it from live sessions.
2067
- */
2068
- purpose?: SessionPurpose;
2069
- /**
2070
- * Answer every write-classified tool call from the host instead of running
2071
- * it, for this session's whole life (create only — a follow-up cannot clear
2072
- * it, so a session that starts as a rehearsal stays one).
2073
- *
2074
- * Reads execute, writes are answered and recorded, and the arguments the
2075
- * model chose stay on the session log as the record of the intended action.
2076
- */
2077
- dryRun?: boolean;
2078
- /**
2079
- * ISO-8601 instant with a timezone, frozen at create: the prompt states
2080
- * it, {@link ToolContext.now} returns it, and every tool call is checked
2081
- * against it — a relative time argument (`now-1h`), an absolute one after
2082
- * the instant, or an omitted window a vendor schema declares is refused so
2083
- * the model retries with explicit absolute bounds. Tools may also declare
2084
- * {@link ToolConfig.timeArgs} for precise per-field checking. The check
2085
- * reads arguments, not behavior: a tool that reads present state without a
2086
- * time argument still answers from the present.
2087
- */
2088
- asOf?: string;
2089
- /**
2090
- * Absolute directory used as the local harness `cwd` for this session.
2091
- * On create, sets the session workspace. On resume (continuation hit),
2092
- * refreshes `workspaceOverride` when the path differs — e.g. a newer PR
2093
- * worktree after synchronize.
2094
- */
2095
- workspaceDir?: string;
2096
- /**
2097
- * Relative path to contents for the next turn. On create, queued for the
2098
- * first turn; on resume, merged into pending files. Prefer this over
2099
- * {@link workspaceDir} when you only need to inject a few host-prepared
2100
- * files. Values may be utf8 strings or
2101
- * `{ encoding: "base64", data }` blobs (Slack attachments, binary docs).
2102
- */
2103
- workspaceFiles?: Record<string, string | { encoding: "base64"; data: string; mimeType?: string }>;
2104
- /**
2105
- * Base64 images for this turn's Cursor SDK `send({ images })` (vision).
2106
- * Cleared after the turn starts. Slack inbound fills this from uploads.
2107
- */
2108
- images?: Array<{ data: string; mimeType: string }>;
2109
- /**
2110
- * Per-session cloud attach options, merged over the agent's static
2111
- * `cloud` config (new sessions only). When set, this session attaches
2112
- * even if {@link AgentConfig.runtime} is `"local"`. Cannot be combined
2113
- * with {@link clearCloudOverride}.
2114
- */
2115
- cloud?: AgentCloudOptions;
2116
- /**
2117
- * Clear cloud attach options retained by an existing continuation
2118
- * session before starting this turn. Cannot be combined with
2119
- * {@link cloud}. No-op on a new session.
2120
- */
2121
- clearCloudOverride?: boolean;
2122
- /**
2123
- * Seed the Cursor SDK agent id for a new session (ignored when the
2124
- * continuation token matches an existing session). A `bc-…` value
2125
- * reattaches the first turn to that hosted conversation.
2126
- */
2127
- sdkAgentId?: string;
2128
- /**
2129
- * Turn admission when a session is already busy.
2130
- * - `"preempt"` (default) — interrupt the in-flight turn (HTTP / MCP).
2131
- * - `"coalesce"` — enqueue and return without interrupting (Slack).
2132
- */
2133
- admission?: "preempt" | "coalesce";
2134
- /**
2135
- * Optional source message timestamp for coalesce queue items. When a
2136
- * mid-turn nudge already delivered this `sourceTs`, boundary resume skips it.
2137
- */
2138
- coalesceSourceTs?: string;
2139
- }
2140
-
2141
- export type SendMessageFn = (
2142
- message: string,
2143
- options?: SendMessageOptions,
2144
- ) => Promise<ChannelSession>;
2145
-
2146
- // ============================================================================
2147
- // Direct tool calls (deterministic invocation, no model turn)
2148
- // ============================================================================
2149
-
2150
- /**
2151
- * Channel id recorded on the synthetic session info handed to tools invoked
2152
- * directly (outside any existing session).
2153
- */
2154
- export const DIRECT_TOOL_CALL_CHANNEL_ID = "direct";
2155
-
2156
- /** Options for {@link CallToolFn} — calling an authored tool directly. */
2157
- export interface CallToolOptions {
2158
- /** Who is calling; becomes the tool context's session auth. */
2159
- auth?: AuthContext | null;
2160
- /**
2161
- * Address the session by its wire continuation token
2162
- * (`<channelId>:<key>`, as `/v1/sessions` lists it). A token that maps
2163
- * to a live (or restorable) session behaves exactly like passing that
2164
- * session's {@link sessionId} — ownership check, turn serialization, and
2165
- * event recording included. A token with no session behind it runs the
2166
- * call scratch-bound with the token's channel id and continuation key as
2167
- * the call's session identity, so deployments whose tools resolve state
2168
- * from the continuation key (e.g. VFS mounts rebuilt by a binding
2169
- * resolver) can serve it with no live session. Mutually exclusive with
2170
- * {@link sessionId}.
2171
- */
2172
- continuationToken?: string;
2173
- /**
2174
- * Run the tool inside an existing session: the tool sees that session's
2175
- * info and materialized workspace, and the call is recorded on the
2176
- * session's event stream (`actions.requested` / `action.result` under a
2177
- * per-call `turnId`). Rejected while a model turn is running on the
2178
- * session. Omit to run against an ephemeral scratch workspace under
2179
- * `<stateRoot>/tool-calls/<callId>` (materialized with seed files and
2180
- * removed after the call) with a synthetic
2181
- * {@link DIRECT_TOOL_CALL_CHANNEL_ID} session info.
2182
- */
2183
- sessionId?: string;
2184
- }
2185
-
2186
- /** Result of a direct (deterministic) tool call. */
2187
- export interface ToolCallOutcome {
2188
- toolName: string;
2189
- /** Correlates with the recorded events for session-bound calls. */
2190
- callId: string;
2191
- /** True when the tool threw or returned an error envelope. */
2192
- isError: boolean;
2193
- /** Normalized result, exactly as the model would receive it. */
2194
- result: unknown;
2195
- /**
2196
- * Human-readable failure text when {@link isError} is true (joined text
2197
- * parts from the error envelope, or a string result). Prefer this over
2198
- * re-parsing {@link result} in channel handlers.
2199
- */
2200
- errorMessage?: string;
2201
- durationMs: number;
2202
- /** Present when the call ran inside an existing session. */
2203
- sessionId?: string;
2204
- /**
2205
- * Present (true) when a session-bound call could not materialize a
2206
- * session-owned harness cwd and ran in a scratch workspace instead.
2207
- * The session identity still applied (read-effect calls only get here),
2208
- * but `ctx.workspaceDir` was not the session workspace — callers
2209
- * rendering results as session state should surface this.
2210
- *
2211
- * A shared `local.workspaceDir` the host cannot create (a phantom path
2212
- * like `/repo`) is kept as-is and does not set this flag.
2213
- */
2214
- scratchWorkspace?: true;
2215
- }
2216
-
2217
- /**
2218
- * Call an authored server tool (`agent/tools/<name>.ts`) deterministically:
2219
- * the input is validated against the tool's schema (zod schemas validate;
2220
- * plain JSON Schema inputs pass through unvalidated, matching the model
2221
- * path) and `execute` runs in-process, without a model turn deciding to
2222
- * call it. Rejects unknown tools, `execution: "agent"` tools, and invalid
2223
- * input by throwing.
2224
- */
2225
- export type CallToolFn = (
2226
- toolName: string,
2227
- input?: unknown,
2228
- options?: CallToolOptions,
2229
- ) => Promise<ToolCallOutcome>;
2230
-
2231
- // ============================================================================
2232
- // Channels (agent/channels/*.ts)
2233
- // ============================================================================
2234
-
2235
- export type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2236
-
2237
- export interface ChannelHandlerArgs {
2238
- /** Route parameters extracted from the path pattern. */
2239
- params: Record<string, string>;
2240
- requestIp: string | null;
2241
- /** Auth context resolved by the channel's auth chain. */
2242
- auth: AuthContext | null;
2243
- /**
2244
- * Validated JSON body when the route declares `bodySchema` (Zod).
2245
- * Prefer this over `request.json()` so the body is not read twice.
2246
- */
2247
- body?: unknown;
2248
- /**
2249
- * Validated query object when the route declares `querySchema` (Zod).
2250
- * Built from `URLSearchParams` (string values) before validation.
2251
- */
2252
- query?: unknown;
2253
- /** Shared host services (MCP / GitHub / Slack). Same as tool `ctx.host`. */
2254
- host: HostContext;
2255
- /** Start or resume a session on this channel. */
2256
- send: SendMessageFn;
2257
- /** Look up an existing session on this channel. */
2258
- getSession(sessionId: string): Promise<ChannelSession | null>;
2259
- /** Hand inbound work to a different channel (cross-channel hand-off). */
2260
- receive(
2261
- channel: ChannelDefinition | HttpChannelDefinition | string,
2262
- input: ReceiveInput,
2263
- ): Promise<ChannelSession>;
2264
- /** Call an authored server tool directly (no model turn). */
2265
- callTool: CallToolFn;
2266
- /** Extend server lifetime tracking for background work. */
2267
- waitUntil(promise: Promise<unknown>): void;
2268
- /**
2269
- * Absolute playground + NDJSON trace URLs for a session on this agent
2270
- * mount (single-agent `""` or multi-agent `"/<slug>"`). Prefer this over
2271
- * rebuilding paths from the request URL.
2272
- */
2273
- sessionUrls(request: Request, sessionId: string): { playgroundUrl: string; traceUrl: string };
2274
- /**
2275
- * Durable artifacts (unbound — channel handlers have no ambient session;
2276
- * pass `sessionId` in `tag` input to attribute one).
2277
- */
2278
- artifacts: ArtifactsApi;
2279
- /** Hosted Slack admission uses this to paint a warm follow-up. */
2280
- hasContinuationSession?(continuationToken: string): Promise<boolean>;
2281
- isContinuationBusy?(continuationToken: string): Promise<boolean>;
2282
- getContinuationLastBotMessageTs?(continuationToken: string): Promise<string | undefined>;
2283
- interruptContinuation?(continuationToken: string): Promise<boolean>;
2284
- }
2285
-
2286
- export type ChannelRouteHandler = (
2287
- request: Request,
2288
- args: ChannelHandlerArgs,
2289
- ) => Response | Promise<Response>;
2290
-
2291
- /**
2292
- * Channel HTTP routes must declare a Zod schema (plain JSON Schema objects
2293
- * are not accepted — TypeScript will reject them).
2294
- */
2295
- export type ChannelRouteSchema = z.ZodTypeAny;
2296
-
2297
- /** Handler args with a required, schema-inferred `query`. */
2298
- export type ChannelHandlerArgsWithQuery<TQuery> = ChannelHandlerArgs & {
2299
- query: TQuery;
2300
- };
2301
-
2302
- /** Handler args with a required, schema-inferred `body`. */
2303
- export type ChannelHandlerArgsWithBody<TBody> = ChannelHandlerArgs & {
2304
- body: TBody;
2305
- };
2306
-
2307
- /** Handler args with inferred `body` and optional inferred `query`. */
2308
- export type ChannelHandlerArgsWithBodyAndQuery<TBody, TQuery> = ChannelHandlerArgs & {
2309
- body: TBody;
2310
- query: TQuery;
2311
- };
2312
-
2313
- /**
2314
- * GET routes must declare a Zod `querySchema` (use `z.object({})` when there
2315
- * are no query params — path params still live on `args.params`).
2316
- */
2317
- export interface ChannelGetRouteSpec<TQuery extends z.ZodTypeAny = z.ZodTypeAny> {
2318
- description?: string;
2319
- querySchema: TQuery;
2320
- handler: (
2321
- request: Request,
2322
- args: ChannelHandlerArgsWithQuery<z.infer<TQuery>>,
2323
- ) => Response | Promise<Response>;
2324
- }
2325
-
2326
- /**
2327
- * POST / PUT / PATCH routes must declare a Zod `bodySchema`. Optional
2328
- * `querySchema` when the route also reads search params.
2329
- */
2330
- export interface ChannelBodyRouteSpec<
2331
- TBody extends z.ZodTypeAny = z.ZodTypeAny,
2332
- TQuery extends z.ZodTypeAny | undefined = undefined,
2333
- > {
2334
- description?: string;
2335
- bodySchema: TBody;
2336
- querySchema?: TQuery;
2337
- handler: (
2338
- request: Request,
2339
- args: TQuery extends z.ZodTypeAny
2340
- ? ChannelHandlerArgsWithBodyAndQuery<z.infer<TBody>, z.infer<TQuery>>
2341
- : ChannelHandlerArgsWithBody<z.infer<TBody>>,
2342
- ) => Response | Promise<Response>;
2343
- }
2344
-
2345
- /**
2346
- * DELETE routes may declare Zod schemas when useful; neither is required.
2347
- */
2348
- export interface ChannelDeleteRouteSpec<
2349
- TBody extends z.ZodTypeAny | undefined = undefined,
2350
- TQuery extends z.ZodTypeAny | undefined = undefined,
2351
- > {
2352
- description?: string;
2353
- bodySchema?: TBody;
2354
- querySchema?: TQuery;
2355
- handler: ChannelRouteHandler;
2356
- }
2357
-
2358
- export interface ChannelRoute {
2359
- method: RouteMethod;
2360
- path: string;
2361
- handler: ChannelRouteHandler;
2362
- description?: string;
2363
- bodySchema?: ChannelRouteSchema;
2364
- querySchema?: ChannelRouteSchema;
2365
- }
2366
-
2367
- /** Input to a channel's `receive` hook (and to `args.receive(...)`). */
2368
- export interface ReceiveInput {
2369
- message: string;
2370
- auth: AuthContext | null;
2371
- /** Channel-specific delivery target (e.g. a chat channel id). */
2372
- target?: JsonObject;
2373
- }
2374
-
2375
- /**
2376
- * Per-event channel context. `state` is mutable. Turn events receive the
2377
- * state snapshot captured for that turn; handler mutations are recursively
2378
- * merged into the latest persisted state so fields refreshed by overlapping
2379
- * deliveries survive. At paths changed by the handler, objects merge
2380
- * recursively, arrays and scalars replace the latest value, and deletion
2381
- * removes the latest value. Events outside a turn receive current live state.
2382
- */
2383
- export interface ChannelEventContext<TState = JsonValue> {
2384
- channelId: string;
2385
- state: TState;
2386
- continuationToken: string | null;
2387
- setContinuationToken(token: string | null): Promise<void>;
2388
- }
2389
-
2390
- /** Per-event session context shared by channel `events` handlers and hooks. */
2391
- export interface SessionContext {
2392
- session: SessionInfo;
2393
- /**
2394
- * Shared host services (MCP / GitHub / Slack / kv / files). Same as
2395
- * tool `ctx.host`. `files` and `otel` are bound to this session, so a
2396
- * relative path cannot read another session's files.
2397
- */
2398
- host: HostContext;
2399
- /**
2400
- * Durable artifacts bound to this event's session and turn. `tag`
2401
- * auto-fills both ids and rejects a conflicting explicit `sessionId`.
2402
- */
2403
- artifacts: ArtifactsApi;
2404
- }
2405
-
2406
- export type ChannelEventHandler<TState = JsonValue, TEvent extends SessionEvent = SessionEvent> = (
2407
- event: TEvent,
2408
- channel: ChannelEventContext<TState>,
2409
- ctx: SessionContext,
2410
- ) => void | Promise<void>;
2411
-
2412
- /** Handlers are keyed by event type and receive the narrowed event. */
2413
- export type ChannelEventHandlers<TState = JsonValue> = {
2414
- [K in SessionEventType]?: ChannelEventHandler<TState, Extract<SessionEvent, { type: K }>>;
2415
- } & {
2416
- "*"?: ChannelEventHandler<TState, SessionEvent>;
2417
- };
2418
-
2419
- /** Bound helpers passed to {@link ChannelConfig.onStart}. */
2420
- export interface ChannelStartArgs {
2421
- send: SendMessageFn;
2422
- /**
2423
- * Hosted architecture from {@link AgentConfig.architecture}. Discovery
2424
- * fills `"v2"` when the author omits it. Host pipelines that call
2425
- * `send()` themselves (instead of letting the channel adapter stamp
2426
- * continuation) branch on this so v1 `continuationToken` and v2 `claim`
2427
- * stay mutually exclusive.
2428
- */
2429
- architecture?: AgentArchitecture;
2430
- getSession(sessionId: string): Promise<ChannelSession | null>;
2431
- receive(
2432
- channel: ChannelDefinition | HttpChannelDefinition | string,
2433
- input: ReceiveInput,
2434
- ): Promise<ChannelSession>;
2435
- /** Call an authored server tool directly (no model turn). */
2436
- callTool: CallToolFn;
2437
- /**
2438
- * Append an assistant message to a session without a model turn and without
2439
- * a user `message.received` bubble. Prefer this over `send()` when a host
2440
- * task already produced the final text (e.g. after staged `callTool`s).
2441
- */
2442
- emitAssistantMessage(sessionId: string, text: string): Promise<void>;
2443
- /** Shared host services (MCP / GitHub / Slack). Same as {@link ChannelHandlerArgs.host}. */
2444
- host: HostContext;
2445
- waitUntil(promise: Promise<unknown>): void;
2446
- /**
2447
- * Whether a live session already exists for a continuation token on this
2448
- * channel (includes lazy restore from storage).
2449
- */
2450
- hasContinuationSession(continuationToken: string): Promise<boolean>;
2451
- /**
2452
- * Whether a model turn is in flight (or being admitted) for the session
2453
- * addressed by this continuation token.
2454
- */
2455
- isContinuationBusy(continuationToken: string): Promise<boolean>;
2456
- /**
2457
- * Slack warm-delta watermark: last agent reply ts recorded on the session's
2458
- * channel state (`lastBotMessageTs`), when present.
2459
- */
2460
- getContinuationLastBotMessageTs(continuationToken: string): Promise<string | undefined>;
2461
- /**
2462
- * Interrupt the in-flight turn for a continuation token and clear any
2463
- * coalesced follow-ups queued behind it. Returns whether work was active.
2464
- */
2465
- interruptContinuation(continuationToken: string): Promise<boolean>;
2466
- /**
2467
- * Approve or deny a parked {@link ToolConfig.needsApproval} tool call
2468
- * for a session on this channel. Channel packs (e.g. Slack Block Kit
2469
- * buttons) use this to unblock the turn without going through the HTTP
2470
- * approvals route.
2471
- */
2472
- resolveApproval(
2473
- sessionId: string,
2474
- callId: string,
2475
- decision: ApprovalDecision,
2476
- auth: AuthContext | null,
2477
- options?: { asSessionOwner?: boolean },
2478
- ): Promise<PendingApproval>;
2479
- /**
2480
- * Mark a parked MCP auth as connected or cancelled. Channel packs
2481
- * (Slack "Connected") use this; the public OAuth callback also
2482
- * resolves after `finishAuth`.
2483
- */
2484
- resolveAuth(
2485
- sessionId: string,
2486
- callId: string,
2487
- decision: ApprovalDecision,
2488
- auth: AuthContext | null,
2489
- options?: { asSessionOwner?: boolean },
2490
- ): Promise<PendingAuth>;
2491
- /**
2492
- * Server log sink (same as {@link ServeOptions.logger}). Channel packs
2493
- * should prefer this over `console.*` so CLI/eval hosts can redirect.
2494
- */
2495
- logger: (line: string) => void;
2496
- /**
2497
- * Durable artifacts (unbound, same facade as
2498
- * {@link ChannelHandlerArgs.artifacts}) — for host pipelines the channel
2499
- * drives outside any route handler.
2500
- */
2501
- artifacts: ArtifactsApi;
2502
- }
2503
-
2504
- /**
2505
- * Metadata a channel pack attaches for discovery, `projectInfo`, and CLI
2506
- * helpers (e.g. `agent-sdk github forward`). Most fields are descriptive;
2507
- * explicitly documented protocol fields may also be consumed by the host.
2508
- */
2509
- export interface ChannelMeta {
2510
- /** Well-known pack kind, e.g. `"github"` or `"slack"`. */
2511
- kind?: string;
2512
- /**
2513
- * For GitHub webhook packs: the webhook event names this channel is wired
2514
- * to dispatch on. Used to derive `gh webhook forward --events`.
2515
- */
2516
- githubWebhookEvents?: readonly string[];
2517
- /**
2518
- * For Origin webhook packs: the Origin event types this channel is wired
2519
- * to dispatch on. Used by `--cursor-events` to subscribe `provider: "origin"`.
2520
- */
2521
- originWebhookEvents?: readonly string[];
2522
- /**
2523
- * For GitLab webhook packs: the `object_kind`s this channel is wired to
2524
- * dispatch on (`merge_request`, `note`, `push`, `pipeline`, `tag_push`).
2525
- */
2526
- gitlabWebhookEvents?: readonly string[];
2527
- /**
2528
- * For Bitbucket webhook packs: the event keys this channel is wired to
2529
- * dispatch on, in the Cloud vocabulary (`pullrequest:created`, …).
2530
- */
2531
- bitbucketWebhookEvents?: readonly string[];
2532
- /**
2533
- * For deployments packs: the factory event types this channel is wired
2534
- * to dispatch on. Extracted into the deploy manifest as `eventTypes`.
2535
- */
2536
- deploymentEventTypes?: readonly string[];
2537
- /**
2538
- * For Change Monitor checkpoint and Factory issue packs: the factory
2539
- * event types this channel is wired to dispatch on. Extracted into the
2540
- * deploy manifest as `eventTypes`. Kept separate from
2541
- * `deploymentEventTypes`.
2542
- */
2543
- factoryEventTypes?: readonly string[];
2544
- /**
2545
- * For Slack packs: the Events API event types this channel dispatches on
2546
- * (`app_mention`, `message`), derived from `engagement`. Extracted into
2547
- * the deploy manifest as `eventTypes` so hosted v2 fanout subscribes to
2548
- * exactly these. Local Socket Mode ignores it (the socket delivers
2549
- * whatever the app manifest subscribed to).
2550
- */
2551
- slackEventTypes?: readonly string[];
2552
- /**
2553
- * Static agentic-reply protocol for hosted Slack ingress. Only literals
2554
- * belong here: the control plane persists this declaration at deploy time
2555
- * and may act before author code starts.
2556
- */
2557
- slackReply?: {
2558
- mode: "agentic";
2559
- ack: string;
2560
- placeholder?: string;
2561
- };
2562
- /**
2563
- * For Slack packs with the opt-in channel watch: the allowlisted channels
2564
- * (ids or `#names`) this channel dispatches on without a mention. Surfaced
2565
- * by `info` so watched channels are auditable.
2566
- */
2567
- slackChannelPosts?: readonly string[];
2568
- /**
2569
- * Author-facing notices about deprecated options the pack still honored.
2570
- * Discovery surfaces each one as a `validate` warning on the channel file.
2571
- */
2572
- deprecations?: readonly string[];
2573
- }
2574
-
2575
- export interface ChannelConfig<TState = JsonValue> {
2576
- /**
2577
- * Route auth chain. Defaults to `[localDevStrict()]`. Include
2578
- * `publicEndpoint()` to serve this channel WITHOUT the platform alias
2579
- * token on Cursor hosting (for webhook senders that cannot attach custom
2580
- * headers — the handler must verify deliveries itself).
2581
- */
2582
- auth?: AuthPolicy[];
2583
- routes?: ChannelRoute[];
2584
- /**
2585
- * Descriptive metadata for tooling (kind, webhook events). Attached by
2586
- * channel packs; ignored by the router and session engine.
2587
- */
2588
- meta?: ChannelMeta;
2589
- /** Initial per-session channel state (JSON-serializable). */
2590
- state?: TState;
2591
- /**
2592
- * Owns inbound cross-channel hand-offs. When omitted, `receive` starts a
2593
- * fresh session with the input message.
2594
- */
2595
- receive?: (
2596
- input: ReceiveInput,
2597
- args: { send: SendMessageFn; artifacts: ArtifactsApi },
2598
- // biome-ignore lint/suspicious/noConfusingVoidType: hooks may return a session, nothing, or an async nothing
2599
- ) => Promise<ChannelSession | undefined | void> | ChannelSession | void;
2600
- /** Stream-event handlers for sessions owned by this channel. */
2601
- events?: ChannelEventHandlers<TState>;
2602
- /** Called once when the server mounts this channel. Optional stop via onStop. */
2603
- onStart?: (args: ChannelStartArgs) => void | Promise<void>;
2604
- /** Called when the server shuts down. */
2605
- onStop?: () => void | Promise<void>;
2606
- }
2607
-
2608
- export type ChannelDefinition<TState = JsonValue> = ChannelConfig<TState> &
2609
- BrandedDefinition<"channel">;
2610
-
2611
- /** Configuration for the built-in HTTP session channel. */
2612
- export interface HttpChannelConfig {
2613
- /** Route auth chain. Defaults to `[localDevStrict()]`. */
2614
- auth?: AuthPolicy[];
2615
- /**
2616
- * Continuation selector. Omit this to inherit the agent architecture's
2617
- * default. Set it explicitly only when migrating persisted identities.
2618
- */
2619
- continuation?: ContinuationIdentity;
2620
- /**
2621
- * Transform the inbound message before the agent sees it (e.g. prepend
2622
- * request-specific context).
2623
- */
2624
- onMessage?: (message: string, info: { auth: AuthContext | null }) => string | Promise<string>;
2625
- /**
2626
- * Bind host state after the control plane names this session's mailbox
2627
- * key and before `send()`.
2628
- */
2629
- onAdmit?: (info: HttpSessionAdmitInfo) => void | Promise<void>;
2630
- /** Stream-event handlers for sessions created over HTTP. */
2631
- events?: ChannelEventHandlers;
2632
- }
2633
-
2634
- /** Subject of a hosted HTTP startSession, seen by {@link HttpChannelConfig.onAdmit}. */
2635
- export type HttpSessionAdmitInfo = {
2636
- message: string;
2637
- sessionKey: string;
2638
- dryRun?: boolean;
2639
- asOf?: string;
2640
- host: HostContext;
2641
- };
2642
-
2643
- /** Reject a hosted startSession subject from {@link HttpChannelConfig.onAdmit}. */
2644
- export class HttpSessionAdmitError extends Error {
2645
- readonly status = 400 as const;
2646
- constructor(message: string) {
2647
- super(message);
2648
- this.name = "HttpSessionAdmitError";
2649
- }
2650
- }
2651
-
2652
- export type HttpChannelDefinition = HttpChannelConfig & BrandedDefinition<"http-channel">;
2653
-
2654
- // ============================================================================
2655
- // Hooks (agent/hooks/*.ts)
2656
- // ============================================================================
2657
-
2658
- export interface HookContext extends SessionContext {
2659
- agent: { name: string };
2660
- channel: { id: string; continuationToken: string | null };
2661
- /**
2662
- * Durable channel state for this session (the turn snapshot when
2663
- * dispatching inside a turn). Same blob `send({ state })` stamped;
2664
- * survives process restart. Null when the session has none.
2665
- */
2666
- channelState: JsonValue | null;
2667
- /**
2668
- * Absolute path of the agent's durable state root (shared across every
2669
- * session of this agent). Hooks that maintain derived state (e.g. the
2670
- * memory journal) write here.
2671
- */
2672
- stateRoot: string;
2673
- /**
2674
- * Durable artifacts, bound to this hook's session: `tag` auto-fills
2675
- * `sessionId` (and `turnId` when known).
2676
- */
2677
- artifacts: ArtifactsApi;
2678
- }
2679
-
2680
- export type HookHandler<TEvent extends SessionEvent = SessionEvent> = (
2681
- event: TEvent,
2682
- ctx: HookContext,
2683
- ) => void | Promise<void>;
2684
-
2685
- /** Handlers are keyed by event type and receive the narrowed event. */
2686
- export type HookEventHandlers = {
2687
- [K in SessionEventType]?: HookHandler<Extract<SessionEvent, { type: K }>>;
2688
- } & {
2689
- "*"?: HookHandler;
2690
- };
2691
-
2692
- export interface HookConfig {
2693
- events: HookEventHandlers;
2694
- }
2695
-
2696
- export type HookDefinition = HookConfig & BrandedDefinition<"hook">;
2697
-
2698
- // ============================================================================
2699
- // Artifacts (agent/artifacts.ts)
2700
- // ============================================================================
2701
-
2702
- /** One declared artifact kind (see {@link ArtifactsConfig.kinds}). */
2703
- export interface ArtifactKindConfig {
2704
- /**
2705
- * What this kind holds. Also the model-facing prompt for the
2706
- * `tag_artifact` built-in tool when {@link ArtifactsConfig.agentTool}
2707
- * is enabled.
2708
- */
2709
- description: string;
2710
- /**
2711
- * Optional Zod schema; `tag` validates the payload against it and
2712
- * persists the parsed output (defaults and coercions applied), so
2713
- * the schema's output must stay JSON-serializable.
2714
- */
2715
- schema?: z.ZodType;
2716
- }
2717
-
2718
- /** Input to `defineArtifacts` (authored at `agent/artifacts.ts`). */
2719
- export interface ArtifactsConfig {
2720
- /**
2721
- * Declared artifact kinds. With kinds declared, `tag` only accepts
2722
- * these; with none, any kind string is accepted freeform.
2723
- */
2724
- kinds?: Record<string, ArtifactKindConfig>;
2725
- /**
2726
- * Expose the model-facing `tag_artifact` built-in tool generated from
2727
- * {@link kinds}. Requires at least one declared kind.
2728
- */
2729
- agentTool?: boolean;
2730
- /**
2731
- * Retention cap (default 1000). Architecture v1 and self-hosted v2
2732
- * evict the oldest-updated artifact on insert past the cap. Hosted
2733
- * architecture v2 does not evict; the installation store keeps every row.
2734
- */
2735
- max?: number;
2736
- }
2737
-
2738
- export type ArtifactsDefinition = ArtifactsConfig & BrandedDefinition<"artifacts">;
2739
-
2740
- /** Who tagged an artifact: host code, or the model via `tag_artifact`. */
2741
- export type ArtifactSource = "host" | "model";
2742
-
2743
- /** One durable tagged artifact. */
2744
- export interface ArtifactRecord {
2745
- /** Stable id: derived from {@link key} when present, else random. */
2746
- id: string;
2747
- kind: string;
2748
- /** Author-chosen upsert key (same key ⇒ same id ⇒ replaces the row). */
2749
- key?: string;
2750
- title?: string;
2751
- data: JsonValue;
2752
- /** Present when the artifact carries a file/blob payload (served at `GET /v1/artifacts/:id/content`). */
2753
- content?: { size: number; contentType?: string };
2754
- sessionId?: string;
2755
- turnId?: string;
2756
- source: ArtifactSource;
2757
- createdAt: string;
2758
- updatedAt: string;
2759
- }
2760
-
2761
- /** Input to {@link ArtifactsApi.tag}. */
2762
- export interface ArtifactTagInput {
2763
- /** Defaults to `"artifact"` when no kinds are declared. */
2764
- kind?: string;
2765
- data: JsonValue;
2766
- title?: string;
2767
- /** Upsert key: tagging the same key again replaces the row. */
2768
- key?: string;
2769
- /**
2770
- * File/blob payload, served via `GET /v1/artifacts/:id/content`.
2771
- * Re-tagging a keyed artifact without `contents` keeps the existing payload.
2772
- */
2773
- contents?: string | Uint8Array;
2774
- /** MIME type reported when serving {@link contents}. */
2775
- contentType?: string;
2776
- /**
2777
- * Session to attribute (and stream an `artifact.tagged` event to). On
2778
- * session-bound facades ({@link ToolContext.artifacts},
2779
- * {@link HookContext.artifacts}) this is auto-filled and a different
2780
- * value is rejected; unbound facades
2781
- * ({@link ChannelHandlerArgs.artifacts}) accept it explicitly.
2782
- */
2783
- sessionId?: string;
2784
- turnId?: string;
2785
- /** Defaults to `"host"`. */
2786
- source?: ArtifactSource;
2787
- }
2788
-
2789
- /** Filter for {@link ArtifactsApi.list} and {@link ArtifactsApi.page}. */
2790
- export interface ArtifactListFilter {
2791
- kind?: string;
2792
- sessionId?: string;
2793
- }
2794
-
2795
- /** Options for {@link ArtifactsApi.page}. */
2796
- export interface ArtifactPageOptions extends ArtifactListFilter {
2797
- /** Page size, clamped to 1–1000. Default 200. */
2798
- limit?: number;
2799
- /**
2800
- * Opaque resume position from the previous page's
2801
- * {@link ArtifactPage.nextCursor}. Pass the same filter on every page of
2802
- * one walk; the cursor marks a position, not a query.
2803
- */
2804
- cursor?: string;
2805
- }
2806
-
2807
- /** One page of {@link ArtifactsApi.page} results, newest-updated first. */
2808
- export interface ArtifactPage {
2809
- records: ArtifactRecord[];
2810
- /**
2811
- * Present while rows remain to examine; pass back as
2812
- * {@link ArtifactPageOptions.cursor}. Each call reads a bounded number of
2813
- * rows, so with a sparse filter a page can carry fewer records than
2814
- * `limit` — even none — while `nextCursor` says the walk is not done.
2815
- */
2816
- nextCursor?: string;
2817
- }
2818
-
2819
- /**
2820
- * The artifacts API, attached as `ctx.artifacts` on tools
2821
- * ({@link ToolContext}), hooks ({@link HookContext}), and channel handlers
2822
- * ({@link ChannelHandlerArgs}). Tool and hook facades are session-bound:
2823
- * `tag` auto-fills the session; the channel facade is unbound.
2824
- */
2825
- export interface ArtifactsApi {
2826
- /** Tag (upsert) one artifact. See {@link ArtifactTagInput}. */
2827
- tag(input: ArtifactTagInput): Promise<ArtifactRecord>;
2828
- /**
2829
- * Tagged artifacts, newest-updated first — the newest page only (at most
2830
- * 200 records). Walk the full set with {@link ArtifactsApi.page}.
2831
- */
2832
- list(filter?: ArtifactListFilter): Promise<ArtifactRecord[]>;
2833
- /** Bounded, cursor-paginated artifacts, newest-updated first. */
2834
- page(options?: ArtifactPageOptions): Promise<ArtifactPage>;
2835
- }
2836
-
2837
- // ============================================================================
2838
- // Schedules (agent/schedules/*)
2839
- // ============================================================================
2840
-
2841
- export interface ScheduleHandlerArgs {
2842
- /** Hand the scheduled work to a channel. */
2843
- receive: (
2844
- channel: ChannelDefinition | HttpChannelDefinition | string,
2845
- input: ReceiveInput,
2846
- ) => Promise<ChannelSession>;
2847
- /** Call an authored server tool directly (no model turn). */
2848
- callTool: CallToolFn;
2849
- /** Keep the dispatch alive past handler return. */
2850
- waitUntil(promise: Promise<unknown>): void;
2851
- /** Pre-built app principal for work the agent does on its own behalf. */
2852
- appAuth: AuthContext;
2853
- /** Shared host services (MCP / GitHub / Slack). Same as tool `ctx.host`. */
2854
- host: HostContext;
2855
- /**
2856
- * Durable artifacts (unbound — schedule handlers have no ambient session;
2857
- * pass `sessionId` explicitly to attribute).
2858
- */
2859
- artifacts: ArtifactsApi;
2860
- }
2861
-
2862
- export interface ScheduleConfig {
2863
- /** Standard 5-field cron expression, evaluated in UTC. */
2864
- cron: string;
2865
- /** Fire-and-forget prompt (task mode). Mutually exclusive with `run`. */
2866
- markdown?: string;
2867
- /** Handler form: full control over dispatch. */
2868
- run?: (args: ScheduleHandlerArgs) => void | Promise<void>;
2869
- }
2870
-
2871
- export type ScheduleDefinition = ScheduleConfig & BrandedDefinition<"schedule">;
2872
-
2873
- // ============================================================================
2874
- // Reminder handlers (agent/reminders/*) — named durable fire policies
2875
- // ============================================================================
2876
-
2877
- /**
2878
- * Authored at `agent/reminders/<name>.ts`. The registry name is the module
2879
- * stem. Pass the discovered definition to {@link ReminderCreateInput.handler}
2880
- * with serializable {@link ReminderCreateInput.args}; the engine persists the
2881
- * stem, not the function.
2882
- */
2883
- export interface ReminderHandlerConfig {
2884
- /**
2885
- * Invoked on every fire with {@link ReminderFireContext} (including the
2886
- * create-time {@link ReminderFireContext.args} blob).
2887
- */
2888
- run: (ctx: ReminderFireContext) => Promise<ReminderFireResult>;
2889
- }
2890
-
2891
- export type ReminderDefinition = ReminderHandlerConfig & BrandedDefinition<"reminder">;
2892
-
2893
- export interface DiscoveredReminder {
2894
- name: string;
2895
- definition: ReminderDefinition;
2896
- }
2897
-
2898
- // ============================================================================
2899
- // Reminders (runtime per-session wakes)
2900
- // ============================================================================
2901
-
2902
- export type ReminderBusyPolicy = "skipIfBusy" | "queueBehindTurn";
2903
-
2904
- /** Public reminder status. Internal claim state (`firing`) is not exposed. */
2905
- export type ReminderStatus = "armed" | "completed" | "cancelled" | "disarmed";
2906
-
2907
- export type ReminderScheduleKind = "every" | "cron" | "delay" | "at";
2908
-
2909
- export type ReminderFireResult =
2910
- | { action: "skip"; reschedule?: ReminderReschedule }
2911
- | { action: "delivered"; reschedule?: ReminderReschedule }
2912
- | { action: "stop" };
2913
-
2914
- export interface ReminderReschedule {
2915
- delay?: string | number;
2916
- at?: Date | string;
2917
- }
2918
-
2919
- export interface ReminderTarget {
2920
- channelId: string;
2921
- continuationToken: string;
2922
- [key: string]: unknown;
2923
- }
2924
-
2925
- export interface ReminderUntilContext {
2926
- id: string;
2927
- purpose: string;
2928
- fireCount: number;
2929
- target: ReminderTarget;
2930
- host: HostContext;
2931
- mcp: HostMcpRegistry;
2932
- }
2933
-
2934
- /**
2935
- * Send fields a reminder followup may carry onto the turn it starts, the
2936
- * subset of {@link SendMessageOptions} a host pipeline needs when the fire
2937
- * itself prepares the turn (channel state for a later host hook,
2938
- * a session title, a cloud-attach reset). Continuation addressing stays the
2939
- * reminder's stored binding and is not overridable here.
2940
- */
2941
- export interface ReminderFollowupOptions {
2942
- /** Initial channel state when the followup creates the session. */
2943
- state?: JsonValue;
2944
- /** Shallow-merged into an existing session's channel state (see {@link SendMessageOptions.refreshState}). */
2945
- refreshState?: JsonValue;
2946
- /** Session display title (applied when creating a new session). */
2947
- title?: string;
2948
- /** See {@link SendMessageOptions.clearCloudOverride}. */
2949
- clearCloudOverride?: boolean;
2950
- /**
2951
- * Open a new session under this principal when the stored continuation
2952
- * has none anywhere (pod or durable storage) — the session an inbound
2953
- * delivery on that key would create, so later deliveries under the same
2954
- * principal keep joining it. A durable session that exists but cannot be
2955
- * materialized still throws, matching prompt fires: opening over it would
2956
- * shadow the record. Omitted, a missing session also keeps the existing
2957
- * behavior: the followup throws.
2958
- */
2959
- openAuth?: AuthContext;
2960
- }
2961
-
2962
- export interface ReminderFireContext extends ReminderUntilContext {
2963
- appAuth: AuthContext;
2964
- /**
2965
- * Serializable args from {@link ReminderCreateInput.args} when the fire
2966
- * uses a named {@link ReminderCreateInput.handler}. Empty object otherwise.
2967
- */
2968
- args: JsonObject;
2969
- /**
2970
- * Wake the reminder's already-bound session (target is implicit). On a
2971
- * hosted architecture v2 deployment this resolves after the woken turn
2972
- * completes, because the pod may stop once the fire's outcome is applied;
2973
- * locally and on v1 it resolves as soon as the turn is admitted.
2974
- */
2975
- followup(args: { message: string } & ReminderFollowupOptions): Promise<ChannelSession>;
2976
- cancel(reason?: string): Promise<void>;
2977
- /**
2978
- * Durable artifacts (unbound — the reminder is bound to a continuation
2979
- * token, not a resolved session; pass `sessionId` in `tag` input to
2980
- * attribute one).
2981
- */
2982
- artifacts: ArtifactsApi;
2983
- }
2984
-
2985
- /**
2986
- * Create a durable wake bound to a channel continuation.
2987
- *
2988
- * Exactly one of `prompt` | `handler` | `run`, and exactly one of
2989
- * `every` | `cron` | `delay` | `at`. Prompt fires always follow up into the
2990
- * bound session. Named `handler` resolves `agent/reminders/<name>.ts` on
2991
- * every fire (survives restart). Anonymous `run` stays supported on local
2992
- * and hosted v1; hosted architecture v2 rejects it at create.
2993
- *
2994
- * @example Recurring (host policy)
2995
- * ```ts
2996
- * await host.reminders.create({
2997
- * purpose: "merge_conflict_watch",
2998
- * channelId: "drive",
2999
- * continuationToken,
3000
- * every: "30m",
3001
- * async run({ followup, host }) {
3002
- * if (await isPrClosed(host)) return { action: "stop" };
3003
- * if (!(await isConflicted(host))) return { action: "skip" };
3004
- * await followup({ message: "Merge conflict detected." });
3005
- * return { action: "delivered" };
3006
- * },
3007
- * });
3008
- * ```
3009
- *
3010
- * @example Named handler (durable across restart / hosted v2)
3011
- * ```ts
3012
- * // agent/reminders/verdict_recheck.ts
3013
- * export default defineReminder({
3014
- * async run({ args, followup }) {
3015
- * // ...
3016
- * return { action: "delivered" };
3017
- * },
3018
- * });
3019
- *
3020
- * import verdictRecheck from "./reminders/verdict_recheck.js";
3021
- *
3022
- * await host.reminders.create({
3023
- * purpose: "verdict_recheck",
3024
- * channelId: "origin",
3025
- * continuationToken,
3026
- * delay: "15m",
3027
- * handler: verdictRecheck,
3028
- * args: { headSha: "abc" },
3029
- * });
3030
- * ```
3031
- *
3032
- * @example One-shot (agent tool / prompt form)
3033
- * ```ts
3034
- * await host.reminders.create({
3035
- * purpose: "ci_recheck",
3036
- * channelId: "drive",
3037
- * continuationToken,
3038
- * delay: "2h",
3039
- * prompt: "Re-check CI. Only act if still failing.",
3040
- * until: "Cancel once CI is green or the PR is merged.",
3041
- * });
3042
- * ```
3043
- */
3044
- export interface ReminderCreateInput {
3045
- purpose: string;
3046
- /** Channel that owns the session (e.g. `drive`). */
3047
- channelId: string;
3048
- /** Channel-local continuation key for the bound session. */
3049
- continuationToken: string;
3050
- /** Optional opaque metadata (e.g. `{ prUrl }`). */
3051
- target?: Record<string, unknown>;
3052
- /** Exactly one of prompt, handler, or run. */
3053
- prompt?: string;
3054
- /**
3055
- * A definition discovered from `agent/reminders/<name>.ts`, or its stem
3056
- * for compatibility. Mutually exclusive with `prompt` and `run`. The
3057
- * definition form avoids coupling callers to a filename string; discovery
3058
- * resolves it to the stable stem persisted by the control plane. Do not
3059
- * combine with {@link until}; encode stop conditions in {@link args} and
3060
- * the handler body.
3061
- */
3062
- handler?: ReminderDefinition | string;
3063
- /**
3064
- * Serializable args for {@link handler} (UTF-8 JSON capped at 32 KiB).
3065
- * Only valid with `handler`.
3066
- */
3067
- args?: JsonObject;
3068
- run?: (ctx: ReminderFireContext) => Promise<ReminderFireResult>;
3069
- /** Exactly one schedule shape. */
3070
- every?: string;
3071
- cron?: string;
3072
- delay?: string | number;
3073
- at?: Date | string | number;
3074
- /**
3075
- * Auto-cancel: function (host evaluates, true → cancel) XOR prompt string
3076
- * (agent-facing stop condition; platform does not interpret it).
3077
- * Valid with `prompt` (string until) and legacy `run` (function until on
3078
- * local / hosted v1). Not valid with named `handler`. Function until is
3079
- * rejected on hosted architecture v2.
3080
- */
3081
- until?: string | ((ctx: ReminderUntilContext) => Promise<boolean>);
3082
- /**
3083
- * Defaults: recurring → `skipIfBusy`; one-shot → `queueBehindTurn`.
3084
- */
3085
- busyPolicy?: ReminderBusyPolicy;
3086
- }
3087
-
3088
- export interface ReminderInfo {
3089
- id: string;
3090
- purpose: string;
3091
- channelId: string;
3092
- continuationToken: string;
3093
- target?: Record<string, unknown>;
3094
- scheduleKind: ReminderScheduleKind;
3095
- scheduleValue: string;
3096
- prompt?: string;
3097
- /** Named handler stem when create used `handler`. */
3098
- handler?: string;
3099
- /** Serializable args when create used `handler`. */
3100
- args?: JsonObject;
3101
- untilPrompt?: string;
3102
- busyPolicy: ReminderBusyPolicy;
3103
- status: ReminderStatus;
3104
- disarmReason?: string;
3105
- fireCount: number;
3106
- nextFireAt: string;
3107
- createdAt: string;
3108
- updatedAt: string;
3109
- hasRunHandler: boolean;
3110
- hasUntilFn: boolean;
3111
- }
3112
-
3113
- /** Host-facing reminder API attached to {@link HostContext.reminders}. */
3114
- export interface ReminderHostApi {
3115
- /** Arm a reminder. See {@link ReminderCreateInput}. */
3116
- create(input: ReminderCreateInput): Promise<ReminderInfo>;
3117
- /** List reminders, optionally filtered. */
3118
- list(filter?: {
3119
- status?: ReminderStatus;
3120
- purpose?: string;
3121
- continuationToken?: string;
3122
- }): Promise<ReminderInfo[]>;
3123
- /** Cancel one reminder by id. No-op (returns undefined) if unknown. */
3124
- cancel(id: string, reason?: string): Promise<ReminderInfo | undefined>;
3125
- /** Cancel all armed reminders for a continuation token. Returns count. */
3126
- cancelForContinuation(continuationToken: string, reason: string): Promise<number>;
3127
- /**
3128
- * Re-key armed reminders after a channel rotates a session's continuation
3129
- * token, so earlier reminders keep waking the conversation. The engine
3130
- * calls this from `setContinuationToken`; channels rarely need to.
3131
- */
3132
- rekeyContinuation(channelId: string, oldToken: string, newToken: string): Promise<number>;
3133
- /**
3134
- * Fire immediately (dev / hillclimb).
3135
- * `outcome` is `"noop"` when already firing or not armed.
3136
- */
3137
- dispatch(id: string): Promise<{
3138
- reminderId: string;
3139
- outcome: "fired" | "noop";
3140
- reason?: string;
3141
- }>;
3142
- }
3143
-
3144
- // ============================================================================
3145
- // Discovery / manifest
3146
- // ============================================================================
3147
-
3148
- export interface Diagnostic {
3149
- severity: "error" | "warning";
3150
- /** Repo-relative or absolute path of the offending file. */
3151
- path?: string;
3152
- message: string;
3153
- }
3154
-
3155
- export interface DiscoveredTool {
3156
- name: string;
3157
- description: string;
3158
- /** JSON Schema advertised to the model. */
3159
- inputSchema: JsonSchemaObject;
3160
- /** Output JSON Schema, advertised only when the tool declares one. */
3161
- outputSchema?: JsonSchemaObject;
3162
- /** Where the tool body runs. Defaults to `"server"`. */
3163
- execution: ToolExecution;
3164
- /**
3165
- * True when the tool may park for human approval (boolean true or a
3166
- * predicate). Runtime evaluation still runs the predicate per call.
3167
- */
3168
- needsApproval: boolean;
3169
- /**
3170
- * The tool's declared {@link ToolEffect} when it declares one statically, or
3171
- * `"dynamic"` when it declares a predicate resolved per call. Absent when it
3172
- * declares nothing, which a dry run treats as a write.
3173
- */
3174
- effect?: ToolEffect | "dynamic";
3175
- /**
3176
- * MCP spec tool annotations, present only on advertised MCP passthroughs
3177
- * whose server declared them (see {@link HostMcpToolInfo.annotations}).
3178
- * Authored tools declare {@link effect} instead. Untrusted hints,
3179
- * propagated so the harness listing carries them and so effect
3180
- * classification can read them; absent is the fail-closed state.
3181
- */
3182
- annotations?: McpToolAnnotations;
3183
- /**
3184
- * True for a 1:1 MCP passthrough synthesized from an advertised
3185
- * connection's listing. The policy treats these differently from authored
3186
- * tools when nothing declares an effect: an undeclared authored tool is
3187
- * stubbed as a write in a dry run, an unclassifiable advertised tool is
3188
- * refused — see `decideToolCall`.
3189
- */
3190
- advertised?: true;
3191
- /** Name of the advertising connection an advertised tool came from. */
3192
- connection?: string;
3193
- /** Mounted extension this tool came from; absent for `agent/tools/`. */
3194
- extension?: string;
3195
- /**
3196
- * Agent tools: script body materialized under
3197
- * `.agent-serve/tools/<name>.sh`.
3198
- */
3199
- script?: string;
3200
- definition: ToolDefinition;
3201
- }
3202
-
3203
- /** A packaged-skill sibling file: inline contents or a file to copy. */
3204
- export type SkillFileSource = { contents: string } | { sourcePath: string };
3205
-
3206
- export interface DiscoveredSkill {
3207
- name: string;
3208
- description: string;
3209
- /** SKILL.md body (without generated frontmatter). */
3210
- markdown: string;
3211
- /** Package-relative sibling files. */
3212
- files: Record<string, SkillFileSource>;
3213
- /** Mounted extension this skill came from; absent for `agent/skills/`. */
3214
- extension?: string;
3215
- }
3216
-
3217
- export interface DiscoveredConnection {
3218
- name: string;
3219
- transport: ConnectionTransport;
3220
- description?: string;
3221
- /** Per-session auth from {@link ConnectionConfig.auth} (http/sse only). */
3222
- auth?: ConnectionAuthProvider;
3223
- /** Advertise-by-name from {@link ConnectionConfig.advertiseTools}. */
3224
- advertiseTools?: boolean;
3225
- /** Skip a listing failure instead of failing the turn. */
3226
- optional?: boolean;
3227
- /**
3228
- * Normalized intended effects from {@link ConnectionConfig.effects}.
3229
- * Absent means every listed tool is advertised.
3230
- */
3231
- effects?: readonly ToolEffect[];
3232
- /**
3233
- * Normalized tool-name allowlist from {@link ConnectionConfig.tools}.
3234
- * Absent means every listed tool is kept.
3235
- */
3236
- tools?: readonly string[];
3237
- /**
3238
- * Normalized tool-name denylist from
3239
- * {@link ConnectionConfig.disallowedTools}.
3240
- */
3241
- disallowedTools?: readonly string[];
3242
- }
3243
-
3244
- export interface DiscoveredChannel {
3245
- id: string;
3246
- definition: ChannelDefinition;
3247
- }
3248
-
3249
- export interface DiscoveredSchedule {
3250
- name: string;
3251
- cron: string;
3252
- kind: "markdown" | "run";
3253
- definition: ScheduleDefinition;
3254
- }
3255
-
3256
- export interface DiscoveredHook {
3257
- name: string;
3258
- definition: HookDefinition;
3259
- }
3260
-
3261
- export interface SeedFile {
3262
- /** Path inside the session workspace. */
3263
- relativePath: string;
3264
- /** Absolute path of the authored source file. */
3265
- sourcePath: string;
3266
- }
3267
-
3268
- /** A fully resolved agent (the root agent or a subagent). */
3269
- export interface ResolvedAgent {
3270
- name: string;
3271
- description?: string;
3272
- model?: ModelSetting;
3273
- /**
3274
- * Remaining models from {@link AgentConfig.fallbacks}, in order. The
3275
- * runner steps down this list when the primary model is rejected before
3276
- * the turn produces output (catalog refusal or capacity).
3277
- */
3278
- modelFallbacks?: readonly ModelSetting[];
3279
- /**
3280
- * Composed system prompt: identity preamble from {@link name}, then
3281
- * authored `instructions.md` / `.ts` / dir (or inline `agent.ts`).
3282
- */
3283
- instructions?: string;
3284
- /** Execution runtime. Root agents default to `"local"`. */
3285
- runtime: AgentRuntime;
3286
- /**
3287
- * Authored {@link AgentConfig.root}. The factory is persisted, not a
3288
- * serialized tree. A resumed session calls it again (or reuses the handle).
3289
- */
3290
- root?: FileSystem | ((ctx: RootContext) => FileSystem | Promise<FileSystem>);
3291
- /** Resolved {@link AgentConfig.cloud} for this agent. */
3292
- cloud?: AgentCloudOptions;
3293
- /**
3294
- * Resolved local harness options from {@link AgentConfig.local}
3295
- * (`cwd` is absolute — relative paths resolved against the project root).
3296
- */
3297
- local?: AgentLocalOptions;
3298
- /**
3299
- * Built-in harness tool allowlist from {@link AgentConfig.tools}, with
3300
- * the "mcp" transport grant injected. Named apart from {@link tools}
3301
- * (the authored `agent/tools/` list).
3302
- */
3303
- allowedTools?: ToolName[];
3304
- /** Managed-hosting declarations from {@link AgentConfig.hosting}. */
3305
- hosting?: AgentHostingOptions;
3306
- /** Validated turn admission limits from {@link AgentConfig.concurrency}. */
3307
- concurrency?: AgentConcurrencyOptions;
3308
- /**
3309
- * Validated architecture from {@link AgentConfig.architecture}.
3310
- * Omitted authors resolve to `"v2"`. `"v2"` deploys onto the v2
3311
- * control plane and stamps kind `/v2` continuation defaults onto
3312
- * channels that omitted a selector.
3313
- */
3314
- architecture?: AgentArchitecture;
3315
- persistent?: boolean;
3316
- tools: DiscoveredTool[];
3317
- skills: DiscoveredSkill[];
3318
- /**
3319
- * Mounted `agent/extensions/`. Their contributions are already merged
3320
- * into the agent and project lists; this records provenance.
3321
- */
3322
- extensions?: DiscoveredExtension[];
3323
- connections: DiscoveredConnection[];
3324
- /**
3325
- * MCP connections from `agent/host-connections/`. Host tools and
3326
- * `mcp oauth` see them; the model does not.
3327
- */
3328
- hostConnections?: DiscoveredConnection[];
3329
- subagents: ResolvedAgent[];
3330
- seedFiles: SeedFile[];
3331
- }
3332
-
3333
- /** The compiled project manifest produced by `loadAgentProject`. */
3334
- export interface AgentProject {
3335
- /** App root (the directory containing package.json / agent/). */
3336
- rootDir: string;
3337
- /** The authored agent directory. */
3338
- agentDir: string;
3339
- name: string;
3340
- agent: ResolvedAgent;
3341
- /** Built-in HTTP session channel. */
3342
- httpChannel: HttpChannelDefinition;
3343
- channels: DiscoveredChannel[];
3344
- schedules: DiscoveredSchedule[];
3345
- /** Named reminder handlers from `agent/reminders/*` (optional / additive). */
3346
- reminders?: DiscoveredReminder[];
3347
- hooks: DiscoveredHook[];
3348
- /** Optional `agent/storage.ts` (`defineStorage`). */
3349
- storage?: StorageDefinition;
3350
- /** Optional `agent/artifacts.ts` (`defineArtifacts`). */
3351
- artifacts?: ArtifactsDefinition;
3352
- /** Optional `agent/otel.ts` (`defineOtel`). */
3353
- otel?: OtelDefinition;
3354
- diagnostics: Diagnostic[];
3355
- }
3356
-
3357
- /** JSON-safe projection of one channel HTTP route on `GET /v1/info`. */
3358
- export interface AgentChannelRouteInfo {
3359
- method: RouteMethod;
3360
- /** Authored path (e.g. `"/findings"`), or the absolute path for built-in http. */
3361
- path: string;
3362
- /** Mount path including `/v1/channels/<id>` (or absolute for built-in http). */
3363
- url: string;
3364
- description?: string;
3365
- bodySchema?: JsonSchemaObject;
3366
- querySchema?: JsonSchemaObject;
3367
- }
3368
-
3369
- /** JSON-safe projection of the manifest returned by `GET /v1/info`. */
3370
- export interface AgentProjectInfo {
3371
- name: string;
3372
- /** Short agent description when authored on `defineAgent`. */
3373
- description?: string;
3374
- model?: ModelSetting;
3375
- runtime: AgentRuntime;
3376
- cloud?: AgentCloudPublicInfo;
3377
- /** Local harness options when authored (`cwd` absolute). */
3378
- local?: { cwd?: string };
3379
- /** Managed-hosting declarations when authored (egress allowlist, expected secrets, container image). */
3380
- hosting?: {
3381
- egressDomains?: string[];
3382
- secretNames?: string[];
3383
- image?: string;
3384
- };
3385
- /** Turn admission limits when authored (`concurrency` on `agent.ts`). */
3386
- concurrency?: { maxRunningTurns?: number };
3387
- /**
3388
- * The agent's own MCP surface (mounted at `<base>/v1/mcp`): other agents
3389
- * and MCP clients delegate to this agent through these tools.
3390
- */
3391
- mcp: { path: string; tools: string[] };
3392
- instructions?: { chars: number; preview: string };
3393
- tools: Array<{
3394
- name: string;
3395
- description: string;
3396
- execution: ToolExecution;
3397
- needsApproval: boolean;
3398
- /**
3399
- * The tool's declared {@link ToolEffect} when static, `"dynamic"` when
3400
- * declared as a predicate. Absent when the author declared nothing —
3401
- * "unknown", not "mutates".
3402
- */
3403
- effect?: ToolEffect | "dynamic";
3404
- inputSchema: JsonSchemaObject;
3405
- }>;
3406
- skills: Array<{ name: string; description: string }>;
3407
- /** Mounted extensions and the tool / skill names each contributed. */
3408
- extensions: DiscoveredExtension[];
3409
- connections: Array<{
3410
- name: string;
3411
- transport: string;
3412
- advertiseTools?: boolean;
3413
- optional?: boolean;
3414
- effects?: readonly ToolEffect[];
3415
- tools?: readonly string[];
3416
- disallowedTools?: readonly string[];
3417
- /**
3418
- * Present only for `cursorAccount` connections: the connector-name
3419
- * allowlist, or `"*"` for every connected server. Structured twin of the
3420
- * `cursor-account[:a,b]` transport label so consumers (e.g. the
3421
- * dashboard's connector scoping) never parse the display string.
3422
- */
3423
- cursorAccountServers?: string[] | "*";
3424
- }>;
3425
- subagents: Array<{
3426
- name: string;
3427
- description?: string;
3428
- model?: ModelSetting;
3429
- }>;
3430
- channels: Array<{
3431
- id: string;
3432
- routes: AgentChannelRouteInfo[];
3433
- /** Pack kind when the channel declares one (e.g. `"github"`). */
3434
- kind?: string;
3435
- /** GitHub webhook events the channel dispatches on, when declared. */
3436
- githubWebhookEvents?: readonly string[];
3437
- /** Origin webhook event types the channel dispatches on, when declared. */
3438
- originWebhookEvents?: readonly string[];
3439
- /** GitLab `object_kind`s the channel dispatches on, when declared. */
3440
- gitlabWebhookEvents?: readonly string[];
3441
- /** Bitbucket event keys (Cloud vocabulary) the channel dispatches on. */
3442
- bitbucketWebhookEvents?: readonly string[];
3443
- /** Factory deployment event types the channel dispatches on, when declared. */
3444
- deploymentEventTypes?: readonly string[];
3445
- /** Change Monitor checkpoint or Factory issue event types the channel dispatches on, when declared. */
3446
- factoryEventTypes?: readonly string[];
3447
- /** Slack Events API event types the channel dispatches on, when declared. */
3448
- slackEventTypes?: readonly string[];
3449
- /** Slack channels watched for posts (opt-in channel watch), when declared. */
3450
- slackChannelPosts?: readonly string[];
3451
- }>;
3452
- schedules: Array<{ name: string; cron: string; kind: "markdown" | "run" }>;
3453
- /** Named reminder handlers (`agent/reminders/<name>.ts`) when present. */
3454
- reminders?: Array<{ name: string }>;
3455
- hooks: string[];
3456
- /** Project storage sink from `agent/storage.ts`, when authored. */
3457
- storage?: { name?: string };
3458
- otel?: { serviceName?: string; enabled: true };
3459
- /** Declared artifact kinds from `agent/artifacts.ts`, when authored. */
3460
- artifacts?: { kinds: string[]; agentTool: boolean; max: number };
3461
- diagnostics: Diagnostic[];
3462
- }
3463
-
3464
- // ============================================================================
3465
- // Runner (the Cursor SDK seam)
3466
- // ============================================================================
3467
-
3468
- /**
3469
- * A streaming update from the harness, re-exported from the Cursor SDK's
3470
- * delta vocabulary.
3471
- */
3472
- export type RunnerUpdate = InteractionUpdate;
3473
-
3474
- export interface RunnerSubagent {
3475
- name: string;
3476
- description: string;
3477
- prompt: string;
3478
- model?: ModelSetting;
3479
- }
3480
-
3481
- export interface RunnerTurnRequest {
3482
- sessionId: string;
3483
- /**
3484
- * Cursor SDK agent id to create/resume. Defaults to {@link sessionId}
3485
- * for local agents; cloud agents use the persisted `bc-…` id after
3486
- * the first turn.
3487
- */
3488
- sdkAgentId?: string;
3489
- /** Absolute path of the session's materialized workspace. */
3490
- workspaceDir: string;
3491
- /** Resolved FileSystem handle when {@link AgentConfig.root} is set. */
3492
- root?: FileSystem;
3493
- /** Run the local harness sandboxed ({@link AgentLocalOptions.sandbox}). */
3494
- sandbox?: boolean;
3495
- /** Built-in tool allowlist ({@link AgentConfig.tools}, resolved). */
3496
- tools?: ToolName[];
3497
- /**
3498
- * Native tools hidden on the Cursor SDK agent because synthesized
3499
- * FileSystem tools own those names. Host-default omitted `tools` only.
3500
- */
3501
- disallowedTools?: ToolName[];
3502
- /** Absolute path for runner-owned durable state (conversation store). */
3503
- runnerStateDir: string;
3504
- prompt: string;
3505
- isFirstTurn: boolean;
3506
- /**
3507
- * Base64 images for this turn (Cursor SDK `SDKUserMessage.images`).
3508
- * Set from {@link SendMessageOptions.images} / Slack attachments.
3509
- */
3510
- images?: Array<{ data: string; mimeType: string }>;
3511
- model?: ModelSetting;
3512
- /**
3513
- * Models to open the turn on, in order, after {@link model} is rejected
3514
- * (catalog refusal or `resource_exhausted` / `[unavailable]`) and before
3515
- * any output was streamed.
3516
- */
3517
- modelFallbacks?: readonly ModelSetting[];
3518
- runtime: AgentRuntime;
3519
- /**
3520
- * The agent's display name. Grokbot turns address the caller's hosted
3521
- * Grok Bot agent of this name: every SDK session of one agent forwards
3522
- * into the same hosted agent and conversation.
3523
- */
3524
- agentName?: string;
3525
- /** Cloud attach options for this turn, when the engine attached. */
3526
- cloud?: AgentCloudOptions;
3527
- /**
3528
- * Composed instructions ({@link ResolvedAgent.instructions} plus identity
3529
- * and tool catalog) delivered as the harness system prompt.
3530
- */
3531
- instructions?: string;
3532
- /**
3533
- * defineAgent directory slug for personal-key cloud creates. Injected
3534
- * by the engine — not part of authored {@link AgentCloudOptions}.
3535
- */
3536
- agentServeAgent?: string;
3537
- /** In-process tools, already bound to the session's tool context. */
3538
- customTools: Record<string, SDKCustomTool>;
3539
- /** MCP servers from `agent/mcp-connections/`. */
3540
- mcpServers: Record<string, ConnectionTransport>;
3541
- /**
3542
- * Configure {@link mcpServers} on every send instead of once on the
3543
- * cached SDK agent handle. Set when an attached connection has
3544
- * per-session `auth`: its headers are re-evaluated at turn-build time,
3545
- * and a handle-pinned copy would keep the first turn's credentials until
3546
- * the handle recycles. The SDK builds the send's MCP session from exactly
3547
- * this set (fresh clients each turn — stdio servers respawn per turn),
3548
- * and the create/resume/prewarm options carry no `mcpServers` at all, so
3549
- * the local executor cache key stays stable while credentials rotate.
3550
- */
3551
- perSendMcpServers?: boolean;
3552
- subagents: RunnerSubagent[];
3553
- onUpdate: (update: RunnerUpdate) => void | Promise<void>;
3554
- /** Called once the SDK agent is open so the engine can persist its id. */
3555
- onSdkAgentId?: (sdkAgentId: string) => void | Promise<void>;
3556
- /**
3557
- * Called once the harness names the run, before it produces anything.
3558
- * Surfaces the request id while the turn is still running rather than at
3559
- * its end.
3560
- */
3561
- onRequestId?: (requestId: string) => void | Promise<void>;
3562
- /**
3563
- * Abort the in-flight run when signalled. The engine aborts this when a
3564
- * follow-up message preempts the current turn; the runner maps it to
3565
- * `run.cancel()`, which tears down execution and marks the SDK run terminal.
3566
- */
3567
- signal?: AbortSignal;
3568
- /**
3569
- * Expire any run still marked active on the SDK agent before starting this
3570
- * one (local runtime `force`). Set on follow-up turns so a preempted or
3571
- * crash-wedged run can never block the next send with "already has active
3572
- * run".
3573
- */
3574
- forceExpireActiveRun?: boolean;
3575
- }
3576
-
3577
- // ============================================================================
3578
- // Serving
3579
- // ============================================================================
3580
-
3581
- export interface ServeOptions {
3582
- /** Port to listen on. Defaults to 3000 (0 picks an ephemeral port). */
3583
- port?: number;
3584
- /** Host to bind. Defaults to 127.0.0.1. */
3585
- host?: string;
3586
- /**
3587
- * Dev mode: mounts `POST /v1/dev/schedules/:scheduleId` and
3588
- * `POST /v1/dev/reminders/:reminderId`, and disables the cron / reminder
3589
- * auto-fire runners (dispatch by hand while iterating).
3590
- */
3591
- dev?: boolean;
3592
- /** Durable state directory. Defaults to `<rootDir>/.agent-serve`. */
3593
- stateRoot?: string;
3594
- /**
3595
- * Cursor API key for the SDK runner and Cursor account MCP connections.
3596
- * When omitted, falls back to `CURSOR_API_KEY`, then
3597
- * `CURSOR_API_KEY_FILE` (hosted default `/run/cursor/secrets/CURSOR_API_KEY`
3598
- * when unset), then `CURSOR_SERVICE_ACCOUNT_KEY`, then the credential
3599
- * stored by `agent-sdk login`. A bind file wins over
3600
- * `CURSOR_SERVICE_ACCOUNT_KEY`.
3601
- */
3602
- apiKey?: string;
3603
- /** Run schedules on their cron cadence. Defaults to `!dev`. */
3604
- schedules?: boolean;
3605
- /**
3606
- * Arm reminder deadline timers automatically. Defaults to `!dev`
3607
- * (same as schedules). Prompt-form reminders still persist on the
3608
- * control plane in `--dev`; fire them via `POST /v1/dev/reminders/:id`
3609
- * or `handle.dispatchReminder`.
3610
- */
3611
- reminders?: boolean;
3612
- /**
3613
- * Serve the bundled web playground at `/playground` (chat, streaming,
3614
- * tool calls, sessions, schedule dispatch). Defaults to true; the API
3615
- * routes it drives keep their normal auth chain either way.
3616
- */
3617
- playground?: boolean;
3618
- /**
3619
- * Serve the built documentation site at `/docs` ("docs" is a reserved
3620
- * slug). Defaults to true. The site is auto-built when missing and the
3621
- * vitepress toolchain is present; published installs ship it prebuilt.
3622
- */
3623
- docs?: boolean;
3624
- /**
3625
- * Replace the default `[localDevStrict()]` route auth with
3626
- * `[bearerAuth(authToken)]` on every channel that doesn't author its own
3627
- * auth chain. Use when exposing the server beyond loopback (e.g. through
3628
- * a tunnel, where every request arrives from 127.0.0.1 and loopback-only
3629
- * policies would admit everyone). Authored `auth` arrays still win.
3630
- */
3631
- authToken?: string;
3632
- /**
3633
- * Replace the default loopback-only route auth with `[allowAll()]` on every
3634
- * channel that doesn't author its own auth chain. For temporary demos behind
3635
- * a trusted network boundary (e.g. Tailscale) — do not combine with
3636
- * {@link authToken}. Authored `auth` arrays still win.
3637
- */
3638
- allowAnonymous?: boolean;
3639
- /**
3640
- * Allow {@link allowAnonymous} together with
3641
- * `githubChannel({ cursorAccount })`. Without this opt-in, `serve` refuses
3642
- * to start because every admitted anonymous caller could drive sessions
3643
- * that hold the signed-in account's repo-scoped GitHub credential. Set it
3644
- * only when the network boundary already authenticates callers (e.g. an
3645
- * SSO/Okta proxy in front of the host).
3646
- */
3647
- allowAnonymousCursorGithub?: boolean;
3648
- /**
3649
- * Allow `--allow-anonymous` together with a `runtime: "grokbot"` mount.
3650
- * Off by default: grokbot turns execute on the signed-in account's hosted
3651
- * Grok Bot computer, so an anonymous caller could drive Shell and other
3652
- * box tools there. Set it only when the network boundary already
3653
- * authenticates callers (e.g. an SSO/Okta proxy in front of the host).
3654
- */
3655
- allowAnonymousGrokbot?: boolean;
3656
- /**
3657
- * Allow {@link allowAnonymous} together with
3658
- * `defineConnection({ cursorAccount: true })`. Without this opt-in, `serve`
3659
- * refuses to start because every admitted anonymous caller could drive the
3660
- * signed-in account's MCP connectors. Set it only when the network boundary
3661
- * already authenticates callers (e.g. an SSO/Okta proxy, or the hosted
3662
- * agent-serve alias token).
3663
- */
3664
- allowAnonymousCursorAccountMcp?: boolean;
3665
- /**
3666
- * Public base URL where this server is reachable from outside the host
3667
- * (e.g. `https://agents.example.com`).
3668
- */
3669
- publicUrl?: string;
3670
- /**
3671
- * Hosting-injected HTTP MCP URL that proxies this deployment's
3672
- * `/v1/mcp/tools`. The resolved Cursor API key authenticates requests.
3673
- */
3674
- cloudToolsUrl?: string;
3675
- /**
3676
- * Pull SCM webhook events from `/v0/scm-events` (Cursor account auth).
3677
- * GitHub and Origin subscriptions are registered independently.
3678
- * The stream is read as the host's Cursor user, so this requires a signed-in
3679
- * host: `serve` throws when no key resolves from `apiKey` here,
3680
- * {@link ServeOptions.apiKey}, `CURSOR_API_KEY`, `CURSOR_API_KEY_FILE`
3681
- * (hosted default `/run/cursor/secrets/CURSOR_API_KEY` when unset),
3682
- * `CURSOR_SERVICE_ACCOUNT_KEY`, or `agent-sdk login`.
3683
- */
3684
- cursorEvents?: {
3685
- repos: string[];
3686
- baseUrl?: string;
3687
- apiKey?: string;
3688
- };
3689
- logger?: (line: string) => void;
3690
- /**
3691
- * OpenTelemetry export. Pass a config object, or `false` to force-disable
3692
- * even when `OTEL_EXPORTER_OTLP_*` env vars / `agent/otel.ts` are set.
3693
- * When omitted, env + authored `defineOtel` still enable export.
3694
- */
3695
- otel?: OtelConfig | false;
3696
- }
3697
-
3698
- /** One agent mounted on a server (its URL slug + compiled project). */
3699
- export interface MountedAgentInfo {
3700
- /**
3701
- * URL slug the agent is mounted under. Empty string in single-agent mode
3702
- * (routes at `/v1/...`); the directory name in multi-agent mode (routes at
3703
- * `/<slug>/v1/...`).
3704
- */
3705
- slug: string;
3706
- project: AgentProject;
3707
- /** Absolute base URL for this agent (server URL + `/<slug>` when slugged). */
3708
- url: string;
3709
- }
3710
-
3711
- export interface AgentServeHandle {
3712
- url: string;
3713
- port: number;
3714
- /**
3715
- * The single served agent's project. In multi-agent mode this is the first
3716
- * mounted agent; use {@link agents} for the full set.
3717
- */
3718
- project: AgentProject;
3719
- /** Every agent mounted on this server. One entry in single-agent mode. */
3720
- agents: MountedAgentInfo[];
3721
- /**
3722
- * Dispatch a schedule by name. In multi-agent mode pass the agent slug as
3723
- * the second argument to target a specific agent.
3724
- */
3725
- dispatchSchedule(name: string, slug?: string): Promise<{ sessionIds: string[] }>;
3726
- /**
3727
- * Create a per-session reminder. In multi-agent mode pass `slug` in options.
3728
- */
3729
- createReminder(input: ReminderCreateInput, slug?: string): Promise<ReminderInfo>;
3730
- /** List reminders for an agent. */
3731
- listReminders(
3732
- filter?: {
3733
- status?: ReminderStatus;
3734
- purpose?: string;
3735
- continuationToken?: string;
3736
- },
3737
- slug?: string,
3738
- ): Promise<ReminderInfo[]>;
3739
- /** Cancel a reminder by id. */
3740
- cancelReminder(
3741
- id: string,
3742
- options?: { reason?: string; slug?: string },
3743
- ): Promise<ReminderInfo | undefined>;
3744
- /**
3745
- * Fire a reminder immediately (same path as the deadline timer / dev route).
3746
- * `outcome` is `"noop"` when the reminder was already firing or not armed.
3747
- */
3748
- dispatchReminder(
3749
- id: string,
3750
- slug?: string,
3751
- ): Promise<{
3752
- reminderId: string;
3753
- outcome: "fired" | "noop";
3754
- reason?: string;
3755
- }>;
3756
- /**
3757
- * Call an authored server tool deterministically (no model turn). In
3758
- * multi-agent mode pass the agent slug in the options to target a
3759
- * specific agent.
3760
- */
3761
- callTool(
3762
- toolName: string,
3763
- input?: unknown,
3764
- options?: CallToolOptions & { slug?: string },
3765
- ): Promise<ToolCallOutcome>;
3766
- /**
3767
- * Vite HMR playground URL when `serve --dev` auto-started it (local
3768
- * checkout with the vite toolchain). Prefer this over the static
3769
- * `/playground` mount while iterating on the SPA. Multi-agent HMR serves
3770
- * the agents index at this URL and each SPA at `/<slug>/playground`.
3771
- */
3772
- playgroundDevUrl?: string;
3773
- /** Where the built documentation site is mounted (`<url>/docs`), when served. */
3774
- docsUrl?: string;
3775
- close(): Promise<void>;
3776
- }