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

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 (100) hide show
  1. package/bootstrap.json +13 -13
  2. package/dist/automations/acceptance.controller.d.ts +29 -0
  3. package/dist/automations/acceptance.controller.js +87 -0
  4. package/dist/automations/automations.module.js +4 -1
  5. package/dist/automations/automations.schemas.d.ts +46 -0
  6. package/dist/automations/automations.schemas.js +31 -0
  7. package/dist/automations/automations.service.js +10 -1
  8. package/dist/automations/errors.d.ts +5 -0
  9. package/dist/automations/errors.js +5 -0
  10. package/dist/automations/events/acceptance.d.ts +205 -0
  11. package/dist/automations/events/acceptance.js +822 -0
  12. package/dist/automations/events/deliver.d.ts +39 -0
  13. package/dist/automations/events/deliver.js +112 -0
  14. package/dist/automations/events/dispatcher.d.ts +26 -10
  15. package/dist/automations/events/dispatcher.js +98 -99
  16. package/dist/automations/events/sweep.job.d.ts +104 -18
  17. package/dist/automations/events/sweep.job.js +311 -45
  18. package/dist/automations/events/trigger-events.service.d.ts +31 -2
  19. package/dist/automations/events/trigger-events.service.js +113 -30
  20. package/dist/automations/store.d.ts +7 -3
  21. package/dist/automations/store.js +6 -0
  22. package/dist/automations/types.d.ts +5 -0
  23. package/dist/catalog/marketplaces.service.d.ts +1 -1
  24. package/dist/config/schema.d.ts +3 -0
  25. package/dist/config/schema.js +14 -0
  26. package/dist/ctx/create-ctx.d.ts +24 -4
  27. package/dist/ctx/create-ctx.js +119 -6
  28. package/dist/db/kernel-schema.d.ts +89 -1
  29. package/dist/errors.d.ts +18 -0
  30. package/dist/errors.js +18 -0
  31. package/dist/extensions/hooks.d.ts +8 -5
  32. package/dist/extensions/hooks.js +2 -1
  33. package/dist/extensions/host.d.ts +12 -2
  34. package/dist/extensions/host.js +21 -1
  35. package/dist/extensions/lifecycle-hooks.d.ts +21 -7
  36. package/dist/extensions/lifecycle-hooks.js +51 -3
  37. package/dist/extensions/permission-set.d.ts +33 -1
  38. package/dist/extensions/permission-set.js +28 -1
  39. package/dist/extensions/permission-view.d.ts +1 -1
  40. package/dist/extensions/permission-view.js +24 -1
  41. package/dist/extensions/run-lifecycle-owe.d.ts +67 -0
  42. package/dist/extensions/run-lifecycle-owe.js +84 -0
  43. package/dist/http/api.module.js +4 -0
  44. package/dist/inbox/inbox-item-actions.d.ts +37 -0
  45. package/dist/inbox/inbox-item-actions.js +69 -0
  46. package/dist/inbox/inbox-items.controller.d.ts +27 -0
  47. package/dist/inbox/inbox-items.controller.js +80 -0
  48. package/dist/inbox/inbox-items.service.d.ts +110 -0
  49. package/dist/inbox/inbox-items.service.js +324 -0
  50. package/dist/inbox/inbox.module.d.ts +2 -1
  51. package/dist/inbox/inbox.module.js +15 -4
  52. package/dist/inbox/inbox.schemas.d.ts +20 -1
  53. package/dist/inbox/inbox.schemas.js +16 -1
  54. package/dist/inbox/inbox.service.d.ts +29 -7
  55. package/dist/inbox/inbox.service.js +29 -8
  56. package/dist/inbox/token.d.ts +5 -0
  57. package/dist/inbox/token.js +5 -0
  58. package/dist/infra/config/kernel-config.service.js +2 -0
  59. package/dist/infra/outbox/registry.d.ts +17 -0
  60. package/dist/infra/outbox/registry.js +15 -0
  61. package/dist/kernel.module.js +6 -0
  62. package/dist/orgs/settings.service.d.ts +20 -0
  63. package/dist/orgs/settings.service.js +4 -0
  64. package/dist/platform/exclusions.js +15 -0
  65. package/dist/platform/operation.d.ts +8 -0
  66. package/dist/platform/ops/automations.ops.d.ts +3 -1
  67. package/dist/platform/ops/automations.ops.js +45 -3
  68. package/dist/platform/ops/inbox.ops.d.ts +3 -1
  69. package/dist/platform/ops/inbox.ops.js +69 -4
  70. package/dist/platform/ops/platform.ops.js +4 -3
  71. package/dist/plugin-reads/plugin-reads.service.d.ts +29 -0
  72. package/dist/plugin-reads/plugin-reads.service.js +210 -0
  73. package/dist/plugin-reads/token.d.ts +5 -0
  74. package/dist/plugin-reads/token.js +5 -0
  75. package/dist/push/jobs.d.ts +5 -0
  76. package/dist/push/jobs.js +2 -0
  77. package/dist/push/preferences.service.d.ts +2 -2
  78. package/dist/push/preferences.service.js +9 -3
  79. package/dist/push/push-owed.d.ts +2 -0
  80. package/dist/push/push-owed.js +10 -1
  81. package/dist/push/push.schemas.d.ts +5 -2
  82. package/dist/push/push.schemas.js +4 -3
  83. package/dist/push/recipients.d.ts +2 -0
  84. package/dist/push/recipients.js +44 -3
  85. package/dist/push/texts.d.ts +14 -5
  86. package/dist/push/texts.js +2 -1
  87. package/dist/push/triggers.d.ts +1 -1
  88. package/dist/runtime/run-finish.js +19 -1
  89. package/dist/runtime/run-jobs.d.ts +12 -2
  90. package/dist/runtime/run-jobs.js +41 -4
  91. package/dist/runtime/run-queue.js +10 -0
  92. package/dist/runtime/waits.js +24 -1
  93. package/dist/tools/builtins/platform.js +2 -0
  94. package/dist/tools/pipeline.d.ts +5 -0
  95. package/dist/tools/pipeline.js +13 -1
  96. package/dist/tools/registry.d.ts +6 -0
  97. package/package.json +3 -3
  98. package/src/migrations/0192_inbox_items.sql +50 -0
  99. package/src/migrations/0193_trigger_cause_handles.sql +49 -0
  100. package/src/migrations/0194_automation_acceptance.sql +83 -0
