@cursor/bdk 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (577) hide show
  1. package/dist/bin/agent-serve.js +9 -1
  2. package/dist/channels/slack/attachments.d.ts +2 -1
  3. package/dist/channels/slack/attachments.d.ts.map +1 -1
  4. package/dist/channels/slack/attachments.js +19 -9
  5. package/dist/channels/slack/dispatch.d.ts.map +1 -1
  6. package/dist/channels/slack/dispatch.js +26 -24
  7. package/dist/channels/slack/thread-context.d.ts +21 -11
  8. package/dist/channels/slack/thread-context.d.ts.map +1 -1
  9. package/dist/channels/slack/thread-context.js +75 -27
  10. package/dist/docs/404.html +2 -2
  11. package/dist/docs/assets/{app.BOIHhrKi.js → app.4kQ8Db_q.js} +4 -4
  12. package/dist/docs/assets/chunks/@localSearchIndexroot.CvuAJ0My.js +1 -0
  13. package/dist/docs/assets/chunks/{VPLocalSearchBox.D49zVZqM.js → VPLocalSearchBox.DY1RwB8Q.js} +1 -1
  14. package/dist/docs/assets/chunks/{arc.hmjb-sc4.js → arc.CxE_fSPK.js} +1 -1
  15. package/dist/docs/assets/chunks/{architectureDiagram-Q4EWVU46.CxEI1KqM.js → architectureDiagram-Q4EWVU46.CPX426ui.js} +1 -1
  16. package/dist/docs/assets/chunks/{baseUniq.DHHvBWoV.js → baseUniq.CB52JrKG.js} +1 -1
  17. package/dist/docs/assets/chunks/{blockDiagram-DXYQGD6D.DnXW-3bu.js → blockDiagram-DXYQGD6D.J0cNaQCL.js} +1 -1
  18. package/dist/docs/assets/chunks/{c4Diagram-AHTNJAMY.e-47O2jM.js → c4Diagram-AHTNJAMY.DJn3vEGT.js} +1 -1
  19. package/dist/docs/assets/chunks/channel.BoNycAoN.js +1 -0
  20. package/dist/docs/assets/chunks/{chunk-4BX2VUAB.3ry4pYXB.js → chunk-4BX2VUAB.Dao618F6.js} +1 -1
  21. package/dist/docs/assets/chunks/{chunk-4TB4RGXK.DGIZFRx6.js → chunk-4TB4RGXK.QW8Rhjai.js} +1 -1
  22. package/dist/docs/assets/chunks/{chunk-55IACEB6.DKBnqg9U.js → chunk-55IACEB6.DfRLLKF_.js} +1 -1
  23. package/dist/docs/assets/chunks/{chunk-EDXVE4YY.BIU8Ue5k.js → chunk-EDXVE4YY.CIV2ApKQ.js} +1 -1
  24. package/dist/docs/assets/chunks/{chunk-FMBD7UC4.DP-TFhjI.js → chunk-FMBD7UC4.BEheSuxp.js} +1 -1
  25. package/dist/docs/assets/chunks/{chunk-OYMX7WX6.Ux0OYj5v.js → chunk-OYMX7WX6.CUN88ENB.js} +1 -1
  26. package/dist/docs/assets/chunks/{chunk-QZHKN3VN.BzHMwYox.js → chunk-QZHKN3VN.CgqCs8b_.js} +1 -1
  27. package/dist/docs/assets/chunks/{chunk-YZCP3GAM.D4OGAsSP.js → chunk-YZCP3GAM.iCH0nnTJ.js} +1 -1
  28. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.C4x07Gkj.js +1 -0
  29. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.C4x07Gkj.js +1 -0
  30. package/dist/docs/assets/chunks/clone.Db22cH_-.js +1 -0
  31. package/dist/docs/assets/chunks/{cose-bilkent-S5V4N54A.Jq_7BUNx.js → cose-bilkent-S5V4N54A.BLcUxhWE.js} +1 -1
  32. package/dist/docs/assets/chunks/{dagre-KV5264BT.Di-skR2x.js → dagre-KV5264BT.Ep7LofOm.js} +1 -1
  33. package/dist/docs/assets/chunks/{diagram-5BDNPKRD.DeREHIdH.js → diagram-5BDNPKRD.Bzf4GSQ4.js} +1 -1
  34. package/dist/docs/assets/chunks/{diagram-G4DWMVQ6.C7Kcqxro.js → diagram-G4DWMVQ6.DD6Jh-eM.js} +1 -1
  35. package/dist/docs/assets/chunks/{diagram-MMDJMWI5.BK3eohyo.js → diagram-MMDJMWI5.oOIl8bWd.js} +1 -1
  36. package/dist/docs/assets/chunks/{diagram-TYMM5635.C6TyymXT.js → diagram-TYMM5635.DHs85Ade.js} +1 -1
  37. package/dist/docs/assets/chunks/{erDiagram-SMLLAGMA.DYGG-gGx.js → erDiagram-SMLLAGMA.BIb5ghCk.js} +1 -1
  38. package/dist/docs/assets/chunks/{flowDiagram-DWJPFMVM.C9nBcSV4.js → flowDiagram-DWJPFMVM.DV4paY9k.js} +1 -1
  39. package/dist/docs/assets/chunks/{ganttDiagram-T4ZO3ILL.wAg_ymsp.js → ganttDiagram-T4ZO3ILL.AyEKA6_v.js} +1 -1
  40. package/dist/docs/assets/chunks/{gitGraphDiagram-UUTBAWPF.B87j9Oeg.js → gitGraphDiagram-UUTBAWPF.BltiCDFo.js} +1 -1
  41. package/dist/docs/assets/chunks/{graph.CuFMj31w.js → graph.DzuEYGdC.js} +1 -1
  42. package/dist/docs/assets/chunks/{infoDiagram-42DDH7IO.P_mLGumP.js → infoDiagram-42DDH7IO.BV2l981J.js} +1 -1
  43. package/dist/docs/assets/chunks/{ishikawaDiagram-UXIWVN3A.DyuL_MsT.js → ishikawaDiagram-UXIWVN3A.BA4Izf-m.js} +1 -1
  44. package/dist/docs/assets/chunks/{journeyDiagram-VCZTEJTY.CtP09IoJ.js → journeyDiagram-VCZTEJTY.DjaFbFS3.js} +1 -1
  45. package/dist/docs/assets/chunks/{kanban-definition-6JOO6SKY.BoeSYPZo.js → kanban-definition-6JOO6SKY.CfTFieDs.js} +1 -1
  46. package/dist/docs/assets/chunks/{layout.B0lMMtNo.js → layout.DzfWqTBV.js} +1 -1
  47. package/dist/docs/assets/chunks/{linear.HxRBiAFX.js → linear.BO6mpulV.js} +1 -1
  48. package/dist/docs/assets/chunks/{min.BGlFFHwS.js → min.BGgTadgT.js} +1 -1
  49. package/dist/docs/assets/chunks/{mindmap-definition-QFDTVHPH.JyLBD9M8.js → mindmap-definition-QFDTVHPH.DPuIXVWY.js} +1 -1
  50. package/dist/docs/assets/chunks/{pieDiagram-DEJITSTG.DnSmNZF8.js → pieDiagram-DEJITSTG.BOnl3bBg.js} +1 -1
  51. package/dist/docs/assets/chunks/{quadrantDiagram-34T5L4WZ.CUCnbfCa.js → quadrantDiagram-34T5L4WZ.DNB6Ckdc.js} +1 -1
  52. package/dist/docs/assets/chunks/{requirementDiagram-MS252O5E.py0IVUn5.js → requirementDiagram-MS252O5E.D5-Qo7vb.js} +1 -1
  53. package/dist/docs/assets/chunks/{sankeyDiagram-XADWPNL6.Bkc-HWYp.js → sankeyDiagram-XADWPNL6.8t65cesf.js} +1 -1
  54. package/dist/docs/assets/chunks/{sequenceDiagram-FGHM5R23.Dqn8Mlv2.js → sequenceDiagram-FGHM5R23.CaG07BdS.js} +1 -1
  55. package/dist/docs/assets/chunks/{stateDiagram-FHFEXIEX.JikkoQUU.js → stateDiagram-FHFEXIEX.TKOweTB6.js} +1 -1
  56. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CuqmyQc4.js +1 -0
  57. package/dist/docs/assets/chunks/{theme.b6HQ6zG_.js → theme.Dx-JhpTB.js} +2 -2
  58. package/dist/docs/assets/chunks/{timeline-definition-GMOUNBTQ.BvpSXiBj.js → timeline-definition-GMOUNBTQ.fE53zQ2s.js} +1 -1
  59. package/dist/docs/assets/chunks/{vennDiagram-DHZGUBPP.CU7MVnZx.js → vennDiagram-DHZGUBPP.DJsZZaJg.js} +1 -1
  60. package/dist/docs/assets/chunks/{wardley-RL74JXVD.BKwC4ctG.js → wardley-RL74JXVD.844kyrjl.js} +1 -1
  61. package/dist/docs/assets/chunks/{wardleyDiagram-NUSXRM2D.BfaF6Uhe.js → wardleyDiagram-NUSXRM2D.CMZ-Ru_t.js} +1 -1
  62. package/dist/docs/assets/chunks/{xychartDiagram-5P7HB3ND.Bg5dcpj4.js → xychartDiagram-5P7HB3ND.XXrhBc7a.js} +1 -1
  63. package/dist/docs/assets/{deployment.md.BJ8i7Q6p.js → deployment.md.UhnJIMr-.js} +2 -2
  64. package/dist/docs/assets/{deployment.md.BJ8i7Q6p.lean.js → deployment.md.UhnJIMr-.lean.js} +1 -1
  65. package/dist/docs/assets/{guides_jev.md.BNDm14Gy.js → guides_jev.md.CRcgmjDb.js} +2 -2
  66. package/dist/docs/assets/{guides_jev.md.BNDm14Gy.lean.js → guides_jev.md.CRcgmjDb.lean.js} +1 -1
  67. package/dist/docs/assets/{reference_agent-config.md.DzGI777n.js → reference_agent-config.md.Cj5uBKp4.js} +1 -1
  68. package/dist/docs/assets/{reference_extensions.md.CPPrkWlJ.js → reference_extensions.md.pa2tN-e4.js} +4 -3
  69. package/dist/docs/assets/{reference_extensions.md.CPPrkWlJ.lean.js → reference_extensions.md.pa2tN-e4.lean.js} +1 -1
  70. package/dist/docs/building-with-agents.html +35 -35
  71. package/dist/docs/deployment.html +37 -37
  72. package/dist/docs/deployment.md +4 -1
  73. package/dist/docs/evals.html +35 -35
  74. package/dist/docs/guides/agent-to-agent.html +35 -35
  75. package/dist/docs/guides/bitbucket.html +35 -35
  76. package/dist/docs/guides/cloud-agents.html +35 -35
  77. package/dist/docs/guides/convert-automation.html +35 -35
  78. package/dist/docs/guides/github.html +35 -35
  79. package/dist/docs/guides/gitlab.html +35 -35
  80. package/dist/docs/guides/grokbot-agents.html +35 -35
  81. package/dist/docs/guides/hooks.html +35 -35
  82. package/dist/docs/guides/improve.html +35 -35
  83. package/dist/docs/guides/jev.html +37 -37
  84. package/dist/docs/guides/jev.md +7 -0
  85. package/dist/docs/guides/mcp-oauth.html +35 -35
  86. package/dist/docs/guides/opentelemetry.html +35 -35
  87. package/dist/docs/guides/slack.html +35 -35
  88. package/dist/docs/guides/webhooks.html +35 -35
  89. package/dist/docs/hashmap.json +1 -1
  90. package/dist/docs/hillclimbing.html +35 -35
  91. package/dist/docs/index.html +35 -35
  92. package/dist/docs/llms-full.txt +25 -2
  93. package/dist/docs/quickstart.html +35 -35
  94. package/dist/docs/reference/agent-config.html +37 -37
  95. package/dist/docs/reference/agent-config.md +1 -1
  96. package/dist/docs/reference/artifacts.html +35 -35
  97. package/dist/docs/reference/channels.html +35 -35
  98. package/dist/docs/reference/cli.html +35 -35
  99. package/dist/docs/reference/connections.html +35 -35
  100. package/dist/docs/reference/evals.html +35 -35
  101. package/dist/docs/reference/extensions.html +39 -38
  102. package/dist/docs/reference/extensions.md +13 -0
  103. package/dist/docs/reference/hooks.html +35 -35
  104. package/dist/docs/reference/http-api.html +35 -35
  105. package/dist/docs/reference/instructions.html +35 -35
  106. package/dist/docs/reference/playground.html +35 -35
  107. package/dist/docs/reference/project-layout.html +35 -35
  108. package/dist/docs/reference/prompt.html +35 -35
  109. package/dist/docs/reference/schedules.html +35 -35
  110. package/dist/docs/reference/sessions.html +35 -35
  111. package/dist/docs/reference/skills.html +35 -35
  112. package/dist/docs/reference/subagents.html +35 -35
  113. package/dist/docs/reference/tools.html +35 -35
  114. package/dist/docs/templates/agentic-owners.html +35 -35
  115. package/dist/docs/templates/security-reviewer.html +35 -35
  116. package/dist/docs/templates/thermo-quality-review.html +35 -35
  117. package/dist/docs/templates/thermo-review.html +35 -35
  118. package/dist/docs/templates/triage.html +35 -35
  119. package/dist/docs/troubleshooting.html +35 -35
  120. package/dist/extensions/jev/extension.d.ts +3 -0
  121. package/dist/extensions/jev/extension.d.ts.map +1 -1
  122. package/dist/extensions/jev/extension.js +10 -1
  123. package/dist/extensions/jev/lib/evaluate.d.ts +4 -0
  124. package/dist/extensions/jev/lib/evaluate.d.ts.map +1 -1
  125. package/dist/extensions/jev/lib/evaluate.js +6 -2
  126. package/dist/extensions.d.ts +4 -2
  127. package/dist/extensions.d.ts.map +1 -1
  128. package/dist/extensions.js +5 -2
  129. package/dist/internal/cli-deploy.d.ts.map +1 -1
  130. package/dist/internal/cli-deploy.js +19 -5
  131. package/dist/internal/discovery/agent-config.d.ts +6 -5
  132. package/dist/internal/discovery/agent-config.d.ts.map +1 -1
  133. package/dist/internal/discovery/agent-config.js +29 -28
  134. package/dist/internal/discovery/agent.js +1 -1
  135. package/dist/internal/discovery/extensions.d.ts.map +1 -1
  136. package/dist/internal/discovery/extensions.js +12 -0
  137. package/dist/internal/hosting.d.ts +8 -0
  138. package/dist/internal/hosting.d.ts.map +1 -1
  139. package/dist/internal/hosting.js +24 -0
  140. package/dist/types.d.ts +18 -2
  141. package/dist/types.d.ts.map +1 -1
  142. package/docs/deployment.md +4 -1
  143. package/docs/guides/jev.md +7 -0
  144. package/docs/reference/agent-config.md +1 -1
  145. package/docs/reference/extensions.md +13 -0
  146. package/package.json +1 -9
  147. package/dist/docs/assets/chunks/@localSearchIndexroot.D5L-b34G.js +0 -1
  148. package/dist/docs/assets/chunks/channel.BbOGaJQP.js +0 -1
  149. package/dist/docs/assets/chunks/classDiagram-6PBFFD2Q.Db58HCb1.js +0 -1
  150. package/dist/docs/assets/chunks/classDiagram-v2-HSJHXN6E.Db58HCb1.js +0 -1
  151. package/dist/docs/assets/chunks/clone.Co4MBflG.js +0 -1
  152. package/dist/docs/assets/chunks/stateDiagram-v2-QKLJ7IA2.CMsKhrW0.js +0 -1
  153. package/src/artifacts.ts +0 -68
  154. package/src/bin/agent-serve.ts +0 -1854
  155. package/src/channels/bitbucket/api.ts +0 -891
  156. package/src/channels/bitbucket/binding.ts +0 -417
  157. package/src/channels/bitbucket/bitbucket-channel.ts +0 -162
  158. package/src/channels/bitbucket/bitbucket-webhook.ts +0 -519
  159. package/src/channels/bitbucket/checks.ts +0 -146
  160. package/src/channels/bitbucket/cursor-account.ts +0 -106
  161. package/src/channels/bitbucket/defaults.ts +0 -100
  162. package/src/channels/bitbucket/events.ts +0 -74
  163. package/src/channels/bitbucket/index.ts +0 -51
  164. package/src/channels/bitbucket/replay.ts +0 -421
  165. package/src/channels/bitbucket/state.ts +0 -59
  166. package/src/channels/bitbucket/types.ts +0 -261
  167. package/src/channels/change-monitors/change-monitors-channel.ts +0 -63
  168. package/src/channels/change-monitors/index.ts +0 -8
  169. package/src/channels/change-monitors/types.ts +0 -42
  170. package/src/channels/checks.ts +0 -185
  171. package/src/channels/deployments/deployments-channel.ts +0 -224
  172. package/src/channels/deployments/index.ts +0 -25
  173. package/src/channels/deployments/types.ts +0 -92
  174. package/src/channels/github/api.ts +0 -526
  175. package/src/channels/github/auth.ts +0 -293
  176. package/src/channels/github/binding.ts +0 -233
  177. package/src/channels/github/checks.ts +0 -145
  178. package/src/channels/github/cursor-account.ts +0 -303
  179. package/src/channels/github/defaults.ts +0 -168
  180. package/src/channels/github/events.ts +0 -67
  181. package/src/channels/github/forward.ts +0 -359
  182. package/src/channels/github/github-channel.ts +0 -2334
  183. package/src/channels/github/index.ts +0 -54
  184. package/src/channels/github/progress.ts +0 -365
  185. package/src/channels/github/replay.ts +0 -372
  186. package/src/channels/github/state.ts +0 -124
  187. package/src/channels/github/types.ts +0 -590
  188. package/src/channels/gitlab/api.ts +0 -329
  189. package/src/channels/gitlab/binding.ts +0 -231
  190. package/src/channels/gitlab/checks.ts +0 -228
  191. package/src/channels/gitlab/cursor-account.ts +0 -105
  192. package/src/channels/gitlab/defaults.ts +0 -80
  193. package/src/channels/gitlab/events.ts +0 -37
  194. package/src/channels/gitlab/gitlab-channel.ts +0 -160
  195. package/src/channels/gitlab/gitlab-webhook.ts +0 -509
  196. package/src/channels/gitlab/index.ts +0 -44
  197. package/src/channels/gitlab/replay.ts +0 -328
  198. package/src/channels/gitlab/state.ts +0 -55
  199. package/src/channels/gitlab/types.ts +0 -247
  200. package/src/channels/issues/index.ts +0 -9
  201. package/src/channels/issues/issues-channel.ts +0 -45
  202. package/src/channels/issues/types.ts +0 -38
  203. package/src/channels/origin/api.ts +0 -507
  204. package/src/channels/origin/binding.ts +0 -114
  205. package/src/channels/origin/checks.ts +0 -250
  206. package/src/channels/origin/cursor-account.ts +0 -58
  207. package/src/channels/origin/defaults.ts +0 -140
  208. package/src/channels/origin/events.ts +0 -35
  209. package/src/channels/origin/index.ts +0 -35
  210. package/src/channels/origin/origin-channel.ts +0 -815
  211. package/src/channels/origin/origin-webhook.ts +0 -296
  212. package/src/channels/origin/reactions.ts +0 -72
  213. package/src/channels/origin/state.ts +0 -54
  214. package/src/channels/origin/types.ts +0 -295
  215. package/src/channels/slack/agentic-delivery.ts +0 -634
  216. package/src/channels/slack/agentic-posted.ts +0 -135
  217. package/src/channels/slack/agentic-signals.ts +0 -231
  218. package/src/channels/slack/api.ts +0 -761
  219. package/src/channels/slack/approvals.ts +0 -279
  220. package/src/channels/slack/assistant.ts +0 -76
  221. package/src/channels/slack/attachments.ts +0 -596
  222. package/src/channels/slack/auth.ts +0 -127
  223. package/src/channels/slack/blocks.ts +0 -131
  224. package/src/channels/slack/bot-mentions.ts +0 -318
  225. package/src/channels/slack/channel-watch.ts +0 -314
  226. package/src/channels/slack/cli-project.ts +0 -249
  227. package/src/channels/slack/code-fences.ts +0 -171
  228. package/src/channels/slack/constants.ts +0 -38
  229. package/src/channels/slack/credentials.ts +0 -88
  230. package/src/channels/slack/defaults.ts +0 -714
  231. package/src/channels/slack/dispatch.ts +0 -1060
  232. package/src/channels/slack/doctor.ts +0 -338
  233. package/src/channels/slack/eval-directive.ts +0 -306
  234. package/src/channels/slack/event-id-dedupe.ts +0 -30
  235. package/src/channels/slack/external-policy.ts +0 -75
  236. package/src/channels/slack/footer.ts +0 -106
  237. package/src/channels/slack/inbound.ts +0 -416
  238. package/src/channels/slack/index.ts +0 -53
  239. package/src/channels/slack/init.ts +0 -169
  240. package/src/channels/slack/interactive.ts +0 -406
  241. package/src/channels/slack/links.ts +0 -23
  242. package/src/channels/slack/live-delivery.ts +0 -489
  243. package/src/channels/slack/log.ts +0 -70
  244. package/src/channels/slack/manifest.ts +0 -240
  245. package/src/channels/slack/message-body.ts +0 -82
  246. package/src/channels/slack/nudge-carrier.ts +0 -224
  247. package/src/channels/slack/nudge-store.ts +0 -334
  248. package/src/channels/slack/paint-start.ts +0 -93
  249. package/src/channels/slack/placeholder.ts +0 -358
  250. package/src/channels/slack/pr-ref.ts +0 -74
  251. package/src/channels/slack/progress-delivery.ts +0 -138
  252. package/src/channels/slack/reasoning-card.ts +0 -125
  253. package/src/channels/slack/reasoning-chip.ts +0 -41
  254. package/src/channels/slack/recording-sink.ts +0 -167
  255. package/src/channels/slack/redact.ts +0 -6
  256. package/src/channels/slack/reply-options.ts +0 -279
  257. package/src/channels/slack/setup.ts +0 -125
  258. package/src/channels/slack/slack-channel.ts +0 -744
  259. package/src/channels/slack/socket-mode.ts +0 -140
  260. package/src/channels/slack/stop.ts +0 -25
  261. package/src/channels/slack/stream.ts +0 -66
  262. package/src/channels/slack/thread-context.ts +0 -485
  263. package/src/channels/slack/tool-approval-events.ts +0 -233
  264. package/src/channels/slack/tool-cards.ts +0 -198
  265. package/src/channels/slack/tool-chip.ts +0 -34
  266. package/src/channels/slack/types.ts +0 -787
  267. package/src/channels/slack/upload.ts +0 -137
  268. package/src/channels.ts +0 -543
  269. package/src/connections.ts +0 -153
  270. package/src/dashboard-session-url.ts +0 -30
  271. package/src/evals/assertions.ts +0 -688
  272. package/src/evals/expect.ts +0 -250
  273. package/src/evals/judge.ts +0 -329
  274. package/src/evals/loaders.ts +0 -111
  275. package/src/evals/matchers.ts +0 -223
  276. package/src/evals/reporters.ts +0 -257
  277. package/src/evals/results.ts +0 -130
  278. package/src/evals/run-facts.ts +0 -306
  279. package/src/evals.ts +0 -709
  280. package/src/extensions/cursor-cloud-agents/extension.ts +0 -131
  281. package/src/extensions/cursor-cloud-agents/lib/backend.ts +0 -386
  282. package/src/extensions/cursor-cloud-agents/lib/channels.ts +0 -11
  283. package/src/extensions/cursor-cloud-agents/lib/fleet.ts +0 -98
  284. package/src/extensions/cursor-cloud-agents/lib/inputs.ts +0 -5
  285. package/src/extensions/cursor-cloud-agents/lib/repos.ts +0 -80
  286. package/src/extensions/cursor-cloud-agents/lib/transcript.ts +0 -19
  287. package/src/extensions/cursor-cloud-agents/skills/handoff.md +0 -37
  288. package/src/extensions/cursor-cloud-agents/tools/cancel.ts +0 -21
  289. package/src/extensions/cursor-cloud-agents/tools/dump.ts +0 -47
  290. package/src/extensions/cursor-cloud-agents/tools/get.ts +0 -18
  291. package/src/extensions/cursor-cloud-agents/tools/launch.ts +0 -62
  292. package/src/extensions/cursor-cloud-agents/tools/list.ts +0 -31
  293. package/src/extensions/cursor-cloud-agents/tools/reply.ts +0 -36
  294. package/src/extensions/cursor-grokbot-agents/extension.ts +0 -132
  295. package/src/extensions/cursor-grokbot-agents/lib/agents.ts +0 -42
  296. package/src/extensions/cursor-grokbot-agents/lib/backend.ts +0 -208
  297. package/src/extensions/cursor-grokbot-agents/lib/contacts.ts +0 -74
  298. package/src/extensions/cursor-grokbot-agents/lib/conversation.ts +0 -260
  299. package/src/extensions/cursor-grokbot-agents/lib/inputs.ts +0 -21
  300. package/src/extensions/cursor-grokbot-agents/lib/lock.ts +0 -26
  301. package/src/extensions/cursor-grokbot-agents/skills/consult.md +0 -40
  302. package/src/extensions/cursor-grokbot-agents/tools/ask.ts +0 -32
  303. package/src/extensions/cursor-grokbot-agents/tools/check.ts +0 -25
  304. package/src/extensions/cursor-grokbot-agents/tools/interrupt.ts +0 -17
  305. package/src/extensions/cursor-grokbot-agents/tools/list.ts +0 -26
  306. package/src/extensions/improve/extension.ts +0 -69
  307. package/src/extensions/improve/skills/yourself.ts +0 -50
  308. package/src/extensions/jev/extension.ts +0 -95
  309. package/src/extensions/jev/lib/evaluate.ts +0 -266
  310. package/src/extensions/jev/skills/gated-write.md +0 -25
  311. package/src/extensions/jev/skills/questions.md +0 -33
  312. package/src/extensions/jev/tools/evaluate.ts +0 -82
  313. package/src/extensions/slack-communication/evals/harness.ts +0 -705
  314. package/src/extensions/slack-communication/evals/slack-communication.eval.ts +0 -830
  315. package/src/extensions/slack-communication/evals/slack-placeholder.eval.ts +0 -172
  316. package/src/extensions/slack-communication/extension.ts +0 -44
  317. package/src/extensions/slack-communication/skills/slack-voice.ts +0 -56
  318. package/src/extensions/slack-communication/tools/delete-message.ts +0 -33
  319. package/src/extensions/slack-communication/tools/edit-message.ts +0 -42
  320. package/src/extensions/slack-communication/tools/post-card.ts +0 -28
  321. package/src/extensions/slack-communication/tools/post-file.ts +0 -82
  322. package/src/extensions/slack-communication/tools/post-update.ts +0 -40
  323. package/src/extensions/slack-communication/tools/react.ts +0 -30
  324. package/src/extensions/slack-communication/tools/set-status.ts +0 -21
  325. package/src/extensions.ts +0 -179
  326. package/src/files-backends/agent-store-presigned-url.ts +0 -11
  327. package/src/files-backends/cursor-hosted.ts +0 -1212
  328. package/src/files-backends/local-fs.ts +0 -163
  329. package/src/files.ts +0 -293
  330. package/src/filesystem.ts +0 -2005
  331. package/src/hooks.ts +0 -30
  332. package/src/index.ts +0 -259
  333. package/src/internal/advertise-tools.ts +0 -370
  334. package/src/internal/approval-gate.ts +0 -103
  335. package/src/internal/artifacts-store.ts +0 -836
  336. package/src/internal/as-of.ts +0 -257
  337. package/src/internal/auth.ts +0 -46
  338. package/src/internal/authored-alias-hooks.ts +0 -138
  339. package/src/internal/authored-loaders.ts +0 -188
  340. package/src/internal/bounded-int.ts +0 -24
  341. package/src/internal/bounded.ts +0 -25
  342. package/src/internal/brand.ts +0 -28
  343. package/src/internal/browser-origin-guard.ts +0 -67
  344. package/src/internal/builtin-tools/artifacts.ts +0 -62
  345. package/src/internal/builtin-tools/index.ts +0 -53
  346. package/src/internal/builtin-tools/reminders.ts +0 -145
  347. package/src/internal/channel-dispatch.ts +0 -129
  348. package/src/internal/channel-route-dispatch.ts +0 -58
  349. package/src/internal/channel-state.ts +0 -83
  350. package/src/internal/chat-client.ts +0 -594
  351. package/src/internal/cli-ax.ts +0 -2318
  352. package/src/internal/cli-bitbucket.ts +0 -438
  353. package/src/internal/cli-convert-automation.ts +0 -335
  354. package/src/internal/cli-cursor.ts +0 -282
  355. package/src/internal/cli-deploy.ts +0 -2519
  356. package/src/internal/cli-docs.ts +0 -192
  357. package/src/internal/cli-github.ts +0 -806
  358. package/src/internal/cli-gitlab.ts +0 -452
  359. package/src/internal/cli-images.ts +0 -672
  360. package/src/internal/cli-manifest.ts +0 -56
  361. package/src/internal/cli-mcp-oauth.ts +0 -396
  362. package/src/internal/cli-mcp.ts +0 -808
  363. package/src/internal/cli-skills.ts +0 -98
  364. package/src/internal/cli-slack-manual.ts +0 -418
  365. package/src/internal/cli-slack.ts +0 -874
  366. package/src/internal/cloud-merge.ts +0 -51
  367. package/src/internal/cloud-turn-cost.ts +0 -159
  368. package/src/internal/connection-env.ts +0 -106
  369. package/src/internal/continuation-channel.ts +0 -233
  370. package/src/internal/continuation-identity.ts +0 -935
  371. package/src/internal/conversation-mirror.ts +0 -423
  372. package/src/internal/convert-automation/convert-workflow.ts +0 -1377
  373. package/src/internal/convert-automation/slug.ts +0 -29
  374. package/src/internal/convert-automation/types.ts +0 -212
  375. package/src/internal/cron.ts +0 -76
  376. package/src/internal/cursor/account-mcp.ts +0 -692
  377. package/src/internal/cursor/backend-client.ts +0 -984
  378. package/src/internal/cursor/bound-secret-file.ts +0 -101
  379. package/src/internal/cursor/credentials.ts +0 -560
  380. package/src/internal/cursor/cursor-api-transport.ts +0 -65
  381. package/src/internal/cursor/github-credentials.ts +0 -228
  382. package/src/internal/cursor/hosted-bound-secrets.ts +0 -71
  383. package/src/internal/cursor/hosted-deployment-secrets.ts +0 -100
  384. package/src/internal/cursor/hosted-store-secrets.ts +0 -152
  385. package/src/internal/cursor/session-token.ts +0 -111
  386. package/src/internal/cursor/store-api-client.ts +0 -323
  387. package/src/internal/cursor-account-mcp-auth.ts +0 -303
  388. package/src/internal/cursor-agent-template.ts +0 -50
  389. package/src/internal/cursor-deployment-relay.ts +0 -315
  390. package/src/internal/cursor-event-relay.ts +0 -675
  391. package/src/internal/cursor-relay-core.ts +0 -563
  392. package/src/internal/deferred-channel-session.ts +0 -61
  393. package/src/internal/deploy-client.ts +0 -1574
  394. package/src/internal/deploy-manifest.ts +0 -361
  395. package/src/internal/deploy-source.ts +0 -144
  396. package/src/internal/describe-error.ts +0 -32
  397. package/src/internal/dev-mode.ts +0 -20
  398. package/src/internal/discovery/agent-config.ts +0 -288
  399. package/src/internal/discovery/agent.ts +0 -381
  400. package/src/internal/discovery/channels.ts +0 -100
  401. package/src/internal/discovery/connections.ts +0 -516
  402. package/src/internal/discovery/context.ts +0 -38
  403. package/src/internal/discovery/cursor-plugin.ts +0 -628
  404. package/src/internal/discovery/extension-overlay.ts +0 -247
  405. package/src/internal/discovery/extensions.ts +0 -490
  406. package/src/internal/discovery/fs.ts +0 -103
  407. package/src/internal/discovery/hooks.ts +0 -63
  408. package/src/internal/discovery/info.ts +0 -174
  409. package/src/internal/discovery/instructions.ts +0 -98
  410. package/src/internal/discovery/modules.ts +0 -107
  411. package/src/internal/discovery/names.ts +0 -45
  412. package/src/internal/discovery/project.ts +0 -319
  413. package/src/internal/discovery/reminders.ts +0 -65
  414. package/src/internal/discovery/runtime.ts +0 -158
  415. package/src/internal/discovery/schedules.ts +0 -120
  416. package/src/internal/discovery/seed-files.ts +0 -34
  417. package/src/internal/discovery/services.ts +0 -151
  418. package/src/internal/discovery/skills.ts +0 -174
  419. package/src/internal/discovery/subagent.ts +0 -138
  420. package/src/internal/discovery/tools.ts +0 -170
  421. package/src/internal/discovery.ts +0 -27
  422. package/src/internal/distribution.ts +0 -126
  423. package/src/internal/docs-site.ts +0 -248
  424. package/src/internal/duration.ts +0 -37
  425. package/src/internal/env-file.ts +0 -83
  426. package/src/internal/eval-judge-model.ts +0 -142
  427. package/src/internal/eval-run-store.ts +0 -585
  428. package/src/internal/eval-runner.ts +0 -823
  429. package/src/internal/evals-client.ts +0 -475
  430. package/src/internal/event-log.ts +0 -342
  431. package/src/internal/event-mapper.ts +0 -811
  432. package/src/internal/expected-delivery-failure.ts +0 -34
  433. package/src/internal/factory-resource-channel.ts +0 -103
  434. package/src/internal/filesystem/errors.ts +0 -207
  435. package/src/internal/filesystem/format.ts +0 -253
  436. package/src/internal/filesystem/merge.ts +0 -192
  437. package/src/internal/filesystem/nearest.ts +0 -112
  438. package/src/internal/filesystem/scratch.ts +0 -239
  439. package/src/internal/filesystem/sdk-schemas.ts +0 -204
  440. package/src/internal/filesystem/tools.ts +0 -804
  441. package/src/internal/filesystem/walk.ts +0 -366
  442. package/src/internal/fixtures/units-server.ts +0 -52
  443. package/src/internal/framework-file-storage.ts +0 -357
  444. package/src/internal/framework-storage-selection.ts +0 -156
  445. package/src/internal/frontmatter.ts +0 -108
  446. package/src/internal/github-fanout.ts +0 -144
  447. package/src/internal/guest-network.ts +0 -391
  448. package/src/internal/handleAgentServeTrigger.ts +0 -286
  449. package/src/internal/host-files.ts +0 -341
  450. package/src/internal/host-kv.ts +0 -81
  451. package/src/internal/host-otel.ts +0 -231
  452. package/src/internal/host-platforms.ts +0 -170
  453. package/src/internal/hosted-admission-adapter.ts +0 -47
  454. package/src/internal/hosted-admission-context.ts +0 -37
  455. package/src/internal/hosted-catch-protocol.ts +0 -112
  456. package/src/internal/hosted-catch.ts +0 -179
  457. package/src/internal/hosted-delivery-protocol.ts +0 -824
  458. package/src/internal/hosted-delivery.ts +0 -1410
  459. package/src/internal/hosted-execution-diag.ts +0 -291
  460. package/src/internal/hosted-execution-flush.ts +0 -136
  461. package/src/internal/hosted-execution-latency.ts +0 -301
  462. package/src/internal/hosted-managed-automation.ts +0 -116
  463. package/src/internal/hosting.ts +0 -114
  464. package/src/internal/http-channel-define.ts +0 -25
  465. package/src/internal/http-channel.ts +0 -669
  466. package/src/internal/http-control-plane-session.ts +0 -110
  467. package/src/internal/ids.ts +0 -39
  468. package/src/internal/incoming-headers-to-fetch.ts +0 -45
  469. package/src/internal/init-interview.ts +0 -360
  470. package/src/internal/init-project.ts +0 -711
  471. package/src/internal/init-scaffold.ts +0 -182
  472. package/src/internal/inline-stdio-define-stub.ts +0 -4
  473. package/src/internal/inline-stdio-mcp.ts +0 -230
  474. package/src/internal/install-cursor-skills.ts +0 -604
  475. package/src/internal/is-record.ts +0 -3
  476. package/src/internal/json-schema.ts +0 -95
  477. package/src/internal/legacy-command-guard.ts +0 -66
  478. package/src/internal/listen-port.ts +0 -85
  479. package/src/internal/local-control-plane.ts +0 -442
  480. package/src/internal/local-env.ts +0 -59
  481. package/src/internal/local-ingress.ts +0 -90
  482. package/src/internal/log-ring.ts +0 -59
  483. package/src/internal/logs-client.ts +0 -477
  484. package/src/internal/map-pool.ts +0 -39
  485. package/src/internal/mcp-endpoint.ts +0 -747
  486. package/src/internal/mcp-host.ts +0 -509
  487. package/src/internal/mcp-oauth-on-demand.ts +0 -337
  488. package/src/internal/mcp-oauth-persist.ts +0 -118
  489. package/src/internal/mcp-oauth.ts +0 -549
  490. package/src/internal/net.ts +0 -29
  491. package/src/internal/open-browser.ts +0 -41
  492. package/src/internal/otel/attrs.ts +0 -16
  493. package/src/internal/otel/collector.ts +0 -937
  494. package/src/internal/otel/config.ts +0 -287
  495. package/src/internal/otel/http.ts +0 -122
  496. package/src/internal/otel/mcp.ts +0 -56
  497. package/src/internal/otel/propagation.ts +0 -17
  498. package/src/internal/otel/runtime.ts +0 -441
  499. package/src/internal/package-inline-stdio.ts +0 -114
  500. package/src/internal/peer-connections.ts +0 -96
  501. package/src/internal/platform-schedule-sync.ts +0 -75
  502. package/src/internal/platform-timers.ts +0 -365
  503. package/src/internal/playground/static.ts +0 -278
  504. package/src/internal/playground/toolchain.ts +0 -270
  505. package/src/internal/playground-proxy.ts +0 -564
  506. package/src/internal/process-memory-telemetry.ts +0 -334
  507. package/src/internal/project-layout.ts +0 -31
  508. package/src/internal/prompt-context.ts +0 -116
  509. package/src/internal/reminder-control-plane-protocol.ts +0 -482
  510. package/src/internal/reminder-runner.ts +0 -1559
  511. package/src/internal/reminder-schedule.ts +0 -104
  512. package/src/internal/reminder-store.ts +0 -176
  513. package/src/internal/request-error-status.ts +0 -95
  514. package/src/internal/request-headers.ts +0 -21
  515. package/src/internal/resolve-prod-target.ts +0 -334
  516. package/src/internal/resolved-connections.ts +0 -190
  517. package/src/internal/router.ts +0 -143
  518. package/src/internal/run-client.ts +0 -354
  519. package/src/internal/runtime-dispatch-runner.ts +0 -50
  520. package/src/internal/sanitize-mcp-tool-name.ts +0 -31
  521. package/src/internal/schedule-runner.ts +0 -154
  522. package/src/internal/scm/pr-url.ts +0 -245
  523. package/src/internal/sdk-runner.ts +0 -959
  524. package/src/internal/serve-restart.ts +0 -113
  525. package/src/internal/server.ts +0 -3147
  526. package/src/internal/session-cost.ts +0 -208
  527. package/src/internal/session-engine.ts +0 -5622
  528. package/src/internal/session-links.ts +0 -84
  529. package/src/internal/session-run-log.ts +0 -535
  530. package/src/internal/session-store.ts +0 -307
  531. package/src/internal/session-urls.ts +0 -32
  532. package/src/internal/sessions-client.ts +0 -239
  533. package/src/internal/skill-catalog.ts +0 -66
  534. package/src/internal/skills-sync.ts +0 -55
  535. package/src/internal/slack-provision-client.ts +0 -544
  536. package/src/internal/slack-thread-key.ts +0 -11
  537. package/src/internal/sleep.ts +0 -3
  538. package/src/internal/start-log-store.ts +0 -164
  539. package/src/internal/steering.ts +0 -17
  540. package/src/internal/storage-coordinator.ts +0 -800
  541. package/src/internal/storage-roles.ts +0 -86
  542. package/src/internal/storage.ts +0 -1
  543. package/src/internal/store-api-protocol.ts +0 -205
  544. package/src/internal/store-mirror.ts +0 -73
  545. package/src/internal/stream-progress.ts +0 -294
  546. package/src/internal/terminal-style.ts +0 -133
  547. package/src/internal/testing/factory-resource-fixtures.ts +0 -84
  548. package/src/internal/testing/scm-continuation-fixtures.ts +0 -285
  549. package/src/internal/tool-catalog.ts +0 -104
  550. package/src/internal/tool-policy.ts +0 -222
  551. package/src/internal/tool-result.ts +0 -50
  552. package/src/internal/trajectory.ts +0 -418
  553. package/src/internal/turn-cost.ts +0 -136
  554. package/src/internal/turn-governor.ts +0 -145
  555. package/src/internal/turn-lease-store.ts +0 -144
  556. package/src/internal/turn-outbox.ts +0 -77
  557. package/src/internal/update-check.ts +0 -517
  558. package/src/internal/v2-hosting.ts +0 -52
  559. package/src/internal/workspace-sync.ts +0 -114
  560. package/src/internal/workspace.ts +0 -505
  561. package/src/kv/memory-kv.ts +0 -94
  562. package/src/kv.ts +0 -18
  563. package/src/memory.ts +0 -487
  564. package/src/otel-public.ts +0 -24
  565. package/src/otel.ts +0 -320
  566. package/src/prompt.ts +0 -80
  567. package/src/reminders.ts +0 -65
  568. package/src/schedules.ts +0 -31
  569. package/src/skills.ts +0 -27
  570. package/src/storage-backends/cursor-hosted-v2.ts +0 -204
  571. package/src/storage-backends/cursor-hosted.ts +0 -388
  572. package/src/storage-backends/file-kv.ts +0 -276
  573. package/src/storage-protocol.ts +0 -261
  574. package/src/storage.ts +0 -408
  575. package/src/tools.ts +0 -166
  576. package/src/types.ts +0 -3776
  577. /package/dist/docs/assets/{reference_agent-config.md.DzGI777n.lean.js → reference_agent-config.md.Cj5uBKp4.lean.js} +0 -0
