@capybara-hq/kernel 0.1.0-rc.108 → 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.
- package/dist/automations/acceptance.controller.d.ts +29 -0
- package/dist/automations/acceptance.controller.js +87 -0
- package/dist/automations/automations.module.js +4 -1
- package/dist/automations/automations.schemas.d.ts +46 -0
- package/dist/automations/automations.schemas.js +31 -0
- package/dist/automations/automations.service.js +10 -1
- package/dist/automations/errors.d.ts +5 -0
- package/dist/automations/errors.js +5 -0
- package/dist/automations/events/acceptance.d.ts +205 -0
- package/dist/automations/events/acceptance.js +822 -0
- package/dist/automations/events/deliver.d.ts +39 -0
- package/dist/automations/events/deliver.js +112 -0
- package/dist/automations/events/dispatcher.d.ts +26 -10
- package/dist/automations/events/dispatcher.js +98 -99
- package/dist/automations/events/sweep.job.d.ts +104 -18
- package/dist/automations/events/sweep.job.js +311 -45
- package/dist/automations/events/trigger-events.service.d.ts +31 -2
- package/dist/automations/events/trigger-events.service.js +113 -30
- package/dist/automations/store.d.ts +7 -3
- package/dist/automations/store.js +6 -0
- package/dist/automations/types.d.ts +5 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +14 -0
- package/dist/ctx/create-ctx.d.ts +24 -4
- package/dist/ctx/create-ctx.js +119 -6
- package/dist/db/kernel-schema.d.ts +89 -1
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +18 -0
- package/dist/extensions/hooks.d.ts +8 -5
- package/dist/extensions/hooks.js +2 -1
- package/dist/extensions/host.d.ts +12 -2
- package/dist/extensions/host.js +21 -1
- package/dist/extensions/lifecycle-hooks.d.ts +21 -7
- package/dist/extensions/lifecycle-hooks.js +51 -3
- package/dist/extensions/permission-set.d.ts +33 -1
- package/dist/extensions/permission-set.js +28 -1
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +24 -1
- package/dist/extensions/run-lifecycle-owe.d.ts +67 -0
- package/dist/extensions/run-lifecycle-owe.js +84 -0
- package/dist/http/api.module.js +4 -0
- package/dist/inbox/inbox-item-actions.d.ts +37 -0
- package/dist/inbox/inbox-item-actions.js +69 -0
- package/dist/inbox/inbox-items.controller.d.ts +27 -0
- package/dist/inbox/inbox-items.controller.js +80 -0
- package/dist/inbox/inbox-items.service.d.ts +110 -0
- package/dist/inbox/inbox-items.service.js +324 -0
- package/dist/inbox/inbox.module.d.ts +2 -1
- package/dist/inbox/inbox.module.js +15 -4
- package/dist/inbox/inbox.schemas.d.ts +20 -1
- package/dist/inbox/inbox.schemas.js +16 -1
- package/dist/inbox/inbox.service.d.ts +29 -7
- package/dist/inbox/inbox.service.js +29 -8
- package/dist/inbox/token.d.ts +5 -0
- package/dist/inbox/token.js +5 -0
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/infra/outbox/registry.d.ts +17 -0
- package/dist/infra/outbox/registry.js +15 -0
- package/dist/kernel.module.js +6 -0
- package/dist/orgs/settings.service.d.ts +20 -0
- package/dist/orgs/settings.service.js +4 -0
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/operation.d.ts +8 -0
- package/dist/platform/ops/automations.ops.d.ts +3 -1
- package/dist/platform/ops/automations.ops.js +45 -3
- package/dist/platform/ops/inbox.ops.d.ts +3 -1
- package/dist/platform/ops/inbox.ops.js +69 -4
- package/dist/platform/ops/platform.ops.js +4 -3
- package/dist/plugin-reads/plugin-reads.service.d.ts +29 -0
- package/dist/plugin-reads/plugin-reads.service.js +210 -0
- package/dist/plugin-reads/token.d.ts +5 -0
- package/dist/plugin-reads/token.js +5 -0
- package/dist/push/jobs.d.ts +5 -0
- package/dist/push/jobs.js +2 -0
- package/dist/push/preferences.service.d.ts +2 -2
- package/dist/push/preferences.service.js +9 -3
- package/dist/push/push-owed.d.ts +2 -0
- package/dist/push/push-owed.js +10 -1
- package/dist/push/push.schemas.d.ts +5 -2
- package/dist/push/push.schemas.js +4 -3
- package/dist/push/recipients.d.ts +2 -0
- package/dist/push/recipients.js +44 -3
- package/dist/push/texts.d.ts +14 -5
- package/dist/push/texts.js +2 -1
- package/dist/push/triggers.d.ts +1 -1
- package/dist/runtime/run-finish.js +19 -1
- package/dist/runtime/run-jobs.d.ts +12 -2
- package/dist/runtime/run-jobs.js +41 -4
- package/dist/runtime/run-queue.js +10 -0
- package/dist/runtime/waits.js +24 -1
- package/dist/tools/builtins/platform.js +2 -0
- package/dist/tools/pipeline.d.ts +5 -0
- package/dist/tools/pipeline.js +13 -1
- package/dist/tools/registry.d.ts +6 -0
- package/package.json +3 -3
- package/src/migrations/0192_inbox_items.sql +50 -0
- package/src/migrations/0193_trigger_cause_handles.sql +49 -0
- package/src/migrations/0194_automation_acceptance.sql +83 -0
|
@@ -0,0 +1,822 @@
|
|
|
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 { InboxError, } from "@capybara-hq/plugin-sdk";
|
|
12
|
+
import { Inject, Injectable, Module } from "@nestjs/common";
|
|
13
|
+
import { sql } from "kysely";
|
|
14
|
+
import { AgentLookup, AgentLookupModule } from "../../agents/agent-lookup.js";
|
|
15
|
+
import { ApiError } from "../../errors.js";
|
|
16
|
+
import { ExtensionDisplayNames } from "../../extensions/display-name.js";
|
|
17
|
+
import { ExtensionsModule } from "../../extensions/extensions.module.js";
|
|
18
|
+
import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
|
|
19
|
+
import { oweOfferDeclinedIn } from "../../extensions/run-lifecycle-owe.js";
|
|
20
|
+
import { audit } from "../../identity/audit.js";
|
|
21
|
+
import { InboxItemsModule, InboxItemsService } from "../../inbox/inbox-items.service.js";
|
|
22
|
+
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
23
|
+
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
24
|
+
import { TransactionHost } from "../../infra/database/transaction-host.js";
|
|
25
|
+
import { Transactional } from "../../infra/database/transactional.decorator.js";
|
|
26
|
+
import { OutboxService } from "../../infra/outbox/outbox.service.js";
|
|
27
|
+
import { KERNEL_LOGGER } from "../../infra/tokens.js";
|
|
28
|
+
import { roleAtLeast } from "../../orgs/roles.js";
|
|
29
|
+
import { pluginDisplayNames } from "../../tools/display-names.js";
|
|
30
|
+
import { readAutomationSettings } from "../effective-settings.js";
|
|
31
|
+
import { eventSourceUnavailable } from "../errors.js";
|
|
32
|
+
import { withDeadline } from "./deadline.js";
|
|
33
|
+
import { deliverEvent } from "./deliver.js";
|
|
34
|
+
import { isSelfTriggered } from "./guards.js";
|
|
35
|
+
/** How long a work offer stays open (collaboration spec §4.4). */
|
|
36
|
+
export const OFFER_TTL_SECONDS = 7 * 24 * 3600;
|
|
37
|
+
/** The prompt of an acceptance automation (model-visible; the event block carries the work). */
|
|
38
|
+
export const ACCEPTANCE_PROMPT = "This work was assigned to you. Read the assigned item, do what it asks within what you are allowed to do, and report what you did.";
|
|
39
|
+
/** The most open offers one inbox read returns. */
|
|
40
|
+
export const OFFERS_LIST_MAX = 100;
|
|
41
|
+
const offerNotFound = () => new ApiError("automation.offer_not_found", "Work offer not found");
|
|
42
|
+
const offerClosed = () => new ApiError("automation.offer_closed", "This work offer was already accepted, declined or has expired");
|
|
43
|
+
const offerUnavailable = (message) => new ApiError("automation.offer_unavailable", message);
|
|
44
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
45
|
+
/** The directed event types a source declares, sorted. */
|
|
46
|
+
const directedTypes = (declared) => [...new Set(declared.filter((d) => d.directed).map((d) => d.type))].sort();
|
|
47
|
+
/** An in-app link a kernel inbox item may carry; anything else is left out. */
|
|
48
|
+
const inAppLink = (url) => url?.startsWith("/") && !url.startsWith("//") && url.length <= 2048 ? url : undefined;
|
|
49
|
+
/** An absolute `http(s)` link (a subject outside the app); anything else is left out. */
|
|
50
|
+
const webLink = (url) => {
|
|
51
|
+
if (url === undefined || url.length > 2048)
|
|
52
|
+
return undefined;
|
|
53
|
+
try {
|
|
54
|
+
const u = new URL(url);
|
|
55
|
+
return u.protocol === "https:" || u.protocol === "http:" ? u.toString() : undefined;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Directed events and acceptance (collaboration spec §4.4). A directed event names the person and
|
|
63
|
+
* the agent the work is for (`audience`); work runs as that person, with that agent, only within
|
|
64
|
+
* what the person allowed:
|
|
65
|
+
*
|
|
66
|
+
* - **Rules.** The person's rule for the source (`automation_acceptance`), else the org's
|
|
67
|
+
* `automations.directedDefault` (default `auto`): `auto` runs the work through the person's
|
|
68
|
+
* acceptance automation for (source, agent), made by the kernel on first need (owner = the
|
|
69
|
+
* person, `subject` mode, no grants, `unattended_ask = wait`, every directed type of the source);
|
|
70
|
+
* `confirm` posts a work offer to the person's inbox; `off` runs nothing. The rule is read on
|
|
71
|
+
* every event, so switching to `confirm` or `off` takes effect even while the acceptance
|
|
72
|
+
* automation exists, and a paused one runs nothing.
|
|
73
|
+
* - **Guards** (before the rule): the type must be directed; the person must be an active member
|
|
74
|
+
* (member role or above) who may use the agent (`AgentLookup.get`) and whom the source's
|
|
75
|
+
* `visible()` admits, in an org with automations on; otherwise the event is `undelivered`. An
|
|
76
|
+
* event caused by a run of that person on that agent (self-trigger) runs nothing.
|
|
77
|
+
* - **Offers.** Accept (the person's own act, never an agent's) makes or reuses the acceptance
|
|
78
|
+
* automation and delivers the event to it, after checking the guards again; decline tells the
|
|
79
|
+
* person who caused the event (`cause_account_id`, else the cause run's trigger account) through
|
|
80
|
+
* a kernel inbox item. An offer is open for {@link OFFER_TTL_SECONDS}; past it, it is `expired`
|
|
81
|
+
* when next read.
|
|
82
|
+
*
|
|
83
|
+
* Every read and write filters by the org; the person acts only on their own rules and offers.
|
|
84
|
+
*/
|
|
85
|
+
let AcceptanceService = class AcceptanceService {
|
|
86
|
+
kdb;
|
|
87
|
+
txHost;
|
|
88
|
+
config;
|
|
89
|
+
points;
|
|
90
|
+
outbox;
|
|
91
|
+
log;
|
|
92
|
+
inbox;
|
|
93
|
+
agents;
|
|
94
|
+
displayNames;
|
|
95
|
+
constructor(kdb, txHost, config, points, outbox, log, inbox, agents, displayNames) {
|
|
96
|
+
this.kdb = kdb;
|
|
97
|
+
this.txHost = txHost;
|
|
98
|
+
this.config = config;
|
|
99
|
+
this.points = points;
|
|
100
|
+
this.outbox = outbox;
|
|
101
|
+
this.log = log;
|
|
102
|
+
this.inbox = inbox;
|
|
103
|
+
this.agents = agents;
|
|
104
|
+
this.displayNames = displayNames;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Routes the pending directed event `ev` (the dispatcher's guards for depth, the source and its
|
|
108
|
+
* declarations already passed), see the class. The event ends `dispatched` (fired, offered, off
|
|
109
|
+
* or self-triggered) or `undelivered`.
|
|
110
|
+
*/
|
|
111
|
+
async route(ev, ctx) {
|
|
112
|
+
const audience = ev.audience;
|
|
113
|
+
if (audience === null)
|
|
114
|
+
throw new Error(`trigger event ${ev.id} is not directed`);
|
|
115
|
+
const orgId = ev.org_id;
|
|
116
|
+
const log = { orgId, eventId: ev.id, plugin: ev.plugin, type: ev.type };
|
|
117
|
+
const refuse = (why) => {
|
|
118
|
+
this.log.info(`directed trigger event undelivered: ${why}`, log);
|
|
119
|
+
return this.settle(orgId, ev.id, "undelivered").then(() => "undelivered");
|
|
120
|
+
};
|
|
121
|
+
if (!ctx.decl.directed)
|
|
122
|
+
return refuse("its type is not declared directed");
|
|
123
|
+
if (!ctx.settings.enabled)
|
|
124
|
+
return refuse("automations are off in the org");
|
|
125
|
+
const problem = await this.audienceProblem(orgId, audience.accountId, audience.agentId);
|
|
126
|
+
if (problem !== null)
|
|
127
|
+
return refuse(problem);
|
|
128
|
+
if (isSelfTriggered(audience, ctx.cause)) {
|
|
129
|
+
this.log.info("directed trigger event caused by its own audience agent; nothing runs", log);
|
|
130
|
+
await this.settle(orgId, ev.id, "dispatched");
|
|
131
|
+
return "skipped";
|
|
132
|
+
}
|
|
133
|
+
const seen = await ctx.visible([audience.accountId]);
|
|
134
|
+
if (seen === undefined)
|
|
135
|
+
return refuse("the source gave no answer on who may see the subject");
|
|
136
|
+
if (!seen.includes(audience.accountId))
|
|
137
|
+
return refuse("the source does not show the subject");
|
|
138
|
+
const mode = await this.modeFor(orgId, audience.accountId, ev.plugin, ctx.settings);
|
|
139
|
+
return this.routeIn(ev, mode, ctx);
|
|
140
|
+
}
|
|
141
|
+
/** {@link route}'s writes, in one transaction under the event row's lock. */
|
|
142
|
+
async routeIn(ev, mode, ctx) {
|
|
143
|
+
const db = this.kdb.db;
|
|
144
|
+
const orgId = ev.org_id;
|
|
145
|
+
const audience = ev.audience;
|
|
146
|
+
const held = await db
|
|
147
|
+
.selectFrom("trigger_events")
|
|
148
|
+
.select("state")
|
|
149
|
+
.where("org_id", "=", orgId)
|
|
150
|
+
.where("id", "=", ev.id)
|
|
151
|
+
.forUpdate()
|
|
152
|
+
.executeTakeFirst();
|
|
153
|
+
// another dispatch of the event settled it first
|
|
154
|
+
if (held?.state !== "pending")
|
|
155
|
+
return "skipped";
|
|
156
|
+
if (mode === "off") {
|
|
157
|
+
await this.oweDeclined(ev, audience, "off");
|
|
158
|
+
this.log.info("directed trigger event: the person's acceptance rule is off", {
|
|
159
|
+
orgId,
|
|
160
|
+
eventId: ev.id,
|
|
161
|
+
plugin: ev.plugin,
|
|
162
|
+
});
|
|
163
|
+
await this.settle(orgId, ev.id, "dispatched");
|
|
164
|
+
return "off";
|
|
165
|
+
}
|
|
166
|
+
if (mode === "confirm") {
|
|
167
|
+
await this.offer(ev, audience);
|
|
168
|
+
await this.settle(orgId, ev.id, "dispatched");
|
|
169
|
+
return "offered";
|
|
170
|
+
}
|
|
171
|
+
const automationId = await this.ensureAutomation(orgId, audience.accountId, audience.agentId, ev.plugin, directedTypes(ctx.declared));
|
|
172
|
+
const added = await deliverEvent({ db, outbox: this.outbox, log: this.log }, ev, [automationId], { decl: ctx.decl, cause: ctx.cause, coalesceSeconds: ctx.settings.coalesceSeconds });
|
|
173
|
+
await this.settle(orgId, ev.id, "dispatched");
|
|
174
|
+
if (added === 0) {
|
|
175
|
+
// the event row is held and the cause checked: only a paused or ended automation takes none
|
|
176
|
+
await this.oweDeclined(ev, audience, "paused");
|
|
177
|
+
this.log.info("directed trigger event: the person's acceptance automation is paused", {
|
|
178
|
+
orgId,
|
|
179
|
+
eventId: ev.id,
|
|
180
|
+
automationId,
|
|
181
|
+
});
|
|
182
|
+
return "paused";
|
|
183
|
+
}
|
|
184
|
+
return "fired";
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Tells the event's source plugin that directed work was not run (`run.lifecycle`
|
|
188
|
+
* `offer_declined`), owed in the caller's transaction; nothing when the plugin does not
|
|
189
|
+
* subscribe in the org.
|
|
190
|
+
*/
|
|
191
|
+
oweDeclined(ev, audience, reason) {
|
|
192
|
+
return oweOfferDeclinedIn(this.kdb.db, this.outbox, {
|
|
193
|
+
orgId: ev.org_id,
|
|
194
|
+
plugin: ev.plugin,
|
|
195
|
+
eventId: ev.id,
|
|
196
|
+
accountId: audience.accountId,
|
|
197
|
+
agentId: audience.agentId,
|
|
198
|
+
subject: ev.subject,
|
|
199
|
+
reason,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Why the audience cannot receive work, or null: an active member (member role or above) of the
|
|
204
|
+
* org who may use the agent.
|
|
205
|
+
*/
|
|
206
|
+
async audienceProblem(orgId, accountId, agentId) {
|
|
207
|
+
const member = await this.kdb.db
|
|
208
|
+
.selectFrom("memberships")
|
|
209
|
+
.innerJoin("accounts", "accounts.id", "memberships.account_id")
|
|
210
|
+
.select("memberships.role")
|
|
211
|
+
.where("memberships.org_id", "=", orgId)
|
|
212
|
+
.where("memberships.account_id", "=", accountId)
|
|
213
|
+
.where("accounts.status", "=", "active")
|
|
214
|
+
.executeTakeFirst();
|
|
215
|
+
if (member === undefined || !roleAtLeast(member.role, "member"))
|
|
216
|
+
return "the person is not an active member who may use automations";
|
|
217
|
+
try {
|
|
218
|
+
await this.agents.get(orgId, agentId, accountId);
|
|
219
|
+
}
|
|
220
|
+
catch (err) {
|
|
221
|
+
if (err instanceof ApiError)
|
|
222
|
+
return "the person may not use the agent";
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
/** The person's rule for `source`, else the org's default. */
|
|
228
|
+
async modeFor(orgId, accountId, source, settings) {
|
|
229
|
+
const row = await this.kdb.db
|
|
230
|
+
.selectFrom("automation_acceptance")
|
|
231
|
+
.select("mode")
|
|
232
|
+
.where("org_id", "=", orgId)
|
|
233
|
+
.where("account_id", "=", accountId)
|
|
234
|
+
.where("source", "=", source)
|
|
235
|
+
.executeTakeFirst();
|
|
236
|
+
return row?.mode ?? settings.directedDefault;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* The live acceptance automation of (org, person, source, agent), made when missing (see the
|
|
240
|
+
* class); an existing one gains directed types its source declares since. The caller runs it in
|
|
241
|
+
* a transaction; the partial unique index makes two concurrent first events make one.
|
|
242
|
+
*/
|
|
243
|
+
async ensureAutomation(orgId, accountId, agentId, source, types) {
|
|
244
|
+
const db = this.kdb.db;
|
|
245
|
+
const find = () => db
|
|
246
|
+
.selectFrom("automations")
|
|
247
|
+
.select(["id", "trigger"])
|
|
248
|
+
.where("org_id", "=", orgId)
|
|
249
|
+
.where("account_id", "=", accountId)
|
|
250
|
+
.where("agent_id", "=", agentId)
|
|
251
|
+
.where("origin", "=", "acceptance")
|
|
252
|
+
.where("deleted_at", "is", null)
|
|
253
|
+
.where(sql `trigger->>'source' = ${source}`)
|
|
254
|
+
.forUpdate()
|
|
255
|
+
.executeTakeFirst();
|
|
256
|
+
const found = await find();
|
|
257
|
+
if (found !== undefined) {
|
|
258
|
+
const t = found.trigger;
|
|
259
|
+
const have = t.kind === "event" ? t.types : [];
|
|
260
|
+
if (types.some((x) => !have.includes(x))) {
|
|
261
|
+
await db
|
|
262
|
+
.updateTable("automations")
|
|
263
|
+
.set({
|
|
264
|
+
trigger: JSON.stringify({
|
|
265
|
+
kind: "event",
|
|
266
|
+
source,
|
|
267
|
+
types: [...new Set([...have, ...types])].sort(),
|
|
268
|
+
filter: [],
|
|
269
|
+
}),
|
|
270
|
+
updated_at: sql `now()`,
|
|
271
|
+
})
|
|
272
|
+
.where("org_id", "=", orgId)
|
|
273
|
+
.where("id", "=", found.id)
|
|
274
|
+
.execute();
|
|
275
|
+
}
|
|
276
|
+
return found.id;
|
|
277
|
+
}
|
|
278
|
+
const [sourceNames, agent] = await Promise.all([
|
|
279
|
+
this.displayNames.many([source]),
|
|
280
|
+
this.agents.get(orgId, agentId, accountId),
|
|
281
|
+
]);
|
|
282
|
+
const sourceName = sourceNames.get(source)?.en ?? source;
|
|
283
|
+
const name = `${sourceName} · ${agent.definition.name}`.slice(0, 200);
|
|
284
|
+
const id = randomUUID();
|
|
285
|
+
const inserted = await db
|
|
286
|
+
.insertInto("automations")
|
|
287
|
+
.values({
|
|
288
|
+
id,
|
|
289
|
+
org_id: orgId,
|
|
290
|
+
account_id: accountId,
|
|
291
|
+
agent_id: agentId,
|
|
292
|
+
name,
|
|
293
|
+
prompt: ACCEPTANCE_PROMPT,
|
|
294
|
+
trigger: JSON.stringify({ kind: "event", source, types, filter: [] }),
|
|
295
|
+
mode: "subject",
|
|
296
|
+
conversation_id: null,
|
|
297
|
+
chat: null,
|
|
298
|
+
model: null,
|
|
299
|
+
effort: null,
|
|
300
|
+
device_id: null,
|
|
301
|
+
unattended_ask: "wait",
|
|
302
|
+
origin: "acceptance",
|
|
303
|
+
principal: JSON.stringify({ kind: "member", accountId }),
|
|
304
|
+
status: "active",
|
|
305
|
+
next_run_at: null,
|
|
306
|
+
jitter_seconds: 0,
|
|
307
|
+
expires_at: null,
|
|
308
|
+
})
|
|
309
|
+
// only the acceptance index can conflict (the id is new): another event made it first
|
|
310
|
+
.onConflict((oc) => oc.doNothing())
|
|
311
|
+
.returning("id")
|
|
312
|
+
.executeTakeFirst();
|
|
313
|
+
if (inserted === undefined) {
|
|
314
|
+
const winner = await find();
|
|
315
|
+
if (winner === undefined)
|
|
316
|
+
throw new Error("acceptance automation insert conflicted");
|
|
317
|
+
return winner.id;
|
|
318
|
+
}
|
|
319
|
+
await audit(db, {
|
|
320
|
+
orgId,
|
|
321
|
+
action: "automation.created",
|
|
322
|
+
target: id,
|
|
323
|
+
detail: { name, agentId, mode: "subject", origin: "acceptance", source, grants: [] },
|
|
324
|
+
});
|
|
325
|
+
return id;
|
|
326
|
+
}
|
|
327
|
+
/** Posts the work offer for `ev` and its inbox item (one offer per event). */
|
|
328
|
+
async offer(ev, audience) {
|
|
329
|
+
const db = this.kdb.db;
|
|
330
|
+
const orgId = ev.org_id;
|
|
331
|
+
const id = randomUUID();
|
|
332
|
+
const row = await db
|
|
333
|
+
.insertInto("automation_offers")
|
|
334
|
+
.values({
|
|
335
|
+
id,
|
|
336
|
+
org_id: orgId,
|
|
337
|
+
account_id: audience.accountId,
|
|
338
|
+
event_id: ev.id,
|
|
339
|
+
source: ev.plugin,
|
|
340
|
+
agent_id: audience.agentId,
|
|
341
|
+
})
|
|
342
|
+
.onConflict((oc) => oc.column("event_id").doNothing())
|
|
343
|
+
.returning("id")
|
|
344
|
+
.executeTakeFirst();
|
|
345
|
+
if (row === undefined)
|
|
346
|
+
return;
|
|
347
|
+
const [names, agentName] = await Promise.all([
|
|
348
|
+
pluginDisplayNames(db, [ev.plugin]),
|
|
349
|
+
this.agentName(orgId, audience.agentId),
|
|
350
|
+
]);
|
|
351
|
+
const sourceName = names.get(ev.plugin)?.en ?? ev.plugin;
|
|
352
|
+
try {
|
|
353
|
+
const { itemId } = await this.inbox.post({ kind: "kernel" }, {
|
|
354
|
+
orgId,
|
|
355
|
+
accountId: audience.accountId,
|
|
356
|
+
kind: "automation_offer",
|
|
357
|
+
title: ev.subject.title.slice(0, 200) || ev.type,
|
|
358
|
+
body: `${sourceName} offers this work to ${agentName || "your agent"}. Accept to let the agent work on it as you, or decline.`,
|
|
359
|
+
link: "/inbox",
|
|
360
|
+
dedupeKey: `automation-offer-${id}`,
|
|
361
|
+
expiresInSeconds: OFFER_TTL_SECONDS,
|
|
362
|
+
});
|
|
363
|
+
await db
|
|
364
|
+
.updateTable("automation_offers")
|
|
365
|
+
.set({ inbox_item_id: itemId })
|
|
366
|
+
.where("org_id", "=", orgId)
|
|
367
|
+
.where("id", "=", id)
|
|
368
|
+
.execute();
|
|
369
|
+
}
|
|
370
|
+
catch (err) {
|
|
371
|
+
if (!(err instanceof InboxError))
|
|
372
|
+
throw err;
|
|
373
|
+
// the offer still lists in the inbox; only its push item is missing
|
|
374
|
+
this.log.warn("work offer inbox item not posted", { orgId, offerId: id, err });
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
async agentName(orgId, agentId) {
|
|
378
|
+
const row = await this.kdb.db
|
|
379
|
+
.selectFrom("agents")
|
|
380
|
+
.innerJoin("agent_versions", (j) => j
|
|
381
|
+
.onRef("agent_versions.agent_id", "=", "agents.id")
|
|
382
|
+
.onRef("agent_versions.version", "=", "agents.current_version"))
|
|
383
|
+
.select(sql `agent_versions.definition->>'name'`.as("name"))
|
|
384
|
+
.where("agents.org_id", "=", orgId)
|
|
385
|
+
.where("agents.id", "=", agentId)
|
|
386
|
+
.executeTakeFirst();
|
|
387
|
+
return row?.name ?? "";
|
|
388
|
+
}
|
|
389
|
+
async settle(orgId, eventId, state) {
|
|
390
|
+
await this.kdb.db
|
|
391
|
+
.updateTable("trigger_events")
|
|
392
|
+
.set({ state })
|
|
393
|
+
.where("org_id", "=", orgId)
|
|
394
|
+
.where("id", "=", eventId)
|
|
395
|
+
.where("state", "=", "pending")
|
|
396
|
+
.execute();
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* The caller's rules (`GET automations/acceptance`): each trigger source that serves the org
|
|
400
|
+
* (not switched off) and declares a directed type, with the caller's rule or null, and the org's
|
|
401
|
+
* default. A source whose `events()` fails or times out is left out.
|
|
402
|
+
*/
|
|
403
|
+
async rules(orgId, accountId) {
|
|
404
|
+
const db = this.kdb.db;
|
|
405
|
+
const settings = await readAutomationSettings(db, this.config, orgId);
|
|
406
|
+
const sources = await this.directedSources(orgId, settings);
|
|
407
|
+
const stored = await db
|
|
408
|
+
.selectFrom("automation_acceptance")
|
|
409
|
+
.select(["source", "mode"])
|
|
410
|
+
.where("org_id", "=", orgId)
|
|
411
|
+
.where("account_id", "=", accountId)
|
|
412
|
+
.execute();
|
|
413
|
+
const mine = new Map(stored.map((r) => [r.source, r.mode]));
|
|
414
|
+
const names = await this.displayNames.many(sources.map((s) => s.source));
|
|
415
|
+
return {
|
|
416
|
+
items: sources.map((s) => ({
|
|
417
|
+
source: s.source,
|
|
418
|
+
name: names.get(s.source) ?? { zh: s.source, en: s.source },
|
|
419
|
+
mode: mine.get(s.source) ?? null,
|
|
420
|
+
})),
|
|
421
|
+
directedDefault: settings.directedDefault,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Sets the caller's rules (`PUT automations/acceptance`): each `{ source, mode }` stores the
|
|
426
|
+
* rule, `mode: null` removes it (the org default applies again). A rule for a source that is not
|
|
427
|
+
* a serving source with directed types is `automation.event_source_unavailable`; removing one is
|
|
428
|
+
* always allowed. Returns {@link rules}.
|
|
429
|
+
*/
|
|
430
|
+
async setRules(orgId, accountId, rules) {
|
|
431
|
+
const settings = await readAutomationSettings(this.kdb.db, this.config, orgId);
|
|
432
|
+
const setting = rules.filter((r) => r.mode !== null);
|
|
433
|
+
if (setting.length > 0) {
|
|
434
|
+
const known = new Set((await this.directedSources(orgId, settings)).map((s) => s.source));
|
|
435
|
+
const unknown = setting.find((r) => !known.has(r.source));
|
|
436
|
+
if (unknown !== undefined) {
|
|
437
|
+
throw eventSourceUnavailable(`${unknown.source} is not an event source of this organization that assigns work (it must be an enabled extension with directed event types, not switched off in the automation settings)`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
await this.writeRules(orgId, accountId, rules);
|
|
441
|
+
return this.rules(orgId, accountId);
|
|
442
|
+
}
|
|
443
|
+
async writeRules(orgId, accountId, rules) {
|
|
444
|
+
const db = this.kdb.db;
|
|
445
|
+
for (const r of rules) {
|
|
446
|
+
if (r.mode === null) {
|
|
447
|
+
await db
|
|
448
|
+
.deleteFrom("automation_acceptance")
|
|
449
|
+
.where("org_id", "=", orgId)
|
|
450
|
+
.where("account_id", "=", accountId)
|
|
451
|
+
.where("source", "=", r.source)
|
|
452
|
+
.execute();
|
|
453
|
+
}
|
|
454
|
+
else {
|
|
455
|
+
await db
|
|
456
|
+
.insertInto("automation_acceptance")
|
|
457
|
+
.values({ org_id: orgId, account_id: accountId, source: r.source, mode: r.mode })
|
|
458
|
+
.onConflict((oc) => oc
|
|
459
|
+
.columns(["org_id", "account_id", "source"])
|
|
460
|
+
.doUpdateSet({ mode: r.mode, updated_at: sql `now()` }))
|
|
461
|
+
.execute();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
await audit(db, {
|
|
465
|
+
actorAccountId: accountId,
|
|
466
|
+
orgId,
|
|
467
|
+
action: "automation.acceptance_changed",
|
|
468
|
+
detail: { rules: rules.map((r) => ({ source: r.source, mode: r.mode })) },
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
/** The trigger sources that serve the org, are not switched off and declare a directed type. */
|
|
472
|
+
async directedSources(orgId, settings) {
|
|
473
|
+
const { providers } = await this.points.providersFor(orgId, "trigger-source");
|
|
474
|
+
const ms = this.config.get().tools.timeoutMs;
|
|
475
|
+
const out = await Promise.all(providers
|
|
476
|
+
.filter((p) => !settings.eventSourcesOff.includes(p.extension))
|
|
477
|
+
.map(async (p) => {
|
|
478
|
+
try {
|
|
479
|
+
const declared = await withDeadline(p.extension, "events()", ms, () => p.impl.events());
|
|
480
|
+
return declared.some((d) => d.directed)
|
|
481
|
+
? { source: p.extension, declared, impl: p.impl, config: p.config }
|
|
482
|
+
: null;
|
|
483
|
+
}
|
|
484
|
+
catch (err) {
|
|
485
|
+
this.log.warn("trigger source events() failed; left out of the acceptance rules", {
|
|
486
|
+
orgId,
|
|
487
|
+
plugin: p.extension,
|
|
488
|
+
err,
|
|
489
|
+
});
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
492
|
+
}));
|
|
493
|
+
return out.filter((s) => s !== null).sort((a, b) => (a.source < b.source ? -1 : 1));
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* The caller's open, unexpired offers, newest first (the inbox's `automation_offer` entries).
|
|
497
|
+
*/
|
|
498
|
+
async openOffers(orgId, accountId) {
|
|
499
|
+
const db = this.kdb.db;
|
|
500
|
+
const rows = await db
|
|
501
|
+
.selectFrom("automation_offers as o")
|
|
502
|
+
.innerJoin("trigger_events as e", "e.id", "o.event_id")
|
|
503
|
+
.select([
|
|
504
|
+
"o.id",
|
|
505
|
+
"o.source",
|
|
506
|
+
"o.agent_id",
|
|
507
|
+
"o.inbox_item_id",
|
|
508
|
+
"o.created_at",
|
|
509
|
+
"e.type",
|
|
510
|
+
"e.subject",
|
|
511
|
+
"e.summary",
|
|
512
|
+
])
|
|
513
|
+
.where("o.org_id", "=", orgId)
|
|
514
|
+
.where("o.account_id", "=", accountId)
|
|
515
|
+
.where("o.state", "=", "open")
|
|
516
|
+
.where("o.created_at", ">", sql `now() - make_interval(secs => ${OFFER_TTL_SECONDS})`)
|
|
517
|
+
.orderBy("o.created_at", "desc")
|
|
518
|
+
.orderBy("o.id")
|
|
519
|
+
.limit(OFFERS_LIST_MAX)
|
|
520
|
+
.execute();
|
|
521
|
+
if (rows.length === 0)
|
|
522
|
+
return [];
|
|
523
|
+
const names = await pluginDisplayNames(db, rows.map((r) => r.source));
|
|
524
|
+
const agentNames = new Map();
|
|
525
|
+
for (const id of new Set(rows.map((r) => r.agent_id)))
|
|
526
|
+
agentNames.set(id, await this.agentName(orgId, id));
|
|
527
|
+
return rows.map((r) => ({
|
|
528
|
+
id: r.id,
|
|
529
|
+
source: r.source,
|
|
530
|
+
sourceName: names.get(r.source) ?? { zh: r.source, en: r.source },
|
|
531
|
+
agent: { id: r.agent_id, name: agentNames.get(r.agent_id) ?? "" },
|
|
532
|
+
eventType: r.type,
|
|
533
|
+
subject: r.subject,
|
|
534
|
+
summary: r.summary,
|
|
535
|
+
inboxItemId: r.inbox_item_id,
|
|
536
|
+
createdAt: r.created_at.toISOString(),
|
|
537
|
+
expiresAt: new Date(r.created_at.getTime() + OFFER_TTL_SECONDS * 1000).toISOString(),
|
|
538
|
+
}));
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* The person accepts their own open offer (`POST automations/offers/:id/accept`): the guards of
|
|
542
|
+
* {@link route} are checked again (`automation.offer_unavailable` when one fails: the source no
|
|
543
|
+
* longer serves the org or shows the subject, the agent cannot be used, automations are off, or
|
|
544
|
+
* the acceptance automation is paused), then the acceptance automation is made or reused and the
|
|
545
|
+
* event delivered to it, and the offer is `accepted`. Another person's offer or an unknown id is
|
|
546
|
+
* `automation.offer_not_found`; one decided or expired is `automation.offer_closed`.
|
|
547
|
+
*/
|
|
548
|
+
async accept(orgId, accountId, offerId) {
|
|
549
|
+
const { offer, ev } = await this.openOffer(orgId, accountId, offerId);
|
|
550
|
+
const db = this.kdb.db;
|
|
551
|
+
const settings = await readAutomationSettings(db, this.config, orgId);
|
|
552
|
+
if (!settings.enabled)
|
|
553
|
+
throw offerUnavailable("Automations are turned off in this organization");
|
|
554
|
+
const problem = await this.audienceProblem(orgId, accountId, offer.agent_id);
|
|
555
|
+
if (problem !== null)
|
|
556
|
+
throw offerUnavailable(`This work cannot be accepted: ${problem}`);
|
|
557
|
+
const source = (await this.directedSources(orgId, settings)).find((s) => s.source === offer.source);
|
|
558
|
+
const decl = source?.declared.find((d) => d.type === ev.type && d.directed);
|
|
559
|
+
if (source === undefined || decl === undefined) {
|
|
560
|
+
throw offerUnavailable(`${offer.source} no longer assigns this work in this organization (it is off, or no longer declares the event)`);
|
|
561
|
+
}
|
|
562
|
+
const ms = this.config.get().tools.timeoutMs;
|
|
563
|
+
let seen;
|
|
564
|
+
try {
|
|
565
|
+
seen = await withDeadline(offer.source, "visible()", ms, () => source.impl.visible({
|
|
566
|
+
orgId,
|
|
567
|
+
accountIds: [accountId],
|
|
568
|
+
subject: ev.subject,
|
|
569
|
+
config: source.config,
|
|
570
|
+
}));
|
|
571
|
+
}
|
|
572
|
+
catch (err) {
|
|
573
|
+
// a source that times out or fails cannot confirm the person still sees the item
|
|
574
|
+
this.log.warn("trigger source visible() failed while accepting an offer", {
|
|
575
|
+
orgId,
|
|
576
|
+
offerId,
|
|
577
|
+
plugin: offer.source,
|
|
578
|
+
err,
|
|
579
|
+
});
|
|
580
|
+
throw offerUnavailable(`${offer.source} did not confirm that you can still see this item; try again later`);
|
|
581
|
+
}
|
|
582
|
+
if (!seen.includes(accountId))
|
|
583
|
+
throw offerUnavailable(`${offer.source} no longer shows you this item`);
|
|
584
|
+
return this.acceptIn(orgId, accountId, offerId, ev, decl, directedTypes(source.declared), settings);
|
|
585
|
+
}
|
|
586
|
+
async acceptIn(orgId, accountId, offerId, ev, decl, types, settings) {
|
|
587
|
+
const db = this.kdb.db;
|
|
588
|
+
const offer = await this.lockOpen(orgId, accountId, offerId);
|
|
589
|
+
const automationId = await this.ensureAutomation(orgId, accountId, offer.agent_id, offer.source, types);
|
|
590
|
+
// the accepting person is the audience; no cause run check: accepting is their own act
|
|
591
|
+
const added = await deliverEvent({ db, outbox: this.outbox, log: this.log }, ev, [automationId], {
|
|
592
|
+
decl,
|
|
593
|
+
cause: null,
|
|
594
|
+
coalesceSeconds: settings.coalesceSeconds,
|
|
595
|
+
});
|
|
596
|
+
if (added === 0) {
|
|
597
|
+
throw offerUnavailable("Your automation that accepts this work is paused or ended; resume it in your automations, then accept again");
|
|
598
|
+
}
|
|
599
|
+
await db
|
|
600
|
+
.updateTable("automation_offers")
|
|
601
|
+
.set({ state: "accepted", automation_id: automationId, decided_at: sql `now()` })
|
|
602
|
+
.where("org_id", "=", orgId)
|
|
603
|
+
.where("id", "=", offerId)
|
|
604
|
+
.execute();
|
|
605
|
+
if (offer.inbox_item_id !== null)
|
|
606
|
+
await this.inbox.close(orgId, offer.inbox_item_id);
|
|
607
|
+
await audit(db, {
|
|
608
|
+
actorAccountId: accountId,
|
|
609
|
+
orgId,
|
|
610
|
+
action: "automation.offer_accepted",
|
|
611
|
+
target: offerId,
|
|
612
|
+
detail: { source: offer.source, agentId: offer.agent_id, automationId, eventId: ev.id },
|
|
613
|
+
});
|
|
614
|
+
return { automationId };
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* The person declines their own open offer (`POST automations/offers/:id/decline`): the offer is
|
|
618
|
+
* `declined`, its inbox item resolved, and the person who caused the event (the event's
|
|
619
|
+
* `cause_account_id`, else the trigger account of the run that caused it; nobody when neither,
|
|
620
|
+
* or when it is the decliner) gets a kernel inbox item `automation_offer_declined`. Errors as
|
|
621
|
+
* {@link accept}'s.
|
|
622
|
+
*/
|
|
623
|
+
async decline(orgId, accountId, offerId) {
|
|
624
|
+
const { ev } = await this.openOffer(orgId, accountId, offerId);
|
|
625
|
+
await this.declineIn(orgId, accountId, offerId, ev);
|
|
626
|
+
}
|
|
627
|
+
async declineIn(orgId, accountId, offerId, ev) {
|
|
628
|
+
const db = this.kdb.db;
|
|
629
|
+
const offer = await this.lockOpen(orgId, accountId, offerId);
|
|
630
|
+
await db
|
|
631
|
+
.updateTable("automation_offers")
|
|
632
|
+
.set({ state: "declined", decided_at: sql `now()` })
|
|
633
|
+
.where("org_id", "=", orgId)
|
|
634
|
+
.where("id", "=", offerId)
|
|
635
|
+
.execute();
|
|
636
|
+
if (offer.inbox_item_id !== null)
|
|
637
|
+
await this.inbox.close(orgId, offer.inbox_item_id);
|
|
638
|
+
await audit(db, {
|
|
639
|
+
actorAccountId: accountId,
|
|
640
|
+
orgId,
|
|
641
|
+
action: "automation.offer_declined",
|
|
642
|
+
target: offerId,
|
|
643
|
+
detail: { source: offer.source, agentId: offer.agent_id, eventId: ev.id },
|
|
644
|
+
});
|
|
645
|
+
await this.oweDeclined(ev, { accountId, agentId: offer.agent_id }, "declined");
|
|
646
|
+
const causer = await this.causerOf(orgId, ev);
|
|
647
|
+
if (causer === null || causer === accountId)
|
|
648
|
+
return;
|
|
649
|
+
const [person, agentName] = await Promise.all([
|
|
650
|
+
db
|
|
651
|
+
.selectFrom("accounts")
|
|
652
|
+
.select("display_name")
|
|
653
|
+
.where("id", "=", accountId)
|
|
654
|
+
.executeTakeFirst(),
|
|
655
|
+
this.agentName(orgId, offer.agent_id),
|
|
656
|
+
]);
|
|
657
|
+
const link = inAppLink(ev.subject.url);
|
|
658
|
+
// a subject outside the app (an absolute URL) is kept as a fact the web opens itself
|
|
659
|
+
const subjectUrl = link === undefined ? webLink(ev.subject.url) : undefined;
|
|
660
|
+
try {
|
|
661
|
+
await this.inbox.post({ kind: "kernel" }, {
|
|
662
|
+
orgId,
|
|
663
|
+
accountId: causer,
|
|
664
|
+
kind: "automation_offer_declined",
|
|
665
|
+
title: ev.subject.title.slice(0, 200) || ev.type,
|
|
666
|
+
body: `${person?.display_name || "The person"} declined this work for ${agentName || "their agent"}.`,
|
|
667
|
+
...(link !== undefined && { link }),
|
|
668
|
+
dedupeKey: `automation-offer-declined-${offerId}`,
|
|
669
|
+
}, {
|
|
670
|
+
detail: {
|
|
671
|
+
declinedBy: { id: accountId, name: person?.display_name ?? "" },
|
|
672
|
+
agent: { id: offer.agent_id, name: agentName },
|
|
673
|
+
...(subjectUrl !== undefined && { subjectUrl }),
|
|
674
|
+
},
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
catch (err) {
|
|
678
|
+
if (!(err instanceof InboxError))
|
|
679
|
+
throw err;
|
|
680
|
+
this.log.info("declined offer notice not posted", { orgId, offerId, err });
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/** Who caused `ev`: its cause account, else its cause run's trigger account, else null. */
|
|
684
|
+
async causerOf(orgId, ev) {
|
|
685
|
+
if (ev.cause_account_id !== null)
|
|
686
|
+
return ev.cause_account_id;
|
|
687
|
+
if (ev.cause_run_id === null)
|
|
688
|
+
return null;
|
|
689
|
+
const run = await this.kdb.db
|
|
690
|
+
.selectFrom("runs")
|
|
691
|
+
.innerJoin("conversations", "conversations.id", "runs.conversation_id")
|
|
692
|
+
.select("runs.trigger_account_id")
|
|
693
|
+
.where("runs.id", "=", ev.cause_run_id)
|
|
694
|
+
.where("conversations.org_id", "=", orgId)
|
|
695
|
+
.executeTakeFirst();
|
|
696
|
+
return run?.trigger_account_id ?? null;
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Marks the open offer `offerId` `expired` when it was made at or before `cutoff` (default: its
|
|
700
|
+
* seven days ago, on the database's clock), resolves its inbox item and tells the event's source
|
|
701
|
+
* plugin (`run.lifecycle` `offer_declined`, reason `expired`), all in one transaction; the trigger
|
|
702
|
+
* event sweep calls it for every stale open offer, and {@link openOffer} for one it finds stale.
|
|
703
|
+
* False when the offer was not open or not yet stale (nothing written).
|
|
704
|
+
*/
|
|
705
|
+
async expireOffer(orgId, offerId, cutoff) {
|
|
706
|
+
const db = this.kdb.db;
|
|
707
|
+
const row = await db
|
|
708
|
+
.updateTable("automation_offers")
|
|
709
|
+
.set({ state: "expired", decided_at: sql `now()` })
|
|
710
|
+
.where("org_id", "=", orgId)
|
|
711
|
+
.where("id", "=", offerId)
|
|
712
|
+
.where("state", "=", "open")
|
|
713
|
+
.where("created_at", "<=", cutoff ?? sql `now() - make_interval(secs => ${OFFER_TTL_SECONDS})`)
|
|
714
|
+
.returning(["event_id", "account_id", "agent_id", "inbox_item_id"])
|
|
715
|
+
.executeTakeFirst();
|
|
716
|
+
if (row === undefined)
|
|
717
|
+
return false;
|
|
718
|
+
if (row.inbox_item_id !== null)
|
|
719
|
+
await this.inbox.close(orgId, row.inbox_item_id);
|
|
720
|
+
const ev = await db
|
|
721
|
+
.selectFrom("trigger_events")
|
|
722
|
+
.selectAll()
|
|
723
|
+
.where("org_id", "=", orgId)
|
|
724
|
+
.where("id", "=", row.event_id)
|
|
725
|
+
.executeTakeFirst();
|
|
726
|
+
if (ev !== undefined)
|
|
727
|
+
await this.oweDeclined(ev, { accountId: row.account_id, agentId: row.agent_id }, "expired");
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* The caller's offer `offerId` and its event, open and unexpired (see {@link accept}'s errors);
|
|
732
|
+
* an offer past its life is marked `expired` ({@link expireOffer}).
|
|
733
|
+
*/
|
|
734
|
+
async openOffer(orgId, accountId, offerId) {
|
|
735
|
+
if (!UUID_RE.test(offerId))
|
|
736
|
+
throw offerNotFound();
|
|
737
|
+
const db = this.kdb.db;
|
|
738
|
+
const offer = await db
|
|
739
|
+
.selectFrom("automation_offers")
|
|
740
|
+
.selectAll()
|
|
741
|
+
.select(sql `created_at <= now() - make_interval(secs => ${OFFER_TTL_SECONDS})`.as("past"))
|
|
742
|
+
.where("org_id", "=", orgId)
|
|
743
|
+
.where("account_id", "=", accountId)
|
|
744
|
+
.where("id", "=", offerId)
|
|
745
|
+
.executeTakeFirst();
|
|
746
|
+
if (offer === undefined)
|
|
747
|
+
throw offerNotFound();
|
|
748
|
+
if (offer.state === "open" && offer.past) {
|
|
749
|
+
await this.expireOffer(orgId, offerId);
|
|
750
|
+
throw offerClosed();
|
|
751
|
+
}
|
|
752
|
+
if (offer.state !== "open")
|
|
753
|
+
throw offerClosed();
|
|
754
|
+
const ev = await db
|
|
755
|
+
.selectFrom("trigger_events")
|
|
756
|
+
.selectAll()
|
|
757
|
+
.where("org_id", "=", orgId)
|
|
758
|
+
.where("id", "=", offer.event_id)
|
|
759
|
+
.executeTakeFirst();
|
|
760
|
+
if (ev === undefined)
|
|
761
|
+
throw offerClosed();
|
|
762
|
+
return { offer, ev };
|
|
763
|
+
}
|
|
764
|
+
/** The caller's offer, locked, still open and unexpired; else `automation.offer_closed`. */
|
|
765
|
+
async lockOpen(orgId, accountId, offerId) {
|
|
766
|
+
const row = await this.kdb.db
|
|
767
|
+
.selectFrom("automation_offers")
|
|
768
|
+
.selectAll()
|
|
769
|
+
.where("org_id", "=", orgId)
|
|
770
|
+
.where("account_id", "=", accountId)
|
|
771
|
+
.where("id", "=", offerId)
|
|
772
|
+
.where("state", "=", "open")
|
|
773
|
+
.where("created_at", ">", sql `now() - make_interval(secs => ${OFFER_TTL_SECONDS})`)
|
|
774
|
+
.forUpdate()
|
|
775
|
+
.executeTakeFirst();
|
|
776
|
+
if (row === undefined)
|
|
777
|
+
throw offerClosed();
|
|
778
|
+
return row;
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
__decorate([
|
|
782
|
+
Transactional()
|
|
783
|
+
], AcceptanceService.prototype, "routeIn", null);
|
|
784
|
+
__decorate([
|
|
785
|
+
Transactional()
|
|
786
|
+
], AcceptanceService.prototype, "writeRules", null);
|
|
787
|
+
__decorate([
|
|
788
|
+
Transactional()
|
|
789
|
+
], AcceptanceService.prototype, "acceptIn", null);
|
|
790
|
+
__decorate([
|
|
791
|
+
Transactional()
|
|
792
|
+
], AcceptanceService.prototype, "declineIn", null);
|
|
793
|
+
__decorate([
|
|
794
|
+
Transactional()
|
|
795
|
+
], AcceptanceService.prototype, "expireOffer", null);
|
|
796
|
+
AcceptanceService = __decorate([
|
|
797
|
+
Injectable(),
|
|
798
|
+
__param(0, Inject(KernelDb)),
|
|
799
|
+
__param(1, Inject(TransactionHost)),
|
|
800
|
+
__param(2, Inject(KernelConfigService)),
|
|
801
|
+
__param(3, Inject(ExtensionPointDefaults)),
|
|
802
|
+
__param(4, Inject(OutboxService)),
|
|
803
|
+
__param(5, Inject(KERNEL_LOGGER)),
|
|
804
|
+
__param(6, Inject(InboxItemsService)),
|
|
805
|
+
__param(7, Inject(AgentLookup)),
|
|
806
|
+
__param(8, Inject(ExtensionDisplayNames))
|
|
807
|
+
], AcceptanceService);
|
|
808
|
+
export { AcceptanceService };
|
|
809
|
+
/**
|
|
810
|
+
* {@link AcceptanceService}: the trigger dispatcher (worker) routes directed events through it; the
|
|
811
|
+
* acceptance routes, the inbox and the Platform operations (API) read and decide through it.
|
|
812
|
+
*/
|
|
813
|
+
let AcceptanceModule = class AcceptanceModule {
|
|
814
|
+
};
|
|
815
|
+
AcceptanceModule = __decorate([
|
|
816
|
+
Module({
|
|
817
|
+
imports: [ExtensionsModule, AgentLookupModule, InboxItemsModule],
|
|
818
|
+
providers: [AcceptanceService],
|
|
819
|
+
exports: [AcceptanceService],
|
|
820
|
+
})
|
|
821
|
+
], AcceptanceModule);
|
|
822
|
+
export { AcceptanceModule };
|