@capybara-hq/kernel 0.1.0-rc.105 → 0.1.0-rc.107

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 (359) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/agents/agents.schemas.d.ts +9 -9
  3. package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
  4. package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
  5. package/dist/automations/automations.module.d.ts +16 -0
  6. package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
  7. package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
  8. package/dist/automations/automations.schemas.js +253 -0
  9. package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
  10. package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
  11. package/dist/{schedules → automations}/calendar.d.ts +8 -8
  12. package/dist/{schedules → automations}/calendar.js +2 -2
  13. package/dist/automations/effective-settings.d.ts +28 -0
  14. package/dist/automations/effective-settings.js +25 -0
  15. package/dist/automations/errors.d.ts +19 -0
  16. package/dist/automations/errors.js +19 -0
  17. package/dist/automations/events/coalesce.d.ts +28 -0
  18. package/dist/automations/events/coalesce.js +131 -0
  19. package/dist/automations/events/deadline.d.ts +10 -0
  20. package/dist/automations/events/deadline.js +24 -0
  21. package/dist/automations/events/dispatcher.d.ts +74 -0
  22. package/dist/automations/events/dispatcher.js +353 -0
  23. package/dist/automations/events/events.module.d.ts +7 -0
  24. package/dist/automations/events/events.module.js +26 -0
  25. package/dist/automations/events/guards.d.ts +32 -0
  26. package/dist/automations/events/guards.js +87 -0
  27. package/dist/automations/events/sweep.job.d.ts +49 -0
  28. package/dist/automations/events/sweep.job.js +202 -0
  29. package/dist/automations/events/token.d.ts +5 -0
  30. package/dist/automations/events/token.js +5 -0
  31. package/dist/automations/events/trigger-events.service.d.ts +47 -0
  32. package/dist/automations/events/trigger-events.service.js +254 -0
  33. package/dist/{schedules → automations}/fire.d.ts +57 -17
  34. package/dist/{schedules → automations}/fire.js +311 -79
  35. package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
  36. package/dist/{schedules → automations}/grant-rules.js +5 -5
  37. package/dist/automations/job-ids.d.ts +113 -0
  38. package/dist/automations/job-ids.js +117 -0
  39. package/dist/{schedules → automations}/pause.d.ts +3 -3
  40. package/dist/{schedules → automations}/pause.js +3 -3
  41. package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
  42. package/dist/{schedules → automations}/run-tracker.js +68 -56
  43. package/dist/{schedules → automations}/scan.job.d.ts +12 -8
  44. package/dist/{schedules → automations}/scan.job.js +39 -23
  45. package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
  46. package/dist/{schedules → automations}/schedule-math.js +17 -7
  47. package/dist/{schedules → automations}/store.d.ts +57 -27
  48. package/dist/{schedules → automations}/store.js +102 -52
  49. package/dist/automations/store.module.d.ts +6 -0
  50. package/dist/{schedules → automations}/store.module.js +9 -9
  51. package/dist/automations/types.d.ts +178 -0
  52. package/dist/{schedules → automations}/unattended.d.ts +22 -11
  53. package/dist/{schedules → automations}/unattended.js +53 -30
  54. package/dist/catalog/marketplaces.service.d.ts +1 -1
  55. package/dist/channels/channels.module.js +7 -6
  56. package/dist/channels/file-delivery.d.ts +26 -11
  57. package/dist/channels/file-delivery.js +32 -11
  58. package/dist/channels/outbound.d.ts +8 -8
  59. package/dist/channels/outbound.js +32 -30
  60. package/dist/channels/threads.d.ts +1 -1
  61. package/dist/channels/threads.js +1 -1
  62. package/dist/config/schema.d.ts +8 -1
  63. package/dist/config/schema.js +56 -6
  64. package/dist/conversations/approval-profile.d.ts +2 -2
  65. package/dist/conversations/approval-profile.js +3 -3
  66. package/dist/conversations/artifacts.d.ts +20 -17
  67. package/dist/conversations/artifacts.js +30 -37
  68. package/dist/conversations/attachments.controller.d.ts +6 -19
  69. package/dist/conversations/attachments.controller.js +8 -59
  70. package/dist/conversations/attachments.service.d.ts +30 -74
  71. package/dist/conversations/attachments.service.js +51 -193
  72. package/dist/conversations/conversations.controller.d.ts +7 -1
  73. package/dist/conversations/conversations.controller.js +26 -10
  74. package/dist/conversations/conversations.module.js +4 -0
  75. package/dist/conversations/conversations.service.d.ts +112 -35
  76. package/dist/conversations/conversations.service.js +160 -43
  77. package/dist/conversations/event-log.d.ts +1 -0
  78. package/dist/conversations/events.d.ts +95 -27
  79. package/dist/conversations/events.js +108 -10
  80. package/dist/conversations/files.d.ts +66 -64
  81. package/dist/conversations/files.js +127 -147
  82. package/dist/conversations/message-context.d.ts +2 -2
  83. package/dist/conversations/message-context.js +1 -1
  84. package/dist/conversations/permission-profile-store.d.ts +2 -1
  85. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  86. package/dist/conversations/permission-profiles.service.js +1 -1
  87. package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
  88. package/dist/conversations/prompt-suggestion-request.js +4 -2
  89. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  90. package/dist/conversations/prompt-suggestions.js +11 -10
  91. package/dist/conversations/queue.d.ts +7 -4
  92. package/dist/conversations/queue.js +6 -2
  93. package/dist/conversations/queue.service.d.ts +5 -5
  94. package/dist/conversations/queue.service.js +27 -16
  95. package/dist/ctx/create-ctx.d.ts +23 -2
  96. package/dist/ctx/create-ctx.js +78 -3
  97. package/dist/db/kernel-schema.d.ts +184 -27
  98. package/dist/devices/device-project-files.service.d.ts +88 -0
  99. package/dist/devices/device-project-files.service.js +249 -0
  100. package/dist/devices/device-projects.service.d.ts +40 -0
  101. package/dist/devices/device-projects.service.js +16 -13
  102. package/dist/devices/devices.controller.d.ts +9 -3
  103. package/dist/devices/devices.controller.js +27 -5
  104. package/dist/devices/devices.module.js +9 -1
  105. package/dist/devices/devices.schemas.js +6 -1
  106. package/dist/devices/dto.d.ts +15 -0
  107. package/dist/devices/dto.js +11 -0
  108. package/dist/devices/project-paths.d.ts +29 -0
  109. package/dist/devices/project-paths.js +66 -0
  110. package/dist/devices/project-rules.d.ts +5 -1
  111. package/dist/devices/project-rules.js +5 -1
  112. package/dist/errors.d.ts +53 -13
  113. package/dist/errors.js +53 -13
  114. package/dist/evals/canonical-json.d.ts +7 -0
  115. package/dist/evals/canonical-json.js +21 -0
  116. package/dist/evals/reconstruct.d.ts +10 -1
  117. package/dist/evals/reconstruct.js +20 -1
  118. package/dist/evals/recorded-tools.d.ts +0 -2
  119. package/dist/evals/recorded-tools.js +1 -16
  120. package/dist/evals/snapshot.d.ts +26 -3
  121. package/dist/evals/snapshot.js +110 -57
  122. package/dist/evals/worker.d.ts +4 -3
  123. package/dist/evals/worker.js +8 -4
  124. package/dist/extensions/host.d.ts +9 -2
  125. package/dist/extensions/host.js +12 -0
  126. package/dist/extensions/instance.d.ts +3 -1
  127. package/dist/extensions/instance.js +4 -0
  128. package/dist/extensions/ledger.d.ts +1 -1
  129. package/dist/extensions/permission-set.d.ts +17 -1
  130. package/dist/extensions/permission-set.js +13 -1
  131. package/dist/extensions/permission-view.d.ts +1 -1
  132. package/dist/extensions/permission-view.js +4 -1
  133. package/dist/files/blob-objects.d.ts +124 -0
  134. package/dist/files/blob-objects.js +341 -0
  135. package/dist/files/blob-sweep.job.d.ts +122 -0
  136. package/dist/files/blob-sweep.job.js +389 -0
  137. package/dist/files/blobs.service.d.ts +135 -0
  138. package/dist/files/blobs.service.js +300 -0
  139. package/dist/files/conversation-media.d.ts +41 -0
  140. package/dist/files/conversation-media.js +124 -0
  141. package/dist/files/deliveries.d.ts +64 -0
  142. package/dist/files/deliveries.js +156 -0
  143. package/dist/files/deliveries.module.d.ts +6 -0
  144. package/dist/files/deliveries.module.js +24 -0
  145. package/dist/files/draft-cleanup.job.d.ts +26 -0
  146. package/dist/files/draft-cleanup.job.js +93 -0
  147. package/dist/files/files.module.d.ts +1 -1
  148. package/dist/files/files.module.js +3 -2
  149. package/dist/files/hash-job.d.ts +127 -0
  150. package/dist/files/hash-job.js +447 -0
  151. package/dist/files/library-backfill.d.ts +63 -0
  152. package/dist/files/library-backfill.js +143 -0
  153. package/dist/files/library-files.service.d.ts +255 -0
  154. package/dist/files/library-files.service.js +883 -0
  155. package/dist/files/library-jobs.module.d.ts +8 -0
  156. package/dist/files/library-jobs.module.js +27 -0
  157. package/dist/files/library-query.d.ts +127 -0
  158. package/dist/files/library-query.js +322 -0
  159. package/dist/files/library-read.module.d.ts +9 -0
  160. package/dist/files/library-read.module.js +30 -0
  161. package/dist/files/library.controller.d.ts +77 -0
  162. package/dist/files/library.controller.js +235 -0
  163. package/dist/files/library.module.d.ts +9 -0
  164. package/dist/files/library.module.js +29 -0
  165. package/dist/files/library.schemas.d.ts +46 -0
  166. package/dist/files/library.schemas.js +49 -0
  167. package/dist/files/previewers.controller.d.ts +20 -0
  168. package/dist/files/previewers.controller.js +47 -0
  169. package/dist/files/previewers.d.ts +25 -11
  170. package/dist/files/previewers.js +43 -27
  171. package/dist/files/referenced-files.d.ts +150 -0
  172. package/dist/files/referenced-files.js +234 -0
  173. package/dist/git/gateway.js +2 -2
  174. package/dist/html/html-document.controller.d.ts +8 -1
  175. package/dist/html/html-document.controller.js +19 -1
  176. package/dist/html/html-document.service.d.ts +19 -4
  177. package/dist/html/html-document.service.js +43 -22
  178. package/dist/html/html-token.d.ts +10 -1
  179. package/dist/html/html-token.js +14 -0
  180. package/dist/html/html.module.js +8 -1
  181. package/dist/http/api.module.js +10 -5
  182. package/dist/http/request-signal.d.ts +8 -0
  183. package/dist/http/request-signal.js +14 -0
  184. package/dist/identity/settings.d.ts +26 -0
  185. package/dist/identity/settings.js +33 -2
  186. package/dist/inbox/inbox.module.js +2 -2
  187. package/dist/inbox/inbox.service.d.ts +8 -8
  188. package/dist/inbox/inbox.service.js +7 -7
  189. package/dist/infra/config/kernel-config.service.js +10 -5
  190. package/dist/infra/outbox/registry.d.ts +111 -2
  191. package/dist/infra/outbox/registry.js +104 -9
  192. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  193. package/dist/infra/throttler/named-throttlers.js +14 -0
  194. package/dist/kernel.module.js +3 -0
  195. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  196. package/dist/models/purposes.js +1 -1
  197. package/dist/orgs/offboarding.js +1 -1
  198. package/dist/orgs/roles.d.ts +1 -1
  199. package/dist/orgs/roles.js +3 -3
  200. package/dist/orgs/settings.controller.d.ts +1 -1
  201. package/dist/orgs/settings.service.d.ts +75 -13
  202. package/dist/orgs/settings.service.js +104 -26
  203. package/dist/platform/exclusions.js +45 -8
  204. package/dist/platform/file-ref.d.ts +18 -3
  205. package/dist/platform/file-ref.js +22 -11
  206. package/dist/platform/operation.js +6 -2
  207. package/dist/platform/ops/admin.ops.js +5 -2
  208. package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
  209. package/dist/platform/ops/automations.ops.js +560 -0
  210. package/dist/platform/ops/devices.ops.d.ts +3 -1
  211. package/dist/platform/ops/devices.ops.js +77 -3
  212. package/dist/platform/ops/files.ops.d.ts +18 -0
  213. package/dist/platform/ops/files.ops.js +267 -0
  214. package/dist/platform/ops/inbox.ops.js +4 -4
  215. package/dist/platform/ops/org-settings.ops.js +6 -2
  216. package/dist/platform/ops/orgs.ops.js +2 -1
  217. package/dist/platform/ops/platform.ops.js +4 -4
  218. package/dist/platform/ops/shares.ops.js +2 -2
  219. package/dist/platform/platform-ops.module.d.ts +3 -2
  220. package/dist/platform/platform-ops.module.js +10 -5
  221. package/dist/platform/route-schemas.js +6 -3
  222. package/dist/push/jobs.d.ts +3 -3
  223. package/dist/push/jobs.js +2 -2
  224. package/dist/push/preferences.service.js +1 -1
  225. package/dist/push/push-owed.d.ts +3 -3
  226. package/dist/push/push-owed.js +6 -6
  227. package/dist/push/push.schemas.d.ts +4 -4
  228. package/dist/push/push.schemas.js +3 -3
  229. package/dist/push/recipients.d.ts +4 -4
  230. package/dist/push/recipients.js +23 -23
  231. package/dist/push/texts.d.ts +3 -3
  232. package/dist/push/texts.js +2 -2
  233. package/dist/push/triggers.d.ts +1 -1
  234. package/dist/roles/worker.module.js +18 -4
  235. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  236. package/dist/runtime/compaction-settings.service.js +16 -1
  237. package/dist/runtime/compaction.service.d.ts +3 -1
  238. package/dist/runtime/compaction.service.js +3 -1
  239. package/dist/runtime/context/build.d.ts +24 -1
  240. package/dist/runtime/context/build.js +33 -11
  241. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  242. package/dist/runtime/context/cache-expiry.js +60 -0
  243. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  244. package/dist/runtime/context/cache-ttl.js +30 -0
  245. package/dist/runtime/context/compaction.d.ts +9 -2
  246. package/dist/runtime/context/compaction.js +64 -21
  247. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  248. package/dist/runtime/context/in-context-compaction.js +310 -0
  249. package/dist/runtime/context/run-context.d.ts +38 -0
  250. package/dist/runtime/context/run-context.js +54 -0
  251. package/dist/runtime/hook-calls.d.ts +2 -1
  252. package/dist/runtime/hook-calls.js +5 -2
  253. package/dist/runtime/maintenance.d.ts +16 -4
  254. package/dist/runtime/maintenance.js +79 -18
  255. package/dist/runtime/model-call.d.ts +34 -5
  256. package/dist/runtime/model-call.js +207 -22
  257. package/dist/runtime/providers.js +11 -1
  258. package/dist/runtime/run-finish.d.ts +4 -4
  259. package/dist/runtime/run-finish.js +3 -3
  260. package/dist/runtime/run-queue.js +12 -7
  261. package/dist/runtime/run-steps.d.ts +4 -2
  262. package/dist/runtime/run-steps.js +10 -5
  263. package/dist/runtime/run-worker.js +7 -1
  264. package/dist/runtime/runtime.module.js +6 -3
  265. package/dist/runtime/subagents/dispatch.js +11 -3
  266. package/dist/sandbox/browse-roots.d.ts +8 -0
  267. package/dist/sandbox/browse-roots.js +22 -0
  268. package/dist/sandbox/network-grants.d.ts +4 -4
  269. package/dist/sandbox/network-grants.js +7 -7
  270. package/dist/sandbox/operation-authority.d.ts +10 -3
  271. package/dist/sandbox/operation-authority.js +20 -10
  272. package/dist/sandbox/operation-intents.d.ts +3 -1
  273. package/dist/sandbox/operation-intents.js +11 -4
  274. package/dist/sandbox/permission-call-grants.js +2 -2
  275. package/dist/sandbox/permission-facts.js +1 -1
  276. package/dist/sandbox/review/classifier.d.ts +2 -2
  277. package/dist/sandbox/review/classifier.js +22 -11
  278. package/dist/sandbox/review/permission-candidate.d.ts +1 -1
  279. package/dist/sandbox/review/permission-candidate.js +1 -1
  280. package/dist/sandbox/sandbox.service.d.ts +15 -5
  281. package/dist/sandbox/sandbox.service.js +14 -8
  282. package/dist/shares/liveness.d.ts +26 -12
  283. package/dist/shares/liveness.js +79 -20
  284. package/dist/shares/revoke.d.ts +16 -11
  285. package/dist/shares/revoke.js +18 -14
  286. package/dist/shares/share-objects.d.ts +16 -21
  287. package/dist/shares/share-objects.js +25 -55
  288. package/dist/shares/share-open.service.d.ts +8 -4
  289. package/dist/shares/share-open.service.js +14 -11
  290. package/dist/shares/shares.controller.d.ts +16 -5
  291. package/dist/shares/shares.controller.js +39 -5
  292. package/dist/shares/shares.module.d.ts +4 -4
  293. package/dist/shares/shares.module.js +7 -6
  294. package/dist/shares/shares.schemas.d.ts +4 -0
  295. package/dist/shares/shares.schemas.js +2 -0
  296. package/dist/shares/shares.service.d.ts +93 -54
  297. package/dist/shares/shares.service.js +292 -131
  298. package/dist/shares/sweep.job.d.ts +18 -39
  299. package/dist/shares/sweep.job.js +47 -206
  300. package/dist/storage/purge.d.ts +1 -1
  301. package/dist/storage/purge.js +2 -2
  302. package/dist/tools/approvals.service.d.ts +6 -6
  303. package/dist/tools/approvals.service.js +19 -19
  304. package/dist/tools/builtin-names.d.ts +12 -12
  305. package/dist/tools/builtin-names.js +29 -29
  306. package/dist/tools/builtins/artifacts.d.ts +21 -13
  307. package/dist/tools/builtins/artifacts.js +81 -51
  308. package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
  309. package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
  310. package/dist/tools/builtins/builtin-tools.d.ts +15 -9
  311. package/dist/tools/builtins/builtin-tools.js +33 -22
  312. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  313. package/dist/tools/builtins/conversation-files.js +62 -83
  314. package/dist/tools/builtins/image/generate.d.ts +7 -1
  315. package/dist/tools/builtins/image/generate.js +1 -1
  316. package/dist/tools/builtins/platform.js +1 -0
  317. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  318. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  319. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  320. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  321. package/dist/tools/call-scope.d.ts +1 -1
  322. package/dist/tools/git-asks.js +1 -1
  323. package/dist/tools/git-push-policy.d.ts +3 -3
  324. package/dist/tools/git-push-policy.js +6 -6
  325. package/dist/tools/network-asks.d.ts +3 -3
  326. package/dist/tools/network-asks.js +3 -3
  327. package/dist/tools/pipeline.d.ts +4 -4
  328. package/dist/tools/pipeline.js +2 -2
  329. package/dist/tools/policy.d.ts +3 -3
  330. package/dist/tools/policy.js +3 -3
  331. package/dist/tools/tools.module.js +15 -9
  332. package/dist/ui/call-extension.d.ts +6 -4
  333. package/dist/ui/call-extension.js +5 -4
  334. package/dist/ui/embed-token.js +6 -3
  335. package/dist/ui/registry.d.ts +21 -5
  336. package/dist/ui/registry.js +24 -6
  337. package/dist/ui/ui.schemas.d.ts +22 -0
  338. package/dist/ui/ui.schemas.js +22 -4
  339. package/dist/ui/views.controller.d.ts +13 -3
  340. package/dist/ui/views.controller.js +33 -2
  341. package/dist/ui/views.d.ts +29 -1
  342. package/dist/ui/views.js +131 -7
  343. package/package.json +3 -3
  344. package/src/migrations/0188_automations_rename.sql +309 -0
  345. package/src/migrations/0189_event_automations.sql +136 -0
  346. package/src/migrations/0190_file_library.sql +285 -0
  347. package/src/migrations/0191_file_library_copy.sql +4 -0
  348. package/dist/platform/ops/schedules.ops.js +0 -509
  349. package/dist/schedules/effective-settings.d.ts +0 -22
  350. package/dist/schedules/effective-settings.js +0 -18
  351. package/dist/schedules/errors.d.ts +0 -8
  352. package/dist/schedules/errors.js +0 -8
  353. package/dist/schedules/job-ids.d.ts +0 -81
  354. package/dist/schedules/job-ids.js +0 -95
  355. package/dist/schedules/schedules.module.d.ts +0 -16
  356. package/dist/schedules/schedules.schemas.js +0 -213
  357. package/dist/schedules/store.module.d.ts +0 -6
  358. package/dist/schedules/types.d.ts +0 -110
  359. /package/dist/{schedules → automations}/types.js +0 -0
