@capybara-hq/kernel 0.1.0-rc.104 → 0.1.0-rc.106

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 (250) hide show
  1. package/dist/agents/agents.schemas.d.ts +9 -9
  2. package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
  3. package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
  4. package/dist/automations/automations.module.d.ts +16 -0
  5. package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
  6. package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
  7. package/dist/automations/automations.schemas.js +253 -0
  8. package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
  9. package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
  10. package/dist/{schedules → automations}/calendar.d.ts +8 -8
  11. package/dist/{schedules → automations}/calendar.js +2 -2
  12. package/dist/automations/effective-settings.d.ts +28 -0
  13. package/dist/automations/effective-settings.js +25 -0
  14. package/dist/automations/errors.d.ts +19 -0
  15. package/dist/automations/errors.js +19 -0
  16. package/dist/automations/events/coalesce.d.ts +28 -0
  17. package/dist/automations/events/coalesce.js +131 -0
  18. package/dist/automations/events/deadline.d.ts +10 -0
  19. package/dist/automations/events/deadline.js +24 -0
  20. package/dist/automations/events/dispatcher.d.ts +74 -0
  21. package/dist/automations/events/dispatcher.js +353 -0
  22. package/dist/automations/events/events.module.d.ts +7 -0
  23. package/dist/automations/events/events.module.js +26 -0
  24. package/dist/automations/events/guards.d.ts +32 -0
  25. package/dist/automations/events/guards.js +87 -0
  26. package/dist/automations/events/sweep.job.d.ts +49 -0
  27. package/dist/automations/events/sweep.job.js +202 -0
  28. package/dist/automations/events/token.d.ts +5 -0
  29. package/dist/automations/events/token.js +5 -0
  30. package/dist/automations/events/trigger-events.service.d.ts +47 -0
  31. package/dist/automations/events/trigger-events.service.js +254 -0
  32. package/dist/{schedules → automations}/fire.d.ts +57 -17
  33. package/dist/{schedules → automations}/fire.js +311 -79
  34. package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
  35. package/dist/{schedules → automations}/grant-rules.js +5 -5
  36. package/dist/automations/job-ids.d.ts +113 -0
  37. package/dist/automations/job-ids.js +117 -0
  38. package/dist/{schedules → automations}/pause.d.ts +3 -3
  39. package/dist/{schedules → automations}/pause.js +3 -3
  40. package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
  41. package/dist/{schedules → automations}/run-tracker.js +68 -56
  42. package/dist/{schedules → automations}/scan.job.d.ts +12 -8
  43. package/dist/{schedules → automations}/scan.job.js +39 -23
  44. package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
  45. package/dist/{schedules → automations}/schedule-math.js +17 -7
  46. package/dist/{schedules → automations}/store.d.ts +57 -27
  47. package/dist/{schedules → automations}/store.js +102 -52
  48. package/dist/automations/store.module.d.ts +6 -0
  49. package/dist/{schedules → automations}/store.module.js +9 -9
  50. package/dist/automations/types.d.ts +178 -0
  51. package/dist/{schedules → automations}/unattended.d.ts +22 -11
  52. package/dist/{schedules → automations}/unattended.js +53 -30
  53. package/dist/catalog/marketplaces.service.d.ts +1 -1
  54. package/dist/channels/channels.module.js +3 -3
  55. package/dist/channels/outbound.d.ts +5 -5
  56. package/dist/channels/outbound.js +17 -17
  57. package/dist/channels/threads.d.ts +1 -1
  58. package/dist/channels/threads.js +1 -1
  59. package/dist/config/schema.d.ts +5 -1
  60. package/dist/config/schema.js +44 -6
  61. package/dist/conversations/approval-profile.d.ts +2 -2
  62. package/dist/conversations/approval-profile.js +3 -3
  63. package/dist/conversations/conversations.controller.d.ts +7 -1
  64. package/dist/conversations/conversations.controller.js +26 -10
  65. package/dist/conversations/conversations.service.d.ts +103 -25
  66. package/dist/conversations/conversations.service.js +138 -33
  67. package/dist/conversations/events.d.ts +48 -1
  68. package/dist/conversations/events.js +61 -9
  69. package/dist/conversations/message-context.d.ts +2 -2
  70. package/dist/conversations/message-context.js +1 -1
  71. package/dist/conversations/permission-profile-store.d.ts +2 -1
  72. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  73. package/dist/conversations/permission-profiles.service.js +1 -1
  74. package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
  75. package/dist/conversations/prompt-suggestion-request.js +2 -1
  76. package/dist/conversations/queue.d.ts +7 -4
  77. package/dist/conversations/queue.js +6 -2
  78. package/dist/conversations/queue.service.d.ts +5 -5
  79. package/dist/conversations/queue.service.js +20 -14
  80. package/dist/ctx/create-ctx.d.ts +20 -1
  81. package/dist/ctx/create-ctx.js +59 -2
  82. package/dist/db/kernel-schema.d.ts +104 -25
  83. package/dist/devices/device-project-files.service.d.ts +88 -0
  84. package/dist/devices/device-project-files.service.js +249 -0
  85. package/dist/devices/device-projects.service.d.ts +40 -0
  86. package/dist/devices/device-projects.service.js +16 -13
  87. package/dist/devices/devices.controller.d.ts +9 -3
  88. package/dist/devices/devices.controller.js +27 -5
  89. package/dist/devices/devices.module.js +9 -1
  90. package/dist/devices/devices.schemas.js +6 -1
  91. package/dist/devices/dto.d.ts +15 -0
  92. package/dist/devices/dto.js +11 -0
  93. package/dist/devices/project-paths.d.ts +29 -0
  94. package/dist/devices/project-paths.js +66 -0
  95. package/dist/devices/project-rules.d.ts +5 -1
  96. package/dist/devices/project-rules.js +5 -1
  97. package/dist/errors.d.ts +47 -13
  98. package/dist/errors.js +47 -13
  99. package/dist/evals/reconstruct.d.ts +10 -1
  100. package/dist/evals/reconstruct.js +7 -0
  101. package/dist/extensions/host.d.ts +6 -1
  102. package/dist/extensions/host.js +10 -0
  103. package/dist/extensions/permission-set.d.ts +17 -1
  104. package/dist/extensions/permission-set.js +13 -1
  105. package/dist/extensions/permission-view.d.ts +1 -1
  106. package/dist/extensions/permission-view.js +4 -1
  107. package/dist/git/gateway.js +2 -2
  108. package/dist/handoff/app-schemes.d.ts +28 -0
  109. package/dist/handoff/app-schemes.js +41 -0
  110. package/dist/handoff/handoff-paths.d.ts +26 -0
  111. package/dist/handoff/handoff-paths.js +25 -0
  112. package/dist/handoff/handoff-tickets.d.ts +28 -0
  113. package/dist/handoff/handoff-tickets.js +111 -0
  114. package/dist/handoff/handoff.controller.d.ts +24 -0
  115. package/dist/handoff/handoff.controller.js +74 -0
  116. package/dist/handoff/handoff.module.d.ts +7 -0
  117. package/dist/handoff/handoff.module.js +26 -0
  118. package/dist/handoff/handoff.schemas.d.ts +13 -0
  119. package/dist/handoff/handoff.schemas.js +3 -0
  120. package/dist/handoff/handoff.service.d.ts +49 -0
  121. package/dist/handoff/handoff.service.js +96 -0
  122. package/dist/http/api.module.js +13 -5
  123. package/dist/http/meta.controller.d.ts +1 -0
  124. package/dist/http/meta.controller.js +7 -0
  125. package/dist/http/request-signal.d.ts +8 -0
  126. package/dist/http/request-signal.js +14 -0
  127. package/dist/identity/sso.controller.d.ts +30 -6
  128. package/dist/identity/sso.controller.js +51 -17
  129. package/dist/identity/sso.d.ts +10 -2
  130. package/dist/identity/sso.js +15 -3
  131. package/dist/inbox/inbox.module.js +2 -2
  132. package/dist/inbox/inbox.service.d.ts +8 -8
  133. package/dist/inbox/inbox.service.js +7 -7
  134. package/dist/infra/config/kernel-config.service.js +10 -5
  135. package/dist/infra/outbox/registry.d.ts +29 -2
  136. package/dist/infra/outbox/registry.js +30 -7
  137. package/dist/kernel.module.js +3 -0
  138. package/dist/orgs/roles.d.ts +1 -1
  139. package/dist/orgs/roles.js +3 -3
  140. package/dist/orgs/settings.controller.d.ts +1 -1
  141. package/dist/orgs/settings.service.d.ts +27 -11
  142. package/dist/orgs/settings.service.js +42 -24
  143. package/dist/overrides.d.ts +4 -4
  144. package/dist/overrides.js +1 -1
  145. package/dist/platform/exclusions.js +5 -0
  146. package/dist/platform/operation.js +2 -2
  147. package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
  148. package/dist/platform/ops/automations.ops.js +560 -0
  149. package/dist/platform/ops/connectors.ops.js +4 -2
  150. package/dist/platform/ops/devices.ops.d.ts +3 -1
  151. package/dist/platform/ops/devices.ops.js +77 -3
  152. package/dist/platform/ops/inbox.ops.js +4 -4
  153. package/dist/platform/ops/orgs.ops.js +1 -1
  154. package/dist/platform/ops/platform.ops.js +4 -4
  155. package/dist/platform/platform-ops.module.d.ts +2 -2
  156. package/dist/platform/platform-ops.module.js +5 -5
  157. package/dist/platform/route-schemas.js +3 -3
  158. package/dist/push/jobs.d.ts +3 -3
  159. package/dist/push/jobs.js +2 -2
  160. package/dist/push/preferences.service.js +1 -1
  161. package/dist/push/push-owed.d.ts +3 -3
  162. package/dist/push/push-owed.js +6 -6
  163. package/dist/push/push.schemas.d.ts +4 -4
  164. package/dist/push/push.schemas.js +3 -3
  165. package/dist/push/recipients.d.ts +4 -4
  166. package/dist/push/recipients.js +23 -23
  167. package/dist/push/texts.d.ts +3 -3
  168. package/dist/push/texts.js +2 -2
  169. package/dist/push/triggers.d.ts +1 -1
  170. package/dist/roles/worker.module.js +3 -3
  171. package/dist/runtime/compaction.service.d.ts +3 -1
  172. package/dist/runtime/compaction.service.js +3 -1
  173. package/dist/runtime/context/build.d.ts +6 -0
  174. package/dist/runtime/context/build.js +14 -3
  175. package/dist/runtime/context/compaction.d.ts +27 -1
  176. package/dist/runtime/context/compaction.js +102 -37
  177. package/dist/runtime/context/run-context.d.ts +38 -0
  178. package/dist/runtime/context/run-context.js +54 -0
  179. package/dist/runtime/maintenance.d.ts +8 -4
  180. package/dist/runtime/maintenance.js +37 -16
  181. package/dist/runtime/model-call.d.ts +6 -4
  182. package/dist/runtime/model-call.js +17 -7
  183. package/dist/runtime/project/knowledge.service.d.ts +16 -7
  184. package/dist/runtime/project/knowledge.service.js +31 -13
  185. package/dist/runtime/run-finish.d.ts +4 -4
  186. package/dist/runtime/run-finish.js +3 -3
  187. package/dist/runtime/run-queue.js +12 -7
  188. package/dist/runtime/run-worker.js +7 -1
  189. package/dist/runtime/runtime.module.js +3 -3
  190. package/dist/runtime/subagents/dispatch.js +11 -3
  191. package/dist/sandbox/browse-roots.d.ts +8 -0
  192. package/dist/sandbox/browse-roots.js +22 -0
  193. package/dist/sandbox/network-grants.d.ts +4 -4
  194. package/dist/sandbox/network-grants.js +7 -7
  195. package/dist/sandbox/operation-authority.d.ts +10 -3
  196. package/dist/sandbox/operation-authority.js +20 -10
  197. package/dist/sandbox/operation-intents.d.ts +3 -1
  198. package/dist/sandbox/operation-intents.js +11 -4
  199. package/dist/sandbox/permission-call-grants.js +2 -2
  200. package/dist/sandbox/permission-facts.js +1 -1
  201. package/dist/sandbox/review/classifier.d.ts +2 -2
  202. package/dist/sandbox/review/classifier.js +22 -11
  203. package/dist/sandbox/review/permission-candidate.d.ts +1 -1
  204. package/dist/sandbox/review/permission-candidate.js +1 -1
  205. package/dist/sandbox/sandbox.service.d.ts +15 -5
  206. package/dist/sandbox/sandbox.service.js +14 -8
  207. package/dist/storage/purge.d.ts +1 -1
  208. package/dist/storage/purge.js +2 -2
  209. package/dist/tools/approvals.service.d.ts +6 -6
  210. package/dist/tools/approvals.service.js +19 -19
  211. package/dist/tools/builtin-names.d.ts +12 -12
  212. package/dist/tools/builtin-names.js +29 -29
  213. package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
  214. package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
  215. package/dist/tools/builtins/builtin-tools.d.ts +8 -8
  216. package/dist/tools/builtins/builtin-tools.js +16 -16
  217. package/dist/tools/call-scope.d.ts +1 -1
  218. package/dist/tools/connectors.service.d.ts +4 -13
  219. package/dist/tools/connectors.service.js +12 -21
  220. package/dist/tools/git-asks.js +1 -1
  221. package/dist/tools/git-push-policy.d.ts +3 -3
  222. package/dist/tools/git-push-policy.js +6 -6
  223. package/dist/tools/network-asks.d.ts +3 -3
  224. package/dist/tools/network-asks.js +3 -3
  225. package/dist/tools/oauth/flow.d.ts +16 -2
  226. package/dist/tools/oauth/flow.js +23 -4
  227. package/dist/tools/oauth/oauth.controller.d.ts +19 -7
  228. package/dist/tools/oauth/oauth.controller.js +42 -12
  229. package/dist/tools/oauth/oauth.schemas.d.ts +14 -1
  230. package/dist/tools/oauth/oauth.schemas.js +4 -1
  231. package/dist/tools/pipeline.d.ts +4 -4
  232. package/dist/tools/pipeline.js +2 -2
  233. package/dist/tools/policy.d.ts +3 -3
  234. package/dist/tools/policy.js +3 -3
  235. package/dist/tools/tools.module.js +9 -9
  236. package/package.json +3 -3
  237. package/src/migrations/0188_automations_rename.sql +309 -0
  238. package/src/migrations/0189_event_automations.sql +136 -0
  239. package/dist/platform/ops/schedules.ops.js +0 -509
  240. package/dist/schedules/effective-settings.d.ts +0 -22
  241. package/dist/schedules/effective-settings.js +0 -18
  242. package/dist/schedules/errors.d.ts +0 -8
  243. package/dist/schedules/errors.js +0 -8
  244. package/dist/schedules/job-ids.d.ts +0 -81
  245. package/dist/schedules/job-ids.js +0 -95
  246. package/dist/schedules/schedules.module.d.ts +0 -16
  247. package/dist/schedules/schedules.schemas.js +0 -213
  248. package/dist/schedules/store.module.d.ts +0 -6
  249. package/dist/schedules/types.d.ts +0 -110
  250. /package/dist/{schedules → automations}/types.js +0 -0
