@capybara-hq/kernel 0.1.0-rc.105 → 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.
- package/dist/agents/agents.schemas.d.ts +9 -9
- package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
- package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
- package/dist/automations/automations.module.d.ts +16 -0
- package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
- package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
- package/dist/automations/automations.schemas.js +253 -0
- package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
- package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
- package/dist/{schedules → automations}/calendar.d.ts +8 -8
- package/dist/{schedules → automations}/calendar.js +2 -2
- package/dist/automations/effective-settings.d.ts +28 -0
- package/dist/automations/effective-settings.js +25 -0
- package/dist/automations/errors.d.ts +19 -0
- package/dist/automations/errors.js +19 -0
- package/dist/automations/events/coalesce.d.ts +28 -0
- package/dist/automations/events/coalesce.js +131 -0
- package/dist/automations/events/deadline.d.ts +10 -0
- package/dist/automations/events/deadline.js +24 -0
- package/dist/automations/events/dispatcher.d.ts +74 -0
- package/dist/automations/events/dispatcher.js +353 -0
- package/dist/automations/events/events.module.d.ts +7 -0
- package/dist/automations/events/events.module.js +26 -0
- package/dist/automations/events/guards.d.ts +32 -0
- package/dist/automations/events/guards.js +87 -0
- package/dist/automations/events/sweep.job.d.ts +49 -0
- package/dist/automations/events/sweep.job.js +202 -0
- package/dist/automations/events/token.d.ts +5 -0
- package/dist/automations/events/token.js +5 -0
- package/dist/automations/events/trigger-events.service.d.ts +47 -0
- package/dist/automations/events/trigger-events.service.js +254 -0
- package/dist/{schedules → automations}/fire.d.ts +57 -17
- package/dist/{schedules → automations}/fire.js +311 -79
- package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
- package/dist/{schedules → automations}/grant-rules.js +5 -5
- package/dist/automations/job-ids.d.ts +113 -0
- package/dist/automations/job-ids.js +117 -0
- package/dist/{schedules → automations}/pause.d.ts +3 -3
- package/dist/{schedules → automations}/pause.js +3 -3
- package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
- package/dist/{schedules → automations}/run-tracker.js +68 -56
- package/dist/{schedules → automations}/scan.job.d.ts +12 -8
- package/dist/{schedules → automations}/scan.job.js +39 -23
- package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
- package/dist/{schedules → automations}/schedule-math.js +17 -7
- package/dist/{schedules → automations}/store.d.ts +57 -27
- package/dist/{schedules → automations}/store.js +102 -52
- package/dist/automations/store.module.d.ts +6 -0
- package/dist/{schedules → automations}/store.module.js +9 -9
- package/dist/automations/types.d.ts +178 -0
- package/dist/{schedules → automations}/unattended.d.ts +22 -11
- package/dist/{schedules → automations}/unattended.js +53 -30
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.module.js +3 -3
- package/dist/channels/outbound.d.ts +5 -5
- package/dist/channels/outbound.js +17 -17
- package/dist/channels/threads.d.ts +1 -1
- package/dist/channels/threads.js +1 -1
- package/dist/config/schema.d.ts +5 -1
- package/dist/config/schema.js +44 -6
- package/dist/conversations/approval-profile.d.ts +2 -2
- package/dist/conversations/approval-profile.js +3 -3
- package/dist/conversations/conversations.controller.d.ts +7 -1
- package/dist/conversations/conversations.controller.js +26 -10
- package/dist/conversations/conversations.service.d.ts +101 -25
- package/dist/conversations/conversations.service.js +132 -32
- package/dist/conversations/events.d.ts +46 -0
- package/dist/conversations/events.js +54 -3
- package/dist/conversations/message-context.d.ts +2 -2
- package/dist/conversations/message-context.js +1 -1
- package/dist/conversations/permission-profile-store.d.ts +2 -1
- package/dist/conversations/permission-profiles.controller.d.ts +3 -0
- package/dist/conversations/permission-profiles.service.js +1 -1
- package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
- package/dist/conversations/prompt-suggestion-request.js +2 -1
- package/dist/conversations/queue.d.ts +7 -4
- package/dist/conversations/queue.js +6 -2
- package/dist/conversations/queue.service.d.ts +5 -5
- package/dist/conversations/queue.service.js +20 -14
- package/dist/ctx/create-ctx.d.ts +20 -1
- package/dist/ctx/create-ctx.js +59 -2
- package/dist/db/kernel-schema.d.ts +104 -25
- package/dist/devices/device-project-files.service.d.ts +88 -0
- package/dist/devices/device-project-files.service.js +249 -0
- package/dist/devices/device-projects.service.d.ts +40 -0
- package/dist/devices/device-projects.service.js +16 -13
- package/dist/devices/devices.controller.d.ts +9 -3
- package/dist/devices/devices.controller.js +27 -5
- package/dist/devices/devices.module.js +9 -1
- package/dist/devices/devices.schemas.js +6 -1
- package/dist/devices/dto.d.ts +15 -0
- package/dist/devices/dto.js +11 -0
- package/dist/devices/project-paths.d.ts +29 -0
- package/dist/devices/project-paths.js +66 -0
- package/dist/devices/project-rules.d.ts +5 -1
- package/dist/devices/project-rules.js +5 -1
- package/dist/errors.d.ts +34 -13
- package/dist/errors.js +34 -13
- package/dist/evals/reconstruct.d.ts +10 -1
- package/dist/evals/reconstruct.js +7 -0
- package/dist/extensions/host.d.ts +6 -1
- package/dist/extensions/host.js +10 -0
- package/dist/extensions/permission-set.d.ts +17 -1
- package/dist/extensions/permission-set.js +13 -1
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +4 -1
- package/dist/git/gateway.js +2 -2
- package/dist/http/api.module.js +5 -5
- package/dist/http/request-signal.d.ts +8 -0
- package/dist/http/request-signal.js +14 -0
- package/dist/inbox/inbox.module.js +2 -2
- package/dist/inbox/inbox.service.d.ts +8 -8
- package/dist/inbox/inbox.service.js +7 -7
- package/dist/infra/config/kernel-config.service.js +10 -5
- package/dist/infra/outbox/registry.d.ts +29 -2
- package/dist/infra/outbox/registry.js +30 -7
- package/dist/kernel.module.js +3 -0
- package/dist/orgs/roles.d.ts +1 -1
- package/dist/orgs/roles.js +3 -3
- package/dist/orgs/settings.controller.d.ts +1 -1
- package/dist/orgs/settings.service.d.ts +27 -11
- package/dist/orgs/settings.service.js +42 -24
- package/dist/platform/operation.js +2 -2
- package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
- package/dist/platform/ops/automations.ops.js +560 -0
- package/dist/platform/ops/devices.ops.d.ts +3 -1
- package/dist/platform/ops/devices.ops.js +77 -3
- package/dist/platform/ops/inbox.ops.js +4 -4
- package/dist/platform/ops/orgs.ops.js +1 -1
- package/dist/platform/ops/platform.ops.js +4 -4
- package/dist/platform/platform-ops.module.d.ts +2 -2
- package/dist/platform/platform-ops.module.js +5 -5
- package/dist/platform/route-schemas.js +3 -3
- package/dist/push/jobs.d.ts +3 -3
- package/dist/push/jobs.js +2 -2
- package/dist/push/preferences.service.js +1 -1
- package/dist/push/push-owed.d.ts +3 -3
- package/dist/push/push-owed.js +6 -6
- package/dist/push/push.schemas.d.ts +4 -4
- package/dist/push/push.schemas.js +3 -3
- package/dist/push/recipients.d.ts +4 -4
- package/dist/push/recipients.js +23 -23
- package/dist/push/texts.d.ts +3 -3
- package/dist/push/texts.js +2 -2
- package/dist/push/triggers.d.ts +1 -1
- package/dist/roles/worker.module.js +3 -3
- package/dist/runtime/context/build.d.ts +6 -0
- package/dist/runtime/context/build.js +14 -3
- package/dist/runtime/context/compaction.js +15 -5
- package/dist/runtime/context/run-context.d.ts +38 -0
- package/dist/runtime/context/run-context.js +54 -0
- package/dist/runtime/maintenance.d.ts +8 -4
- package/dist/runtime/maintenance.js +37 -16
- package/dist/runtime/run-finish.d.ts +4 -4
- package/dist/runtime/run-finish.js +3 -3
- package/dist/runtime/run-queue.js +12 -7
- package/dist/runtime/run-worker.js +7 -1
- package/dist/runtime/runtime.module.js +3 -3
- package/dist/runtime/subagents/dispatch.js +11 -3
- package/dist/sandbox/browse-roots.d.ts +8 -0
- package/dist/sandbox/browse-roots.js +22 -0
- package/dist/sandbox/network-grants.d.ts +4 -4
- package/dist/sandbox/network-grants.js +7 -7
- package/dist/sandbox/operation-authority.d.ts +10 -3
- package/dist/sandbox/operation-authority.js +20 -10
- package/dist/sandbox/operation-intents.d.ts +3 -1
- package/dist/sandbox/operation-intents.js +11 -4
- package/dist/sandbox/permission-call-grants.js +2 -2
- package/dist/sandbox/permission-facts.js +1 -1
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +22 -11
- package/dist/sandbox/review/permission-candidate.d.ts +1 -1
- package/dist/sandbox/review/permission-candidate.js +1 -1
- package/dist/sandbox/sandbox.service.d.ts +15 -5
- package/dist/sandbox/sandbox.service.js +14 -8
- package/dist/storage/purge.d.ts +1 -1
- package/dist/storage/purge.js +2 -2
- package/dist/tools/approvals.service.d.ts +6 -6
- package/dist/tools/approvals.service.js +19 -19
- package/dist/tools/builtin-names.d.ts +12 -12
- package/dist/tools/builtin-names.js +29 -29
- package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
- package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
- package/dist/tools/builtins/builtin-tools.d.ts +8 -8
- package/dist/tools/builtins/builtin-tools.js +16 -16
- package/dist/tools/call-scope.d.ts +1 -1
- package/dist/tools/git-asks.js +1 -1
- package/dist/tools/git-push-policy.d.ts +3 -3
- package/dist/tools/git-push-policy.js +6 -6
- package/dist/tools/network-asks.d.ts +3 -3
- package/dist/tools/network-asks.js +3 -3
- package/dist/tools/pipeline.d.ts +4 -4
- package/dist/tools/pipeline.js +2 -2
- package/dist/tools/policy.d.ts +3 -3
- package/dist/tools/policy.js +3 -3
- package/dist/tools/tools.module.js +9 -9
- package/package.json +3 -3
- package/src/migrations/0188_automations_rename.sql +309 -0
- package/src/migrations/0189_event_automations.sql +136 -0
- package/dist/platform/ops/schedules.ops.js +0 -509
- package/dist/schedules/effective-settings.d.ts +0 -22
- package/dist/schedules/effective-settings.js +0 -18
- package/dist/schedules/errors.d.ts +0 -8
- package/dist/schedules/errors.js +0 -8
- package/dist/schedules/job-ids.d.ts +0 -81
- package/dist/schedules/job-ids.js +0 -95
- package/dist/schedules/schedules.module.d.ts +0 -16
- package/dist/schedules/schedules.schemas.js +0 -213
- package/dist/schedules/store.module.d.ts +0 -6
- package/dist/schedules/types.d.ts +0 -110
- /package/dist/{schedules → automations}/types.js +0 -0
|
@@ -0,0 +1,202 @@
|
|
|
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 { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { sql } from "kysely";
|
|
12
|
+
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
13
|
+
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
14
|
+
import { asPlatform, withOrgScope } from "../../infra/database/org-scope.js";
|
|
15
|
+
import { TransactionHost } from "../../infra/database/transaction-host.js";
|
|
16
|
+
import { Transactional } from "../../infra/database/transactional.decorator.js";
|
|
17
|
+
import { LockService } from "../../infra/lock/lock.service.js";
|
|
18
|
+
import { OutboxService } from "../../infra/outbox/outbox.service.js";
|
|
19
|
+
import { LockedCron } from "../../infra/schedule/locked-cron.decorator.js";
|
|
20
|
+
import { KERNEL_LOGGER } from "../../infra/tokens.js";
|
|
21
|
+
import { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
|
|
22
|
+
import { readAutomationSettings } from "../effective-settings.js";
|
|
23
|
+
import { AUTOMATION_COALESCE_JOB, TRIGGER_EVENT_SWEEP_JOB, } from "../job-ids.js";
|
|
24
|
+
import { COALESCE_STALE_MS, coalesceJobIdOfKey } from "./guards.js";
|
|
25
|
+
const DAY_MS = 86_400_000;
|
|
26
|
+
/** Events deleted per transaction. */
|
|
27
|
+
const DELETE_BATCH = 500;
|
|
28
|
+
/** Batches per sweep; what is left waits for the next one. */
|
|
29
|
+
const MAX_BATCHES = 40;
|
|
30
|
+
/** Waiting windows looked at per sweep. */
|
|
31
|
+
const MAX_WINDOWS = 1000;
|
|
32
|
+
/**
|
|
33
|
+
* The trigger event sweep (collaboration spec §4.7), every five minutes across replicas:
|
|
34
|
+
*
|
|
35
|
+
* - **Retention.** A trigger event settled (`dispatched`, `undelivered`, `depth_stopped`) more than
|
|
36
|
+
* `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run, is
|
|
37
|
+
* deleted with its deliveries (the foreign key cascades), in batches of {@link DELETE_BATCH}, one
|
|
38
|
+
* transaction each. A `pending` event (a directed one waiting for acceptance routing) stays. A
|
|
39
|
+
* run keeps its `trigger_key` and a kernel run its `trigger_event_id` (neither has a foreign
|
|
40
|
+
* key); a chain whose event is gone restarts at depth 0.
|
|
41
|
+
* - **Lost windows.** The dispatcher owes one coalesce job per window, from the delivery that opens
|
|
42
|
+
* it. A window whose first delivery has waited longer than the org's `coalesceSeconds` plus
|
|
43
|
+
* {@link COALESCE_STALE_MS} lost its job for good (dead in the outbox, or failed in the queue);
|
|
44
|
+
* unless an outbox row for it is still pending, the sweep owes a coalesce job of its own
|
|
45
|
+
* (`<window job id>-sweep-<minute>`, due now). The flush is idempotent, so a duplicate finds
|
|
46
|
+
* nothing waiting.
|
|
47
|
+
*/
|
|
48
|
+
let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
49
|
+
kdb;
|
|
50
|
+
txHost;
|
|
51
|
+
config;
|
|
52
|
+
outbox;
|
|
53
|
+
lockService;
|
|
54
|
+
log;
|
|
55
|
+
constructor(kdb, txHost, config, outbox, lockService, log) {
|
|
56
|
+
this.kdb = kdb;
|
|
57
|
+
this.txHost = txHost;
|
|
58
|
+
this.config = config;
|
|
59
|
+
this.outbox = outbox;
|
|
60
|
+
this.lockService = lockService;
|
|
61
|
+
this.log = log;
|
|
62
|
+
}
|
|
63
|
+
async sweep() {
|
|
64
|
+
await this.sweepAt(new Date());
|
|
65
|
+
}
|
|
66
|
+
/** One sweep as of `now` (tests pass their own): how many events it deleted and windows it owed. */
|
|
67
|
+
async sweepAt(now) {
|
|
68
|
+
const days = this.config.get().automations.eventRetentionDays;
|
|
69
|
+
const cutoff = new Date(now.getTime() - days * DAY_MS);
|
|
70
|
+
let deleted = 0;
|
|
71
|
+
for (let i = 0; i < MAX_BATCHES; i++) {
|
|
72
|
+
const n = await this.deleteBatch(cutoff);
|
|
73
|
+
deleted += n;
|
|
74
|
+
if (n < DELETE_BATCH)
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
if (deleted > 0)
|
|
78
|
+
this.log.info("old trigger events deleted", { deleted, retentionDays: days });
|
|
79
|
+
let owed = 0;
|
|
80
|
+
for (const w of await this.waitingWindows(now)) {
|
|
81
|
+
if (await withOrgScope(w.orgId, () => this.oweFlush(w, now)))
|
|
82
|
+
owed++;
|
|
83
|
+
}
|
|
84
|
+
return { deleted, owed };
|
|
85
|
+
}
|
|
86
|
+
/** Deletes one batch of settled events older than `cutoff` (see the class); returns how many. */
|
|
87
|
+
async deleteBatch(cutoff) {
|
|
88
|
+
const db = this.kdb.db;
|
|
89
|
+
return asPlatform("deployment-wide trigger event retention sweep", async () => {
|
|
90
|
+
const r = await sql `
|
|
91
|
+
DELETE FROM capybara.trigger_events
|
|
92
|
+
WHERE id IN (
|
|
93
|
+
SELECT e.id FROM capybara.trigger_events e
|
|
94
|
+
WHERE e.state IN ('dispatched', 'undelivered', 'depth_stopped')
|
|
95
|
+
AND e.created_at < ${cutoff}
|
|
96
|
+
AND NOT EXISTS (
|
|
97
|
+
SELECT 1 FROM capybara.automation_event_deliveries d
|
|
98
|
+
WHERE d.event_id = e.id AND d.automation_run_id IS NULL
|
|
99
|
+
)
|
|
100
|
+
ORDER BY e.created_at
|
|
101
|
+
LIMIT ${DELETE_BATCH}
|
|
102
|
+
FOR UPDATE SKIP LOCKED
|
|
103
|
+
)
|
|
104
|
+
RETURNING id`.execute(db);
|
|
105
|
+
return r.rows.length;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The windows whose first waiting delivery is older than their org's `coalesceSeconds` plus
|
|
110
|
+
* {@link COALESCE_STALE_MS} (see the class), oldest first.
|
|
111
|
+
*/
|
|
112
|
+
async waitingWindows(now) {
|
|
113
|
+
const db = this.kdb.db;
|
|
114
|
+
// coalesceSeconds is at least 1: anything younger than the stale margin is not stale anywhere
|
|
115
|
+
const older = new Date(now.getTime() - COALESCE_STALE_MS);
|
|
116
|
+
const rows = await asPlatform("deployment-wide lost coalescing window sweep", () => sql `
|
|
117
|
+
SELECT DISTINCT ON (d.automation_id, d.subject_key)
|
|
118
|
+
d.org_id, d.automation_id, d.subject_key, d.event_id AS first_event_id,
|
|
119
|
+
d.created_at AS first
|
|
120
|
+
FROM capybara.automation_event_deliveries d
|
|
121
|
+
JOIN capybara.trigger_events e ON e.id = d.event_id
|
|
122
|
+
WHERE d.automation_run_id IS NULL
|
|
123
|
+
AND d.created_at < ${older}
|
|
124
|
+
ORDER BY d.automation_id, d.subject_key, d.created_at, e.created_at, e.id
|
|
125
|
+
LIMIT ${MAX_WINDOWS}`.execute(db));
|
|
126
|
+
const settings = new Map();
|
|
127
|
+
const out = [];
|
|
128
|
+
for (const r of rows.rows) {
|
|
129
|
+
let coalesceSeconds = settings.get(r.org_id);
|
|
130
|
+
if (coalesceSeconds === undefined) {
|
|
131
|
+
coalesceSeconds = (await withOrgScope(r.org_id, () => readAutomationSettings(db, this.config, r.org_id))).coalesceSeconds;
|
|
132
|
+
settings.set(r.org_id, coalesceSeconds);
|
|
133
|
+
}
|
|
134
|
+
const first = new Date(r.first);
|
|
135
|
+
if (now.getTime() - first.getTime() <= coalesceSeconds * 1000 + COALESCE_STALE_MS)
|
|
136
|
+
continue;
|
|
137
|
+
out.push({
|
|
138
|
+
orgId: r.org_id,
|
|
139
|
+
automationId: r.automation_id,
|
|
140
|
+
subjectKey: r.subject_key,
|
|
141
|
+
firstEventId: r.first_event_id,
|
|
142
|
+
first,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return out.sort((a, b) => a.first.getTime() - b.first.getTime());
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Owes the window's coalesce job unless an outbox row for it (the dispatcher's or an earlier
|
|
149
|
+
* sweep's) is still pending; true when it owed one.
|
|
150
|
+
*/
|
|
151
|
+
async oweFlush(w, now) {
|
|
152
|
+
const db = this.kdb.db;
|
|
153
|
+
const base = `${coalesceJobIdOfKey(w.automationId, w.subjectKey)}-${w.firstEventId}`;
|
|
154
|
+
const pending = await db
|
|
155
|
+
.selectFrom("outbox")
|
|
156
|
+
.select("id")
|
|
157
|
+
.where("org_id", "=", w.orgId)
|
|
158
|
+
.where("queue", "=", MAINTENANCE_QUEUE_NAME)
|
|
159
|
+
.where("job_name", "=", AUTOMATION_COALESCE_JOB)
|
|
160
|
+
.where((eb) => eb.or([eb("job_id", "=", base), sql `starts_with(job_id, ${`${base}-sweep-`})`]))
|
|
161
|
+
.where("dead_at", "is", null)
|
|
162
|
+
.limit(1)
|
|
163
|
+
.executeTakeFirst();
|
|
164
|
+
if (pending !== undefined)
|
|
165
|
+
return false;
|
|
166
|
+
this.log.warn("coalescing window lost its job; the sweep owes one", {
|
|
167
|
+
orgId: w.orgId,
|
|
168
|
+
automationId: w.automationId,
|
|
169
|
+
subjectKey: w.subjectKey,
|
|
170
|
+
waitingSince: w.first.toISOString(),
|
|
171
|
+
});
|
|
172
|
+
return this.outbox.add({
|
|
173
|
+
queue: MAINTENANCE_QUEUE_NAME,
|
|
174
|
+
name: AUTOMATION_COALESCE_JOB,
|
|
175
|
+
jobId: `${base}-sweep-${Math.floor(now.getTime() / 60_000)}`,
|
|
176
|
+
data: { orgId: w.orgId, automationId: w.automationId, subjectKey: w.subjectKey },
|
|
177
|
+
orgId: w.orgId,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
__decorate([
|
|
182
|
+
LockedCron("*/5 * * * *", { name: TRIGGER_EVENT_SWEEP_JOB })
|
|
183
|
+
], TriggerEventSweepJob.prototype, "sweep", null);
|
|
184
|
+
__decorate([
|
|
185
|
+
Transactional()
|
|
186
|
+
], TriggerEventSweepJob.prototype, "deleteBatch", null);
|
|
187
|
+
__decorate([
|
|
188
|
+
Transactional()
|
|
189
|
+
], TriggerEventSweepJob.prototype, "oweFlush", null);
|
|
190
|
+
TriggerEventSweepJob = __decorate([
|
|
191
|
+
Injectable()
|
|
192
|
+
// org-filter: deployment-wide sweeps of trigger events and waiting deliveries (LockedCron), each
|
|
193
|
+
// owed job in its own org
|
|
194
|
+
,
|
|
195
|
+
__param(0, Inject(KernelDb)),
|
|
196
|
+
__param(1, Inject(TransactionHost)),
|
|
197
|
+
__param(2, Inject(KernelConfigService)),
|
|
198
|
+
__param(3, Inject(OutboxService)),
|
|
199
|
+
__param(4, Inject(LockService)),
|
|
200
|
+
__param(5, Inject(KERNEL_LOGGER))
|
|
201
|
+
], TriggerEventSweepJob);
|
|
202
|
+
export { TriggerEventSweepJob };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type TriggerEvent } from "@capybara-hq/plugin-sdk";
|
|
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
|
+
/** Most facts one event may carry. */
|
|
6
|
+
export declare const TRIGGER_MAX_FACTS = 64;
|
|
7
|
+
/** Most UTF-8 bytes of one string fact value (also of each item of a `string[]` fact). */
|
|
8
|
+
export declare const TRIGGER_FACT_STRING_MAX_BYTES = 256;
|
|
9
|
+
/** Most UTF-8 bytes of `subject.kind`, `subject.id`, `dedupeKey` and each fact name. */
|
|
10
|
+
export declare const TRIGGER_KEY_MAX_BYTES = 256;
|
|
11
|
+
/** Most UTF-8 bytes of `subject.title`. */
|
|
12
|
+
export declare const TRIGGER_TITLE_MAX_BYTES = 1024;
|
|
13
|
+
/** Most UTF-8 bytes of `subject.url`. */
|
|
14
|
+
export declare const TRIGGER_URL_MAX_BYTES = 2048;
|
|
15
|
+
/** Most items of one `string[]` fact. */
|
|
16
|
+
export declare const TRIGGER_FACT_LIST_MAX_ITEMS = 64;
|
|
17
|
+
/**
|
|
18
|
+
* Stores the events extensions emit (`ctx.triggers.emit`, collaboration spec §4.2) and owes their
|
|
19
|
+
* dispatch. The emitting extension, the event types it may emit (its approved manifest's
|
|
20
|
+
* `permissions.triggers.emit`) and the cause's run and depth are the kernel's: an extension cannot
|
|
21
|
+
* name another plugin, an undeclared type, a run of another org or a chain depth of its choosing.
|
|
22
|
+
*/
|
|
23
|
+
export declare class TriggerEventsService {
|
|
24
|
+
private readonly kdb;
|
|
25
|
+
readonly txHost: TransactionHost;
|
|
26
|
+
private readonly outbox;
|
|
27
|
+
constructor(kdb: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">);
|
|
28
|
+
/**
|
|
29
|
+
* Validates `e` for `plugin` (whose approved manifest declares `declared`), checks the plugin is
|
|
30
|
+
* enabled in the event's org and verifies the cause: a tool call context must be one the tool
|
|
31
|
+
* pipeline made (its run read from the call scope, never from the context's own fields) for a
|
|
32
|
+
* run of the event's org, and the event's depth is that run's trigger event's depth + 1 (0 when
|
|
33
|
+
* the run started from no event); an account must be an active member of the org (depth 0).
|
|
34
|
+
* Then inserts the `trigger_events` row and owes its `trigger-dispatch` job in the same
|
|
35
|
+
* transaction. An event already stored for (org, plugin, dedupe key) is a duplicate: its id comes
|
|
36
|
+
* back with `duplicate: true` and nothing is owed. The caller runs it in the event's org scope.
|
|
37
|
+
*
|
|
38
|
+
* Throws `TriggerError`: `type_not_declared`, `invalid_event` (a missing or malformed field, a
|
|
39
|
+
* forged or foreign cause), `org_disabled` (the plugin is not enabled in the org).
|
|
40
|
+
*/
|
|
41
|
+
emit(plugin: string, declared: readonly string[], e: TriggerEvent): Promise<{
|
|
42
|
+
eventId: string;
|
|
43
|
+
duplicate: boolean;
|
|
44
|
+
}>;
|
|
45
|
+
/** The verified cause of `e` (see {@link emit}); no cause is depth 0 with nobody behind it. */
|
|
46
|
+
private verifyCause;
|
|
47
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
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 { TriggerError, validateTriggerEvent, } from "@capybara-hq/plugin-sdk";
|
|
12
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
13
|
+
import { isExtensionEnabled } from "../../extensions/enabled.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 { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
|
|
19
|
+
import { callScopeOf } from "../../tools/call-scope.js";
|
|
20
|
+
import { TRIGGER_DISPATCH_JOB, triggerDispatchJobId, } from "../job-ids.js";
|
|
21
|
+
/** Most facts one event may carry. */
|
|
22
|
+
export const TRIGGER_MAX_FACTS = 64;
|
|
23
|
+
/** Most UTF-8 bytes of one string fact value (also of each item of a `string[]` fact). */
|
|
24
|
+
export const TRIGGER_FACT_STRING_MAX_BYTES = 256;
|
|
25
|
+
/** Most UTF-8 bytes of `subject.kind`, `subject.id`, `dedupeKey` and each fact name. */
|
|
26
|
+
export const TRIGGER_KEY_MAX_BYTES = 256;
|
|
27
|
+
/** Most UTF-8 bytes of `subject.title`. */
|
|
28
|
+
export const TRIGGER_TITLE_MAX_BYTES = 1024;
|
|
29
|
+
/** Most UTF-8 bytes of `subject.url`. */
|
|
30
|
+
export const TRIGGER_URL_MAX_BYTES = 2048;
|
|
31
|
+
/** Most items of one `string[]` fact. */
|
|
32
|
+
export const TRIGGER_FACT_LIST_MAX_ITEMS = 64;
|
|
33
|
+
const bytes = (s) => Buffer.byteLength(s, "utf8");
|
|
34
|
+
const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
35
|
+
const nonEmpty = (v) => typeof v === "string" && v !== "";
|
|
36
|
+
const invalid = (message) => new TriggerError("invalid_event", message);
|
|
37
|
+
/**
|
|
38
|
+
* What the SDK's `validateTriggerEvent` leaves to the kernel boundary: lengths in UTF-8 bytes
|
|
39
|
+
* (`subject.kind`, `subject.id`, `dedupeKey` and fact names {@link TRIGGER_KEY_MAX_BYTES},
|
|
40
|
+
* `subject.title` {@link TRIGGER_TITLE_MAX_BYTES}, `subject.url` {@link TRIGGER_URL_MAX_BYTES});
|
|
41
|
+
* `facts` is a flat object
|
|
42
|
+
* of at most {@link TRIGGER_MAX_FACTS} values, each a string (at most
|
|
43
|
+
* {@link TRIGGER_FACT_STRING_MAX_BYTES} bytes), a finite number, a boolean or a list of such
|
|
44
|
+
* strings (at most {@link TRIGGER_FACT_LIST_MAX_ITEMS}); `subject.url` is a string when given;
|
|
45
|
+
* `audience` names an account and an agent; `cause` is one of its two shapes.
|
|
46
|
+
*/
|
|
47
|
+
/** An absolute `http:` or `https:` URL. */
|
|
48
|
+
function isWebUrl(url) {
|
|
49
|
+
try {
|
|
50
|
+
const u = new URL(url);
|
|
51
|
+
return u.protocol === "http:" || u.protocol === "https:";
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function checkShape(e) {
|
|
58
|
+
const capped = [
|
|
59
|
+
["subject.kind", e.subject.kind, TRIGGER_KEY_MAX_BYTES],
|
|
60
|
+
["subject.id", e.subject.id, TRIGGER_KEY_MAX_BYTES],
|
|
61
|
+
["subject.title", e.subject.title, TRIGGER_TITLE_MAX_BYTES],
|
|
62
|
+
["dedupeKey", e.dedupeKey, TRIGGER_KEY_MAX_BYTES],
|
|
63
|
+
];
|
|
64
|
+
for (const [field, value, max] of capped)
|
|
65
|
+
if (bytes(value) > max)
|
|
66
|
+
throw invalid(`${field} is at most ${max} bytes`);
|
|
67
|
+
if (!isPlainObject(e.facts))
|
|
68
|
+
throw invalid("facts must be an object of fact values");
|
|
69
|
+
const facts = Object.entries(e.facts);
|
|
70
|
+
if (facts.length > TRIGGER_MAX_FACTS)
|
|
71
|
+
throw invalid(`facts holds at most ${TRIGGER_MAX_FACTS} values`);
|
|
72
|
+
const okString = (s) => typeof s === "string" && bytes(s) <= TRIGGER_FACT_STRING_MAX_BYTES;
|
|
73
|
+
for (const [name, v] of facts) {
|
|
74
|
+
if (bytes(name) > TRIGGER_KEY_MAX_BYTES)
|
|
75
|
+
throw invalid(`fact names are at most ${TRIGGER_KEY_MAX_BYTES} bytes`);
|
|
76
|
+
const ok = typeof v === "boolean" ||
|
|
77
|
+
(typeof v === "number" && Number.isFinite(v)) ||
|
|
78
|
+
okString(v) ||
|
|
79
|
+
(Array.isArray(v) && v.length <= TRIGGER_FACT_LIST_MAX_ITEMS && v.every(okString));
|
|
80
|
+
if (!ok)
|
|
81
|
+
throw invalid(`fact "${name}" must be a string of at most ${TRIGGER_FACT_STRING_MAX_BYTES} bytes, a finite number, a boolean or a list of at most ${TRIGGER_FACT_LIST_MAX_ITEMS} such strings`);
|
|
82
|
+
}
|
|
83
|
+
if (e.subject.url !== undefined && typeof e.subject.url !== "string")
|
|
84
|
+
throw invalid("subject.url must be a string");
|
|
85
|
+
if (e.subject.url !== undefined && bytes(e.subject.url) > TRIGGER_URL_MAX_BYTES)
|
|
86
|
+
throw invalid(`subject.url is at most ${TRIGGER_URL_MAX_BYTES} bytes`);
|
|
87
|
+
// model-visible and shown as a link: only a web address
|
|
88
|
+
if (e.subject.url !== undefined && !isWebUrl(e.subject.url))
|
|
89
|
+
throw invalid("subject.url must be an http or https URL");
|
|
90
|
+
if (e.audience !== undefined) {
|
|
91
|
+
if (!isPlainObject(e.audience) ||
|
|
92
|
+
!nonEmpty(e.audience.accountId) ||
|
|
93
|
+
!nonEmpty(e.audience.agentId))
|
|
94
|
+
throw invalid("audience must name a non-empty accountId and agentId");
|
|
95
|
+
}
|
|
96
|
+
if (e.cause !== undefined) {
|
|
97
|
+
const c = e.cause;
|
|
98
|
+
const call = isPlainObject(c) && "call" in c;
|
|
99
|
+
const account = isPlainObject(c) && "accountId" in c;
|
|
100
|
+
if (call === account)
|
|
101
|
+
throw invalid("cause must be { call } (a tool call context) or { accountId }");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Stores the events extensions emit (`ctx.triggers.emit`, collaboration spec §4.2) and owes their
|
|
106
|
+
* dispatch. The emitting extension, the event types it may emit (its approved manifest's
|
|
107
|
+
* `permissions.triggers.emit`) and the cause's run and depth are the kernel's: an extension cannot
|
|
108
|
+
* name another plugin, an undeclared type, a run of another org or a chain depth of its choosing.
|
|
109
|
+
*/
|
|
110
|
+
let TriggerEventsService = class TriggerEventsService {
|
|
111
|
+
kdb;
|
|
112
|
+
txHost;
|
|
113
|
+
outbox;
|
|
114
|
+
constructor(kdb, txHost, outbox) {
|
|
115
|
+
this.kdb = kdb;
|
|
116
|
+
this.txHost = txHost;
|
|
117
|
+
this.outbox = outbox;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Validates `e` for `plugin` (whose approved manifest declares `declared`), checks the plugin is
|
|
121
|
+
* enabled in the event's org and verifies the cause: a tool call context must be one the tool
|
|
122
|
+
* pipeline made (its run read from the call scope, never from the context's own fields) for a
|
|
123
|
+
* run of the event's org, and the event's depth is that run's trigger event's depth + 1 (0 when
|
|
124
|
+
* the run started from no event); an account must be an active member of the org (depth 0).
|
|
125
|
+
* Then inserts the `trigger_events` row and owes its `trigger-dispatch` job in the same
|
|
126
|
+
* transaction. An event already stored for (org, plugin, dedupe key) is a duplicate: its id comes
|
|
127
|
+
* back with `duplicate: true` and nothing is owed. The caller runs it in the event's org scope.
|
|
128
|
+
*
|
|
129
|
+
* Throws `TriggerError`: `type_not_declared`, `invalid_event` (a missing or malformed field, a
|
|
130
|
+
* forged or foreign cause), `org_disabled` (the plugin is not enabled in the org).
|
|
131
|
+
*/
|
|
132
|
+
async emit(plugin, declared, e) {
|
|
133
|
+
if (!isPlainObject(e))
|
|
134
|
+
throw invalid("the event must be an object");
|
|
135
|
+
const errs = validateTriggerEvent(e, declared);
|
|
136
|
+
if (errs.includes("type_not_declared"))
|
|
137
|
+
throw new TriggerError("type_not_declared", `event type "${e.type}" is not declared in permissions.triggers.emit of ${plugin}`);
|
|
138
|
+
if (errs.length > 0)
|
|
139
|
+
throw invalid(`invalid event: ${errs.join(", ")}`);
|
|
140
|
+
checkShape(e);
|
|
141
|
+
const db = this.kdb.db;
|
|
142
|
+
if (!(await isExtensionEnabled(db, e.orgId, plugin)))
|
|
143
|
+
throw new TriggerError("org_disabled", `${plugin} is not enabled in org ${e.orgId}`);
|
|
144
|
+
const cause = await this.verifyCause(e);
|
|
145
|
+
const subject = {
|
|
146
|
+
kind: e.subject.kind,
|
|
147
|
+
id: e.subject.id,
|
|
148
|
+
title: e.subject.title,
|
|
149
|
+
...(e.subject.url !== undefined && { url: e.subject.url }),
|
|
150
|
+
};
|
|
151
|
+
const facts = Object.fromEntries(Object.entries(e.facts).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v]));
|
|
152
|
+
const id = randomUUID();
|
|
153
|
+
const inserted = await db
|
|
154
|
+
.insertInto("trigger_events")
|
|
155
|
+
.values({
|
|
156
|
+
id,
|
|
157
|
+
org_id: e.orgId,
|
|
158
|
+
plugin,
|
|
159
|
+
type: e.type,
|
|
160
|
+
subject: JSON.stringify(subject),
|
|
161
|
+
facts: JSON.stringify(facts),
|
|
162
|
+
summary: e.summary,
|
|
163
|
+
dedupe_key: e.dedupeKey,
|
|
164
|
+
audience: e.audience === undefined
|
|
165
|
+
? null
|
|
166
|
+
: JSON.stringify({ accountId: e.audience.accountId, agentId: e.audience.agentId }),
|
|
167
|
+
cause_account_id: cause.accountId,
|
|
168
|
+
cause_run_id: cause.runId,
|
|
169
|
+
depth: cause.depth,
|
|
170
|
+
})
|
|
171
|
+
.onConflict((oc) => oc.columns(["org_id", "plugin", "dedupe_key"]).doNothing())
|
|
172
|
+
.returning("id")
|
|
173
|
+
.executeTakeFirst();
|
|
174
|
+
if (inserted === undefined) {
|
|
175
|
+
const existing = await db
|
|
176
|
+
.selectFrom("trigger_events")
|
|
177
|
+
.select("id")
|
|
178
|
+
.where("org_id", "=", e.orgId)
|
|
179
|
+
.where("plugin", "=", plugin)
|
|
180
|
+
.where("dedupe_key", "=", e.dedupeKey)
|
|
181
|
+
.executeTakeFirstOrThrow();
|
|
182
|
+
return { eventId: existing.id, duplicate: true };
|
|
183
|
+
}
|
|
184
|
+
await this.outbox.add({
|
|
185
|
+
queue: MAINTENANCE_QUEUE_NAME,
|
|
186
|
+
name: TRIGGER_DISPATCH_JOB,
|
|
187
|
+
jobId: triggerDispatchJobId(id),
|
|
188
|
+
data: { orgId: e.orgId, eventId: id },
|
|
189
|
+
orgId: e.orgId,
|
|
190
|
+
});
|
|
191
|
+
return { eventId: id, duplicate: false };
|
|
192
|
+
}
|
|
193
|
+
/** The verified cause of `e` (see {@link emit}); no cause is depth 0 with nobody behind it. */
|
|
194
|
+
async verifyCause(e) {
|
|
195
|
+
const cause = e.cause;
|
|
196
|
+
if (cause === undefined)
|
|
197
|
+
return { runId: null, accountId: null, depth: 0 };
|
|
198
|
+
const db = this.kdb.db;
|
|
199
|
+
if ("call" in cause) {
|
|
200
|
+
// only the pipeline attaches run facts: a context built by the extension has none
|
|
201
|
+
const facts = isPlainObject(cause.call) ? callScopeOf(cause.call)?.facts : undefined;
|
|
202
|
+
if (facts === undefined)
|
|
203
|
+
throw invalid("cause.call must be the tool call context the kernel passed to the handler");
|
|
204
|
+
const run = await db
|
|
205
|
+
.selectFrom("runs")
|
|
206
|
+
.innerJoin("conversations", "conversations.id", "runs.conversation_id")
|
|
207
|
+
.select(["runs.id", "runs.trigger_account_id", "runs.trigger_event_id"])
|
|
208
|
+
.where("runs.id", "=", facts.runId)
|
|
209
|
+
.where("conversations.org_id", "=", e.orgId)
|
|
210
|
+
.executeTakeFirst();
|
|
211
|
+
if (run === undefined)
|
|
212
|
+
throw invalid("cause.call is a run of another org");
|
|
213
|
+
let depth = 0;
|
|
214
|
+
if (run.trigger_event_id !== null) {
|
|
215
|
+
const from = await db
|
|
216
|
+
.selectFrom("trigger_events")
|
|
217
|
+
.select("depth")
|
|
218
|
+
.where("id", "=", run.trigger_event_id)
|
|
219
|
+
.where("org_id", "=", e.orgId)
|
|
220
|
+
.executeTakeFirst();
|
|
221
|
+
// the column has no foreign key: an event no longer stored (the trigger event sweep deletes
|
|
222
|
+
// settled events after `automations.eventRetentionDays`) cannot extend a chain, which
|
|
223
|
+
// restarts at 0
|
|
224
|
+
depth = from === undefined ? 0 : from.depth + 1;
|
|
225
|
+
}
|
|
226
|
+
return { runId: run.id, accountId: run.trigger_account_id, depth };
|
|
227
|
+
}
|
|
228
|
+
if (!nonEmpty(cause.accountId))
|
|
229
|
+
throw invalid("cause.accountId must be an account id");
|
|
230
|
+
const member = await db
|
|
231
|
+
.selectFrom("memberships")
|
|
232
|
+
.innerJoin("orgs", "orgs.id", "memberships.org_id")
|
|
233
|
+
.innerJoin("accounts", "accounts.id", "memberships.account_id")
|
|
234
|
+
.select("memberships.account_id")
|
|
235
|
+
.where("memberships.org_id", "=", e.orgId)
|
|
236
|
+
.where("memberships.account_id", "=", cause.accountId)
|
|
237
|
+
.where("orgs.deleted_at", "is", null)
|
|
238
|
+
.where("accounts.status", "=", "active")
|
|
239
|
+
.executeTakeFirst();
|
|
240
|
+
if (member === undefined)
|
|
241
|
+
throw invalid("cause.accountId is not an active member of the event's org");
|
|
242
|
+
return { runId: null, accountId: cause.accountId, depth: 0 };
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
__decorate([
|
|
246
|
+
Transactional()
|
|
247
|
+
], TriggerEventsService.prototype, "emit", null);
|
|
248
|
+
TriggerEventsService = __decorate([
|
|
249
|
+
Injectable(),
|
|
250
|
+
__param(0, Inject(KernelDb)),
|
|
251
|
+
__param(1, Inject(TransactionHost)),
|
|
252
|
+
__param(2, Inject(OutboxService))
|
|
253
|
+
], TriggerEventsService);
|
|
254
|
+
export { TriggerEventsService };
|