@@ -8,13 +8,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { CHANNEL_EXTENSION_POINT } from "@capybara-hq/plugin-sdk";
11
+ import { CHANNEL_EXTENSION_POINT, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { AgentLookup } from "../agents/agent-lookup.js";
14
14
  import { ConversationAccess } from "../conversations/access.js";
15
15
  import { readMessageContext } from "../conversations/message-context.js";
16
16
  import { ApiError } from "../errors.js";
17
+ import { ExtensionDisplayNames } from "../extensions/display-name.js";
17
18
  import { enabledExtensionsByOrg, isExtensionEnabled } from "../extensions/enabled.js";
19
+ import { ExtensionPointDefaults } from "../extensions/point-defaults.js";
18
20
  import { ExtensionRegistry } from "../extensions/registry.js";
19
21
  import { loadPeople } from "../identity/account-avatar.js";
20
22
  import { audit } from "../identity/audit.js";
@@ -34,13 +36,15 @@ import { SandboxService } from "../sandbox/sandbox.service.js";
34
36
  import { isTimeZone } from "../time-zone.js";
35
37
  import { ToolRegistry } from "../tools/registry.js";
36
38
  import { assembleCalendar, CALENDAR_LIMITS, CALENDAR_RANGE_DAYS, CALENDAR_TASK_RANGE_DAYS, calendarRunReadLimit, } from "./calendar.js";
37
- import { readScheduleSettings } from "./effective-settings.js";
38
- import { grantNotAllowed, scheduleDisabled, scheduleForbidden, scheduleNotFound, targetInvalid, } from "./errors.js";
39
+ import { readAutomationSettings } from "./effective-settings.js";
40
+ import { automationDisabled, automationForbidden, automationNotFound, eventSourceUnavailable, eventTypeUnknown, filterInvalid, grantNotAllowed, runNowUnsupported, targetInvalid, } from "./errors.js";
41
+ import { TriggerSourceTimeout, withDeadline } from "./events/deadline.js";
42
+ import { validateFilter } from "./events/guards.js";
39
43
  import { GIT_GRANT_SPEC_HASH, GIT_PUSH_GRANT, gitGrantRefusal, grantRefusal, grantRefusalOf, isGitGrantKey, isNetworkGrantKey, isPolicyGrantKey, isTierGrantKey, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantHost, networkGrantRefusal, normalizeGitGrantKey, tierGrantRefusal, } from "./grant-rules.js";
40
- import { oweSchedFire, oweSchedSettleUnfired } from "./job-ids.js";
44
+ import { oweAutomationFire, oweAutomationSettleUnfired } from "./job-ids.js";
41
45
  import { pauseTaskIn } from "./pause.js";
42
46
  import { jitterForGap, minGapMinutes, nextTick, validateTrigger } from "./schedule-math.js";
43
- import { ScheduledTaskStore } from "./store.js";
47
+ import { AutomationStore, runOrderMoment } from "./store.js";
44
48
  export { grantRefusal, grantRefusalOf, networkGrantRefusal, };
45
49
  /** The refusal of a network grant written outside a person's web session. */
46
50
  const NETWORK_GRANT_NEEDS_PERSON = "Network domains are approved on the task page by a person.";
@@ -60,16 +64,16 @@ const PROMPT_MAX = 20_000;
60
64
  /** A DM thread's key on `channel_threads` (`channels/threads.ts` `threadKeyOf`). */
61
65
  const DM_THREAD_PREFIX = "dm:";
62
66
  /**
63
- * Scheduled tasks for people (spec §5, §7–§10): create, edit, pause, resume, delete, their runs
67
+ * Automations for people (spec §5, §7–§10): create, edit, pause, resume, delete, their runs
64
68
  * and grants. Every write runs in one transaction under the org row lock (`OrgLock`), which also
65
69
  * serializes the per-member and per-org caps, re-reads the actor's role there, and holds the task
66
70
  * row (`FOR UPDATE`) so the scanner skips it until the write commits.
67
71
  *
68
- * Roles: `schedules.use` (member) creates and edits one's own tasks; `schedules.manage` (admin)
72
+ * Roles: `automations.use` (member) creates and edits one's own tasks; `automations.manage` (admin)
69
73
  * lists, pauses, resumes and deletes any task of the org, never edits another person's (the task
70
- * runs as its creator). A task the caller may not see is `schedule.not_found`.
74
+ * runs as its creator). A task the caller may not see is `automation.not_found`.
71
75
  */
72
- let ScheduledTasksService = class ScheduledTasksService {
76
+ let AutomationsService = class AutomationsService {
73
77
  db;
74
78
  txHost;
75
79
  config;
@@ -83,13 +87,17 @@ let ScheduledTasksService = class ScheduledTasksService {
83
87
  log;
84
88
  outbox;
85
89
  sandbox;
90
+ points;
91
+ displayNames;
86
92
  constructor(db, txHost, config, store, orgLock, agents, access, tools, extensions,
87
93
  /** A task's model must resolve for the org and declare its effort (as a message's switch). */
88
94
  providers, log,
89
95
  /** "Run now" owes the fire job (consumed by the worker role). */
90
96
  outbox,
91
97
  /** Network grants: the org's sandbox-mode network (network ask-to-allow spec §8.1). */
92
- sandbox) {
98
+ sandbox,
99
+ /** Event automations: the trigger sources that serve an org (`trigger-source@1`). */
100
+ points, displayNames) {
93
101
  this.db = db;
94
102
  this.txHost = txHost;
95
103
  this.config = config;
@@ -103,32 +111,43 @@ let ScheduledTasksService = class ScheduledTasksService {
103
111
  this.log = log;
104
112
  this.outbox = outbox;
105
113
  this.sandbox = sandbox;
114
+ this.points = points;
115
+ this.displayNames = displayNames;
106
116
  }
107
117
  async create(orgId, accountId, input, browserTimeZone, source = {}) {
108
- const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "schedules.use");
118
+ const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "automations.use");
109
119
  const t = this.db.db;
110
- const settings = await readScheduleSettings(t, this.config, orgId);
120
+ const settings = await readAutomationSettings(t, this.config, orgId);
111
121
  if (!settings.enabled)
112
- throw scheduleDisabled();
122
+ throw automationDisabled();
113
123
  if ((await this.store.countActive(t, orgId, accountId)) >= settings.maxTasksPerMember) {
114
- throw new ApiError("schedule.limit_reached", `You already have ${settings.maxTasksPerMember} scheduled tasks in this organization; delete one to create another`);
124
+ throw new ApiError("automation.limit_reached", `You already have ${settings.maxTasksPerMember} automations in this organization; delete one to create another`);
115
125
  }
116
126
  if ((await this.store.countActive(t, orgId)) >= settings.maxTasksPerOrg) {
117
- throw new ApiError("schedule.limit_reached", `This organization already has ${settings.maxTasksPerOrg} scheduled tasks; delete one to create another`);
127
+ throw new ApiError("automation.limit_reached", `This organization already has ${settings.maxTasksPerOrg} automations; delete one to create another`);
118
128
  }
119
129
  const name = requiredText(input.name, "name", NAME_MAX);
120
130
  const prompt = requiredText(input.prompt, "prompt", PROMPT_MAX);
121
131
  const agent = await this.agents.get(orgId, input.agentId, accountId);
122
- const timeZone = input.timeZone ??
123
- (await readMessageContext(t, {
124
- orgId,
125
- accountId,
126
- ...(browserTimeZone !== undefined && { browser: { timeZone: browserTimeZone } }),
127
- })).timeZone ??
128
- "UTC";
129
132
  const now = new Date();
130
- const trigger = withZone(input.trigger, timeZone);
131
- const gap = checkTrigger(trigger, now, settings);
133
+ let trigger;
134
+ let gap = null;
135
+ if (input.trigger.kind === "event") {
136
+ trigger = await this.checkEventTrigger(orgId, input.trigger, settings);
137
+ }
138
+ else {
139
+ const timeZone = input.timeZone ??
140
+ (await readMessageContext(t, {
141
+ orgId,
142
+ accountId,
143
+ ...(browserTimeZone !== undefined && { browser: { timeZone: browserTimeZone } }),
144
+ })).timeZone ??
145
+ "UTC";
146
+ const timed = withZone(input.trigger, timeZone);
147
+ gap = checkTrigger(timed, now, settings);
148
+ trigger = timed;
149
+ }
150
+ checkModeFits(input.mode, trigger);
132
151
  const target = {
133
152
  mode: input.mode,
134
153
  conversationId: input.conversationId ?? null,
@@ -155,6 +174,7 @@ let ScheduledTasksService = class ScheduledTasksService {
155
174
  trigger,
156
175
  ...target,
157
176
  ...pick,
177
+ unattendedAsk: input.unattendedAsk ?? null,
158
178
  status: "active",
159
179
  nextRunAt: fireAt(trigger, now, jitter),
160
180
  jitterSeconds: jitter,
@@ -165,7 +185,7 @@ let ScheduledTasksService = class ScheduledTasksService {
165
185
  await audit(t, {
166
186
  actorAccountId: accountId,
167
187
  orgId,
168
- action: "schedule.created",
188
+ action: "automation.created",
169
189
  target: id,
170
190
  detail: {
171
191
  name,
@@ -177,12 +197,12 @@ let ScheduledTasksService = class ScheduledTasksService {
177
197
  });
178
198
  return task;
179
199
  }
180
- /** Creator only: an org admin gets `schedule.forbidden`, anyone else `schedule.not_found`. */
200
+ /** Creator only: an org admin gets `automation.forbidden`, anyone else `automation.not_found`. */
181
201
  async update(orgId, accountId, id, patch) {
182
- const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "schedules.use");
202
+ const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "automations.use");
183
203
  const t = this.db.db;
184
204
  const task = await this.lockOwn(orgId, accountId, role, id);
185
- const settings = await readScheduleSettings(t, this.config, orgId);
205
+ const settings = await readAutomationSettings(t, this.config, orgId);
186
206
  const now = new Date();
187
207
  const changes = {};
188
208
  if (patch.name !== undefined)
@@ -220,12 +240,26 @@ let ScheduledTasksService = class ScheduledTasksService {
220
240
  await this.checkTarget(orgId, accountId, agentId, target);
221
241
  Object.assign(changes, target);
222
242
  }
223
- if (patch.trigger !== undefined || patch.timeZone !== undefined) {
224
- const zone = patch.timeZone ?? task.trigger.timeZone;
243
+ if (patch.trigger?.kind === "event") {
244
+ // an event automation has no zone, tick or jitter: the next run time is cleared
245
+ changes.trigger = await this.checkEventTrigger(orgId, patch.trigger, settings);
246
+ changes.jitterSeconds = 0;
247
+ changes.nextRunAt = null;
248
+ }
249
+ else if (patch.trigger !== undefined || patch.timeZone !== undefined) {
250
+ // an event automation has no zone or tick to keep: a time trigger replacing its event
251
+ // trigger names both
252
+ const current = task.trigger.kind === "event" ? null : task.trigger;
253
+ const zone = patch.timeZone ?? current?.timeZone;
225
254
  const base = patch.trigger ??
226
- (task.trigger.kind === "cron"
227
- ? { kind: "cron", expr: task.trigger.expr }
228
- : { kind: "once", at: task.trigger.at });
255
+ (current === null
256
+ ? undefined
257
+ : current.kind === "cron"
258
+ ? { kind: "cron", expr: current.expr }
259
+ : { kind: "once", at: current.at });
260
+ if (zone === undefined || base === undefined) {
261
+ throw new ApiError("validation_failed", "An event automation takes a new trigger and a time zone together");
262
+ }
229
263
  const trigger = withZone(base, zone);
230
264
  const gap = checkTrigger(trigger, now, settings);
231
265
  changes.trigger = trigger;
@@ -234,13 +268,23 @@ let ScheduledTasksService = class ScheduledTasksService {
234
268
  changes.nextRunAt = fireAt(trigger, now, changes.jitterSeconds);
235
269
  }
236
270
  }
237
- // model, effort and device: `new` mode only (leaving it clears them), checked when they or
238
- // the agent change
239
- const pick = target.mode === "new"
271
+ // the mode and the trigger after the patch must fit (subject needs events, chat needs time)
272
+ if (patch.trigger !== undefined || patch.mode !== undefined) {
273
+ checkModeFits(target.mode, changes.trigger ?? task.trigger);
274
+ }
275
+ if (patch.unattendedAsk !== undefined)
276
+ changes.unattendedAsk = patch.unattendedAsk;
277
+ // model, effort and device: `new` mode takes all three and `subject` mode a model and effort
278
+ // (leaving them clears them), checked when they or the agent change
279
+ const pick = target.mode === "new" || target.mode === "subject"
240
280
  ? {
241
281
  model: patch.model !== undefined ? patch.model : task.model,
242
282
  effort: patch.effort !== undefined ? patch.effort : task.effort,
243
- deviceId: patch.deviceId !== undefined ? patch.deviceId : task.deviceId,
283
+ deviceId: target.mode === "subject"
284
+ ? (patch.deviceId ?? null)
285
+ : patch.deviceId !== undefined
286
+ ? patch.deviceId
287
+ : task.deviceId,
244
288
  }
245
289
  : {
246
290
  model: patch.model ?? null,
@@ -267,13 +311,13 @@ let ScheduledTasksService = class ScheduledTasksService {
267
311
  await audit(t, {
268
312
  actorAccountId: accountId,
269
313
  orgId,
270
- action: "schedule.updated",
314
+ action: "automation.updated",
271
315
  target: task.id,
272
316
  detail: { fields: Object.keys(changes).sort() },
273
317
  });
274
318
  return updated;
275
319
  }
276
- /** The creator, or an org admin (`schedules.manage`); a task not active is returned as is. */
320
+ /** The creator, or an org admin (`automations.manage`); a task not active is returned as is. */
277
321
  async pause(orgId, actor, id) {
278
322
  const { task, byAdmin } = await this.lockManaged(orgId, actor.accountId, id, "org.read");
279
323
  if (task.status !== "active")
@@ -287,29 +331,30 @@ let ScheduledTasksService = class ScheduledTasksService {
287
331
  await audit(this.db.db, {
288
332
  actorAccountId: actor.accountId,
289
333
  orgId,
290
- action: "schedule.paused",
334
+ action: "automation.paused",
291
335
  target: task.id,
292
336
  detail: { reason: byAdmin ? "admin" : "creator", creator: task.accountId },
293
337
  });
294
338
  return paused ?? task;
295
339
  }
296
340
  /**
297
- * The creator (`schedules.use`), or an org admin. The next run is computed from now (missed ticks
341
+ * The creator (`automations.use`), or an org admin. The next run is computed from now (missed ticks
298
342
  * are not caught up) and the failure count starts over. An ended task cannot be resumed.
299
343
  */
300
344
  async resume(orgId, actor, id) {
301
- const { task, byAdmin } = await this.lockManaged(orgId, actor.accountId, id, "schedules.use");
345
+ const { task, byAdmin } = await this.lockManaged(orgId, actor.accountId, id, "automations.use");
302
346
  if (task.status === "active")
303
347
  return task;
304
348
  if (task.status === "ended")
305
- throw new ApiError("conflict", "This scheduled task has ended");
306
- const settings = await readScheduleSettings(this.db.db, this.config, orgId);
349
+ throw new ApiError("conflict", "This automation has ended");
350
+ const settings = await readAutomationSettings(this.db.db, this.config, orgId);
307
351
  if (!settings.enabled)
308
- throw scheduleDisabled();
352
+ throw automationDisabled();
309
353
  const now = new Date();
310
- const next = fireAt(task.trigger, now, task.jitterSeconds);
311
- if (next === null) {
312
- throw new ApiError("schedule.once_in_past", "The task's time has passed; set a new time");
354
+ // an event automation has no next run time
355
+ const next = task.trigger.kind === "event" ? null : fireAt(task.trigger, now, task.jitterSeconds);
356
+ if (next === null && task.trigger.kind !== "event") {
357
+ throw new ApiError("automation.once_in_past", "The task's time has passed; set a new time");
313
358
  }
314
359
  const resumed = await this.store.updateTask(this.db.db, task.id, {
315
360
  status: "active",
@@ -321,7 +366,7 @@ let ScheduledTasksService = class ScheduledTasksService {
321
366
  await audit(this.db.db, {
322
367
  actorAccountId: actor.accountId,
323
368
  orgId,
324
- action: "schedule.resumed",
369
+ action: "automation.resumed",
325
370
  target: task.id,
326
371
  detail: { byAdmin, creator: task.accountId },
327
372
  });
@@ -334,7 +379,7 @@ let ScheduledTasksService = class ScheduledTasksService {
334
379
  await audit(this.db.db, {
335
380
  actorAccountId: actor.accountId,
336
381
  orgId,
337
- action: "schedule.deleted",
382
+ action: "automation.deleted",
338
383
  target: task.id,
339
384
  detail: { byAdmin, creator: task.accountId, name: task.name },
340
385
  });
@@ -343,8 +388,8 @@ let ScheduledTasksService = class ScheduledTasksService {
343
388
  async get(orgId, actor, id) {
344
389
  const role = await this.liveRole(orgId, actor.accountId);
345
390
  const task = await this.store.getTask(this.db.db, orgId, id);
346
- if (!task || (task.accountId !== actor.accountId && !can(role, "schedules.manage"))) {
347
- throw scheduleNotFound();
391
+ if (!task || (task.accountId !== actor.accountId && !can(role, "automations.manage"))) {
392
+ throw automationNotFound();
348
393
  }
349
394
  const [view] = await this.withAccounts([task]);
350
395
  return view;
@@ -359,8 +404,8 @@ let ScheduledTasksService = class ScheduledTasksService {
359
404
  const role = await this.liveRole(orgId, actor.accountId);
360
405
  let tasks;
361
406
  if (opts.all === true) {
362
- if (!can(role, "schedules.manage")) {
363
- throw new ApiError("forbidden", "Only org admins can list every scheduled task");
407
+ if (!can(role, "automations.manage")) {
408
+ throw new ApiError("forbidden", "Only org admins can list every automation");
364
409
  }
365
410
  tasks = await this.store.listForOrg(this.db.db, orgId);
366
411
  }
@@ -375,16 +420,16 @@ let ScheduledTasksService = class ScheduledTasksService {
375
420
  /**
376
421
  * The calendar between two instants (calendar spec §5): the runs and planned occurrences of the
377
422
  * actor's own tasks, or with `all` (org admins only, else `forbidden`) every task of the org; with
378
- * `taskId` only that task (one the actor may see, else `schedule.not_found`), never collapsed.
423
+ * `taskId` only that task (one the actor may see, else `automation.not_found`), never collapsed.
379
424
  * Another creator's runs come without `conversationId`, `error` and `missingGrants` (§15 Q3).
380
425
  * A range longer than 43 days (2 with `taskId`), or not forward, is `validation_failed`. `now`
381
426
  * is for tests.
382
427
  */
383
428
  async calendar(orgId, actor, q, now = new Date(), limits = CALENDAR_LIMITS) {
384
429
  const role = await this.liveRole(orgId, actor.accountId);
385
- const manage = can(role, "schedules.manage");
430
+ const manage = can(role, "automations.manage");
386
431
  if (q.all === true && !manage) {
387
- throw new ApiError("forbidden", "Only org admins can read every scheduled task");
432
+ throw new ApiError("forbidden", "Only org admins can read every automation");
388
433
  }
389
434
  const span = q.to.getTime() - q.from.getTime();
390
435
  const maxDays = q.taskId === undefined ? CALENDAR_RANGE_DAYS : CALENDAR_TASK_RANGE_DAYS;
@@ -398,7 +443,7 @@ let ScheduledTasksService = class ScheduledTasksService {
398
443
  if (q.taskId !== undefined) {
399
444
  const task = await this.store.getTask(t, orgId, q.taskId);
400
445
  if (!task || (task.accountId !== actor.accountId && !manage))
401
- throw scheduleNotFound();
446
+ throw automationNotFound();
402
447
  tasks = [task];
403
448
  }
404
449
  else {
@@ -410,7 +455,7 @@ let ScheduledTasksService = class ScheduledTasksService {
410
455
  const runs = await this.store.listRunsBetween(t, orgId, tasks.map((x) => x.id), q.from, q.to,
411
456
  // one row past the caps tells the assembly where to cut
412
457
  calendarRunReadLimit(limits));
413
- const settings = await readScheduleSettings(t, this.config, orgId);
458
+ const settings = await readAutomationSettings(t, this.config, orgId);
414
459
  return assembleCalendar({
415
460
  tasks,
416
461
  runs,
@@ -450,18 +495,18 @@ let ScheduledTasksService = class ScheduledTasksService {
450
495
  return [];
451
496
  const tasks = await this.withAccounts(plain);
452
497
  const rows = await this.db.db
453
- .selectFrom("scheduled_task_runs")
454
- .select(["task_id", "status", "skip_reason", "fired_at", "scheduled_for"])
455
- .distinctOn("task_id")
498
+ .selectFrom("automation_runs")
499
+ .select(["automation_id", "status", "skip_reason", "fired_at", "scheduled_for", "created_at"])
500
+ .distinctOn("automation_id")
456
501
  .where("org_id", "=", orgId)
457
- .where("task_id", "in", tasks.map((t) => t.id))
502
+ .where("automation_id", "in", tasks.map((t) => t.id))
458
503
  .where("trial", "=", false)
459
504
  .where("status", "in", ["completed", "failed", "skipped"])
460
- .orderBy("task_id")
461
- .orderBy("scheduled_for", "desc")
505
+ .orderBy("automation_id")
506
+ .orderBy(runOrderMoment, "desc")
462
507
  .orderBy("id", "desc")
463
508
  .execute();
464
- const last = new Map(rows.map((r) => [r.task_id, r]));
509
+ const last = new Map(rows.map((r) => [r.automation_id, r]));
465
510
  return tasks.map((t) => {
466
511
  const r = last.get(t.id);
467
512
  return {
@@ -471,15 +516,97 @@ let ScheduledTasksService = class ScheduledTasksService {
471
516
  : {
472
517
  status: r.status,
473
518
  skipReason: r.skip_reason,
474
- at: new Date(r.fired_at ?? r.scheduled_for),
519
+ at: runMoment(r.fired_at, r.scheduled_for, r.created_at),
475
520
  },
476
521
  };
477
522
  });
478
523
  }
524
+ /**
525
+ * The trigger sources that serve the org now (`trigger-source@1` providers enabled in it with a
526
+ * valid config) and the org has not switched off (`eventSourcesOff`), each with its extension's
527
+ * display name and event declarations: what the automation form builds its event picker and
528
+ * filter rows from. A source whose `events()` fails or does not answer within `tools.timeoutMs`
529
+ * is left out (logged), so one broken source does not take the others' list down.
530
+ */
531
+ async eventSources(orgId) {
532
+ const settings = await readAutomationSettings(this.db.db, this.config, orgId);
533
+ const { providers } = await this.points.providersFor(orgId, "trigger-source");
534
+ const on = providers.filter((p) => !settings.eventSourcesOff.includes(p.extension));
535
+ const declared = await Promise.all(on.map(async (p) => {
536
+ try {
537
+ return { p, events: await this.declaredEvents(p) };
538
+ }
539
+ catch (err) {
540
+ this.log.warn("trigger source events() failed; left out of the event sources", {
541
+ orgId,
542
+ plugin: p.extension,
543
+ err,
544
+ });
545
+ return null;
546
+ }
547
+ }));
548
+ const ok = declared.filter((d) => d !== null);
549
+ const names = await this.displayNames.many(ok.map((d) => d.p.extension));
550
+ return ok.map(({ p, events }) => ({
551
+ source: p.extension,
552
+ name: names.get(p.extension) ?? { zh: p.extension, en: p.extension },
553
+ events,
554
+ }));
555
+ }
556
+ /** A trigger source's declarations, within `tools.timeoutMs` (as the dispatcher asks it). */
557
+ async declaredEvents(p) {
558
+ const ms = this.config.get().tools.timeoutMs;
559
+ return withDeadline(p.extension, "events()", ms, () => p.impl.events());
560
+ }
561
+ /**
562
+ * An event trigger as stored: the source must serve the org and not be switched off
563
+ * (`automation.event_source_unavailable`), every type must be declared by it and not directed
564
+ * (`automation.event_type_unknown`: a directed event wakes one agent through acceptance, never
565
+ * through an automation), and the filter must fit the selected types' facts
566
+ * (`automation.filter_invalid`). Whether an owner may see a subject is not checked here: dispatch
567
+ * enforces it through the source's `visible()` for the automation's owner.
568
+ */
569
+ async checkEventTrigger(orgId, input, settings) {
570
+ const source = input.source.trim();
571
+ const { providers } = await this.points.providersFor(orgId, "trigger-source");
572
+ const provider = providers.find((p) => p.extension === source);
573
+ if (provider === undefined || settings.eventSourcesOff.includes(source)) {
574
+ throw eventSourceUnavailable(`${source} is not an event source of this organization (it must be an enabled extension that provides trigger events, and not switched off in the automation settings)`);
575
+ }
576
+ let declared;
577
+ try {
578
+ declared = await this.declaredEvents(provider);
579
+ }
580
+ catch (err) {
581
+ this.log.warn("trigger source events() failed while checking an event trigger", {
582
+ orgId,
583
+ plugin: source,
584
+ err,
585
+ });
586
+ throw eventSourceUnavailable(`${source} did not answer with its event types (${err instanceof TriggerSourceTimeout ? "it timed out" : "it failed"}); try again later, or use another source or a schedule`);
587
+ }
588
+ const types = [...new Set(input.types.map((x) => x.trim()))];
589
+ const decls = [];
590
+ for (const type of types) {
591
+ const d = declared.find((e) => e.type === type);
592
+ if (d === undefined) {
593
+ throw eventTypeUnknown(`${source} declares no event type "${type}"; it declares: ${declared.map((e) => e.type).join(", ") || "none"}`);
594
+ }
595
+ if (d.directed) {
596
+ throw eventTypeUnknown(`Event type "${type}" is directed at one agent and cannot trigger an automation`);
597
+ }
598
+ decls.push(d);
599
+ }
600
+ const filter = input.filter ?? [];
601
+ const problems = validateFilter(filter, decls);
602
+ if (problems.length > 0)
603
+ throw filterInvalid(problems.join("; "));
604
+ return { kind: "event", source, types, filter };
605
+ }
479
606
  /**
480
607
  * The chats the caller can point a `chat` task at (spec §8): per active connection of the org
481
608
  * whose extension is enabled in it, their DM threads (archived included) and, on a channel with
482
- * threads, the groups they have a thread in. Members up (`schedules.use`, the route's).
609
+ * threads, the groups they have a thread in. Members up (`automations.use`, the route's).
483
610
  */
484
611
  async chatTargets(orgId, accountId) {
485
612
  await this.liveRole(orgId, accountId);
@@ -532,7 +659,7 @@ let ScheduledTasksService = class ScheduledTasksService {
532
659
  async grantableTools(orgId, accountId, agentId) {
533
660
  const role = await this.liveRole(orgId, accountId);
534
661
  const agent = await this.agents.get(orgId, agentId, accountId);
535
- const settings = await readScheduleSettings(this.db.db, this.config, orgId);
662
+ const settings = await readAutomationSettings(this.db.db, this.config, orgId);
536
663
  const d = agent.definition;
537
664
  const { tools } = await this.tools.forAgent(orgId, {
538
665
  disabledTools: d.disabledTools ?? [],
@@ -589,10 +716,10 @@ let ScheduledTasksService = class ScheduledTasksService {
589
716
  * session (`source.fromSession`).
590
717
  */
591
718
  async addGrants(orgId, accountId, id, grants, source = {}) {
592
- const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "schedules.use");
719
+ const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "automations.use");
593
720
  const t = this.db.db;
594
721
  const task = await this.lockOwn(orgId, accountId, role, id);
595
- const settings = await readScheduleSettings(t, this.config, orgId);
722
+ const settings = await readAutomationSettings(t, this.config, orgId);
596
723
  const agent = await this.agents.get(orgId, task.agentId, accountId);
597
724
  const resolved = await this.resolveGrants(orgId, role, agent, settings, grants, await this.taskDeviceOf(orgId, task), source);
598
725
  for (const g of resolved)
@@ -600,7 +727,7 @@ let ScheduledTasksService = class ScheduledTasksService {
600
727
  await audit(t, {
601
728
  actorAccountId: accountId,
602
729
  orgId,
603
- action: "schedule.grants_changed",
730
+ action: "automation.grants_changed",
604
731
  target: task.id,
605
732
  detail: { added: resolved.map((g) => g.toolKey) },
606
733
  });
@@ -608,21 +735,21 @@ let ScheduledTasksService = class ScheduledTasksService {
608
735
  }
609
736
  /** Creator only; removing a grant the task does not have is a no-op. */
610
737
  async removeGrant(orgId, accountId, id, toolKey) {
611
- const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "schedules.use");
738
+ const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "automations.use");
612
739
  const t = this.db.db;
613
740
  const task = await this.lockOwn(orgId, accountId, role, id);
614
741
  if (await this.store.removeGrant(t, task.id, toolKey)) {
615
742
  await audit(t, {
616
743
  actorAccountId: accountId,
617
744
  orgId,
618
- action: "schedule.grants_changed",
745
+ action: "automation.grants_changed",
619
746
  target: task.id,
620
747
  detail: { removed: [toolKey] },
621
748
  });
622
749
  }
623
750
  }
624
751
  /**
625
- * The creator's scheduled tasks that need attention (spec §8), derived live: a paused task whose
752
+ * The creator's automations that need attention (spec §8), derived live: a paused task whose
626
753
  * reason is not `creator` (resuming clears it), an active task whose latest settled non-trial
627
754
  * run failed (the next good run clears it), and a task whose latest settled non-trial run was
628
755
  * refused tools, connections or domains (a tool granted since drops out, a domain too while the
@@ -639,29 +766,37 @@ let ScheduledTasksService = class ScheduledTasksService {
639
766
  const ids = tasks.map((t) => t.id);
640
767
  // the latest settled non-trial run of each task, and every grant of these tasks, in one query each
641
768
  const latest = await db
642
- .selectFrom("scheduled_task_runs")
643
- .select(["task_id", "fired_at", "scheduled_for", "missing_grants", "status", "error"])
644
- .distinctOn("task_id")
769
+ .selectFrom("automation_runs")
770
+ .select([
771
+ "automation_id",
772
+ "fired_at",
773
+ "scheduled_for",
774
+ "created_at",
775
+ "missing_grants",
776
+ "status",
777
+ "error",
778
+ ])
779
+ .distinctOn("automation_id")
645
780
  .where("org_id", "=", orgId)
646
- .where("task_id", "in", ids)
781
+ .where("automation_id", "in", ids)
647
782
  .where("trial", "=", false)
648
783
  .where("status", "<>", "skipped")
649
- .orderBy("task_id")
650
- .orderBy("scheduled_for", "desc")
784
+ .orderBy("automation_id")
785
+ .orderBy(runOrderMoment, "desc")
651
786
  .orderBy("id", "desc")
652
787
  .execute();
653
- const runs = new Map(latest.map((r) => [r.task_id, r]));
788
+ const runs = new Map(latest.map((r) => [r.automation_id, r]));
654
789
  const grantRows = await db
655
- .selectFrom("scheduled_task_grants")
656
- .select(["task_id", "tool_key", "spec_hash"])
657
- .where("task_id", "in", ids)
790
+ .selectFrom("automation_grants")
791
+ .select(["automation_id", "tool_key", "spec_hash"])
792
+ .where("automation_id", "in", ids)
658
793
  .execute();
659
794
  /** Per task: each granted tool key with the definition hash it was granted for. */
660
795
  const granted = new Map();
661
796
  for (const g of grantRows) {
662
- const byKey = granted.get(g.task_id) ?? new Map();
797
+ const byKey = granted.get(g.automation_id) ?? new Map();
663
798
  byKey.set(g.tool_key, g.spec_hash);
664
- granted.set(g.task_id, byKey);
799
+ granted.set(g.automation_id, byKey);
665
800
  }
666
801
  let loaded = false;
667
802
  let role = null;
@@ -705,7 +840,7 @@ let ScheduledTasksService = class ScheduledTasksService {
705
840
  needsRole: [],
706
841
  needsAdmin: [],
707
842
  error: run.error,
708
- at: run.fired_at ?? new Date(run.scheduled_for),
843
+ at: runMoment(run.fired_at, run.scheduled_for, run.created_at),
709
844
  });
710
845
  }
711
846
  const have = granted.get(task.id);
@@ -756,7 +891,7 @@ let ScheduledTasksService = class ScheduledTasksService {
756
891
  needsAdmin,
757
892
  // the wire field stays for the web; no network grant is refused by a device now
758
893
  error: null,
759
- at: run.fired_at ?? new Date(run.scheduled_for),
894
+ at: runMoment(run.fired_at, run.scheduled_for, run.created_at),
760
895
  });
761
896
  }
762
897
  return out.sort((a, b) => b.at.getTime() - a.at.getTime());
@@ -796,7 +931,7 @@ let ScheduledTasksService = class ScheduledTasksService {
796
931
  catch (e) {
797
932
  if (e instanceof ApiError && e.code === "agent.not_found")
798
933
  return new Map();
799
- this.log.warn("scheduled task: the agent's tools could not be read", {
934
+ this.log.warn("automation: the agent's tools could not be read", {
800
935
  orgId,
801
936
  agentId,
802
937
  error: e instanceof Error ? e.message : String(e),
@@ -818,16 +953,20 @@ let ScheduledTasksService = class ScheduledTasksService {
818
953
  * fire job its transaction owes. `trial`: an attended trial run whose approvals become the task's
819
954
  * grants (§7). Counted in the rate limit like any run. An ended task cannot run; a paused one
820
955
  * can (only its creator gets here: the run is `manual`, which the fire's paused check lets by).
956
+ * An event automation has neither (`automation.run_now_unsupported`): its runs are made from its
957
+ * events (collaboration spec §4.1).
821
958
  */
822
959
  async runNow(orgId, accountId, id, opts) {
823
- const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "schedules.use");
960
+ const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "automations.use");
824
961
  const t = this.db.db;
825
962
  const task = await this.lockOwn(orgId, accountId, role, id);
826
963
  if (task.status === "ended")
827
- throw new ApiError("conflict", "This scheduled task has ended");
828
- const settings = await readScheduleSettings(t, this.config, orgId);
964
+ throw new ApiError("conflict", "This automation has ended");
965
+ if (task.trigger.kind === "event")
966
+ throw runNowUnsupported();
967
+ const settings = await readAutomationSettings(t, this.config, orgId);
829
968
  if (!settings.enabled)
830
- throw scheduleDisabled();
969
+ throw automationDisabled();
831
970
  const run = await this.store.insertRun(t, {
832
971
  id: randomUUID(),
833
972
  taskId: task.id,
@@ -841,16 +980,16 @@ let ScheduledTasksService = class ScheduledTasksService {
841
980
  await audit(t, {
842
981
  actorAccountId: accountId,
843
982
  orgId,
844
- action: "schedule.run_now",
983
+ action: "automation.run_now",
845
984
  target: task.id,
846
985
  detail: { taskRunId: run.id, trial: opts.trial },
847
986
  });
848
- await oweSchedFire(this.outbox, run.id, orgId);
987
+ await oweAutomationFire(this.outbox, run.id, orgId);
849
988
  // a fire job that fails for good before its claim leaves the run to this check (`removed`)
850
- await oweSchedSettleUnfired(this.outbox, run.id, orgId, run.scheduledFor, null);
989
+ await oweAutomationSettleUnfired(this.outbox, run.id, orgId, run.scheduledFor, null);
851
990
  return run;
852
991
  }
853
- /** The live role of a member of the org; not a member → `schedule.not_found`. */
992
+ /** The live role of a member of the org; not a member → `automation.not_found`. */
854
993
  async liveRole(orgId, accountId) {
855
994
  const m = await this.db
856
995
  .selectFrom("memberships")
@@ -861,36 +1000,36 @@ let ScheduledTasksService = class ScheduledTasksService {
861
1000
  .where("orgs.deleted_at", "is", null)
862
1001
  .executeTakeFirst();
863
1002
  if (!m)
864
- throw scheduleNotFound();
1003
+ throw automationNotFound();
865
1004
  return m.role;
866
1005
  }
867
- /** The actor's own task, row-locked; another's: `schedule.forbidden` for an admin, else 404. */
1006
+ /** The actor's own task, row-locked; another's: `automation.forbidden` for an admin, else 404. */
868
1007
  async lockOwn(orgId, accountId, role, id) {
869
1008
  const task = await this.store.lockTask(this.db.db, orgId, id);
870
1009
  if (!task)
871
- throw scheduleNotFound();
1010
+ throw automationNotFound();
872
1011
  if (task.accountId !== accountId) {
873
- throw can(role, "schedules.manage") ? scheduleForbidden() : scheduleNotFound();
1012
+ throw can(role, "automations.manage") ? automationForbidden() : automationNotFound();
874
1013
  }
875
1014
  return task;
876
1015
  }
877
1016
  /**
878
1017
  * A task the actor may pause, resume or delete, row-locked under the org lock: their own (with
879
- * `creatorAction`), or any as an org admin (`schedules.manage`); otherwise `schedule.not_found`.
1018
+ * `creatorAction`), or any as an org admin (`automations.manage`); otherwise `automation.not_found`.
880
1019
  */
881
1020
  async lockManaged(orgId, accountId, id, creatorAction) {
882
1021
  const { role } = await this.orgLock.lockAndAuthorize(orgId, accountId, "org.read");
883
1022
  const task = await this.store.lockTask(this.db.db, orgId, id);
884
1023
  if (!task)
885
- throw scheduleNotFound();
1024
+ throw automationNotFound();
886
1025
  if (task.accountId === accountId) {
887
1026
  if (!can(role, creatorAction)) {
888
1027
  throw new ApiError("forbidden", "Insufficient organization role");
889
1028
  }
890
1029
  return { task, byAdmin: false };
891
1030
  }
892
- if (!can(role, "schedules.manage"))
893
- throw scheduleNotFound();
1031
+ if (!can(role, "automations.manage"))
1032
+ throw automationNotFound();
894
1033
  return { task, byAdmin: true };
895
1034
  }
896
1035
  /**
@@ -907,6 +1046,9 @@ let ScheduledTasksService = class ScheduledTasksService {
907
1046
  if (mode === "new" && (conversationId !== null || chat !== null)) {
908
1047
  throw targetInvalid("A task that starts new conversations takes no conversation or chat");
909
1048
  }
1049
+ if (mode === "subject" && (conversationId !== null || chat !== null)) {
1050
+ throw targetInvalid("A task that opens a conversation per subject takes no conversation or chat");
1051
+ }
910
1052
  if (mode === "conversation" && (conversationId === null || chat !== null)) {
911
1053
  throw targetInvalid("A conversation task needs a conversation id and no chat");
912
1054
  }
@@ -974,20 +1116,24 @@ let ScheduledTasksService = class ScheduledTasksService {
974
1116
  return entry?.impl?.features;
975
1117
  }
976
1118
  /**
977
- * A task's model, effort and device (spec §4): `new` mode only, since a conversation or chat
978
- * task runs with that conversation's selection and device (a task must not switch a person's
979
- * conversation for their later turns), so another mode refuses them (`validation_failed`).
1119
+ * A task's model, effort and device (spec §4): `new` mode takes all three and `subject` mode a
1120
+ * model and effort (not a device). A conversation or chat task runs with that conversation's
1121
+ * selection and device (a task must not switch a person's conversation for their later turns),
1122
+ * so those modes refuse them (`validation_failed`).
980
1123
  * The model must resolve for the org (`agent.model_unavailable`, as a message's switch) and
981
1124
  * declare the effort (`validation_failed`); the device must be one of the creator's
982
1125
  * (`checkDevice`, when `deviceChanged`).
983
1126
  */
984
1127
  async checkPick(orgId, accountId, agent, mode, pick, deviceChanged = true) {
985
- if (mode !== "new") {
1128
+ if (mode === "conversation" || mode === "chat") {
986
1129
  if (pick.model !== null || pick.effort !== null || pick.deviceId !== null) {
987
1130
  throw new ApiError("validation_failed", "Only a task that starts new conversations takes a model, effort or device; a conversation or chat task runs with that conversation's");
988
1131
  }
989
1132
  return;
990
1133
  }
1134
+ if (mode === "subject" && pick.deviceId !== null) {
1135
+ throw new ApiError("validation_failed", "A task with one conversation per subject takes a model and effort but no device; only a task that starts new conversations takes a device");
1136
+ }
991
1137
  if (pick.model !== null || pick.effort !== null) {
992
1138
  const { info } = await this.providers.resolve(orgId, pick.model ?? agent.definition.model);
993
1139
  if (pick.effort !== null) {
@@ -1025,7 +1171,7 @@ let ScheduledTasksService = class ScheduledTasksService {
1025
1171
  * `deviceId`, the task's device (null: none can be determined, the device rule is skipped),
1026
1172
  * stored with `spec_hash` `network` and no connector (plan P-D7), and only when
1027
1173
  * `source.fromSession` (a person on the task page; never a token, the Platform tool or the
1028
- * schedule tools). Each git push key (`git:push`, `git:push:<owner>/<repo>`, the repository
1174
+ * automation tools). Each git push key (`git:push`, `git:push:<owner>/<repo>`, the repository
1029
1175
  * lower-cased) is refused by {@link gitGrantRefusal} and stored with `spec_hash` `git` and no
1030
1176
  * connector, also only when `source.fromSession`. Duplicates keep the last.
1031
1177
  */
@@ -1137,34 +1283,34 @@ let ScheduledTasksService = class ScheduledTasksService {
1137
1283
  };
1138
1284
  __decorate([
1139
1285
  Transactional()
1140
- ], ScheduledTasksService.prototype, "create", null);
1286
+ ], AutomationsService.prototype, "create", null);
1141
1287
  __decorate([
1142
1288
  Transactional()
1143
- ], ScheduledTasksService.prototype, "update", null);
1289
+ ], AutomationsService.prototype, "update", null);
1144
1290
  __decorate([
1145
1291
  Transactional()
1146
- ], ScheduledTasksService.prototype, "pause", null);
1292
+ ], AutomationsService.prototype, "pause", null);
1147
1293
  __decorate([
1148
1294
  Transactional()
1149
- ], ScheduledTasksService.prototype, "resume", null);
1295
+ ], AutomationsService.prototype, "resume", null);
1150
1296
  __decorate([
1151
1297
  Transactional()
1152
- ], ScheduledTasksService.prototype, "remove", null);
1298
+ ], AutomationsService.prototype, "remove", null);
1153
1299
  __decorate([
1154
1300
  Transactional()
1155
- ], ScheduledTasksService.prototype, "addGrants", null);
1301
+ ], AutomationsService.prototype, "addGrants", null);
1156
1302
  __decorate([
1157
1303
  Transactional()
1158
- ], ScheduledTasksService.prototype, "removeGrant", null);
1304
+ ], AutomationsService.prototype, "removeGrant", null);
1159
1305
  __decorate([
1160
1306
  Transactional()
1161
- ], ScheduledTasksService.prototype, "runNow", null);
1162
- ScheduledTasksService = __decorate([
1307
+ ], AutomationsService.prototype, "runNow", null);
1308
+ AutomationsService = __decorate([
1163
1309
  Injectable(),
1164
1310
  __param(0, Inject(KernelDb)),
1165
1311
  __param(1, Inject(TransactionHost)),
1166
1312
  __param(2, Inject(KernelConfigService)),
1167
- __param(3, Inject(ScheduledTaskStore)),
1313
+ __param(3, Inject(AutomationStore)),
1168
1314
  __param(4, Inject(OrgLock)),
1169
1315
  __param(5, Inject(AgentLookup)),
1170
1316
  __param(6, Inject(ConversationAccess)),
@@ -1173,9 +1319,11 @@ ScheduledTasksService = __decorate([
1173
1319
  __param(9, Inject(ProviderRegistry)),
1174
1320
  __param(10, Inject(KERNEL_LOGGER)),
1175
1321
  __param(11, Inject(OutboxService)),
1176
- __param(12, Inject(SandboxService))
1177
- ], ScheduledTasksService);
1178
- export { ScheduledTasksService };
1322
+ __param(12, Inject(SandboxService)),
1323
+ __param(13, Inject(ExtensionPointDefaults)),
1324
+ __param(14, Inject(ExtensionDisplayNames))
1325
+ ], AutomationsService);
1326
+ export { AutomationsService };
1179
1327
  /** A required text field, trimmed; empty or longer than `max` → `validation_failed`. */
1180
1328
  function requiredText(v, field, max) {
1181
1329
  const s = v.trim();
@@ -1186,6 +1334,26 @@ function requiredText(v, field, max) {
1186
1334
  }
1187
1335
  return s;
1188
1336
  }
1337
+ /**
1338
+ * When a run happened, for lists: its fire time, else its tick, else when it was recorded (an
1339
+ * event run has no tick and no fire time before its claim).
1340
+ */
1341
+ function runMoment(firedAt, scheduledFor, createdAt) {
1342
+ return new Date(firedAt ?? scheduledFor ?? createdAt);
1343
+ }
1344
+ /**
1345
+ * The mode must fit the trigger: `subject` (one conversation per event subject) needs an event
1346
+ * trigger, and an event automation does not post into an IM chat yet (`chat` is a time
1347
+ * automation's mode).
1348
+ */
1349
+ function checkModeFits(mode, trigger) {
1350
+ if (mode === "subject" && trigger.kind !== "event") {
1351
+ throw targetInvalid("Mode subject (one conversation per event subject) needs an event trigger; use new, conversation or chat with a schedule");
1352
+ }
1353
+ if (mode === "chat" && trigger.kind === "event") {
1354
+ throw targetInvalid("An event automation cannot post into an IM chat yet; use mode new, conversation or subject");
1355
+ }
1356
+ }
1189
1357
  function withZone(t, timeZone) {
1190
1358
  return t.kind === "cron"
1191
1359
  ? { kind: "cron", expr: t.expr.trim(), timeZone }
@@ -1197,25 +1365,25 @@ function withZone(t, timeZone) {
1197
1365
  */
1198
1366
  function checkTrigger(t, now, settings) {
1199
1367
  if (!isTimeZone(t.timeZone)) {
1200
- throw new ApiError("schedule.invalid_time_zone", `${t.timeZone} is not an IANA time zone`);
1368
+ throw new ApiError("automation.invalid_time_zone", `${t.timeZone} is not an IANA time zone`);
1201
1369
  }
1202
1370
  const v = validateTrigger(t, now);
1203
1371
  if (!v.ok) {
1204
1372
  const message = {
1205
- "schedule.invalid_cron": "The schedule is not a 5-field cron expression",
1206
- "schedule.invalid_time_zone": `${t.timeZone} is not an IANA time zone`,
1207
- "schedule.invalid_once_time": "The time is not a local date-time such as 2026-12-01T09:00",
1208
- "schedule.once_in_past": "The time is not in the future",
1373
+ "automation.invalid_cron": "The schedule is not a 5-field cron expression",
1374
+ "automation.invalid_time_zone": `${t.timeZone} is not an IANA time zone`,
1375
+ "automation.invalid_once_time": "The time is not a local date-time such as 2026-12-01T09:00",
1376
+ "automation.once_in_past": "The time is not in the future",
1209
1377
  };
1210
1378
  throw new ApiError(v.code, message[v.code]);
1211
1379
  }
1212
1380
  if (t.kind === "cron") {
1213
1381
  if (nextTick(t, now) === null) {
1214
- throw new ApiError("schedule.invalid_cron", "The schedule never fires");
1382
+ throw new ApiError("automation.invalid_cron", "The schedule never fires");
1215
1383
  }
1216
1384
  const gap = minGapMinutes(t, now);
1217
1385
  if (gap !== null && gap < settings.minIntervalMinutes) {
1218
- throw new ApiError("schedule.interval_too_short", `The schedule fires every ${gap} minutes; this organization allows at least ${settings.minIntervalMinutes}`);
1386
+ throw new ApiError("automation.interval_too_short", `The schedule fires every ${gap} minutes; this organization allows at least ${settings.minIntervalMinutes}`);
1219
1387
  }
1220
1388
  return gap;
1221
1389
  }
@@ -1228,13 +1396,14 @@ function fireAt(t, now, jitter) {
1228
1396
  }
1229
1397
  /**
1230
1398
  * A task's expiry: an explicit one must lie in the future; null (not given) is now + the org's
1231
- * `defaultExpiryDays` for a cron task when the org sets one, else never. The same on create and
1232
- * update, so a creator cannot clear the org's expiry policy by sending null.
1399
+ * `defaultExpiryDays` for a cron or event task when the org sets one (a `once` task ends at its
1400
+ * run), else never. The same on create and update, so a creator cannot clear the org's expiry
1401
+ * policy by sending null.
1233
1402
  */
1234
1403
  function expiryOf(v, trigger, now, settings) {
1235
1404
  if (v !== null)
1236
1405
  return checkExpiry(v, now);
1237
- return trigger.kind === "cron" && settings.defaultExpiryDays !== null
1406
+ return trigger.kind !== "once" && settings.defaultExpiryDays !== null
1238
1407
  ? new Date(now.getTime() + settings.defaultExpiryDays * DAY_MS)
1239
1408
  : null;
1240
1409
  }