@@ -0,0 +1,39 @@
1
+ import { type TriggerEventDeclaration } from "@capybara-hq/plugin-sdk";
2
+ import { type Selectable } from "kysely";
3
+ import type { KernelSchemaDb, TriggerEventsTable } from "../../db/kernel-schema.js";
4
+ import type { OutboxService } from "../../infra/outbox/outbox.service.js";
5
+ import type { KernelLogger } from "../../log.js";
6
+ export type EventRow = Selectable<TriggerEventsTable>;
7
+ /** The owner and agent of the run that caused an event (self-trigger), or null. */
8
+ export type EventCause = {
9
+ runAccountId: string;
10
+ runAgentId: string;
11
+ } | null;
12
+ /**
13
+ * A filter on a fact the source does not declare filterable never matches: an automation cannot
14
+ * filter on a fact its source keeps out of filters (collaboration spec §4.3).
15
+ */
16
+ export declare function filterAllowed(filter: readonly {
17
+ fact: string;
18
+ }[], decl: TriggerEventDeclaration): boolean;
19
+ /**
20
+ * Delivers `ev` to each of `automationIds` that still takes it, and owes each opened window's
21
+ * coalesce job (collaboration spec §4.7); the caller runs it in a transaction and decides the
22
+ * event's state. Each automation row is locked (id order, as the flush takes it) and read again:
23
+ * one switched off, expired or deleted since, whose trigger no longer selects the event, made by
24
+ * the event's cause run (self-trigger), or of the wrong kind gets nothing. A directed event
25
+ * (`audience` set) reaches only the acceptance automation of its audience (account and agent); an
26
+ * undirected one only automations a person made. The delivery that opens a window for its
27
+ * (automation, subject) pair owes the pair's `automation-coalesce` job, due `coalesceSeconds` on;
28
+ * later events of the window find its deliveries waiting and owe nothing. Returns how many
29
+ * deliveries it added.
30
+ */
31
+ export declare function deliverEvent(deps: {
32
+ db: KernelSchemaDb;
33
+ outbox: Pick<OutboxService, "add">;
34
+ log: Pick<KernelLogger, "warn">;
35
+ }, ev: EventRow, automationIds: readonly string[], match: {
36
+ decl: TriggerEventDeclaration;
37
+ cause: EventCause;
38
+ coalesceSeconds: number;
39
+ }): Promise<number>;
@@ -0,0 +1,112 @@
1
+ import { matchesFilter } from "@capybara-hq/plugin-sdk";
2
+ import { sql } from "kysely";
3
+ import { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
4
+ import { AUTOMATION_COALESCE_JOB } from "../job-ids.js";
5
+ import { COALESCE_STALE_MS, coalesceJobId, isSelfTriggered, subjectKey } from "./guards.js";
6
+ /**
7
+ * A filter on a fact the source does not declare filterable never matches: an automation cannot
8
+ * filter on a fact its source keeps out of filters (collaboration spec §4.3).
9
+ */
10
+ export function filterAllowed(filter, decl) {
11
+ return filter.every((c) => {
12
+ const fact = Object.hasOwn(decl.facts, c.fact) ? decl.facts[c.fact] : undefined;
13
+ return fact?.filterable === true;
14
+ });
15
+ }
16
+ /** Whether the automation's trigger still selects the event (re-read under its row lock). */
17
+ function triggerSelects(trigger, ev, decl) {
18
+ if (trigger.kind !== "event" || trigger.source !== ev.plugin)
19
+ return false;
20
+ if (!trigger.types.includes(ev.type))
21
+ return false;
22
+ const filter = trigger.filter ?? [];
23
+ return filterAllowed(filter, decl) && matchesFilter(filter, ev.facts);
24
+ }
25
+ /**
26
+ * Delivers `ev` to each of `automationIds` that still takes it, and owes each opened window's
27
+ * coalesce job (collaboration spec §4.7); the caller runs it in a transaction and decides the
28
+ * event's state. Each automation row is locked (id order, as the flush takes it) and read again:
29
+ * one switched off, expired or deleted since, whose trigger no longer selects the event, made by
30
+ * the event's cause run (self-trigger), or of the wrong kind gets nothing. A directed event
31
+ * (`audience` set) reaches only the acceptance automation of its audience (account and agent); an
32
+ * undirected one only automations a person made. The delivery that opens a window for its
33
+ * (automation, subject) pair owes the pair's `automation-coalesce` job, due `coalesceSeconds` on;
34
+ * later events of the window find its deliveries waiting and owe nothing. Returns how many
35
+ * deliveries it added.
36
+ */
37
+ export async function deliverEvent(deps, ev, automationIds, match) {
38
+ const { db, outbox, log } = deps;
39
+ const { decl, cause, coalesceSeconds } = match;
40
+ const orgId = ev.org_id;
41
+ const key = subjectKey(ev.subject);
42
+ const now = Date.now();
43
+ let added = 0;
44
+ for (const automationId of [...automationIds].sort()) {
45
+ const live = await db
46
+ .selectFrom("automations")
47
+ .select(["account_id", "agent_id", "trigger", "origin"])
48
+ .where("org_id", "=", orgId)
49
+ .where("id", "=", automationId)
50
+ .where("status", "=", "active")
51
+ .where("deleted_at", "is", null)
52
+ .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]))
53
+ .forUpdate()
54
+ .executeTakeFirst();
55
+ if (live === undefined)
56
+ continue;
57
+ const audience = ev.audience;
58
+ if (audience === null) {
59
+ if (live.origin !== "person")
60
+ continue;
61
+ }
62
+ else if (live.origin !== "acceptance" ||
63
+ live.account_id !== audience.accountId ||
64
+ live.agent_id !== audience.agentId) {
65
+ continue;
66
+ }
67
+ if (!triggerSelects(live.trigger, ev, decl))
68
+ continue;
69
+ if (isSelfTriggered({ accountId: live.account_id, agentId: live.agent_id }, cause))
70
+ continue;
71
+ const waiting = await db
72
+ .selectFrom("automation_event_deliveries")
73
+ .select((eb) => eb.fn.min("created_at").as("first"))
74
+ .where("org_id", "=", orgId)
75
+ .where("automation_id", "=", automationId)
76
+ .where("subject_key", "=", key)
77
+ .where("automation_run_id", "is", null)
78
+ .executeTakeFirst();
79
+ const inserted = await db
80
+ .insertInto("automation_event_deliveries")
81
+ .values({ org_id: orgId, automation_id: automationId, event_id: ev.id, subject_key: key })
82
+ .onConflict((oc) => oc.columns(["automation_id", "event_id"]).doNothing())
83
+ .returning("event_id")
84
+ .executeTakeFirst();
85
+ if (inserted === undefined)
86
+ continue;
87
+ added++;
88
+ const first = waiting?.first ?? null;
89
+ const open = first !== null &&
90
+ now - new Date(first).getTime() < coalesceSeconds * 1000 + COALESCE_STALE_MS;
91
+ if (open)
92
+ continue;
93
+ if (first !== null) {
94
+ log.warn("coalescing window outlived its job; a new window takes its events", {
95
+ orgId,
96
+ automationId,
97
+ subjectKey: key,
98
+ });
99
+ }
100
+ await outbox.add({
101
+ queue: MAINTENANCE_QUEUE_NAME,
102
+ name: AUTOMATION_COALESCE_JOB,
103
+ // one id per window: an add while an earlier window's job of the pair is still active
104
+ // (flushing) or kept would otherwise be swallowed by BullMQ
105
+ jobId: `${coalesceJobId(automationId, ev.subject)}-${ev.id}`,
106
+ data: { orgId, automationId, subjectKey: key },
107
+ runAt: new Date(now + coalesceSeconds * 1000),
108
+ orgId,
109
+ });
110
+ }
111
+ return added;
112
+ }
@@ -1,25 +1,31 @@
1
1
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
2
+ import { InboxItemsService } from "../../inbox/inbox-items.service.js";
2
3
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
3
4
  import { KernelDb } from "../../infra/database/kernel-db.js";