@@ -1,1559 +0,0 @@
1
- /**
2
- * Per-session reminder runner: durable wake subscriptions with
3
- * prompt XOR named handler XOR run, every/cron/delay/at schedules, and
4
- * until as function XOR prompt.
5
- */
6
-
7
- import { randomBytes } from "node:crypto";
8
- import type {
9
- AuthContext,
10
- ChannelSession,
11
- DiscoveredReminder,
12
- HostOtelApi,
13
- JsonObject,
14
- JsonValue,
15
- ReminderCreateInput,
16
- ReminderDefinition,
17
- ReminderFireContext,
18
- ReminderFireResult,
19
- ReminderFollowupOptions,
20
- ReminderInfo,
21
- ReminderStatus,
22
- ReminderUntilContext,
23
- TurnOutcome,
24
- } from "../types.js";
25
- import { channelContinuationIdentity, httpContinuationIdentity } from "./continuation-channel.js";
26
- import { continuationSource } from "./continuation-identity.js";
27
- import { NAME_PATTERN } from "./discovery/names.js";
28
- import { parseDuration } from "./duration.js";
29
- import type { PlatformTimers } from "./platform-timers.js";
30
- import {
31
- REMINDER_CP_PROTOCOL_VERSION,
32
- type ReminderControlPlane,
33
- type ReminderCreateIntent,
34
- type ReminderExecutionOutcome,
35
- type ReminderFireDescriptor,
36
- scheduleSpecFromCreateInput,
37
- toWireReschedule,
38
- } from "./reminder-control-plane-protocol.js";
39
- import {
40
- defaultBusyPolicy,
41
- MAX_TIMER_MS,
42
- nextCronFireMs,
43
- ReminderValidationError,
44
- resolveSchedule,
45
- } from "./reminder-schedule.js";
46
- import type { ReminderBusyPolicy, ReminderRecord } from "./reminder-store.js";
47
- import { APP_AUTH } from "./schedule-runner.js";
48
- import {
49
- type EngineSendOptions,
50
- HTTP_CHANNEL_ID,
51
- SessionAuthError,
52
- SessionBusyError,
53
- type SessionEngine,
54
- } from "./session-engine.js";
55
-
56
- export { ReminderValidationError } from "./reminder-schedule.js";
57
-
58
- /** Max UTF-8 byte length of `JSON.stringify(args)` on named-handler create. */
59
- export const REMINDER_ARGS_MAX_BYTES: number = 32 * 1024;
60
-
61
- export class UnknownReminderError extends Error {
62
- constructor(
63
- reminderId: string,
64
- readonly availableReminderIds: string[],
65
- ) {
66
- super(`Unknown reminder "${reminderId}"`);
67
- this.name = "UnknownReminderError";
68
- }
69
- }
70
-
71
- interface LiveHandlers {
72
- run?: (ctx: ReminderFireContext) => Promise<ReminderFireResult>;
73
- untilFn?: (ctx: ReminderUntilContext) => Promise<boolean>;
74
- }
75
-
76
- export interface ReminderRunnerOptions {
77
- /** Discovered `agent/reminders/*` handlers, keyed by module stem. */
78
- namedHandlers?: readonly DiscoveredReminder[];
79
- /**
80
- * Architecture v2: reject anonymous `run` and function `until` at create
81
- * (named `handler` + prompt remain), whether local or hosted.
82
- */
83
- rejectAnonymousHandlers?: boolean;
84
- /**
85
- * When set (local self-hosted architecture v2), create/cancel/rekey go
86
- * through the control-plane protocol and fires are guest executions of
87
- * immutable descriptors.
88
- */
89
- controlPlane?: ReminderControlPlane;
90
- /** Agent architecture; used with {@link controlPlane} for v2 protocol path. */
91
- architecture?: "v1" | "v2";
92
- /**
93
- * Hosted v2 guest (`--no-control-plane`, architecture v2). A pod starts
94
- * for one delivery and stops when it settles, so a fire usually lands on
95
- * a pod that holds no session for the reminder's continuation, and the
96
- * pod may stop as soon as the fire's outcome is applied. The runner then
97
- * opens a session on the stored continuation key and waits for the turn.
98
- */
99
- hostedGuest?: ReminderHostedGuestOptions;
100
- }
101
-
102
- export interface ReminderHostedGuestOptions {
103
- /**
104
- * Principal for the session a prompt fire opens when the pod holds none.
105
- * Hosted admissions open sessions with the same value, so a session the
106
- * engine restores from durable storage keeps its principal. Return
107
- * `undefined` when no principal applies; the fire then skips with a
108
- * reschedule so the control plane keeps the reminder armed.
109
- */
110
- fireAuth: () => AuthContext | null | undefined;
111
- }
112
-
113
- /**
114
- * Reschedule applied when a hosted fire cannot open a session (no
115
- * principal). A one-shot `skipped` outcome without a reschedule completes
116
- * the reminder, which would lose the check-in for good.
117
- */
118
- export const REMINDER_SESSION_OPEN_RETRY_DELAY = "5m";
119
-
120
- /**
121
- * `reason` tag on `agent_sdk.reminder.fire_outcome`. Prompt fires report
122
- * how the session was reached: `session_joined` (held by this pod),
123
- * `session_restored` (read back from durable storage), `session_opened`
124
- * (fresh session on the stored key), `session_gone` (no session and none
125
- * could be opened). `fire_threw` pairs with kind `error`: the fire raised
126
- * and the hosted admission retries it.
127
- */
128
- export type ReminderFireOutcomeReason =
129
- | "session_gone"
130
- | "session_opened"
131
- | "session_restored"
132
- | "session_joined"
133
- | "handler_missing"
134
- | "handler_lost_on_restart"
135
- | "missing_handler"
136
- | "run_stop"
137
- | "run_skip"
138
- | "run_delivered"
139
- | "until_fn"
140
- | "busy"
141
- | "followup_failed"
142
- | "fire_threw";
143
-
144
- export const REMINDER_FIRE_OUTCOME_METRIC = "agent_sdk.reminder.fire_outcome";
145
-
146
- /** What one `executeFire` reports: the CP outcome plus the telemetry tags. */
147
- interface FireExecution {
148
- outcome: ReminderExecutionOutcome;
149
- reason: ReminderFireOutcomeReason;
150
- /** Set when the hosted guest awaited the turn before reporting. */
151
- turnStatus?: TurnOutcome["status"];
152
- }
153
-
154
- interface PromptDelivery {
155
- result: ReminderFireResult;
156
- reason: ReminderFireOutcomeReason;
157
- turnStatus?: TurnOutcome["status"];
158
- }
159
-
160
- /** Out-params `sendFollowup` fills in for the fire's telemetry. */
161
- interface FollowupSettle {
162
- turnStatus?: TurnOutcome["status"];
163
- skipReason?: Extract<ReminderFireOutcomeReason, "busy" | "followup_failed">;
164
- }
165
-
166
- /** How a prompt fire reached (or failed to reach) its session. */
167
- type FollowupTarget =
168
- | {
169
- auth: AuthContext | null;
170
- reached: Extract<ReminderFireOutcomeReason, "session_joined" | "session_restored">;
171
- }
172
- | {
173
- auth: undefined;
174
- /**
175
- * `session_gone`: no session anywhere. `session_unreadable`: the durable
176
- * index has one but the local re-read missed; never open a fresh
177
- * session over it.
178
- */
179
- reached: "session_gone" | "session_unreadable";
180
- };
181
-
182
- /** Guest-side read surface shared by v1 timed-work and the v2 CP client. */
183
- interface ReminderReader {
184
- getReminder(id: string): Promise<ReminderRecord | undefined>;
185
- listReminders(): Promise<ReminderRecord[]>;
186
- }
187
-
188
- /**
189
- * Server wiring for {@link ReminderRunnerOptions.rejectAnonymousHandlers}:
190
- * architecture v2 always rejects anonymous run/until (local or hosted).
191
- */
192
- export function rejectAnonymousReminderHandlers(options: {
193
- noControlPlane?: boolean;
194
- architecture?: string;
195
- }): boolean {
196
- return options.architecture === "v2";
197
- }
198
-
199
- function newReminderId(): string {
200
- return `rem_${randomBytes(8).toString("hex")}`;
201
- }
202
-
203
- function isJsonObject(value: unknown): value is JsonObject {
204
- return (
205
- typeof value === "object" &&
206
- value !== null &&
207
- !Array.isArray(value) &&
208
- Object.values(value as Record<string, unknown>).every(isJsonValue)
209
- );
210
- }
211
-
212
- function isJsonValue(value: unknown): value is JsonValue {
213
- if (value === null || typeof value === "string" || typeof value === "boolean") {
214
- return true;
215
- }
216
- if (typeof value === "number") {
217
- return Number.isFinite(value);
218
- }
219
- if (Array.isArray(value)) {
220
- return value.every(isJsonValue);
221
- }
222
- return isJsonObject(value);
223
- }
224
-
225
- /** Same stem rules as `agent/reminders/<name>.ts` discovery. */
226
- function isValidReminderHandlerName(name: string): boolean {
227
- return NAME_PATTERN.test(name) && !name.includes("__");
228
- }
229
-
230
- function assertReminderArgsSize(args: JsonObject): void {
231
- const bytes = Buffer.byteLength(JSON.stringify(args), "utf8");
232
- if (bytes > REMINDER_ARGS_MAX_BYTES) {
233
- throw new ReminderValidationError(
234
- `reminders.create args exceed ${REMINDER_ARGS_MAX_BYTES} bytes (got ${bytes})`,
235
- );
236
- }
237
- }
238
-
239
- function toInfo(record: ReminderRecord): ReminderInfo {
240
- return {
241
- id: record.id,
242
- purpose: record.purpose,
243
- channelId: record.channelId,
244
- continuationToken: record.continuationToken,
245
- target: record.target,
246
- scheduleKind: record.scheduleKind,
247
- scheduleValue: record.scheduleValue,
248
- prompt: record.prompt,
249
- handler: record.handler,
250
- args: record.args,
251
- untilPrompt: record.untilPrompt,
252
- busyPolicy: record.busyPolicy,
253
- status: record.status === "firing" ? "armed" : record.status,
254
- disarmReason: record.disarmReason,
255
- fireCount: record.fireCount,
256
- nextFireAt: new Date(record.nextFireAtMs).toISOString(),
257
- createdAt: record.createdAt,
258
- updatedAt: record.updatedAt,
259
- hasRunHandler: record.hasRunHandler === true,
260
- hasUntilFn: record.hasUntilFn === true,
261
- };
262
- }
263
-
264
- function stopFire(
265
- reason: Extract<
266
- ReminderFireOutcomeReason,
267
- "handler_missing" | "handler_lost_on_restart" | "missing_handler" | "until_fn"
268
- >,
269
- ): FireExecution {
270
- return { outcome: { kind: "stop", reason }, reason };
271
- }
272
-
273
- function runReason(result: ReminderFireResult): ReminderFireOutcomeReason {
274
- switch (result.action) {
275
- case "stop":
276
- return "run_stop";
277
- case "skip":
278
- return "run_skip";
279
- case "delivered":
280
- return "run_delivered";
281
- }
282
- }
283
-
284
- function buildFirePrompt(record: ReminderRecord): string {
285
- const recurring = record.scheduleKind === "every" || record.scheduleKind === "cron";
286
- const lines = [
287
- `[reminder] id=${record.id} purpose=${record.purpose}`,
288
- record.prompt ?? "Reminder fired. Check current state and only act if needed.",
289
- ];
290
- if (record.untilPrompt !== undefined && record.untilPrompt.trim() !== "") {
291
- lines.push("", `Stop condition: ${record.untilPrompt}`);
292
- if (recurring) {
293
- lines.push(`When the stop condition is met, call reminders_cancel with id=${record.id}.`);
294
- } else {
295
- lines.push(
296
- "This is a one-shot reminder (auto-completes after this fire); no cancel needed unless you armed a separate recurring reminder.",
297
- );
298
- }
299
- }
300
- return lines.join("\n");
301
- }
302
-
303
- export class ReminderRunner {
304
- private readonly records = new Map<string, ReminderRecord>();
305
- private readonly handlers = new Map<string, LiveHandlers>();
306
- private readonly namedHandlers = new Map<string, ReminderDefinition>();
307
- private readonly namedHandlerNames = new Map<ReminderDefinition, string>();
308
- private readonly timers = new Map<string, NodeJS.Timeout>();
309
- private readonly firing = new Set<string>();
310
- /** Single-flight idle gates keyed by `channelId:continuationToken`. */
311
- private readonly idleGates = new Map<string, Promise<void>>();
312
- private started = false;
313
- private readonly rejectAnonymousHandlers: boolean;
314
- private readonly controlPlane: ReminderControlPlane | undefined;
315
- private readonly architecture: "v1" | "v2" | undefined;
316
- private readonly hostedGuest: ReminderHostedGuestOptions | undefined;
317
- /**
318
- * A control-plane read failure is logged once per outage, not per call.
319
- * The next successful read re-arms the log.
320
- */
321
- private controlPlaneReadFailureLogged = false;
322
-
323
- constructor(
324
- private readonly engine: SessionEngine,
325
- private readonly logger: (line: string) => void = () => {},
326
- private readonly platformTimers?: PlatformTimers,
327
- options: ReminderRunnerOptions = {},
328
- ) {
329
- this.rejectAnonymousHandlers = options.rejectAnonymousHandlers === true;
330
- this.controlPlane = options.controlPlane;
331
- this.architecture = options.architecture;
332
- this.hostedGuest = options.hostedGuest;
333
- for (const reminder of options.namedHandlers ?? []) {
334
- this.namedHandlers.set(reminder.name, reminder.definition);
335
- this.namedHandlerNames.set(reminder.definition, reminder.name);
336
- }
337
- }
338
-
339
- /** True when create/cancel/rekey/fire go through the CP protocol. */
340
- private get usesControlPlaneProtocol(): boolean {
341
- return this.controlPlane !== undefined && this.architecture === "v2";
342
- }
343
-
344
- /**
345
- * Where reminder documents are read from. Under the CP protocol that is
346
- * the v2 control-plane client; the v1 timed-work route answers 405 for a
347
- * v2 deployment, which used to leave `list()` with only this process's
348
- * in-memory map (breaking arm idempotence and `cancelForContinuation`).
349
- */
350
- private get reminderReader(): ReminderReader | undefined {
351
- if (this.usesControlPlaneProtocol) {
352
- return this.controlPlane;
353
- }
354
- return this.platformTimers;
355
- }
356
-
357
- private logControlPlaneReadFailure(what: string, error: unknown): void {
358
- if (this.usesControlPlaneProtocol && this.controlPlaneReadFailureLogged) {
359
- return;
360
- }
361
- this.controlPlaneReadFailureLogged = true;
362
- this.logger(
363
- `[agent-sdk] reminders: control-plane ${what} failed: ${
364
- error instanceof Error ? error.message : String(error)
365
- }`,
366
- );
367
- }
368
-
369
- /**
370
- * Load reminder documents from the control plane into memory. Does not
371
- * arm in-process timers — the CP owns clocks.
372
- */
373
- async hydrate(): Promise<void> {
374
- const reader = this.reminderReader;
375
- if (reader === undefined) {
376
- return;
377
- }
378
- let remote: ReminderRecord[] = [];
379
- try {
380
- remote = await reader.listReminders();
381
- } catch (error) {
382
- this.logControlPlaneReadFailure("list", error);
383
- return;
384
- }
385
- this.controlPlaneReadFailureLogged = false;
386
- this.records.clear();
387
- for (const record of remote) {
388
- this.records.set(record.id, record);
389
- }
390
- if (this.usesControlPlaneProtocol) {
391
- // The CP owns status; a fire whose handler is missing reports `stop`
392
- // from executeFire instead of the guest writing a disarm.
393
- if (remote.length > 0) {
394
- this.logger(
395
- `[agent-sdk] reminders: hydrated ${remote.length} reminder(s) from control plane`,
396
- );
397
- }
398
- return;
399
- }
400
- let disarmedOrphan = 0;
401
- for (const record of [...this.records.values()]) {
402
- if (record.status !== "armed") {
403
- continue;
404
- }
405
- if (record.handler !== undefined) {
406
- if (this.namedHandlers.get(record.handler) === undefined) {
407
- await this.disarm(record, "handler_missing");
408
- disarmedOrphan += 1;
409
- }
410
- continue;
411
- }
412
- if (
413
- (record.hasRunHandler === true || record.hasUntilFn === true) &&
414
- this.handlers.get(record.id) === undefined
415
- ) {
416
- await this.disarm(record, "handler_lost_on_restart");
417
- disarmedOrphan += 1;
418
- }
419
- }
420
- if (remote.length > 0 || disarmedOrphan > 0) {
421
- this.logger(
422
- `[agent-sdk] reminders: hydrated ${remote.length} reminder(s) from control plane` +
423
- (disarmedOrphan > 0 ? `; disarmed ${disarmedOrphan} without live handlers` : ""),
424
- );
425
- }
426
- }
427
-
428
- /** Start deadline timers for armed reminders (tests / no control plane). */
429
- async start(): Promise<void> {
430
- if (this.started) return;
431
- this.started = true;
432
- await this.hydrate();
433
- if (this.platformTimers !== undefined) {
434
- return;
435
- }
436
- const armed = [...this.records.values()].filter(r => r.status === "armed");
437
- let restored = 0;
438
- let disarmedOrphan = 0;
439
- for (const record of armed) {
440
- if (record.handler !== undefined) {
441
- if (this.namedHandlers.get(record.handler) === undefined) {
442
- await this.disarm(record, "handler_missing");
443
- disarmedOrphan += 1;
444
- continue;
445
- }
446
- this.armTimer(record);
447
- restored += 1;
448
- continue;
449
- }
450
- if (
451
- (record.hasRunHandler === true || record.hasUntilFn === true) &&
452
- this.handlers.get(record.id) === undefined
453
- ) {
454
- await this.disarm(record, "handler_lost_on_restart");
455
- disarmedOrphan += 1;
456
- continue;
457
- }
458
- this.armTimer(record);
459
- restored += 1;
460
- }
461
- if (restored > 0 || disarmedOrphan > 0) {
462
- this.logger(
463
- `[agent-sdk] reminders: restored ${restored} armed reminder(s)` +
464
- (disarmedOrphan > 0 ? `; disarmed ${disarmedOrphan} without live handlers` : ""),
465
- );
466
- }
467
- }
468
-
469
- private async persist(record: ReminderRecord): Promise<void> {
470
- if (this.platformTimers !== undefined) {
471
- await this.platformTimers.putReminder(record);
472
- }
473
- this.records.set(record.id, record);
474
- }
475
-
476
- private async getRecord(id: string): Promise<ReminderRecord | undefined> {
477
- const reader = this.reminderReader;
478
- if (reader !== undefined) {
479
- try {
480
- const remote = await reader.getReminder(id);
481
- this.controlPlaneReadFailureLogged = false;
482
- if (remote === undefined) {
483
- this.records.delete(id);
484
- return undefined;
485
- }
486
- this.records.set(id, remote);
487
- return remote;
488
- } catch (error) {
489
- this.logControlPlaneReadFailure(`get for ${id}`, error);
490
- return this.records.get(id);
491
- }
492
- }
493
- return this.records.get(id);
494
- }
495
-
496
- /**
497
- * Under the CP protocol a list failure propagates: the in-memory map is
498
- * only what this process created, and returning it would let a caller
499
- * arm duplicates or miss rows to cancel. v1 keeps the best-effort form.
500
- */
501
- private async allRecords(): Promise<ReminderRecord[]> {
502
- const reader = this.reminderReader;
503
- if (reader !== undefined) {
504
- try {
505
- const remote = await reader.listReminders();
506
- this.controlPlaneReadFailureLogged = false;
507
- this.records.clear();
508
- for (const record of remote) {
509
- this.records.set(record.id, record);
510
- }
511
- } catch (error) {
512
- this.logControlPlaneReadFailure("list", error);
513
- if (this.usesControlPlaneProtocol) {
514
- throw error;
515
- }
516
- }
517
- }
518
- return [...this.records.values()];
519
- }
520
-
521
- stop(): void {
522
- this.started = false;
523
- for (const timer of this.timers.values()) {
524
- clearTimeout(timer);
525
- }
526
- this.timers.clear();
527
- this.idleGates.clear();
528
- }
529
-
530
- async create(input: ReminderCreateInput): Promise<ReminderInfo> {
531
- const hasPrompt = input.prompt !== undefined;
532
- const hasRun = input.run !== undefined;
533
- const hasHandler = input.handler !== undefined;
534
- const formCount = [hasPrompt, hasRun, hasHandler].filter(Boolean).length;
535
- if (formCount !== 1) {
536
- throw new ReminderValidationError(
537
- "reminders.create requires exactly one of prompt, handler, or run",
538
- );
539
- }
540
- if (input.continuationToken.trim() === "") {
541
- throw new ReminderValidationError("continuationToken is required");
542
- }
543
- if (input.channelId.trim() === "") {
544
- throw new ReminderValidationError("channelId is required");
545
- }
546
- if (input.purpose.trim() === "") {
547
- throw new ReminderValidationError("purpose is required");
548
- }
549
-
550
- const untilPrompt = typeof input.until === "string" ? input.until : undefined;
551
- const untilFn = typeof input.until === "function" ? input.until : undefined;
552
-
553
- if (hasHandler && input.until !== undefined) {
554
- throw new ReminderValidationError(
555
- "reminders.create: until is not valid with handler; encode the stop condition in args and the handler body",
556
- );
557
- }
558
-
559
- if (this.rejectAnonymousHandlers) {
560
- if (hasRun) {
561
- throw new ReminderValidationError(
562
- "reminders.create: anonymous run handlers are not durable on architecture v2; author reminders/<name>.ts under the project root and pass handler + args",
563
- );
564
- }
565
- if (untilFn !== undefined) {
566
- throw new ReminderValidationError(
567
- "reminders.create: function until is not durable on architecture v2; use a string until prompt",
568
- );
569
- }
570
- }
571
-
572
- let handlerName: string | undefined;
573
- let handlerArgs: JsonObject | undefined;
574
- if (hasHandler) {
575
- const handler = input.handler!;
576
- const name =
577
- typeof handler === "string" ? handler.trim() : this.namedHandlerNames.get(handler);
578
- if (name === undefined) {
579
- throw new ReminderValidationError(
580
- "Unknown reminder handler definition (expected a default export discovered under reminders/)",
581
- );
582
- }
583
- if (name === "") {
584
- throw new ReminderValidationError("handler name is required");
585
- }
586
- if (!isValidReminderHandlerName(name)) {
587
- throw new ReminderValidationError(
588
- name.includes("__")
589
- ? `Invalid reminder handler name "${name}": may not contain "__"`
590
- : `Invalid reminder handler name "${name}": must match ${NAME_PATTERN}`,
591
- );
592
- }
593
- if (this.namedHandlers.get(name) === undefined) {
594
- throw new ReminderValidationError(
595
- `Unknown reminder handler "${name}" (expected reminders/${name}.ts under the project root)`,
596
- );
597
- }
598
- if (input.args !== undefined && !isJsonObject(input.args)) {
599
- throw new ReminderValidationError("reminders.create args must be a JSON object");
600
- }
601
- handlerName = name;
602
- handlerArgs = input.args ?? {};
603
- assertReminderArgsSize(handlerArgs);
604
- } else if (input.args !== undefined) {
605
- throw new ReminderValidationError("reminders.create args is only valid with handler");
606
- }
607
-
608
- const schedule = resolveSchedule(input);
609
- const busyPolicy: ReminderBusyPolicy = input.busyPolicy ?? defaultBusyPolicy(schedule.kind);
610
- const hasRunHandler = input.run !== undefined;
611
- const hasUntilFn = untilFn !== undefined;
612
-
613
- let record: ReminderRecord;
614
- if (this.usesControlPlaneProtocol) {
615
- const intent: ReminderCreateIntent = {
616
- protocolVersion: REMINDER_CP_PROTOCOL_VERSION,
617
- purpose: input.purpose,
618
- channelId: input.channelId,
619
- continuationToken: input.continuationToken,
620
- target: input.target,
621
- // CP recalculates nextFireAtMs / intervalMs from the raw schedule.
622
- schedule: scheduleSpecFromCreateInput(input),
623
- prompt: input.prompt,
624
- handler: handlerName,
625
- args: handlerArgs,
626
- hasRunHandler,
627
- hasUntilFn,
628
- untilPrompt,
629
- busyPolicy,
630
- };
631
- record = await this.controlPlane!.createReminder(intent);
632
- this.records.set(record.id, record);
633
- } else {
634
- const now = new Date().toISOString();
635
- const id = newReminderId();
636
- record = {
637
- version: 1,
638
- id,
639
- purpose: input.purpose,
640
- channelId: input.channelId,
641
- continuationToken: input.continuationToken,
642
- target: input.target,
643
- scheduleKind: schedule.kind,
644
- scheduleValue: schedule.value,
645
- intervalMs: schedule.intervalMs,
646
- prompt: input.prompt,
647
- handler: handlerName,
648
- args: handlerArgs,
649
- hasRunHandler,
650
- hasUntilFn,
651
- untilPrompt,
652
- busyPolicy,
653
- status: "armed",
654
- fireCount: 0,
655
- nextFireAtMs: schedule.nextFireAtMs,
656
- generation: 0,
657
- createdAt: now,
658
- updatedAt: now,
659
- };
660
- await this.persist(record);
661
- }
662
-
663
- this.handlers.set(record.id, {
664
- run: input.run,
665
- untilFn,
666
- });
667
- if (this.started && this.platformTimers === undefined && !this.usesControlPlaneProtocol) {
668
- this.armTimer(record);
669
- }
670
-
671
- return toInfo(record);
672
- }
673
-
674
- async list(filter?: {
675
- status?: ReminderStatus;
676
- purpose?: string;
677
- continuationToken?: string;
678
- }): Promise<ReminderInfo[]> {
679
- const all = await this.allRecords();
680
- return all
681
- .filter(r => {
682
- if (filter?.status !== undefined) {
683
- const publicStatus = r.status === "firing" ? "armed" : r.status;
684
- if (publicStatus !== filter.status) {
685
- return false;
686
- }
687
- }
688
- if (filter?.purpose !== undefined && r.purpose !== filter.purpose) {
689
- return false;
690
- }
691
- if (
692
- filter?.continuationToken !== undefined &&
693
- r.continuationToken !== filter.continuationToken
694
- ) {
695
- return false;
696
- }
697
- return true;
698
- })
699
- .map(r => {
700
- const live = this.handlers.get(r.id);
701
- const info = toInfo(r);
702
- if (live === undefined) return info;
703
- return {
704
- ...info,
705
- hasRunHandler: live.run !== undefined || info.hasRunHandler,
706
- hasUntilFn: live.untilFn !== undefined || info.hasUntilFn,
707
- };
708
- });
709
- }
710
-
711
- async cancel(id: string, reason = "explicit_cancel"): Promise<ReminderInfo | undefined> {
712
- if (this.usesControlPlaneProtocol) {
713
- const updated = await this.controlPlane!.cancelReminder(id, reason);
714
- if (updated === undefined) {
715
- this.records.delete(id);
716
- this.handlers.delete(id);
717
- return undefined;
718
- }
719
- this.records.set(id, updated);
720
- this.handlers.delete(id);
721
- return toInfo(updated);
722
- }
723
- const record = await this.getRecord(id);
724
- if (record === undefined) {
725
- return undefined;
726
- }
727
- if (record.status !== "armed" && record.status !== "firing") {
728
- return toInfo(record);
729
- }
730
- this.clearTimer(id);
731
- const updated: ReminderRecord = {
732
- ...record,
733
- status: "cancelled",
734
- disarmReason: reason,
735
- generation: (record.generation ?? 0) + 1,
736
- updatedAt: new Date().toISOString(),
737
- };
738
- await this.persist(updated);
739
- this.handlers.delete(id);
740
- return toInfo(updated);
741
- }
742
-
743
- /** Cancel all armed reminders matching a continuation token (e.g. PR closed). */
744
- async cancelForContinuation(continuationToken: string, reason: string): Promise<number> {
745
- const armed = (await this.allRecords()).filter(r => r.status === "armed");
746
- let n = 0;
747
- for (const record of armed) {
748
- if (record.continuationToken === continuationToken) {
749
- await this.cancel(record.id, reason);
750
- n += 1;
751
- }
752
- }
753
- return n;
754
- }
755
-
756
- /**
757
- * Re-key armed reminders when a channel rotates a session's continuation
758
- * token (the built-in HTTP channel rotates after every follow-up). Without
759
- * this, a reminder armed before the rotation misses its session at fire
760
- * time and disarms as `session_gone`.
761
- */
762
- async rekeyContinuation(channelId: string, oldToken: string, newToken: string): Promise<number> {
763
- if (this.usesControlPlaneProtocol) {
764
- return this.controlPlane!.rekeyReminders(channelId, oldToken, newToken);
765
- }
766
- const armed = (await this.allRecords()).filter(
767
- r => r.status === "armed" || r.status === "firing",
768
- );
769
- let n = 0;
770
- for (const record of armed) {
771
- if (record.channelId !== channelId || record.continuationToken !== oldToken) {
772
- continue;
773
- }
774
- await this.persist({
775
- ...record,
776
- continuationToken: newToken,
777
- generation: (record.generation ?? 0) + 1,
778
- updatedAt: new Date().toISOString(),
779
- });
780
- n += 1;
781
- }
782
- return n;
783
- }
784
-
785
- /** Fire one reminder immediately (dev / hillclimb / control plane). */
786
- async dispatch(
787
- reminderId: string,
788
- opts: { expectedFireCount?: number } = {},
789
- ): Promise<{
790
- reminderId: string;
791
- outcome: "fired" | "noop";
792
- reason?: string;
793
- }> {
794
- const record = await this.getRecord(reminderId);
795
- if (record === undefined) {
796
- const ids = (await this.allRecords()).map(r => r.id);
797
- throw new UnknownReminderError(reminderId, ids);
798
- }
799
- if (opts.expectedFireCount !== undefined && record.fireCount !== opts.expectedFireCount) {
800
- return {
801
- reminderId,
802
- outcome: "noop",
803
- reason: "stale_fire_count",
804
- };
805
- }
806
- const result = await this.fire(record.id, { force: true });
807
- return { reminderId, ...result };
808
- }
809
-
810
- /**
811
- * Architecture v2 / CP protocol guest entrypoint: execute an immutable fire
812
- * descriptor and return an outcome. Does not mint ids or mutate
813
- * authoritative status/fireCount — the control plane applies the outcome.
814
- */
815
- async executeFire(descriptor: ReminderFireDescriptor): Promise<ReminderExecutionOutcome> {
816
- const record = this.recordFromDescriptor(descriptor);
817
- this.records.set(record.id, record);
818
- let fire: FireExecution;
819
- try {
820
- fire = await this.runFire(record);
821
- } catch (error) {
822
- // The hosted admission maps the throw to a retryable failure; count
823
- // it so the retry loop is visible beside the settled outcomes.
824
- this.recordFireOutcome(record, {
825
- kind: "error",
826
- reason: "fire_threw",
827
- detail: error instanceof Error ? error.message : String(error),
828
- });
829
- throw error;
830
- }
831
- this.recordFireOutcome(record, {
832
- kind: fire.outcome.kind,
833
- reason: fire.reason,
834
- turnStatus: fire.turnStatus,
835
- });
836
- return fire.outcome;
837
- }
838
-
839
- private async runFire(record: ReminderRecord): Promise<FireExecution> {
840
- const live = this.handlers.get(record.id) ?? {};
841
- if (record.handler !== undefined) {
842
- if (this.resolveNamedHandler(record.handler) === undefined) {
843
- return stopFire("handler_missing");
844
- }
845
- } else if (
846
- (record.hasRunHandler === true || record.hasUntilFn === true) &&
847
- live.run === undefined &&
848
- live.untilFn === undefined
849
- ) {
850
- return stopFire("handler_lost_on_restart");
851
- }
852
-
853
- if (live.untilFn !== undefined) {
854
- try {
855
- const done = await live.untilFn(this.buildUntilContext(record));
856
- if (done) {
857
- return stopFire("until_fn");
858
- }
859
- } catch (error) {
860
- this.logger(
861
- `[agent-sdk] reminder "${record.id}" until() failed: ${
862
- error instanceof Error ? error.message : String(error)
863
- }`,
864
- );
865
- }
866
- }
867
-
868
- if (await this.isSessionBusy(record.channelId, record.continuationToken)) {
869
- if (record.busyPolicy === "skipIfBusy") {
870
- return { outcome: { kind: "skipped" }, reason: "busy" };
871
- }
872
- await this.whenSessionIdle(record.channelId, record.continuationToken);
873
- }
874
-
875
- let result: ReminderFireResult;
876
- let reason: ReminderFireOutcomeReason;
877
- let turnStatus: TurnOutcome["status"] | undefined;
878
- if (record.handler !== undefined) {
879
- const named = this.resolveNamedHandler(record.handler);
880
- if (named === undefined) {
881
- return stopFire("handler_missing");
882
- }
883
- result = await named.run(this.buildFireContext(record));
884
- reason = runReason(result);
885
- } else if (live.run !== undefined) {
886
- result = await live.run(this.buildFireContext(record));
887
- reason = runReason(result);
888
- } else if (record.prompt !== undefined) {
889
- const delivery = await this.deliverPromptFire(record);
890
- result = delivery.result;
891
- reason = delivery.reason;
892
- turnStatus = delivery.turnStatus;
893
- } else {
894
- return stopFire("missing_handler");
895
- }
896
-
897
- if (result.action === "stop") {
898
- return { outcome: { kind: "stop", reason }, reason };
899
- }
900
- const reschedule =
901
- result.reschedule !== undefined ? toWireReschedule(result.reschedule) : undefined;
902
- return {
903
- outcome: {
904
- kind: result.action === "skip" ? "skipped" : "delivered",
905
- reschedule,
906
- },
907
- reason,
908
- turnStatus,
909
- };
910
- }
911
-
912
- /**
913
- * One structured line and one `agent_sdk.reminder.fire_outcome` count per
914
- * fire. Emitted through the host OTel meter, the same path hosted v2
915
- * exports turn/tool metrics on, so a fire that ends in `stop` is visible
916
- * beside the control plane's `timed_work.fire` count.
917
- */
918
- private recordFireOutcome(
919
- record: ReminderRecord,
920
- fire: {
921
- kind: ReminderExecutionOutcome["kind"] | "error";
922
- reason: ReminderFireOutcomeReason;
923
- turnStatus?: TurnOutcome["status"];
924
- detail?: string;
925
- },
926
- ): void {
927
- this.logger(
928
- `[agent-sdk] reminder fire_outcome kind=${fire.kind} reason=${fire.reason}` +
929
- ` reminderId=${record.id} purpose=${record.purpose}` +
930
- ` channelId=${record.channelId} fireCount=${record.fireCount}` +
931
- (fire.turnStatus === undefined ? "" : ` turn=${fire.turnStatus}`) +
932
- (fire.detail === undefined ? "" : ` detail=${JSON.stringify(fire.detail)}`),
933
- );
934
- // Test doubles may omit `host.otel`; the metric is best-effort.
935
- const otel: HostOtelApi | undefined = this.engine.host.otel;
936
- if (otel === undefined) {
937
- return;
938
- }
939
- try {
940
- otel.increment(REMINDER_FIRE_OUTCOME_METRIC, {
941
- kind: fire.kind,
942
- reason: fire.reason,
943
- purpose: record.purpose,
944
- });
945
- } catch (error) {
946
- this.logger(
947
- `[agent-sdk] reminder fire_outcome metric failed: ${
948
- error instanceof Error ? error.message : String(error)
949
- }`,
950
- );
951
- }
952
- }
953
-
954
- private recordFromDescriptor(descriptor: ReminderFireDescriptor): ReminderRecord {
955
- const now = new Date().toISOString();
956
- return {
957
- version: 1,
958
- id: descriptor.id,
959
- purpose: descriptor.purpose,
960
- channelId: descriptor.channelId,
961
- continuationToken: descriptor.continuationToken,
962
- target: descriptor.target,
963
- scheduleKind: descriptor.scheduleKind,
964
- scheduleValue: descriptor.scheduleValue,
965
- intervalMs: descriptor.intervalMs,
966
- prompt: descriptor.prompt,
967
- handler: descriptor.handler,
968
- args: descriptor.args,
969
- hasRunHandler: descriptor.hasRunHandler,
970
- hasUntilFn: descriptor.hasUntilFn,
971
- untilPrompt: descriptor.untilPrompt,
972
- busyPolicy: descriptor.busyPolicy,
973
- status: "firing",
974
- fireCount: descriptor.fireCount,
975
- nextFireAtMs: descriptor.nextFireAtMs,
976
- generation: descriptor.generation,
977
- createdAt: now,
978
- updatedAt: now,
979
- };
980
- }
981
-
982
- private armTimer(record: ReminderRecord): void {
983
- this.clearTimer(record.id);
984
- if (!this.started || record.status !== "armed") return;
985
- const nextFireAtMs = Number.isFinite(record.nextFireAtMs) ? record.nextFireAtMs : Date.now();
986
- const delay = Math.min(MAX_TIMER_MS, Math.max(0, nextFireAtMs - Date.now()));
987
- const timer = setTimeout(() => {
988
- void this.fire(record.id).catch(async error => {
989
- this.logger(
990
- `[agent-sdk] reminder "${record.id}" fire failed: ${
991
- error instanceof Error ? error.message : String(error)
992
- }`,
993
- );
994
- // Keep recurring reminders alive after unexpected throws.
995
- // One-shots stay armed so a failed wake can be retried / dispatched.
996
- try {
997
- const current = await this.getRecord(record.id);
998
- if (current === undefined || current.status !== "armed") return;
999
- const oneShot = current.scheduleKind === "delay" || current.scheduleKind === "at";
1000
- if (oneShot) {
1001
- this.armTimer(current);
1002
- return;
1003
- }
1004
- await this.afterFire(current, "skip");
1005
- } catch (rescheduleError) {
1006
- this.logger(
1007
- `[agent-sdk] reminder "${record.id}" reschedule after failure failed: ${
1008
- rescheduleError instanceof Error ? rescheduleError.message : String(rescheduleError)
1009
- }`,
1010
- );
1011
- }
1012
- });
1013
- }, delay);
1014
- timer.unref?.();
1015
- this.timers.set(record.id, timer);
1016
- }
1017
-
1018
- private clearTimer(id: string): void {
1019
- const timer = this.timers.get(id);
1020
- if (timer !== undefined) {
1021
- clearTimeout(timer);
1022
- this.timers.delete(id);
1023
- }
1024
- }
1025
-
1026
- private resolveNamedHandler(name: string): ReminderDefinition | undefined {
1027
- return this.namedHandlers.get(name);
1028
- }
1029
-
1030
- private async fire(
1031
- id: string,
1032
- opts: { force?: boolean } = {},
1033
- ): Promise<{ outcome: "fired" | "noop"; reason?: string }> {
1034
- if (this.firing.has(id)) {
1035
- return { outcome: "noop", reason: "already_firing" };
1036
- }
1037
- this.firing.add(id);
1038
- try {
1039
- const record = await this.getRecord(id);
1040
- if (record === undefined || record.status !== "armed") {
1041
- this.clearTimer(id);
1042
- return { outcome: "noop", reason: "not_armed" };
1043
- }
1044
-
1045
- if (!opts.force && record.nextFireAtMs > Date.now() + 50) {
1046
- // Spurious early wake — re-arm.
1047
- this.armTimer(record);
1048
- return { outcome: "noop", reason: "not_due" };
1049
- }
1050
-
1051
- const live = this.handlers.get(id) ?? {};
1052
- if (record.handler !== undefined) {
1053
- if (this.resolveNamedHandler(record.handler) === undefined) {
1054
- await this.disarm(record, "handler_missing");
1055
- return { outcome: "noop", reason: "handler_missing" };
1056
- }
1057
- } else if (
1058
- (record.hasRunHandler === true || record.hasUntilFn === true) &&
1059
- live.run === undefined &&
1060
- live.untilFn === undefined
1061
- ) {
1062
- await this.disarm(record, "handler_lost_on_restart");
1063
- return { outcome: "noop", reason: "handler_lost_on_restart" };
1064
- }
1065
-
1066
- const untilCtx = this.buildUntilContext(record);
1067
-
1068
- if (live.untilFn !== undefined) {
1069
- try {
1070
- const done = await live.untilFn(untilCtx);
1071
- if (done) {
1072
- await this.disarm(record, "until_fn");
1073
- return { outcome: "fired", reason: "until_fn" };
1074
- }
1075
- } catch (error) {
1076
- this.logger(
1077
- `[agent-sdk] reminder "${id}" until() failed: ${
1078
- error instanceof Error ? error.message : String(error)
1079
- }`,
1080
- );
1081
- }
1082
- }
1083
-
1084
- if (await this.isSessionBusy(record.channelId, record.continuationToken)) {
1085
- if (record.busyPolicy === "skipIfBusy") {
1086
- await this.afterFire(record, "skip");
1087
- this.logger(`[agent-sdk] reminder "${id}" (${record.purpose}) skipped: session busy`);
1088
- return { outcome: "fired", reason: "skipped_busy" };
1089
- }
1090
- await this.whenSessionIdle(record.channelId, record.continuationToken);
1091
- const still = await this.getRecord(id);
1092
- if (still === undefined || still.status !== "armed") {
1093
- return { outcome: "noop", reason: "disarmed_while_waiting" };
1094
- }
1095
- }
1096
-
1097
- let result: ReminderFireResult;
1098
- if (record.handler !== undefined) {
1099
- const named = this.resolveNamedHandler(record.handler);
1100
- if (named === undefined) {
1101
- await this.disarm(record, "handler_missing");
1102
- return { outcome: "noop", reason: "handler_missing" };
1103
- }
1104
- result = await named.run(this.buildFireContext(record));
1105
- } else if (live.run !== undefined) {
1106
- result = await live.run(this.buildFireContext(record));
1107
- } else if (record.prompt !== undefined) {
1108
- result = await this.deliverPrompt(record);
1109
- } else {
1110
- await this.disarm(record, "missing_handler");
1111
- return { outcome: "noop", reason: "missing_handler" };
1112
- }
1113
-
1114
- // Cancel / disarm during the handler must win over reschedule.
1115
- const latest = await this.getRecord(id);
1116
- if (result.action === "stop") {
1117
- if (latest !== undefined && latest.status === "armed") {
1118
- await this.disarm(latest, "run_stop");
1119
- this.logger(`[agent-sdk] reminder "${id}" (${record.purpose}) disarmed: run_stop`);
1120
- return { outcome: "fired", reason: "run_stop" };
1121
- }
1122
- return {
1123
- outcome: "fired",
1124
- reason: latest?.disarmReason ?? "run_stop",
1125
- };
1126
- }
1127
- if (latest === undefined || latest.status !== "armed") {
1128
- return { outcome: "noop", reason: "disarmed_during_fire" };
1129
- }
1130
-
1131
- if (result.action === "skip") {
1132
- await this.afterFire(latest, "skip", result.reschedule);
1133
- this.logger(`[agent-sdk] reminder "${id}" (${record.purpose}) skipped`);
1134
- return { outcome: "fired", reason: "skipped" };
1135
- }
1136
- await this.afterFire(latest, "delivered", result.reschedule);
1137
- this.logger(`[agent-sdk] reminder "${id}" (${record.purpose}) fired`);
1138
- return { outcome: "fired", reason: "delivered" };
1139
- } finally {
1140
- this.firing.delete(id);
1141
- }
1142
- }
1143
-
1144
- private async isSessionBusy(channelId: string, continuationToken: string): Promise<boolean> {
1145
- const existing = await this.engine.sessions.findByContinuation(channelId, continuationToken);
1146
- if (existing === undefined) return false;
1147
- return this.engine.isTurnRunning(existing.sessionId);
1148
- }
1149
-
1150
- private whenSessionIdle(channelId: string, continuationToken: string): Promise<void> {
1151
- const sessionKey = `${channelId}:${continuationToken}`;
1152
- const existing = this.idleGates.get(sessionKey);
1153
- if (existing !== undefined) return existing;
1154
-
1155
- const gate = (async () => {
1156
- const session = await this.engine.sessions.findByContinuation(channelId, continuationToken);
1157
- if (session === undefined) return;
1158
- await this.engine.waitForCompletion(session.sessionId);
1159
- })().finally(() => {
1160
- this.idleGates.delete(sessionKey);
1161
- });
1162
- this.idleGates.set(sessionKey, gate);
1163
- return gate;
1164
- }
1165
-
1166
- /**
1167
- * Follow-ups must use the bound session's principal. If the session is gone,
1168
- * disarm rather than creating a fresh APP_AUTH conversation.
1169
- */
1170
- private async resolveFollowupAuth(
1171
- channelId: string,
1172
- continuationToken: string,
1173
- ): Promise<AuthContext | null | undefined> {
1174
- const existing = await this.engine.sessions.findByContinuation(channelId, continuationToken);
1175
- if (existing !== undefined) {
1176
- return existing.auth;
1177
- }
1178
- return undefined;
1179
- }
1180
-
1181
- private async deliverPrompt(record: ReminderRecord): Promise<ReminderFireResult> {
1182
- return (await this.deliverPromptFire(record)).result;
1183
- }
1184
-
1185
- /**
1186
- * Where a prompt fire joins. The pod's own store first; on a hosted guest
1187
- * the durable mirror next, because the pod that armed the reminder is
1188
- * usually gone and the session lives only in storage. A restored session
1189
- * keeps its own principal (channel admissions may carry a sender), so the
1190
- * fire joins under that, never under {@link ReminderHostedGuestOptions.fireAuth}.
1191
- */
1192
- private async resolveFollowupTarget(record: ReminderRecord): Promise<FollowupTarget> {
1193
- const local = await this.resolveFollowupAuth(record.channelId, record.continuationToken);
1194
- if (local !== undefined) {
1195
- return { auth: local, reached: "session_joined" };
1196
- }
1197
- if (this.hostedGuest === undefined) {
1198
- return { auth: undefined, reached: "session_gone" };
1199
- }
1200
- // Materializes the durable record locally; a storage error propagates
1201
- // and the hosted admission retries the fire.
1202
- const restored = await this.engine.hasContinuationSession(
1203
- record.channelId,
1204
- record.continuationToken,
1205
- );
1206
- if (!restored) {
1207
- return { auth: undefined, reached: "session_gone" };
1208
- }
1209
- const auth = await this.resolveFollowupAuth(record.channelId, record.continuationToken);
1210
- return auth === undefined
1211
- ? { auth: undefined, reached: "session_unreadable" }
1212
- : { auth, reached: "session_restored" };
1213
- }
1214
-
1215
- private async deliverPromptFire(record: ReminderRecord): Promise<PromptDelivery> {
1216
- const target = await this.resolveFollowupTarget(record);
1217
- if (target.auth !== undefined) {
1218
- return this.promptDelivery(record, target.auth, target.reached);
1219
- }
1220
- if (target.reached === "session_unreadable") {
1221
- this.logger(
1222
- `[agent-sdk] reminder "${record.id}" (${record.purpose}) durable session did not materialize locally; not opening a new one`,
1223
- );
1224
- return { result: { action: "stop" }, reason: "session_gone" };
1225
- }
1226
- if (
1227
- this.hostedGuest !== undefined &&
1228
- this.channelUsesControlPlaneContinuation(record.channelId)
1229
- ) {
1230
- // No session on this pod and none in durable storage. Open one on the
1231
- // stored key the way an inbound event on a fresh key does, instead of
1232
- // consuming the fire with no turn.
1233
- const fireAuth = this.hostedGuest.fireAuth();
1234
- if (fireAuth === undefined) {
1235
- return {
1236
- result: {
1237
- action: "skip",
1238
- reschedule: { delay: REMINDER_SESSION_OPEN_RETRY_DELAY },
1239
- },
1240
- reason: "session_gone",
1241
- };
1242
- }
1243
- try {
1244
- return await this.promptDelivery(record, fireAuth, "session_opened");
1245
- } catch (error) {
1246
- if (!(error instanceof SessionAuthError)) {
1247
- throw error;
1248
- }
1249
- // A session landed on this key under another principal between the
1250
- // lookup and the send. That does not change on retry, so stop
1251
- // rather than let the control plane re-admit until its attempt cap.
1252
- this.logger(
1253
- `[agent-sdk] reminder "${record.id}" (${record.purpose}) cannot join session on its continuation: ${error.message}`,
1254
- );
1255
- return { result: { action: "stop" }, reason: "session_gone" };
1256
- }
1257
- }
1258
- // Under CP protocol, return stop and let the CP apply/CAS; do not
1259
- // mutate authoritative status from the guest mid-fire.
1260
- if (!this.usesControlPlaneProtocol) {
1261
- await this.disarm(record, "session_gone");
1262
- }
1263
- return { result: { action: "stop" }, reason: "session_gone" };
1264
- }
1265
-
1266
- private async promptDelivery(
1267
- record: ReminderRecord,
1268
- auth: AuthContext | null,
1269
- delivered: Extract<
1270
- ReminderFireOutcomeReason,
1271
- "session_joined" | "session_restored" | "session_opened"
1272
- >,
1273
- ): Promise<PromptDelivery> {
1274
- const settle: FollowupSettle = {};
1275
- const result = await this.sendFollowup(record, buildFirePrompt(record), auth, settle);
1276
- return {
1277
- result,
1278
- reason: result.action === "skip" ? (settle.skipReason ?? "busy") : delivered,
1279
- turnStatus: settle.turnStatus,
1280
- };
1281
- }
1282
-
1283
- /**
1284
- * Join the reminder's existing session. Control-plane (`/v2`) channels
1285
- * refuse authored `continuationToken`; pass the stored key as
1286
- * {@link EngineSendOptions.mailboxContinuation} so the engine reuses the
1287
- * CP-selected identity without channel admission.
1288
- */
1289
- private followupSendOptions(record: ReminderRecord, auth: AuthContext | null): EngineSendOptions {
1290
- if (this.channelUsesControlPlaneContinuation(record.channelId)) {
1291
- return {
1292
- auth,
1293
- mailboxContinuation: { key: record.continuationToken },
1294
- };
1295
- }
1296
- return {
1297
- auth,
1298
- continuationToken: record.continuationToken,
1299
- };
1300
- }
1301
-
1302
- private channelUsesControlPlaneContinuation(channelId: string): boolean {
1303
- const project = this.engine.project;
1304
- // Test doubles may omit `project`; keep the legacy continuationToken path.
1305
- if (project === undefined) {
1306
- return false;
1307
- }
1308
- const identity =
1309
- channelId === HTTP_CHANNEL_ID
1310
- ? httpContinuationIdentity(project.httpChannel)
1311
- : channelContinuationIdentity(
1312
- project.channels.find(channel => channel.id === channelId)?.definition,
1313
- );
1314
- return continuationSource(identity) === "control-plane";
1315
- }
1316
-
1317
- /**
1318
- * Local and v1 track the turn in the background: the process outlives the
1319
- * fire. A hosted v2 guest waits for the turn and its durable writes first,
1320
- * because the control plane may stop the pod as soon as the fire's
1321
- * outcome is applied, and `delivered` must mean the turn ran.
1322
- */
1323
- private async settleFollowup(
1324
- session: ChannelSession,
1325
- settle: FollowupSettle | undefined,
1326
- ): Promise<void> {
1327
- const completion = this.engine.waitForCompletion(session.id);
1328
- if (this.hostedGuest === undefined) {
1329
- this.engine.trackBackground(completion);
1330
- return;
1331
- }
1332
- const outcome = await completion;
1333
- await this.engine.drainSessionDurability(session.id);
1334
- if (settle !== undefined) {
1335
- settle.turnStatus = outcome.status;
1336
- }
1337
- }
1338
-
1339
- private async sendFollowup(
1340
- record: ReminderRecord,
1341
- message: string,
1342
- auth: AuthContext | null,
1343
- settle?: FollowupSettle,
1344
- extra?: ReminderFollowupOptions,
1345
- ): Promise<ReminderFireResult> {
1346
- const sendOptions: EngineSendOptions = {
1347
- ...this.followupSendOptions(record, auth),
1348
- state: extra?.state,
1349
- refreshState: extra?.refreshState,
1350
- title: extra?.title,
1351
- clearCloudOverride: extra?.clearCloudOverride,
1352
- };
1353
- try {
1354
- const session = await this.engine.send(record.channelId, message, sendOptions);
1355
- await this.settleFollowup(session, settle);
1356
- return { action: "delivered" };
1357
- } catch (error) {
1358
- if (error instanceof SessionBusyError) {
1359
- if (record.busyPolicy === "skipIfBusy") {
1360
- if (settle !== undefined) {
1361
- settle.skipReason = "busy";
1362
- }
1363
- return { action: "skip" };
1364
- }
1365
- await this.whenSessionIdle(record.channelId, record.continuationToken);
1366
- try {
1367
- const session = await this.engine.send(record.channelId, message, sendOptions);
1368
- await this.settleFollowup(session, settle);
1369
- return { action: "delivered" };
1370
- } catch (retryError) {
1371
- this.logger(
1372
- `[agent-sdk] reminder "${record.id}" followup failed after wait: ${
1373
- retryError instanceof Error ? retryError.message : String(retryError)
1374
- }`,
1375
- );
1376
- if (settle !== undefined) {
1377
- settle.skipReason = "followup_failed";
1378
- }
1379
- return { action: "skip" };
1380
- }
1381
- }
1382
- throw error;
1383
- }
1384
- }
1385
-
1386
- private buildFireContext(record: ReminderRecord): ReminderFireContext {
1387
- const self = this;
1388
- return {
1389
- id: record.id,
1390
- purpose: record.purpose,
1391
- fireCount: record.fireCount,
1392
- target: {
1393
- channelId: record.channelId,
1394
- continuationToken: record.continuationToken,
1395
- ...(record.target ?? {}),
1396
- },
1397
- args: record.args ?? {},
1398
- host: this.engine.host,
1399
- mcp: this.engine.host.mcp,
1400
- appAuth: APP_AUTH,
1401
- artifacts: this.engine.artifacts,
1402
- async followup(args: { message: string } & ReminderFollowupOptions) {
1403
- const target = await self.resolveFollowupTarget(record);
1404
- let auth = target.auth;
1405
- // `openAuth` opens only when nothing exists anywhere: an unreadable
1406
- // durable session must not be shadowed by a second one on the same
1407
- // key (prompt-fire parity).
1408
- if (
1409
- auth === undefined &&
1410
- target.reached === "session_gone" &&
1411
- args.openAuth !== undefined
1412
- ) {
1413
- auth = args.openAuth;
1414
- }
1415
- if (auth === undefined) {
1416
- // Under the CP protocol the guest never writes reminder status;
1417
- // the fire's `stop` outcome carries the reason instead.
1418
- if (!self.usesControlPlaneProtocol) {
1419
- await self.disarm(record, "session_gone");
1420
- }
1421
- throw new Error(`Reminder "${record.id}" followup: session gone for continuation`);
1422
- }
1423
- const result = await self.sendFollowup(record, args.message, auth, undefined, args);
1424
- if (result.action === "skip") {
1425
- throw new Error(`Reminder "${record.id}" followup skipped: session busy`);
1426
- }
1427
- const existing = await self.engine.sessions.findByContinuation(
1428
- record.channelId,
1429
- record.continuationToken,
1430
- );
1431
- if (existing === undefined) {
1432
- throw new Error(`Reminder "${record.id}" followup: session not found for continuation`);
1433
- }
1434
- const session = await self.engine.getChannelSession(record.channelId, existing.sessionId);
1435
- if (session === null) {
1436
- throw new Error(`Reminder "${record.id}" followup: channel session missing`);
1437
- }
1438
- return session;
1439
- },
1440
- async cancel(reason = "handler_cancel") {
1441
- await self.cancel(record.id, reason);
1442
- },
1443
- };
1444
- }
1445
-
1446
- private buildUntilContext(record: ReminderRecord): ReminderUntilContext {
1447
- return {
1448
- id: record.id,
1449
- purpose: record.purpose,
1450
- fireCount: record.fireCount,
1451
- target: {
1452
- channelId: record.channelId,
1453
- continuationToken: record.continuationToken,
1454
- ...(record.target ?? {}),
1455
- },
1456
- host: this.engine.host,
1457
- mcp: this.engine.host.mcp,
1458
- };
1459
- }
1460
-
1461
- private async disarm(record: ReminderRecord, reason: string): Promise<void> {
1462
- this.clearTimer(record.id);
1463
- const updated: ReminderRecord = {
1464
- ...record,
1465
- status: "disarmed",
1466
- disarmReason: reason,
1467
- updatedAt: new Date().toISOString(),
1468
- };
1469
- await this.persist(updated);
1470
- this.handlers.delete(record.id);
1471
- }
1472
-
1473
- private async afterFire(
1474
- record: ReminderRecord,
1475
- _outcome: "skip" | "delivered",
1476
- reschedule?: { delay?: string | number; at?: Date | string },
1477
- ): Promise<void> {
1478
- const current = await this.getRecord(record.id);
1479
- if (current === undefined || current.status !== "armed") {
1480
- return;
1481
- }
1482
-
1483
- const now = Date.now();
1484
- const oneShot = current.scheduleKind === "delay" || current.scheduleKind === "at";
1485
-
1486
- if (reschedule !== undefined) {
1487
- let nextFireAtMs: number;
1488
- if (reschedule.delay !== undefined) {
1489
- nextFireAtMs = now + parseDuration(reschedule.delay);
1490
- } else if (reschedule.at !== undefined) {
1491
- nextFireAtMs =
1492
- reschedule.at instanceof Date
1493
- ? reschedule.at.getTime()
1494
- : Date.parse(String(reschedule.at));
1495
- if (!Number.isFinite(nextFireAtMs)) {
1496
- throw new ReminderValidationError(`Invalid reschedule.at for reminder "${current.id}"`);
1497
- }
1498
- } else {
1499
- throw new ReminderValidationError(
1500
- `reschedule requires delay or at for reminder "${current.id}"`,
1501
- );
1502
- }
1503
- const updated: ReminderRecord = {
1504
- ...current,
1505
- fireCount: current.fireCount + 1,
1506
- nextFireAtMs,
1507
- // Promote to one-shot-from-now semantics if they rescheduled
1508
- scheduleKind: reschedule.delay !== undefined ? "delay" : "at",
1509
- scheduleValue:
1510
- reschedule.delay !== undefined ? String(reschedule.delay) : String(reschedule.at),
1511
- updatedAt: new Date().toISOString(),
1512
- };
1513
- await this.persist(updated);
1514
- if (this.platformTimers === undefined) {
1515
- this.armTimer(updated);
1516
- }
1517
- return;
1518
- }
1519
-
1520
- if (oneShot) {
1521
- this.clearTimer(current.id);
1522
- const updated: ReminderRecord = {
1523
- ...current,
1524
- fireCount: current.fireCount + 1,
1525
- status: "completed",
1526
- disarmReason: "one_shot_complete",
1527
- updatedAt: new Date().toISOString(),
1528
- };
1529
- await this.persist(updated);
1530
- this.handlers.delete(current.id);
1531
- return;
1532
- }
1533
-
1534
- // Recurring
1535
- let nextFireAtMs: number;
1536
- if (current.scheduleKind === "every" && current.intervalMs !== undefined) {
1537
- nextFireAtMs = now + current.intervalMs;
1538
- } else if (current.scheduleKind === "cron") {
1539
- nextFireAtMs = nextCronFireMs(current.scheduleValue, now);
1540
- } else {
1541
- throw new Error(
1542
- `Reminder "${current.id}" has recurring status with scheduleKind=${current.scheduleKind}`,
1543
- );
1544
- }
1545
- const updated: ReminderRecord = {
1546
- ...current,
1547
- fireCount: current.fireCount + 1,
1548
- nextFireAtMs,
1549
- updatedAt: new Date().toISOString(),
1550
- };
1551
- await this.persist(updated);
1552
- if (this.platformTimers === undefined) {
1553
- this.armTimer(updated);
1554
- }
1555
- }
1556
- }
1557
-
1558
- // Re-export store record type for tests
1559
- export type { ReminderRecord } from "./reminder-store.js";