@@ -1,4 +1,4 @@
1
- import type { ScheduledTask, ScheduleMode, SchedulePauseReason, ScheduleStatus, ScheduleTrigger, TaskRun, TaskRunSkipReason, TaskRunStatus } from "./types.js";
1
+ import type { Automation, AutomationMode, AutomationPauseReason, AutomationStatus, AutomationTrigger, TaskRunSkipReason, TaskRunStatus, TimedTaskRun } from "./types.js";
2
2
  /** Planned occurrences reach this far ahead of now (spec §5.2, "about six weeks"). */
3
3
  export declare const CALENDAR_HORIZON_DAYS = 42;
4
4
  /** The longest range one request may ask for: a 6-week month grid plus a DST hour (§5.1). */
@@ -47,10 +47,10 @@ export interface CalendarTask {
47
47
  name: string;
48
48
  agentId: string;
49
49
  accountId: string;
50
- status: ScheduleStatus;
51
- pauseReason: SchedulePauseReason | null;
52
- trigger: ScheduleTrigger;
53
- mode: ScheduleMode;
50
+ status: AutomationStatus;
51
+ pauseReason: AutomationPauseReason | null;
52
+ trigger: AutomationTrigger;
53
+ mode: AutomationMode;
54
54
  jitterSeconds: number;
55
55
  nextRunAt: string | null;
56
56
  }