4
5
  import { TransactionHost } from "../../infra/database/transaction-host.js";
5
6
  import { OutboxService } from "../../infra/outbox/outbox.service.js";
6
7
  import type { KernelLogger } from "../../log.js";
7
- import { type TriggerDispatchJobData } from "../job-ids.js";
8
+ import type { TriggerDispatchJobData } from "../job-ids.js";
9
+ import { AcceptanceService } from "./acceptance.js";
8
10
  export { TriggerSourceTimeout } from "./deadline.js";
9
11
  /**
10
12
  * Routes one stored trigger event to the event automations it fires (collaboration spec §4.3,
11
13
  * §4.7), the `trigger-dispatch` job. In order:
12
14
  * - 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
+ * - past the org's `maxEventDepth` the event is `depth_stopped`, and the owner of the chain's last
16
+ * automation (the one whose run caused the event) gets a kernel inbox item
17
+ * `automation_depth_stopped` linking to it, one open item per automation;
15
18
  * - a source the org switched off (`eventSourcesOff`), or one that does not serve the org now (its
16
19
  * extension disabled, unloaded, its config invalid) or no longer declares the type, leaves the
17
20
  * event `undelivered`: no run, no retry. A provider whose status could not be read (a transient
18
21
  * 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;
22
+ * - a directed event (`audience` set) is routed by its audience's acceptance rule
23
+ * ({@link AcceptanceService.route}): it reaches at most that person's acceptance automation for
24
+ * the source and agent, or becomes a work offer, or nothing;
25
+ * - the active, unexpired event automations people made in the org on this source and type whose
26
+ * filter matches the facts, minus the ones the event's cause run made (the same owner and the
27
+ * agent of the run's root conversation: self-trigger), are checked with the source's `visible()`
28
+ * once for all their owners; an owner it does not admit gets nothing;
23
29
  * - each remaining automation gets a delivery, and the delivery that opens a window for its
24
30
  * (automation, subject) pair owes the pair's `automation-coalesce` job, due `coalesceSeconds`
25
31
  * on; later events of the window find its deliveries waiting and owe nothing, so the window ends
@@ -36,7 +42,9 @@ export declare class TriggerDispatcher {
36
42
  private readonly points;
37
43
  private readonly outbox;
38
44
  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">);
45
+ private readonly inbox;
46
+ private readonly acceptance;
47
+ constructor(kdb: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get">, points: Pick<ExtensionPointDefaults, "providersFor">, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "info" | "warn">, inbox: Pick<InboxItemsService, "post">, acceptance: Pick<AcceptanceService, "route">);
40
48
  /**
41
49
  * Dispatches event `eventId` of org `orgId` (see the class). The source's `events()` and
42
50
  * `visible()` each have `tools.timeoutMs`: past it the job fails with
@@ -54,8 +62,16 @@ export declare class TriggerDispatcher {
54
62
  */
