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