@@ -103,12 +103,12 @@ export interface CalendarAnswer {
103
103
  }
104
104
  export interface CalendarInput {
105
105
  /** The live tasks the viewer may see in this request. */
106
- tasks: readonly ScheduledTask[];
106
+ tasks: readonly Automation[];
107
107
  /**
108
108
  * Their runs with `scheduledFor` in `[from, to)`, trial included, ordered by `scheduledFor`, at
109
109
  * most {@link calendarRunReadLimit} (rows past it are not read; the range is cut before them).
110
110
  */
111
- runs: readonly TaskRun[];
111
+ runs: readonly TimedTaskRun[];
112
112
  /** The viewer: another creator's runs lose `conversationId`, `error` and `missingGrants`. */
113
113
  viewerAccountId: string;
114
114
  from: Date;
@@ -116,7 +116,7 @@ export interface CalendarInput {
116
116
  /** The viewer's zone: local days for the collapse and the cut. */
117
117
  timeZone: string;
118
118
  now: Date;
119
- /** False when the org turned scheduled tasks off: nothing would fire, so nothing is planned. */
119
+ /** False when the org turned automations off: nothing would fire, so nothing is planned. */
120
120
  plan: boolean;
121
121
  /** The org's catch-up window, as the scanner reads it. */
122
122
  catchUpWindowMinutes: number;
@@ -1,8 +1,8 @@
1
1
  import { scanStep, tickerOf, ticksIn } from "./schedule-math.js";
2
2
  /**
3
- * The scheduled task calendar (spec 2026-11-12-scheduled-tasks-calendar-design.md §5): recorded
3
+ * The automation calendar (spec 2026-11-12-scheduled-tasks-calendar-design.md §5): recorded
4
4
  * runs and planned occurrences between two instants, dense task-days collapsed, cut at a whole
5
- * day when a limit is reached. The assembly here is pure; `ScheduledTasksService.calendar` reads
5
+ * day when a limit is reached. The assembly here is pure; `AutomationsService.calendar` reads
6
6
  * the rows and decides who sees what.
7
7
  */
8
8
  const DAY_MS = 86_400_000;
@@ -0,0 +1,28 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { type AutomationsSettings } from "../orgs/settings.service.js";
4
+ /** The platform's bounds for the org settings (kernel config `automations.*`). */
5
+ export interface AutomationBounds {
6
+ minIntervalFloorMinutes: number;
7
+ maxTasksPerMemberCap: number;
8
+ maxTasksPerOrgCap: number;
9
+ maxRunsPerHourCap: number;
10
+ maxEventDepthCap: number;
11
+ coalesceSecondsCap: number;
12
+ maxEventRunsPerSubjectPerHourCap: number;
13
+ }
14
+ /**
15
+ * The org's automation settings after clamping to the platform bounds. `forbiddenToolsUnreadable`:
16
+ * the stored list cannot be read (`invalidStoredForbiddenTools`); `forbiddenTools` is then `[]`
17
+ * and unattended runs of the org must fail instead of running with nothing forbidden.
18
+ */
19
+ export type EffectiveAutomationSettings = AutomationsSettings & {
20
+ forbiddenToolsUnreadable: boolean;
21
+ };
22
+ /**
23
+ * An org value outside the platform bounds is clamped: the interval up, the counts, the event
24
+ * chain depth and the coalescing window down.
25
+ */
26
+ export declare function effectiveAutomationSettings(org: AutomationsSettings, bounds: AutomationBounds, forbiddenToolsUnreadable?: boolean): EffectiveAutomationSettings;
27
+ /** Read the org's effective settings live (PG and the current kernel config). */
28
+ export declare function readAutomationSettings(db: KernelSchemaDb, config: Pick<KernelConfigService, "get">, orgId: string): Promise<EffectiveAutomationSettings>;
@@ -0,0 +1,25 @@
1
+ import { invalidStoredForbiddenTools, parseOrgSettings, readStoredOrgSettings, } from "../orgs/settings.service.js";
2
+ /**
3
+ * An org value outside the platform bounds is clamped: the interval up, the counts, the event
4
+ * chain depth and the coalescing window down.
5
+ */
6
+ export function effectiveAutomationSettings(org, bounds, forbiddenToolsUnreadable = false) {
7
+ return {
8
+ ...org,
9
+ forbiddenTools: [...org.forbiddenTools],
10
+ eventSourcesOff: [...org.eventSourcesOff],
11
+ forbiddenToolsUnreadable,
12
+ minIntervalMinutes: Math.max(org.minIntervalMinutes, bounds.minIntervalFloorMinutes),
13
+ maxTasksPerMember: Math.min(org.maxTasksPerMember, bounds.maxTasksPerMemberCap),
14
+ maxTasksPerOrg: Math.min(org.maxTasksPerOrg, bounds.maxTasksPerOrgCap),
15
+ maxRunsPerHour: Math.min(org.maxRunsPerHour, bounds.maxRunsPerHourCap),
16
+ maxEventDepth: Math.min(org.maxEventDepth, bounds.maxEventDepthCap),
17
+ coalesceSeconds: Math.min(org.coalesceSeconds, bounds.coalesceSecondsCap),
18
+ maxEventRunsPerSubjectPerHour: Math.min(org.maxEventRunsPerSubjectPerHour, bounds.maxEventRunsPerSubjectPerHourCap),
19
+ };
20
+ }
21
+ /** Read the org's effective settings live (PG and the current kernel config). */
22
+ export async function readAutomationSettings(db, config, orgId) {
23
+ const raw = await readStoredOrgSettings(db, orgId);
24
+ return effectiveAutomationSettings(parseOrgSettings(raw).automations, config.get().automations, invalidStoredForbiddenTools(raw));
25
+ }
@@ -0,0 +1,19 @@
1
+ import { ApiError } from "../errors.js";
2
+ /** The task is missing, deleted, in another org or not the caller's to see (never 403). */
3
+ export declare const automationNotFound: () => ApiError;
4
+ /** An org admin acting on another person's task in a way only its creator may (spec §10). */
5
+ export declare const automationForbidden: () => ApiError;
6
+ export declare const automationDisabled: () => ApiError;
7
+ export declare const targetInvalid: (message: string) => ApiError;
8
+ export declare const grantNotAllowed: (message: string) => ApiError;
9
+ /** The event source is not an enabled trigger source of the org (or the org switched it off). */
10
+ export declare const eventSourceUnavailable: (message: string) => ApiError;
11
+ /** An event type the source does not declare (or one that is directed). */
12
+ export declare const eventTypeUnknown: (message: string) => ApiError;
13
+ /**
14
+ * "Run now" or a trial run of an event automation: its runs are made from its events (collaboration
15
+ * spec §4.1), so there is nothing to run outside them.
16
+ */
17
+ export declare const runNowUnsupported: () => ApiError;
18
+ /** A filter clause on a missing, unfilterable or mistyped fact. */
19
+ export declare const filterInvalid: (message: string) => ApiError;
@@ -0,0 +1,19 @@
1
+ import { ApiError } from "../errors.js";
2
+ /** The task is missing, deleted, in another org or not the caller's to see (never 403). */
3
+ export const automationNotFound = () => new ApiError("automation.not_found", "Automation not found");
4
+ /** An org admin acting on another person's task in a way only its creator may (spec §10). */
5
+ export const automationForbidden = () => new ApiError("automation.forbidden", "Only the task's creator can change its prompt, schedule, target or approved tools");
6
+ export const automationDisabled = () => new ApiError("automation.disabled", "Automations are turned off in this organization");
7
+ export const targetInvalid = (message) => new ApiError("automation.target_invalid", message);
8
+ export const grantNotAllowed = (message) => new ApiError("automation.grant_not_allowed", message);
9
+ /** The event source is not an enabled trigger source of the org (or the org switched it off). */
10
+ export const eventSourceUnavailable = (message) => new ApiError("automation.event_source_unavailable", message);
11
+ /** An event type the source does not declare (or one that is directed). */
12
+ export const eventTypeUnknown = (message) => new ApiError("automation.event_type_unknown", message);
13
+ /**
14
+ * "Run now" or a trial run of an event automation: its runs are made from its events (collaboration
15
+ * spec §4.1), so there is nothing to run outside them.
16
+ */
17
+ export const runNowUnsupported = () => new ApiError("automation.run_now_unsupported", "An event automation runs only when its events arrive, so it cannot be run now or as a trial; make an event of its source happen to test it, or switch it to a schedule");
18
+ /** A filter clause on a missing, unfilterable or mistyped fact. */
19
+ export const filterInvalid = (message) => new ApiError("automation.filter_invalid", message);
@@ -0,0 +1,28 @@
1
+ import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
2
+ import { KernelDb } from "../../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../../infra/database/transaction-host.js";
4
+ import { OutboxService } from "../../infra/outbox/outbox.service.js";
5
+ import type { KernelLogger } from "../../log.js";
6
+ import { type AutomationCoalesceJobData } from "../job-ids.js";
7
+ import { AutomationStore } from "../store.js";
8
+ /**
9
+ * Ends one coalescing window of an event automation (collaboration spec §4.7), the
10
+ * `automation-coalesce` job: under the automation row lock, the deliveries of the (automation,
11
+ * subject) pair still waiting for a run, in the order their events were stored, become one run
12
+ * keyed by the first event (`trigger_key`). A pair that already made
13
+ * `maxEventRunsPerSubjectPerHour` runs (not skipped) in the last hour gets a run skipped with
14
+ * `subject_rate` instead, so the drop is visible in the run list. A pending run owes its
15
+ * `automation-fire` job and its unfired check, as a "run now" does; everything else (paused, rate
16
+ * limit, overlap, the start) is the fire job's.
17
+ */
18
+ export declare class EventCoalescer {
19
+ private readonly kdb;
20
+ readonly txHost: TransactionHost;
21
+ private readonly config;
22
+ private readonly store;
23
+ private readonly outbox;
24
+ private readonly log;
25
+ constructor(kdb: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get">, store: AutomationStore, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "info">);
26
+ /** Flushes the waiting deliveries of the pair (see the class); nothing when none wait. */
27
+ flush(data: AutomationCoalesceJobData): Promise<void>;
28
+ }
@@ -0,0 +1,131 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomUUID } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
14
+ import { KernelDb } from "../../infra/database/kernel-db.js";
15
+ import { TransactionHost } from "../../infra/database/transaction-host.js";
16
+ import { Transactional } from "../../infra/database/transactional.decorator.js";
17
+ import { OutboxService } from "../../infra/outbox/outbox.service.js";
18
+ import { KERNEL_LOGGER } from "../../infra/tokens.js";
19
+ import { readAutomationSettings } from "../effective-settings.js";
20
+ import { oweAutomationFire, oweAutomationSettleUnfired, } from "../job-ids.js";
21
+ import { AutomationStore } from "../store.js";
22
+ const HOUR_MS = 60 * 60_000;
23
+ /**
24
+ * Ends one coalescing window of an event automation (collaboration spec §4.7), the
25
+ * `automation-coalesce` job: under the automation row lock, the deliveries of the (automation,
26
+ * subject) pair still waiting for a run, in the order their events were stored, become one run
27
+ * keyed by the first event (`trigger_key`). A pair that already made
28
+ * `maxEventRunsPerSubjectPerHour` runs (not skipped) in the last hour gets a run skipped with
29
+ * `subject_rate` instead, so the drop is visible in the run list. A pending run owes its
30
+ * `automation-fire` job and its unfired check, as a "run now" does; everything else (paused, rate
31
+ * limit, overlap, the start) is the fire job's.
32
+ */
33
+ let EventCoalescer = class EventCoalescer {
34
+ kdb;
35
+ txHost;
36
+ config;
37
+ store;
38
+ outbox;
39
+ log;
40
+ constructor(kdb, txHost, config, store, outbox, log) {
41
+ this.kdb = kdb;
42
+ this.txHost = txHost;
43
+ this.config = config;
44
+ this.store = store;
45
+ this.outbox = outbox;
46
+ this.log = log;
47
+ }
48
+ /** Flushes the waiting deliveries of the pair (see the class); nothing when none wait. */
49
+ async flush(data) {
50
+ const { orgId, automationId, subjectKey } = data;
51
+ const db = this.kdb.db;
52
+ // the dispatcher takes the same row before it looks for a window: no delivery lands between
53
+ // the read below and the run that takes it
54
+ const task = await this.store.lockTask(db, orgId, automationId);
55
+ if (task === null)
56
+ return;
57
+ const waiting = await db
58
+ .selectFrom("automation_event_deliveries as d")
59
+ .innerJoin("trigger_events as e", "e.id", "d.event_id")
60
+ .select("d.event_id")
61
+ .where("d.org_id", "=", orgId)
62
+ .where("d.automation_id", "=", automationId)
63
+ .where("d.subject_key", "=", subjectKey)
64
+ .where("d.automation_run_id", "is", null)
65
+ .orderBy("e.created_at")
66
+ .orderBy("e.id")
67
+ .execute();
68
+ const first = waiting[0];
69
+ if (first === undefined)
70
+ return;
71
+ const settings = await readAutomationSettings(db, this.config, orgId);
72
+ const since = new Date(Date.now() - HOUR_MS);
73
+ const made = await db
74
+ .selectFrom("automation_runs as r")
75
+ .select((eb) => eb.fn.countAll().as("n"))
76
+ .where("r.org_id", "=", orgId)
77
+ .where("r.automation_id", "=", automationId)
78
+ .where("r.status", "!=", "skipped")
79
+ .where("r.created_at", ">=", since)
80
+ .where(({ exists, selectFrom }) => exists(selectFrom("automation_event_deliveries as s")
81
+ .select(sql `1`.as("one"))
82
+ .whereRef("s.automation_run_id", "=", "r.id")
83
+ .where("s.subject_key", "=", subjectKey)))
84
+ .executeTakeFirstOrThrow();
85
+ const limited = Number(made.n) >= settings.maxEventRunsPerSubjectPerHour;
86
+ const run = await this.store.insertRun(db, {
87
+ id: randomUUID(),
88
+ taskId: automationId,
89
+ orgId,
90
+ scheduledFor: null,
91
+ triggerKey: first.event_id,
92
+ trial: false,
93
+ ...(limited && { status: "skipped", skipReason: "subject_rate" }),
94
+ });
95
+ // the first event is waiting, so no run took it yet: a taken key is a broken invariant
96
+ if (run === null)
97
+ throw new Error(`event ${first.event_id} already keys a run of ${task.id}`);
98
+ await db
99
+ .updateTable("automation_event_deliveries")
100
+ .set({ automation_run_id: run.id })
101
+ .where("org_id", "=", orgId)
102
+ .where("automation_id", "=", automationId)
103
+ .where("event_id", "in", waiting.map((w) => w.event_id))
104
+ .execute();
105
+ if (limited) {
106
+ this.log.info("event automation run skipped: the subject's hourly run limit is reached", {
107
+ orgId,
108
+ automationId,
109
+ subjectKey,
110
+ taskRunId: run.id,
111
+ events: waiting.length,
112
+ });
113
+ return;
114
+ }
115
+ await oweAutomationFire(this.outbox, run.id, orgId);
116
+ await oweAutomationSettleUnfired(this.outbox, run.id, orgId, null, null);
117
+ }
118
+ };
119
+ __decorate([
120
+ Transactional()
121
+ ], EventCoalescer.prototype, "flush", null);
122
+ EventCoalescer = __decorate([
123
+ Injectable(),
124
+ __param(0, Inject(KernelDb)),
125
+ __param(1, Inject(TransactionHost)),
126
+ __param(2, Inject(KernelConfigService)),
127
+ __param(3, Inject(AutomationStore)),
128
+ __param(4, Inject(OutboxService)),
129
+ __param(5, Inject(KERNEL_LOGGER))
130
+ ], EventCoalescer);
131
+ export { EventCoalescer };
@@ -0,0 +1,10 @@
1
+ /** A trigger source's `events()` or `visible()` did not settle within its deadline. */
2
+ export declare class TriggerSourceTimeout extends Error {
3
+ constructor(plugin: string, call: string, ms: number);
4
+ }
5
+ /**
6
+ * `call()` raced against `ms`: a provider whose promise never settles must not hold a maintenance
7
+ * slot (BullMQ renews the job's lock while the process lives) or a request. A synchronous throw
8
+ * of `call` rejects like an asynchronous one.
9
+ */
10
+ export declare function withDeadline<T>(plugin: string, what: string, ms: number, call: () => T | Promise<T>): Promise<T>;
@@ -0,0 +1,24 @@
1
+ /** A trigger source's `events()` or `visible()` did not settle within its deadline. */
2
+ export class TriggerSourceTimeout extends Error {
3
+ constructor(plugin, call, ms) {
4
+ super(`trigger source ${plugin}: ${call} did not answer within ${ms} ms`);
5
+ this.name = "TriggerSourceTimeout";
6
+ }
7
+ }
8
+ /**
9
+ * `call()` raced against `ms`: a provider whose promise never settles must not hold a maintenance
10
+ * slot (BullMQ renews the job's lock while the process lives) or a request. A synchronous throw
11
+ * of `call` rejects like an asynchronous one.
12
+ */
13
+ export async function withDeadline(plugin, what, ms, call) {
14
+ let timer;
15
+ const deadline = new Promise((_, reject) => {
16
+ timer = setTimeout(() => reject(new TriggerSourceTimeout(plugin, what, ms)), ms);
17
+ });
18
+ try {
19
+ return await Promise.race([Promise.resolve().then(call), deadline]);
20
+ }
21
+ finally {
22
+ clearTimeout(timer);
23
+ }
24
+ }
@@ -0,0 +1,74 @@
1
+ import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
2
+ import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
3
+ import { KernelDb } from "../../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../../infra/database/transaction-host.js";
5
+ import { OutboxService } from "../../infra/outbox/outbox.service.js";
6
+ import type { KernelLogger } from "../../log.js";
7
+ import { type TriggerDispatchJobData } from "../job-ids.js";
8
+ export { TriggerSourceTimeout } from "./deadline.js";
9
+ /**
10
+ * Routes one stored trigger event to the event automations it fires (collaboration spec §4.3,
11
+ * §4.7), the `trigger-dispatch` job. In order:
12
+ * - an event no longer `pending` was dispatched before (a retried job): nothing to do;
13
+ * - a directed event (`audience` set) is left `pending` for acceptance routing (PR C);
14
+ * - past the org's `maxEventDepth` the event is `depth_stopped`;
15
+ * - a source the org switched off (`eventSourcesOff`), or one that does not serve the org now (its
16
+ * extension disabled, unloaded, its config invalid) or no longer declares the type, leaves the
17
+ * event `undelivered`: no run, no retry. A provider whose status could not be read (a transient
18
+ * error) fails the job, so BullMQ retries it;
19
+ * - the active, unexpired event automations of the org on this source and type whose filter
20
+ * matches the facts, minus the ones the event's cause run made (the same owner and the agent of
21
+ * the run's root conversation: self-trigger), are checked with the source's `visible()` once for
22
+ * all their owners; an owner it does not admit gets nothing;
23
+ * - each remaining automation gets a delivery, and the delivery that opens a window for its
24
+ * (automation, subject) pair owes the pair's `automation-coalesce` job, due `coalesceSeconds`
25
+ * on; later events of the window find its deliveries waiting and owe nothing, so the window ends
26
+ * in one run ({@link EventCoalescer}). The event becomes `dispatched`.
27
+ *
28
+ * The provider is asked outside any transaction; the deliveries, the owed jobs and the state are
29
+ * written in one, each automation row locked (id order), so a flush and a dispatch of one pair never
30
+ * interleave.
31
+ */
32
+ export declare class TriggerDispatcher {
33
+ private readonly kdb;
34
+ readonly txHost: TransactionHost;
35
+ private readonly config;
36
+ private readonly points;
37
+ private readonly outbox;
38
+ private readonly log;
39
+ constructor(kdb: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get">, points: Pick<ExtensionPointDefaults, "providersFor">, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "info" | "warn">);
40
+ /**
41
+ * Dispatches event `eventId` of org `orgId` (see the class). The source's `events()` and
42
+ * `visible()` each have `tools.timeoutMs`: past it the job fails with
43
+ * {@link TriggerSourceTimeout} (BullMQ retries it), and on its last attempt (`finalAttempt`) the
44
+ * event is `undelivered` instead.
45
+ */
46
+ dispatch(data: TriggerDispatchJobData, opts?: {
47
+ finalAttempt?: boolean;
48
+ }): Promise<void>;
49
+ /**
50
+ * Delivers `ev` to `automationIds` and owes each opened window's coalesce job (see the class),
51
+ * then marks the event `dispatched`; nothing when another dispatch of it got there first. Each
52
+ * automation's trigger and agent are read again under its row lock: one edited since the match
53
+ * (another type, source or filter; the cause run's agent now) gets no delivery.
54
+ */
55
+ private record;
56
+ /**
57
+ * The active, unexpired event automations of the org on `plugin` whose types include `type` (one
58
+ * past its `expires_at` gets nothing; the scan ends it).
59
+ */
60
+ private candidates;
61
+ /**
62
+ * The owner and agent of the run that caused the event (self-trigger), or null. The agent is
63
+ * the root conversation's: a sub-agent dispatched by an automation's run (its conversation a
64
+ * child of the run's) acts for that run, so its events count as the automation's own.
65
+ */
66
+ private causeOf;
67
+ private setState;
68
+ }
69
+ /**
70
+ * The trigger event dispatcher and the coalescer, for the maintenance processor, and the trigger
71
+ * event sweep (`@LockedCron`): worker only (imported by `MaintenanceModule` alone).
72
+ */
73
+ export declare class TriggerDispatchModule {
74
+ }