55
63
  private record;
56
64
  /**
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).
65
+ * Marks `ev` `depth_stopped` and tells the owner of the chain's last automation (the automation
66
+ * whose run emitted the event) with a kernel inbox item, in one transaction; nothing when another
67
+ * dispatch settled the event first. The item links to the automation and is posted once per
68
+ * automation while open (`dedupeKey`); an owner no longer an active member gets none.
69
+ */
70
+ private stopForDepth;
71
+ /**
72
+ * The active, unexpired event automations people made in the org on `plugin` whose types include
73
+ * `type` (one past its `expires_at` gets nothing; the scan ends it). Acceptance automations take
74
+ * only directed events, through the acceptance routing.
59
75
  */
60
76
  private candidates;
61
77
  /**
@@ -7,60 +7,46 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { matchesFilter, } from "@capybara-hq/plugin-sdk";
10
+ import { InboxError, matchesFilter, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Module } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { conversationAncestors } from "../../conversations/tree.js";
14
14
  import { ExtensionsModule } from "../../extensions/extensions.module.js";
15
15
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
16
+ import { InboxItemsModule, InboxItemsService } from "../../inbox/inbox-items.service.js";
16
17
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
17
18
  import { KernelDb } from "../../infra/database/kernel-db.js";
18
19
  import { TransactionHost } from "../../infra/database/transaction-host.js";
19
20
  import { Transactional } from "../../infra/database/transactional.decorator.js";
20
21
  import { OutboxService } from "../../infra/outbox/outbox.service.js";
21
22
  import { KERNEL_LOGGER } from "../../infra/tokens.js";
22
- import { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
23
23
  import { readAutomationSettings } from "../effective-settings.js";
24
- import { AUTOMATION_COALESCE_JOB, } from "../job-ids.js";
25
24
  import { AutomationStoreModule } from "../store.module.js";
25
+ import { AcceptanceModule, AcceptanceService } from "./acceptance.js";
26
26
  import { EventCoalescer } from "./coalesce.js";
27
27
  import { TriggerSourceTimeout, withDeadline } from "./deadline.js";
28
- import { COALESCE_STALE_MS, coalesceJobId, depthExceeded, isSelfTriggered, subjectKey, } from "./guards.js";
28
+ import { deliverEvent, filterAllowed } from "./deliver.js";
29
+ import { depthExceeded, isSelfTriggered } from "./guards.js";
29
30
  import { TriggerEventSweepJob } from "./sweep.job.js";
30
31
  export { TriggerSourceTimeout } from "./deadline.js";
31
- /** Whether the automation's trigger still selects the event (re-read under its row lock). */
32
- function triggerSelects(trigger, ev, decl) {
33
- if (trigger.kind !== "event" || trigger.source !== ev.plugin)
34
- return false;
35
- if (!trigger.types.includes(ev.type))
36
- return false;
37
- const filter = trigger.filter ?? [];
38
- return filterAllowed(filter, decl) && matchesFilter(filter, ev.facts);
39
- }
40
- /**
41
- * A filter on a fact the source does not declare filterable never matches: an automation cannot
42
- * filter on a fact its source keeps out of filters (collaboration spec §4.3).
43
- */
44
- function filterAllowed(filter, decl) {
45
- return filter.every((c) => {
46
- const fact = Object.hasOwn(decl.facts, c.fact) ? decl.facts[c.fact] : undefined;
47
- return fact?.filterable === true;
48
- });
49
- }
50
32
  /**
51
33
  * Routes one stored trigger event to the event automations it fires (collaboration spec §4.3,
52
34
  * §4.7), the `trigger-dispatch` job. In order:
53
35
  * - an event no longer `pending` was dispatched before (a retried job): nothing to do;
54
- * - a directed event (`audience` set) is left `pending` for acceptance routing (PR C);
55
- * - past the org's `maxEventDepth` the event is `depth_stopped`;
36
+ * - past the org's `maxEventDepth` the event is `depth_stopped`, and the owner of the chain's last
37
+ * automation (the one whose run caused the event) gets a kernel inbox item
38
+ * `automation_depth_stopped` linking to it, one open item per automation;
56
39
  * - a source the org switched off (`eventSourcesOff`), or one that does not serve the org now (its
57
40
  * extension disabled, unloaded, its config invalid) or no longer declares the type, leaves the
58
41
  * event `undelivered`: no run, no retry. A provider whose status could not be read (a transient
59
42
  * error) fails the job, so BullMQ retries it;
60
- * - the active, unexpired event automations of the org on this source and type whose filter
61
- * matches the facts, minus the ones the event's cause run made (the same owner and the agent of
62
- * the run's root conversation: self-trigger), are checked with the source's `visible()` once for
63
- * all their owners; an owner it does not admit gets nothing;
43
+ * - a directed event (`audience` set) is routed by its audience's acceptance rule
44
+ * ({@link AcceptanceService.route}): it reaches at most that person's acceptance automation for
45
+ * the source and agent, or becomes a work offer, or nothing;
46
+ * - the active, unexpired event automations people made in the org on this source and type whose
47
+ * filter matches the facts, minus the ones the event's cause run made (the same owner and the
48
+ * agent of the run's root conversation: self-trigger), are checked with the source's `visible()`
49
+ * once for all their owners; an owner it does not admit gets nothing;
64
50
  * - each remaining automation gets a delivery, and the delivery that opens a window for its
65
51
  * (automation, subject) pair owes the pair's `automation-coalesce` job, due `coalesceSeconds`
66
52
  * on; later events of the window find its deliveries waiting and owe nothing, so the window ends
@@ -77,13 +63,17 @@ let TriggerDispatcher = class TriggerDispatcher {
77
63
  points;
78
64
  outbox;
79
65
  log;
80
- constructor(kdb, txHost, config, points, outbox, log) {
66
+ inbox;
67
+ acceptance;
68
+ constructor(kdb, txHost, config, points, outbox, log, inbox, acceptance) {
81
69
  this.kdb = kdb;
82
70
  this.txHost = txHost;
83
71
  this.config = config;
84
72
  this.points = points;
85
73
  this.outbox = outbox;
86
74
  this.log = log;
75
+ this.inbox = inbox;
76
+ this.acceptance = acceptance;
87
77
  }
88
78
  /**
89
79
  * Dispatches event `eventId` of org `orgId` (see the class). The source's `events()` and
@@ -103,20 +93,14 @@ let TriggerDispatcher = class TriggerDispatcher {
103
93
  if (ev === undefined || ev.state !== "pending")
104
94
  return;
105
95
  const ctx = { orgId, eventId, plugin: ev.plugin, type: ev.type };
106
- if (ev.audience !== null) {
107
- // TODO(collaboration C2): directed events are routed by the acceptance rules
108
- this.log.info("directed trigger event left pending for acceptance routing", ctx);
109
- return;
110
- }
111
96
  const settings = await readAutomationSettings(db, this.config, orgId);
112
97
  if (depthExceeded(ev.depth, settings.maxEventDepth)) {
113
- // TODO(collaboration C1): the inbox notice to the owners of the chain's last automation
114
98
  this.log.warn("trigger event past the org's chain depth; not dispatched", {
115
99
  ...ctx,
116
100
  depth: ev.depth,
117
101
  maxEventDepth: settings.maxEventDepth,
118
102
  });
119
- await this.setState(orgId, eventId, "depth_stopped");
103
+ await this.stopForDepth(ev);
120
104
  return;
121
105
  }
122
106
  if (settings.eventSourcesOff.includes(ev.plugin)) {
@@ -161,6 +145,21 @@ let TriggerDispatcher = class TriggerDispatcher {
161
145
  return;
162
146
  }
163
147
  const cause = await this.causeOf(orgId, ev.cause_run_id);
148
+ if (ev.audience !== null) {
149
+ await this.acceptance.route(ev, {
150
+ decl,
151
+ declared,
152
+ cause,
153
+ settings,
154
+ visible: async (accountIds) => ask("visible()", () => source.impl.visible({
155
+ orgId,
156
+ accountIds,
157
+ subject: ev.subject,
158
+ config: source.config,
159
+ })),
160
+ });
161
+ return;
162
+ }
164
163
  const matching = (await this.candidates(orgId, ev.plugin, ev.type)).filter((a) => filterAllowed(a.filter, decl) &&
165
164
  matchesFilter(a.filter, ev.facts) &&
166
165
  !isSelfTriggered(a, cause));
@@ -198,71 +197,65 @@ let TriggerDispatcher = class TriggerDispatcher {
198
197
  .executeTakeFirst();
199
198
  if (held?.state !== "pending")
200
199
  return;
201
- const key = subjectKey(ev.subject);
202
- const now = Date.now();
203
- for (const automationId of [...automationIds].sort()) {
204
- // the automation row first, as the flush takes it: switched off, expired or deleted since,
205
- // skipped
206
- const live = await db
207
- .selectFrom("automations")
208
- .select(["account_id", "agent_id", "trigger"])
209
- .where("org_id", "=", orgId)
210
- .where("id", "=", automationId)
211
- .where("status", "=", "active")
212
- .where("deleted_at", "is", null)
213
- .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]))
214
- .forUpdate()
215
- .executeTakeFirst();
216
- if (live === undefined)
217
- continue;
218
- if (!triggerSelects(live.trigger, ev, decl))
219
- continue;
220
- if (isSelfTriggered({ accountId: live.account_id, agentId: live.agent_id }, cause))
221
- continue;
222
- const waiting = await db
223
- .selectFrom("automation_event_deliveries")
224
- .select((eb) => eb.fn.min("created_at").as("first"))
225
- .where("org_id", "=", orgId)
226
- .where("automation_id", "=", automationId)
227
- .where("subject_key", "=", key)
228
- .where("automation_run_id", "is", null)
229
- .executeTakeFirst();
230
- const inserted = await db
231
- .insertInto("automation_event_deliveries")
232
- .values({ org_id: orgId, automation_id: automationId, event_id: ev.id, subject_key: key })
233
- .onConflict((oc) => oc.columns(["automation_id", "event_id"]).doNothing())
234
- .returning("event_id")
235
- .executeTakeFirst();
236
- if (inserted === undefined)
237
- continue;
238
- const first = waiting?.first ?? null;
239
- const open = first !== null &&
240
- now - new Date(first).getTime() < coalesceSeconds * 1000 + COALESCE_STALE_MS;
241
- if (open)
242
- continue;
243
- if (first !== null) {
244
- this.log.warn("coalescing window outlived its job; a new window takes its events", {
245
- orgId,
246
- automationId,
247
- subjectKey: key,
248
- });
249
- }
250
- await this.outbox.add({
251
- queue: MAINTENANCE_QUEUE_NAME,
252
- name: AUTOMATION_COALESCE_JOB,
253
- // one id per window: an add while an earlier window's job of the pair is still active
254
- // (flushing) or kept would otherwise be swallowed by BullMQ
255
- jobId: `${coalesceJobId(automationId, ev.subject)}-${ev.id}`,
256
- data: { orgId, automationId, subjectKey: key },
257
- runAt: new Date(now + coalesceSeconds * 1000),
200
+ await deliverEvent({ db, outbox: this.outbox, log: this.log }, ev, automationIds, {
201
+ decl,
202
+ cause,
203
+ coalesceSeconds,
204
+ });
205
+ await this.setState(orgId, ev.id, "dispatched");
206
+ }
207
+ /**
208
+ * Marks `ev` `depth_stopped` and tells the owner of the chain's last automation (the automation
209
+ * whose run emitted the event) with a kernel inbox item, in one transaction; nothing when another
210
+ * dispatch settled the event first. The item links to the automation and is posted once per
211
+ * automation while open (`dedupeKey`); an owner no longer an active member gets none.
212
+ */
213
+ async stopForDepth(ev) {
214
+ const db = this.kdb.db;
215
+ const orgId = ev.org_id;
216
+ const held = await db
217
+ .updateTable("trigger_events")
218
+ .set({ state: "depth_stopped" })
219
+ .where("org_id", "=", orgId)
220
+ .where("id", "=", ev.id)
221
+ .where("state", "=", "pending")
222
+ .returning("id")
223
+ .executeTakeFirst();
224
+ if (held === undefined || ev.cause_run_id === null)
225
+ return;
226
+ const last = await db
227
+ .selectFrom("runs")
228
+ .innerJoin("automation_runs", "automation_runs.id", "runs.automation_run_id")
229
+ .innerJoin("automations", "automations.id", "automation_runs.automation_id")
230
+ .select(["automations.id", "automations.account_id", "automations.name"])
231
+ .where("runs.id", "=", ev.cause_run_id)
232
+ .where("automation_runs.org_id", "=", orgId)
233
+ .where("automations.org_id", "=", orgId)
234
+ .where("automations.deleted_at", "is", null)
235
+ .executeTakeFirst();
236
+ if (last === undefined)
237
+ return;
238
+ try {
239
+ await this.inbox.post({ kind: "kernel" }, {
258
240
  orgId,
241
+ accountId: last.account_id,
242
+ kind: "automation_depth_stopped",
243
+ title: last.name,
244
+ body: `An event from ${ev.plugin} (${ev.type}) was not delivered: the chain of automations it came from reached the organization's depth limit.`,
245
+ link: `/automations/${encodeURIComponent(last.id)}`,
246
+ dedupeKey: `automation-depth-${last.id}`,
259
247
  });
260
248
  }
261
- await this.setState(orgId, ev.id, "dispatched");
249
+ catch (err) {
250
+ if (!(err instanceof InboxError))
251
+ throw err;
252
+ this.log.info("chain depth notice not posted", { orgId, eventId: ev.id, err });
253
+ }
262
254
  }
263
255
  /**
264
- * The active, unexpired event automations of the org on `plugin` whose types include `type` (one
265
- * past its `expires_at` gets nothing; the scan ends it).
256
+ * The active, unexpired event automations people made in the org on `plugin` whose types include
257
+ * `type` (one past its `expires_at` gets nothing; the scan ends it). Acceptance automations take
258
+ * only directed events, through the acceptance routing.
266
259
  */
267
260
  async candidates(orgId, plugin, type) {
268
261
  const rows = await this.kdb.db
@@ -270,6 +263,7 @@ let TriggerDispatcher = class TriggerDispatcher {
270
263
  .select(["id", "account_id", "agent_id", "trigger"])
271
264
  .where("org_id", "=", orgId)
272
265
  .where("status", "=", "active")
266
+ .where("origin", "=", "person")
273
267
  .where("deleted_at", "is", null)
274
268
  .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]))
275
269
  .where(sql `trigger->>'kind' = 'event'`)
@@ -327,6 +321,9 @@ let TriggerDispatcher = class TriggerDispatcher {
327
321
  __decorate([
328
322
  Transactional()
329
323
  ], TriggerDispatcher.prototype, "record", null);
324
+ __decorate([
325
+ Transactional()
326
+ ], TriggerDispatcher.prototype, "stopForDepth", null);
330
327
  TriggerDispatcher = __decorate([
331
328
  Injectable(),
332
329
  __param(0, Inject(KernelDb)),
@@ -334,7 +331,9 @@ TriggerDispatcher = __decorate([
334
331
  __param(2, Inject(KernelConfigService)),
335
332
  __param(3, Inject(ExtensionPointDefaults)),
336
333
  __param(4, Inject(OutboxService)),
337
- __param(5, Inject(KERNEL_LOGGER))
334
+ __param(5, Inject(KERNEL_LOGGER)),
335
+ __param(6, Inject(InboxItemsService)),
336
+ __param(7, Inject(AcceptanceService))
338
337
  ], TriggerDispatcher);
339
338
  export { TriggerDispatcher };
340
339
  /**
@@ -345,7 +344,7 @@ let TriggerDispatchModule = class TriggerDispatchModule {
345
344
  };
346
345
  TriggerDispatchModule = __decorate([
347
346
  Module({
348
- imports: [ExtensionsModule, AutomationStoreModule],
347
+ imports: [ExtensionsModule, AutomationStoreModule, InboxItemsModule, AcceptanceModule],
349
348
  providers: [TriggerDispatcher, EventCoalescer, TriggerEventSweepJob],
350
349
  exports: [TriggerDispatcher, EventCoalescer],
351
350
  })