@sentry/junior 0.296.0 → 0.298.0
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/{admin-z_lgDi-z.js → admin-BF3DbYGf.js} +2 -2
- package/dist/{agent-runner-HoQiUKLL.js → agent-runner-Q9GkoerG.js} +407 -1895
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +38 -267
- package/dist/{app-C75Ft-A_.d.ts → app-DOg_mCtV.d.ts} +7 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +64 -44
- package/dist/attempt-selection-ClP3MMPr.js +61 -0
- package/dist/{automation-yJX3C7i3.js → automation-Cn8qmbdr.js} +1 -1
- package/dist/{background-compaction-queue-Cre1wFt9.js → background-compaction-queue-BZhGFOK6.js} +4 -88
- package/dist/{briefs-BXECHduJ.js → briefs-CQrCRF6-.js} +3 -3
- package/dist/{catalog-runtime-CpCmlD9L.js → catalog-runtime-DZeD2WbL.js} +1 -1
- package/dist/cli/chat.js +19 -15
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-CCPHvTqx.js → config-BOByVnxe.js} +2 -2
- package/dist/{connections-B5pWh8e2.js → connections-BNN5cJam.js} +6 -6
- package/dist/{conversation-CMkSmi02.js → conversation-DCkzvxqB.js} +51 -17
- package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-CMA12Rjs.js} +1 -1
- package/dist/{conversation-privacy-CZD5soDW.js → conversation-privacy-C0eRxsgb.js} +1 -1
- package/dist/conversation-turn-D9qvcDX6.js +805 -0
- package/dist/{credential-sync-DwLkIvXI.js → credential-sync-B_iUpxGL.js} +14 -13
- package/dist/{db-C1M1y-bh.js → db-CoMNr2Zm.js} +43 -15
- package/dist/{db-B3iyr_Or.d.ts → db-DoMcnYol.d.ts} +13 -1
- package/dist/{executor-DUSEwXaO.js → executor-C-m8VrzX.js} +14 -6
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-D0svFM8r.js → logging-CJTi5niy.js} +1 -1
- package/dist/{message-BFnIwKpx.js → message-Q6_5DAWR.js} +15 -13
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -2
- package/dist/{session-stop-hYNTNpVf.js → notification-Bv25xbj0.js} +11 -930
- package/dist/{oauth-callback-server-BXRtD6Fk.js → oauth-callback-server-CH5XAyo-.js} +2 -2
- package/dist/{projection-B6VS7kbo.js → projection-BgwEE36_.js} +333 -106
- package/dist/{prompt-CD11tfG8.js → prompt-DXc9DYT9.js} +4 -4
- package/dist/prompt-input-BUr4J9RO.js +1424 -0
- package/dist/{registry-CHewwYEo.js → registry-9XwqSnM-.js} +1 -1
- package/dist/reporting-window-DopzcOHh.js +137 -0
- package/dist/{resolve-1owMH4qo.js → resolve-DUIAbcRL.js} +3 -3
- package/dist/result-C2Vn8QGn.js +463 -0
- package/dist/{runner-BtWvJslp.js → runner-CXGtw-Mc.js} +9 -8
- package/dist/{sandbox-egress-signals-ByftwJVt.js → sandbox-egress-signals-Di3S_dO7.js} +1 -1
- package/dist/{schema-Ct1Zf2xy.d.ts → schema-BnbZ-rKv.d.ts} +14 -107
- package/dist/{schema-D2iGyYIp.js → schema-Dyp7racy.js} +11 -48
- package/dist/{service-account-BZEuMKdo.js → service-account-DM3KBBeG.js} +3 -3
- package/dist/{service-account-DLoeoHww.js → service-account-GzAMUQ8a.js} +3 -3
- package/dist/session-stop-D4i7e6iT.js +181 -0
- package/dist/{skills-DXgd5Inh.js → skills-DCK9SD_l.js} +2 -2
- package/dist/{spawn-YeqlNDv8.js → spawn-6cX6xE9G.js} +6 -5
- package/dist/{state-C3CbtD_m.js → state-CSuA2J1V.js} +2 -2
- package/dist/{stop-Cze_pEL8.js → stop-Dh2DfwpK.js} +66 -159
- package/dist/{store-CZ9vqR4P.js → store-B1zepKG8.js} +11 -4
- package/dist/{task-runner-CMiNGsER.js → store-DrA17Fbz.js} +939 -1593
- package/dist/task-queue-D1rXWfFN.js +89 -0
- package/dist/task-runner-CT4M8oDz.js +291 -0
- package/dist/thread-context-DnqUkbzN.js +248 -0
- package/dist/turn-cancel-l460pfGW.js +201 -0
- package/dist/turn-session-routing-VXDVXLRl.js +380 -0
- package/dist/{turn-failure-response-pXhZ2wMK.js → turn-user-message-BSPmkm7X.js} +181 -392
- package/dist/turn-wake-DVFVXyhX.js +161 -0
- package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
- package/dist/{validation-Du7NdkOR.js → validation-zxAJBDDy.js} +1 -1
- package/dist/{version-EN3Wnq-R.js → version-DcZ40a0g.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-Agxi_o5c.js → viewer-CgiGjW10.js} +3 -3
- package/dist/warmup-CwKbxQLl.js +2698 -0
- package/dist/{worker-BALVdWbv.js → worker-CbDUzaBA.js} +20 -8
- package/migrations/0102_code_change_last_activity.sql +1 -0
- package/migrations/0103_agent_invocation_fork.sql +8 -0
- package/migrations/meta/0102_snapshot.json +4502 -0
- package/migrations/meta/0103_snapshot.json +4509 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +4 -4
- package/dist/result-CEqQFrEf.js +0 -305
- package/dist/result-event-type-DD6BAgT7.js +0 -11
- package/dist/warmup-CY2ArYag.js +0 -2017
- package/dist/work-EA98F0ia.js +0 -768
|
@@ -1,1199 +1,1062 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { v as
|
|
9
|
-
import {
|
|
10
|
-
import { i as readActorIdentity } from "./viewer-Agxi_o5c.js";
|
|
11
|
-
import { a as getStateAdapter } from "./state-C3CbtD_m.js";
|
|
12
|
-
import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-Cre1wFt9.js";
|
|
13
|
-
import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-yJX3C7i3.js";
|
|
1
|
+
import { $i as escapeSlackMrkdwnText, Ci as getDashboardTaskLink, Ei as ToolInputError, ca as openSlackDirectMessage, da as postSlackMessage, ea as formatSlackLink, vi as JUNIOR_THREAD_STATE_TTL_MS, w as fallbackShortTitle } from "./projection-BgwEE36_.js";
|
|
2
|
+
import { n as botConfig } from "./config-BOByVnxe.js";
|
|
3
|
+
import { _ as runBestEffort, h as logWarn } from "./logging-CJTi5niy.js";
|
|
4
|
+
import { J as agentTurnTotalTokens, o as getDb, q as agentTurnCostUsd } from "./db-CoMNr2Zm.js";
|
|
5
|
+
import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-C-m8VrzX.js";
|
|
6
|
+
import { h as credentialSubjectSchema } from "./registry-9XwqSnM-.js";
|
|
7
|
+
import { a as getStateAdapter } from "./state-CSuA2J1V.js";
|
|
8
|
+
import { u as automationEventCatalog, v as registeredEventTriggerProblems } from "./turn-session-routing-VXDVXLRl.js";
|
|
9
|
+
import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-Cn8qmbdr.js";
|
|
14
10
|
import { createHash } from "node:crypto";
|
|
15
11
|
import * as z from "zod";
|
|
16
12
|
import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
|
|
17
|
-
import {
|
|
18
|
-
// src/chat/
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
13
|
+
import { destinationSchema, destinationVisibilitySchema, eventMatches, isSlackDestination, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
|
|
14
|
+
// src/chat/automations/revision.ts
|
|
15
|
+
/** Storage revisions prevent stale edits from replacing newer values. */
|
|
16
|
+
var AutomationConflictError = class extends ToolInputError {
|
|
17
|
+
constructor() {
|
|
18
|
+
super("This Automation changed after it was loaded. Reload it before saving.");
|
|
19
|
+
this.name = "AutomationConflictError";
|
|
20
|
+
}
|
|
24
21
|
};
|
|
25
|
-
/**
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
22
|
+
/** Sort object keys so equal values produce equal JSON. */
|
|
23
|
+
function canonicalJson(value) {
|
|
24
|
+
if (Array.isArray(value)) return value.map(canonicalJson);
|
|
25
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalJson(child)]));
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
/** Identify the stored values being edited, including lifecycle and creator authority. */
|
|
29
|
+
function automationRevision(task) {
|
|
30
|
+
return createHash("sha256").update(JSON.stringify(canonicalJson(task))).digest("hex");
|
|
31
|
+
}
|
|
32
|
+
/** Reject a stale edit while the storage owner holds the write lock. */
|
|
33
|
+
function requireAutomationRevision(task, revision) {
|
|
34
|
+
if (!task || automationRevision(task) !== revision) throw new AutomationConflictError();
|
|
35
|
+
}
|
|
36
|
+
// src/chat/automations/versions.ts
|
|
37
|
+
/** Automation versions keep each saved definition so people can see how it changed. */
|
|
38
|
+
/** Return the versioned part of an Automation. Lifecycle and run state are excluded. */
|
|
39
|
+
function automationDefinition(task) {
|
|
40
|
+
const common = {
|
|
41
|
+
title: task.title?.trim() || null,
|
|
42
|
+
task: task.task,
|
|
43
|
+
credentialMode: task.credentialMode,
|
|
44
|
+
destination: task.destination,
|
|
45
|
+
outcomes: task.outcomes
|
|
46
|
+
};
|
|
47
|
+
return "schedule" in task ? {
|
|
48
|
+
...common,
|
|
49
|
+
schedule: task.schedule
|
|
50
|
+
} : {
|
|
51
|
+
...common,
|
|
52
|
+
trigger: task.trigger
|
|
34
53
|
};
|
|
35
54
|
}
|
|
36
|
-
/**
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
function hasEventCatalogEntries(catalog) {
|
|
40
|
-
return Object.keys(catalog).length > 0;
|
|
55
|
+
/** Compare definition values after key sorting. */
|
|
56
|
+
function sameDefinitionValue(left, right) {
|
|
57
|
+
return JSON.stringify(canonicalJson(left)) === JSON.stringify(canonicalJson(right));
|
|
41
58
|
}
|
|
42
59
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
* and trigger availability. A namespace with no such resource type left is
|
|
47
|
-
* removed.
|
|
60
|
+
* Save a version when the definition changed. Call this in the same
|
|
61
|
+
* transaction and lock as the Automation write. Without `current`, the
|
|
62
|
+
* Automation is new, so the creator saves version 1.
|
|
48
63
|
*/
|
|
49
|
-
function
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
64
|
+
async function recordAutomationVersion(db, task, current, editedBy) {
|
|
65
|
+
const definition = automationDefinition(task);
|
|
66
|
+
if (current && sameDefinitionValue(automationDefinition(current), definition)) return;
|
|
67
|
+
await db.insert(juniorAutomationVersions).values({
|
|
68
|
+
automationId: task.id,
|
|
69
|
+
version: sql`(
|
|
70
|
+
SELECT coalesce(max(${juniorAutomationVersions.version}), 0) + 1
|
|
71
|
+
FROM ${juniorAutomationVersions}
|
|
72
|
+
WHERE ${juniorAutomationVersions.automationId} = ${task.id}
|
|
73
|
+
)`,
|
|
74
|
+
createdAtMs: Date.now(),
|
|
75
|
+
editedBy: editedBy ?? (current ? null : task.createdBy),
|
|
76
|
+
definition
|
|
77
|
+
});
|
|
61
78
|
}
|
|
62
|
-
/**
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Select the newest saved version with the same definition as `task`.
|
|
81
|
+
*
|
|
82
|
+
* An Automation run stores this version so that a reader can see the
|
|
83
|
+
* instruction that ran after the definition changes. The value is null when
|
|
84
|
+
* no saved version has this definition.
|
|
85
|
+
*/
|
|
86
|
+
function automationVersionOf(task) {
|
|
87
|
+
return sql`(
|
|
88
|
+
SELECT max(${juniorAutomationVersions.version})
|
|
89
|
+
FROM ${juniorAutomationVersions}
|
|
90
|
+
WHERE ${juniorAutomationVersions.automationId} = ${task.id}
|
|
91
|
+
AND ${juniorAutomationVersions.definition} = ${JSON.stringify(automationDefinition(task))}::jsonb
|
|
92
|
+
)`;
|
|
66
93
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
94
|
+
const versionColumns = {
|
|
95
|
+
createdAtMs: juniorAutomationVersions.createdAtMs,
|
|
96
|
+
definition: juniorAutomationVersions.definition,
|
|
97
|
+
editedBy: juniorAutomationVersions.editedBy,
|
|
98
|
+
kind: juniorAutomations.kind,
|
|
99
|
+
version: juniorAutomationVersions.version
|
|
100
|
+
};
|
|
101
|
+
function parseVersionRow(row) {
|
|
102
|
+
return automationVersionSchema.parse({
|
|
103
|
+
kind: row.kind,
|
|
104
|
+
version: row.version,
|
|
105
|
+
createdAt: new Date(row.createdAtMs).toISOString(),
|
|
106
|
+
editedBy: row.editedBy,
|
|
107
|
+
definition: row.definition
|
|
108
|
+
});
|
|
70
109
|
}
|
|
71
|
-
/**
|
|
72
|
-
function
|
|
73
|
-
|
|
110
|
+
/** Read one saved definition. */
|
|
111
|
+
async function readAutomationVersion(db, automationId, version) {
|
|
112
|
+
const [row] = await db.select(versionColumns).from(juniorAutomationVersions).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationVersions.automationId)).where(and(eq(juniorAutomationVersions.automationId, automationId), eq(juniorAutomationVersions.version, version))).limit(1);
|
|
113
|
+
return row ? parseVersionRow(row) : void 0;
|
|
74
114
|
}
|
|
75
|
-
/**
|
|
76
|
-
function
|
|
77
|
-
return
|
|
115
|
+
/** Read saved definitions, newest first. */
|
|
116
|
+
async function listAutomationVersions(db, automationId, limit) {
|
|
117
|
+
return (await db.select(versionColumns).from(juniorAutomationVersions).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationVersions.automationId)).where(eq(juniorAutomationVersions.automationId, automationId)).orderBy(desc(juniorAutomationVersions.version)).limit(limit)).map(parseVersionRow);
|
|
78
118
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
119
|
+
// src/chat/event-automations/run-limit.ts
|
|
120
|
+
const RUN_LIST_PREFIX = "junior:event_automation_runs:v1";
|
|
121
|
+
const RUN_LIST_BURST_ROOM = 100;
|
|
122
|
+
const runEntrySchema = z.union([z.object({
|
|
123
|
+
atMs: z.number().finite(),
|
|
124
|
+
id: z.string().min(1)
|
|
125
|
+
}).strict(), z.object({ reset: z.literal(true) }).strict()]);
|
|
126
|
+
function runListKey(automationId) {
|
|
127
|
+
return `${RUN_LIST_PREFIX}:${automationId}`;
|
|
82
128
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
* once for the event, so every resource type and a trigger with no resource
|
|
86
|
-
* type get the same guidance.
|
|
87
|
-
*/
|
|
88
|
-
function eventGuidance(catalog, namespace, eventType) {
|
|
89
|
-
return catalog[namespace]?.events[eventType]?.guidance;
|
|
129
|
+
function runListMaxLength() {
|
|
130
|
+
return botConfig.maxEventAutomationRuns + RUN_LIST_BURST_ROOM;
|
|
90
131
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
132
|
+
async function appendRunEntry(state, automationId, entry) {
|
|
133
|
+
await state.connect();
|
|
134
|
+
await state.appendToList(runListKey(automationId), entry, {
|
|
135
|
+
maxLength: runListMaxLength(),
|
|
136
|
+
ttlMs: botConfig.eventAutomationRunWindowMs
|
|
137
|
+
});
|
|
94
138
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
139
|
+
function describeRunWindow(windowMs) {
|
|
140
|
+
for (const [unit, unitMs] of [
|
|
141
|
+
["day", 864e5],
|
|
142
|
+
["hour", 36e5],
|
|
143
|
+
["minute", 6e4],
|
|
144
|
+
["second", 1e3]
|
|
145
|
+
]) if (windowMs % unitMs === 0) {
|
|
146
|
+
const count = windowMs / unitMs;
|
|
147
|
+
return count === 1 ? unit : `${count} ${unit}s`;
|
|
148
|
+
}
|
|
149
|
+
return `${windowMs} ms`;
|
|
102
150
|
}
|
|
103
|
-
/**
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
function describeRegisteredEventTrigger(catalog, selection) {
|
|
108
|
-
return describeEventTrigger(catalog[selection.namespace] ?? NO_SOURCE, selection);
|
|
151
|
+
/** Reason stored on an Event automation that the run limit blocked. */
|
|
152
|
+
function eventAutomationRunLimitReason() {
|
|
153
|
+
const window = describeRunWindow(botConfig.eventAutomationRunWindowMs);
|
|
154
|
+
return `This automation reached its limit of ${botConfig.maxEventAutomationRuns} runs per ${window}. Check that its trigger is not too broad, then resume it.`;
|
|
109
155
|
}
|
|
110
|
-
function
|
|
111
|
-
|
|
112
|
-
|
|
156
|
+
function hasRunKey(entries, runKey) {
|
|
157
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
158
|
+
const entry = entries[index];
|
|
159
|
+
if ("reset" in entry) return false;
|
|
160
|
+
if (entry.id === runKey) return true;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
113
163
|
}
|
|
114
164
|
/**
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
* as its plugin declares them.
|
|
165
|
+
* Count one run of an Event automation, or refuse when its window is full.
|
|
166
|
+
*
|
|
167
|
+
* `runKey` is the dispatch idempotency key, so a provider retry of the same
|
|
168
|
+
* Event does not count again.
|
|
120
169
|
*/
|
|
121
|
-
function
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
170
|
+
async function admitEventAutomationRun(args) {
|
|
171
|
+
const state = args.state ?? getStateAdapter();
|
|
172
|
+
await state.connect();
|
|
173
|
+
const readEntries = async () => {
|
|
174
|
+
const values = await state.getList(runListKey(args.automationId));
|
|
175
|
+
return {
|
|
176
|
+
entries: values.flatMap((value) => {
|
|
177
|
+
const entry = runEntrySchema.safeParse(value);
|
|
178
|
+
return entry.success ? [entry.data] : [];
|
|
179
|
+
}),
|
|
180
|
+
length: values.length
|
|
181
|
+
};
|
|
126
182
|
};
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
183
|
+
if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
|
|
184
|
+
atMs: args.nowMs,
|
|
185
|
+
id: args.runKey
|
|
186
|
+
});
|
|
187
|
+
const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
|
|
188
|
+
const { entries, length } = await readEntries();
|
|
189
|
+
let lastReset = -1;
|
|
190
|
+
entries.forEach((entry, index) => {
|
|
191
|
+
if ("reset" in entry) lastReset = index;
|
|
192
|
+
});
|
|
193
|
+
const oldest = entries[0];
|
|
194
|
+
const full = lastReset === -1 && length >= runListMaxLength() && oldest !== void 0 && "atMs" in oldest && oldest.atMs > windowStartMs;
|
|
195
|
+
const runKeys = /* @__PURE__ */ new Set();
|
|
196
|
+
for (const entry of entries.slice(lastReset + 1)) {
|
|
197
|
+
if ("reset" in entry) continue;
|
|
198
|
+
if (entry.atMs > windowStartMs) runKeys.add(entry.id);
|
|
199
|
+
if (entry.id === args.runKey) return full || runKeys.size > botConfig.maxEventAutomationRuns ? "limited" : "allowed";
|
|
132
200
|
}
|
|
133
|
-
return
|
|
201
|
+
return "limited";
|
|
134
202
|
}
|
|
135
203
|
/**
|
|
136
|
-
*
|
|
204
|
+
* Forget the runs counted for one Event automation.
|
|
137
205
|
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
206
|
+
* Resume and revive call this so the automation starts with a new window.
|
|
207
|
+
* Call it before the automation becomes active, so an Event cannot see the
|
|
208
|
+
* old full count and block it again.
|
|
140
209
|
*/
|
|
141
|
-
function
|
|
142
|
-
|
|
143
|
-
const identifier = normalizeEventIdentifier(registration, input.identifier);
|
|
144
|
-
const resourceTypes = registration?.resourceTypes ?? [];
|
|
145
|
-
const fits = (resourceType) => resourceType.identifier !== void 0 && new RegExp(resourceType.identifier.pattern).test(identifier);
|
|
146
|
-
const resourceType = resourceTypes.find((candidate) => candidate.type === input.resourceType);
|
|
147
|
-
if (!resourceType?.identifier || fits(resourceType)) return identifier;
|
|
148
|
-
const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
|
|
149
|
-
throw new ToolInputError([`Identifier "${identifier}" does not fit resource_type "${input.resourceType}" in namespace "${input.namespace}". Expected format: "${resourceType.identifier.format}".`, ...fitting.length > 0 ? [`If the identifier is correct, use one of these resource_type values: ${fitting.map((type) => `"${type}"`).join(", ")}.`] : []].join(" "));
|
|
210
|
+
async function clearEventAutomationRuns(automationId, state = getStateAdapter()) {
|
|
211
|
+
await appendRunEntry(state, automationId, { reset: true });
|
|
150
212
|
}
|
|
151
|
-
// src/
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
213
|
+
// src/chat/event-automations/store.ts
|
|
214
|
+
/**
|
|
215
|
+
* Validate an event automation and split it into its SQL columns. Lifecycle
|
|
216
|
+
* columns are written separately.
|
|
217
|
+
*/
|
|
218
|
+
function eventAutomationColumns(task) {
|
|
219
|
+
const { status: _status, statusReason: _statusReason, title, ...definition } = task;
|
|
220
|
+
const { createdAtMs: _createdAtMs, creatorIdentityId, id: _id, ...record } = eventAutomationSchema.parse(definition);
|
|
221
|
+
return {
|
|
222
|
+
channelId: record.destination.channelId,
|
|
223
|
+
creatorIdentityId,
|
|
224
|
+
creatorSlackUserId: record.createdBy.slackUserId,
|
|
225
|
+
identifier: record.trigger.identifier ?? null,
|
|
226
|
+
...automationTaskColumns(record.task),
|
|
227
|
+
namespace: record.trigger.namespace,
|
|
228
|
+
record,
|
|
229
|
+
teamId: record.destination.teamId,
|
|
230
|
+
title: title?.trim() || null
|
|
231
|
+
};
|
|
158
232
|
}
|
|
159
|
-
function
|
|
160
|
-
return
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
${source.usage}->>'cacheCreationTokens'
|
|
167
|
-
) IS NOT NULL
|
|
168
|
-
THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
|
|
169
|
-
+ COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
|
|
170
|
-
+ COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
|
|
171
|
-
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
172
|
-
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
173
|
-
THEN (${source.usage}->>'totalTokens')::double precision
|
|
174
|
-
ELSE NULL
|
|
175
|
-
END
|
|
176
|
-
`;
|
|
233
|
+
function eventAutomationRowInput(row) {
|
|
234
|
+
return {
|
|
235
|
+
...row.record,
|
|
236
|
+
createdAtMs: row.createdAtMs,
|
|
237
|
+
creatorIdentityId: row.creatorIdentityId,
|
|
238
|
+
id: row.id
|
|
239
|
+
};
|
|
177
240
|
}
|
|
178
|
-
|
|
179
|
-
|
|
241
|
+
/** Decode an event Automation row with its SQL-backed fields. */
|
|
242
|
+
function parseEventAutomationRow(row) {
|
|
243
|
+
return withRowFields(row, eventAutomationSchema.parse(eventAutomationRowInput(row)));
|
|
180
244
|
}
|
|
181
|
-
/**
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
194
|
-
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
195
|
-
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
196
|
-
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
197
|
-
ELSE NULL
|
|
198
|
-
END
|
|
199
|
-
`;
|
|
245
|
+
/**
|
|
246
|
+
* Decode a row for Event matching. Log and skip a row that does not parse,
|
|
247
|
+
* so one bad row cannot stop matching for its whole namespace.
|
|
248
|
+
*/
|
|
249
|
+
function readMatchableEventAutomationRow(row) {
|
|
250
|
+
const parsed = eventAutomationSchema.safeParse(eventAutomationRowInput(row));
|
|
251
|
+
if (parsed.success) return withRowFields(row, parsed.data);
|
|
252
|
+
logWarn("event_automation.row.invalid", {
|
|
253
|
+
"app.task.id": row.id,
|
|
254
|
+
"app.task.type": "event",
|
|
255
|
+
"error.message": parsed.error.message
|
|
256
|
+
});
|
|
200
257
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const metrics = sources?.metrics ?? juniorConversations;
|
|
204
|
-
const roots = sources?.roots ?? juniorConversations;
|
|
205
|
-
const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
|
|
258
|
+
function withRowFields(row, task) {
|
|
259
|
+
const title = row.title?.trim();
|
|
206
260
|
return {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
212
|
-
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
213
|
-
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
214
|
-
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
215
|
-
failed: sql`${conversationCount} FILTER (
|
|
216
|
-
WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
|
|
217
|
-
)::integer`,
|
|
218
|
-
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
219
|
-
tokens: sql`SUM(${tokenValue(metrics)})::double precision`
|
|
261
|
+
...task,
|
|
262
|
+
status: row.status,
|
|
263
|
+
...row.statusReason ? { statusReason: row.statusReason } : void 0,
|
|
264
|
+
...title ? { title } : void 0
|
|
220
265
|
};
|
|
221
266
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
return {
|
|
225
|
-
firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
|
|
226
|
-
lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
|
|
227
|
-
};
|
|
267
|
+
function eventAutomationWhere(id) {
|
|
268
|
+
return and(eq(juniorAutomations.id, id), eq(juniorAutomations.kind, "event"));
|
|
228
269
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
"blocked",
|
|
232
|
-
"completed",
|
|
233
|
-
"failed"
|
|
234
|
-
];
|
|
235
|
-
/** An execution is a run with an outcome. Skipped runs are not executions. */
|
|
236
|
-
function isExecution() {
|
|
237
|
-
return and(inArray(juniorAutomationRuns.status, [...AUTOMATION_EXECUTION_STATUSES]), isNotNull(juniorAutomationRuns.completedAtMs));
|
|
270
|
+
function activeEventAutomationWhere() {
|
|
271
|
+
return and(eq(juniorAutomations.kind, "event"), ne(juniorAutomations.status, "deleted"));
|
|
238
272
|
}
|
|
239
|
-
|
|
240
|
-
|
|
273
|
+
/** Read one event automation by id, including deleted rows when present. */
|
|
274
|
+
async function getEventAutomation(db, id) {
|
|
275
|
+
const rows = await db.select().from(juniorAutomations).where(eventAutomationWhere(id)).limit(1);
|
|
276
|
+
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
241
277
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
278
|
+
/** Create one retry-stable event automation, or revive a deleted row with the new payload. */
|
|
279
|
+
async function createEventAutomation(db, task) {
|
|
280
|
+
const columns = eventAutomationColumns(task);
|
|
281
|
+
if ((await getEventAutomation(db, task.id))?.status === "deleted") await clearEventAutomationRuns(task.id);
|
|
282
|
+
return db.transaction(async (tx) => {
|
|
283
|
+
const inserted = await tx.insert(juniorAutomations).values({
|
|
284
|
+
...columns,
|
|
285
|
+
createdAtMs: task.createdAtMs,
|
|
286
|
+
id: task.id,
|
|
287
|
+
kind: "event",
|
|
288
|
+
status: "active"
|
|
289
|
+
}).onConflictDoNothing().returning();
|
|
290
|
+
if (inserted[0]) {
|
|
291
|
+
const created = parseEventAutomationRow(inserted[0]);
|
|
292
|
+
await recordAutomationVersion(tx, created, void 0);
|
|
293
|
+
return created;
|
|
294
|
+
}
|
|
295
|
+
const existing = await getEventAutomation(tx, task.id);
|
|
296
|
+
if (!existing) throw new Error(`Automation ${task.id} already exists with another kind.`);
|
|
297
|
+
if (existing.status !== "deleted") return existing;
|
|
298
|
+
const rows = await tx.update(juniorAutomations).set({
|
|
299
|
+
...columns,
|
|
300
|
+
status: "active",
|
|
301
|
+
statusReason: null
|
|
302
|
+
}).where(and(eventAutomationWhere(task.id), eq(juniorAutomations.status, "deleted"))).returning();
|
|
303
|
+
if (!rows[0]) return await getEventAutomation(tx, task.id);
|
|
304
|
+
const revived = parseEventAutomationRow(rows[0]);
|
|
305
|
+
await recordAutomationVersion(tx, revived, void 0);
|
|
306
|
+
return revived;
|
|
307
|
+
});
|
|
251
308
|
}
|
|
252
|
-
|
|
253
|
-
|
|
309
|
+
/**
|
|
310
|
+
* Replace an existing non-deleted event automation under a row lock.
|
|
311
|
+
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
312
|
+
*/
|
|
313
|
+
async function saveEventAutomation(db, task, expectedRevision, editedBy) {
|
|
314
|
+
const columns = eventAutomationColumns(task);
|
|
315
|
+
return db.transaction(async (tx) => {
|
|
316
|
+
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(task.id)).for("update");
|
|
317
|
+
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
318
|
+
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
319
|
+
if (!current || current.status === "deleted") return void 0;
|
|
320
|
+
const saved = parseEventAutomationRow((await tx.update(juniorAutomations).set(columns).where(eventAutomationWhere(task.id)).returning())[0]);
|
|
321
|
+
await recordAutomationVersion(tx, saved, current, editedBy);
|
|
322
|
+
return saved;
|
|
323
|
+
});
|
|
254
324
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
costUsd: 0,
|
|
260
|
-
date,
|
|
261
|
-
failed: 0
|
|
262
|
-
};
|
|
325
|
+
/** Mark one existing event automation deleted while retaining the row for history. */
|
|
326
|
+
async function deleteEventAutomation(db, id) {
|
|
327
|
+
const rows = await db.update(juniorAutomations).set({ status: "deleted" }).where(and(eq(juniorAutomations.id, id), activeEventAutomationWhere())).returning();
|
|
328
|
+
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
263
329
|
}
|
|
264
330
|
/**
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
* `conversation_id` is a foreign key.
|
|
331
|
+
* List deleted event automations created by one user, newest first.
|
|
332
|
+
* Used only to keep historical runs after the live automation list drops the row.
|
|
268
333
|
*/
|
|
269
|
-
function
|
|
270
|
-
|
|
334
|
+
async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
|
|
335
|
+
const identityIds = user.identities.map((identity) => identity.id);
|
|
336
|
+
if (identityIds.length === 0) return [];
|
|
337
|
+
return (await db.select().from(juniorAutomations).where(and(inArray(juniorAutomations.creatorIdentityId, identityIds), eq(juniorAutomations.kind, "event"), eq(juniorAutomations.status, "deleted"))).orderBy(desc(juniorAutomations.createdAtMs), desc(juniorAutomations.id)).limit(limit)).map(parseEventAutomationRow);
|
|
271
338
|
}
|
|
272
339
|
/**
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
340
|
+
* Select live rows whose identifier is one of these, and rows with no
|
|
341
|
+
* identifier. A row with no identifier runs for every resource of its
|
|
342
|
+
* namespace, so it gets every copy of an Event.
|
|
276
343
|
*/
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
const status = options.status ?? "completed";
|
|
280
|
-
const outcome = {
|
|
281
|
-
completedAtMs: nowMs,
|
|
282
|
-
errorMessage: options.errorMessage ?? null,
|
|
283
|
-
status
|
|
284
|
-
};
|
|
285
|
-
try {
|
|
286
|
-
await getDb().insert(juniorAutomationRuns).values({
|
|
287
|
-
id: options.executionId,
|
|
288
|
-
automationId,
|
|
289
|
-
conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
|
|
290
|
-
...outcome
|
|
291
|
-
}).onConflictDoUpdate({
|
|
292
|
-
target: juniorAutomationRuns.id,
|
|
293
|
-
set: {
|
|
294
|
-
...outcome,
|
|
295
|
-
conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`
|
|
296
|
-
},
|
|
297
|
-
setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
|
|
298
|
-
});
|
|
299
|
-
} catch (error) {
|
|
300
|
-
logWarn("task.execution.stat_failed", {
|
|
301
|
-
error,
|
|
302
|
-
"app.task.execution.id": options.executionId,
|
|
303
|
-
"app.task.execution.status": status,
|
|
304
|
-
"app.task.execution.task_id": automationId
|
|
305
|
-
});
|
|
306
|
-
}
|
|
344
|
+
function eventIdentifierWhere(identifiers) {
|
|
345
|
+
return or(isNull(juniorAutomations.identifier), ...identifiers.length > 0 ? [inArray(juniorAutomations.identifier, [...identifiers])] : []);
|
|
307
346
|
}
|
|
308
|
-
/**
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
312
|
-
const oneDayAgoMs = nowMs - 864e5;
|
|
313
|
-
const sevenDaysAgoMs = nowMs - 6048e5;
|
|
314
|
-
const thirtyDaysAgoMs = nowMs - 2592e6;
|
|
315
|
-
const ninetyDaysAgoMs = nowMs - 7776e6;
|
|
316
|
-
const db = getDb();
|
|
317
|
-
const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
|
|
318
|
-
const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
|
|
319
|
-
status: juniorAutomationRuns.status,
|
|
320
|
-
conversationId: juniorAutomationRuns.conversationId,
|
|
321
|
-
automationId: juniorAutomationRuns.automationId
|
|
322
|
-
}).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
|
|
323
|
-
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
324
|
-
const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
|
|
325
|
-
const summaryRows = db.select({
|
|
326
|
-
costLast1Day: costSince(oneDayAgoMs),
|
|
327
|
-
costLast7Days: costSince(sevenDaysAgoMs),
|
|
328
|
-
costLast30Days: costSince(thirtyDaysAgoMs),
|
|
329
|
-
costLast90Days: costSince(ninetyDaysAgoMs),
|
|
330
|
-
lastRunStatus: latest.status,
|
|
331
|
-
lastConversationId: latest.conversationId,
|
|
332
|
-
lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
|
|
333
|
-
runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
|
|
334
|
-
runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
|
|
335
|
-
runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
|
|
336
|
-
runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
|
|
337
|
-
automationId: juniorAutomationRuns.automationId,
|
|
338
|
-
totalCostUsd: sql`coalesce(sum(${conversationCost}), 0)::double precision`,
|
|
339
|
-
totalRuns: sql`count(*)::int`
|
|
340
|
-
}).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
|
|
341
|
-
const [rows, recentRuns] = await Promise.all([summaryRows, readAutomationRecentRuns(automationIds)]);
|
|
342
|
-
return new Map(rows.map((row) => [row.automationId, {
|
|
343
|
-
costUsd: {
|
|
344
|
-
1: addUsd(0, row.costLast1Day),
|
|
345
|
-
7: addUsd(0, row.costLast7Days),
|
|
346
|
-
30: addUsd(0, row.costLast30Days),
|
|
347
|
-
90: addUsd(0, row.costLast90Days)
|
|
348
|
-
},
|
|
349
|
-
lastRunStatus: row.lastRunStatus,
|
|
350
|
-
...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
|
|
351
|
-
...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
|
|
352
|
-
recentRuns: recentRuns.get(row.automationId) ?? [],
|
|
353
|
-
runs: {
|
|
354
|
-
1: row.runsLast1Day,
|
|
355
|
-
7: row.runsLast7Days,
|
|
356
|
-
30: row.runsLast30Days,
|
|
357
|
-
90: row.runsLast90Days
|
|
358
|
-
},
|
|
359
|
-
totalCostUsd: addUsd(0, row.totalCostUsd),
|
|
360
|
-
totalRuns: row.totalRuns
|
|
361
|
-
}]));
|
|
347
|
+
/** SQL for rows whose trigger selects any of these event types. */
|
|
348
|
+
function eventTypesWhere(eventTypes) {
|
|
349
|
+
return or(...eventTypes.map((eventType) => sql`${juniorAutomations.record}->'trigger'->'events' @> ${JSON.stringify([eventType])}::jsonb`));
|
|
362
350
|
}
|
|
363
351
|
/**
|
|
364
|
-
*
|
|
365
|
-
*
|
|
366
|
-
*
|
|
352
|
+
* Return why a row must not run for an Event with one of these identifiers,
|
|
353
|
+
* or nothing when it may.
|
|
354
|
+
*
|
|
355
|
+
* The identifier column and the saved trigger must agree. A row with no
|
|
356
|
+
* identifier must also have a trigger that the enabled `catalog` accepts. A
|
|
357
|
+
* plugin can later require a filter or stop letting an event run for every
|
|
358
|
+
* resource, and the row must not stay broad.
|
|
367
359
|
*/
|
|
368
|
-
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
status: juniorAutomationRuns.status
|
|
375
|
-
}).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, juniorAutomations.id))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(20).as("recent_run");
|
|
376
|
-
const rows = await db.select({
|
|
377
|
-
automationId: juniorAutomations.id,
|
|
378
|
-
durationMs: recent.durationMs,
|
|
379
|
-
executedAtMs: recent.executedAtMs,
|
|
380
|
-
status: recent.status
|
|
381
|
-
}).from(juniorAutomations).innerJoinLateral(recent, sql`true`).where(inArray(juniorAutomations.id, automationIds)).orderBy(juniorAutomations.id, asc(recent.executedAtMs), asc(recent.executionId));
|
|
382
|
-
const byAutomation = /* @__PURE__ */ new Map();
|
|
383
|
-
for (const row of rows) {
|
|
384
|
-
const durationMs = positiveDuration(row.durationMs);
|
|
385
|
-
const runs = byAutomation.get(row.automationId) ?? [];
|
|
386
|
-
runs.push({
|
|
387
|
-
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
388
|
-
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
389
|
-
status: row.status
|
|
390
|
-
});
|
|
391
|
-
byAutomation.set(row.automationId, runs);
|
|
392
|
-
}
|
|
393
|
-
return byAutomation;
|
|
360
|
+
function eventAutomationGateProblem(row, task, identifiers, catalog) {
|
|
361
|
+
const identifier = task.trigger.identifier;
|
|
362
|
+
if (identifier !== void 0) return identifier === row.identifier && identifiers.includes(identifier) ? void 0 : "The saved trigger has a different identifier from its row.";
|
|
363
|
+
if (row.identifier !== null) return "The saved trigger has no identifier, but its row has one.";
|
|
364
|
+
const problems = registeredEventTriggerProblems(catalog, task.trigger);
|
|
365
|
+
return problems.length > 0 ? problems.map((problem) => problem.message).join(" ") : void 0;
|
|
394
366
|
}
|
|
395
|
-
/**
|
|
396
|
-
|
|
397
|
-
|
|
367
|
+
/**
|
|
368
|
+
* Read the rows that can match an Event: live rows of one team and
|
|
369
|
+
* namespace whose identifier is one of these, or that have no identifier,
|
|
370
|
+
* and that select one of these event types. Skip and log a row that does
|
|
371
|
+
* not parse or that the gate rejects.
|
|
372
|
+
*/
|
|
373
|
+
async function readGatedEventAutomations(db, input) {
|
|
374
|
+
const rows = await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.kind, "event"), eq(juniorAutomations.teamId, input.teamId), eq(juniorAutomations.namespace, input.namespace), eventIdentifierWhere(input.identifiers), eventTypesWhere(input.eventTypes), eq(juniorAutomations.status, "active"))).orderBy(asc(juniorAutomations.createdAtMs), asc(juniorAutomations.id));
|
|
375
|
+
const plugins = automationEventCatalog(input.catalog);
|
|
376
|
+
return rows.flatMap((row) => {
|
|
377
|
+
const task = readMatchableEventAutomationRow(row);
|
|
378
|
+
if (!task) return [];
|
|
379
|
+
const problem = eventAutomationGateProblem(row, task, input.identifiers, plugins);
|
|
380
|
+
if (problem === void 0) return [task];
|
|
381
|
+
logWarn("event_automation.gate.rejected", {
|
|
382
|
+
"app.task.id": task.id,
|
|
383
|
+
"app.task.type": "event",
|
|
384
|
+
"app.event_automation.skip_reason": problem
|
|
385
|
+
});
|
|
386
|
+
return [];
|
|
387
|
+
});
|
|
398
388
|
}
|
|
399
|
-
/**
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
automationId: juniorAutomationRuns.automationId
|
|
404
|
-
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(eq(juniorAutomationRuns.conversationId, args.conversationId)).limit(1);
|
|
405
|
-
return row;
|
|
389
|
+
/** The filters of a match whose keys are in this data. */
|
|
390
|
+
function knownMatch(match, data) {
|
|
391
|
+
if (!match) return void 0;
|
|
392
|
+
return Object.fromEntries(Object.entries(match).filter(([key]) => data[key] !== void 0));
|
|
406
393
|
}
|
|
407
394
|
/**
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
411
|
-
*
|
|
395
|
+
* Collect match keys from live event automations for these identifiers and
|
|
396
|
+
* event types, and from automations with no identifier. Does not evaluate
|
|
397
|
+
* match values, except for automations with no identifier: one whose
|
|
398
|
+
* filters on the keys in `data` fail adds no keys. So a broad trigger for
|
|
399
|
+
* one repository does not make every repository load its lazy data.
|
|
412
400
|
*/
|
|
413
|
-
async function
|
|
414
|
-
const
|
|
415
|
-
const
|
|
416
|
-
if (
|
|
417
|
-
const
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
401
|
+
async function collectEventAutomationMatchKeys(db, input) {
|
|
402
|
+
const eventTypes = [...new Set(input.eventTypes.map((eventType) => eventType.trim()).filter(Boolean))];
|
|
403
|
+
const identifiers = [...new Set(input.identifiers.map((value) => value.trim()).filter(Boolean))];
|
|
404
|
+
if (eventTypes.length === 0) return [];
|
|
405
|
+
const tasks = await readGatedEventAutomations(db, {
|
|
406
|
+
catalog: input.catalog,
|
|
407
|
+
eventTypes,
|
|
408
|
+
identifiers,
|
|
409
|
+
namespace: input.namespace,
|
|
410
|
+
teamId: input.teamId
|
|
411
|
+
});
|
|
412
|
+
const keys = /* @__PURE__ */ new Set();
|
|
413
|
+
for (const task of tasks) {
|
|
414
|
+
if (task.trigger.identifier === void 0 && input.data && !eventMatches(knownMatch(task.trigger.match, input.data), input.data)) continue;
|
|
415
|
+
for (const key of Object.keys(task.trigger.match ?? {})) keys.add(key);
|
|
425
416
|
}
|
|
426
|
-
return
|
|
427
|
-
}
|
|
428
|
-
/** Load newest-first executions for one automation, with conversation titles when present. */
|
|
429
|
-
async function readAutomationExecutions(args) {
|
|
430
|
-
return (await getDb().select(executionColumns).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).leftJoin(juniorAutomationVersions, executionVersion()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(args.limit)).map((row) => mapAutomationExecutionRecord(row));
|
|
431
|
-
}
|
|
432
|
-
/** Load newest-first executions for the supplied viewer-visible automations. */
|
|
433
|
-
async function readAutomationRuns(args) {
|
|
434
|
-
if (args.automationIds.length === 0) return [];
|
|
435
|
-
return (await getDb().select({
|
|
436
|
-
...executionColumns,
|
|
437
|
-
kind: juniorAutomations.kind,
|
|
438
|
-
automationId: juniorAutomationRuns.automationId
|
|
439
|
-
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).leftJoin(juniorAutomationVersions, executionVersion()).where(and(isExecution(), inArray(juniorAutomationRuns.automationId, args.automationIds))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(args.limit)).map((row) => ({
|
|
440
|
-
...mapAutomationExecutionRecord(row),
|
|
441
|
-
kind: row.kind,
|
|
442
|
-
automationId: row.automationId
|
|
443
|
-
}));
|
|
417
|
+
return [...keys].sort();
|
|
444
418
|
}
|
|
445
|
-
/**
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
419
|
+
/**
|
|
420
|
+
* Find every live task matching each normalized event, with one read for all
|
|
421
|
+
* of them: tasks for its exact identifier, and tasks with no identifier whose
|
|
422
|
+
* filters match. Returns one list per event, in order. The events must share
|
|
423
|
+
* one namespace. The gate skips a row whose trigger and identifier column
|
|
424
|
+
* disagree, and a row with no identifier whose trigger the enabled `catalog`
|
|
425
|
+
* rejects.
|
|
426
|
+
*/
|
|
427
|
+
async function findMatchingEventAutomations(db, events, teamId, catalog) {
|
|
428
|
+
const namespace = events[0]?.namespace;
|
|
429
|
+
if (namespace === void 0) return [];
|
|
430
|
+
if (events.some((event) => event.namespace !== namespace)) throw new Error("Events to match must share one namespace.");
|
|
431
|
+
const tasks = await readGatedEventAutomations(db, {
|
|
432
|
+
catalog,
|
|
433
|
+
eventTypes: [...new Set(events.map((event) => event.eventType))],
|
|
434
|
+
identifiers: [...new Set(events.map((event) => event.identifier))],
|
|
435
|
+
namespace,
|
|
436
|
+
teamId
|
|
437
|
+
});
|
|
438
|
+
return events.map((event) => tasks.filter((task) => (task.trigger.identifier === void 0 || task.trigger.identifier === event.identifier) && task.trigger.events.includes(event.eventType) && eventMatches(task.trigger.match, event.data)));
|
|
462
439
|
}
|
|
463
|
-
|
|
464
|
-
|
|
440
|
+
/**
|
|
441
|
+
* Change lifecycle under the same row lock as edits, without changing
|
|
442
|
+
* credentials. A pause keeps an unresolved block reason, so resuming a paused
|
|
443
|
+
* blocked automation returns it to blocked. Resume a blocked automation to
|
|
444
|
+
* clear the reason. A resume also clears the run-limit count first.
|
|
445
|
+
*/
|
|
446
|
+
async function setEventAutomationStatus(db, id, status, revision) {
|
|
447
|
+
if (status === "active" && (await getEventAutomation(db, id))?.status !== "active") await clearEventAutomationRuns(id);
|
|
448
|
+
return db.transaction(async (tx) => {
|
|
449
|
+
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(id)).for("update");
|
|
450
|
+
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
451
|
+
requireAutomationRevision(current, revision);
|
|
452
|
+
if (!current || current.status === "deleted") throw new Error("Automation no longer exists.");
|
|
453
|
+
const next = status === "paused" ? {
|
|
454
|
+
status,
|
|
455
|
+
statusReason: current.statusReason
|
|
456
|
+
} : current.status === "paused" && current.statusReason ? {
|
|
457
|
+
status: "blocked",
|
|
458
|
+
statusReason: current.statusReason
|
|
459
|
+
} : {
|
|
460
|
+
status,
|
|
461
|
+
statusReason: void 0
|
|
462
|
+
};
|
|
463
|
+
await tx.update(juniorAutomations).set({
|
|
464
|
+
status: next.status,
|
|
465
|
+
statusReason: next.statusReason ?? null
|
|
466
|
+
}).where(eventAutomationWhere(id));
|
|
467
|
+
const { statusReason: _statusReason, ...rest } = current;
|
|
468
|
+
return {
|
|
469
|
+
...rest,
|
|
470
|
+
status: next.status,
|
|
471
|
+
...next.statusReason ? { statusReason: next.statusReason } : void 0
|
|
472
|
+
};
|
|
473
|
+
});
|
|
465
474
|
}
|
|
466
|
-
|
|
467
|
-
|
|
475
|
+
/**
|
|
476
|
+
* Stop an event automation after a run reports a problem that only its
|
|
477
|
+
* creator can fix. An active automation becomes blocked. A paused automation
|
|
478
|
+
* stays paused and keeps the reason, so resume returns it to blocked.
|
|
479
|
+
* Deleted automations do not change. Returns true only when this call set
|
|
480
|
+
* the automation to blocked, so the creator notice goes once and never for
|
|
481
|
+
* an automation that the dashboard shows as paused.
|
|
482
|
+
*/
|
|
483
|
+
async function blockEventAutomation(db, id, reason) {
|
|
484
|
+
return (await db.update(juniorAutomations).set({
|
|
485
|
+
status: sql`case when ${juniorAutomations.status} = 'active' then 'blocked' else ${juniorAutomations.status} end`,
|
|
486
|
+
statusReason: reason
|
|
487
|
+
}).where(and(eventAutomationWhere(id), or(eq(juniorAutomations.status, "active"), and(eq(juniorAutomations.status, "paused"), sql`${juniorAutomations.statusReason} is distinct from ${reason}`)))).returning({ status: juniorAutomations.status }))[0]?.status === "blocked";
|
|
468
488
|
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
const
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
...row.conversationId ? { conversationId: row.conversationId } : void 0,
|
|
480
|
-
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
481
|
-
...row.credentialMode === "creator" || row.credentialMode === "system" ? { credentialMode: row.credentialMode } : void 0,
|
|
482
|
-
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
483
|
-
...error ? { error } : void 0,
|
|
484
|
-
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
485
|
-
executionId: row.executionId,
|
|
486
|
-
...scheduledFor ? { scheduledFor } : void 0,
|
|
487
|
-
...startedAt ? { startedAt } : void 0,
|
|
489
|
+
// src/chat/scheduled-automations/tasks.ts
|
|
490
|
+
const SCHEDULER_KEY_PREFIX = "junior:scheduler";
|
|
491
|
+
/** Decode a Scheduled automation row. Returns undefined for an invalid row. */
|
|
492
|
+
function parseScheduledAutomationRow(row) {
|
|
493
|
+
const columns = {
|
|
494
|
+
createdAtMs: row.createdAtMs,
|
|
495
|
+
creatorIdentityId: row.creatorIdentityId,
|
|
496
|
+
id: row.id,
|
|
497
|
+
nextRunAtMs: row.nextRunAtMs,
|
|
498
|
+
runNowAtMs: row.runNowAtMs,
|
|
488
499
|
status: row.status,
|
|
489
|
-
|
|
490
|
-
|
|
500
|
+
statusReason: row.statusReason,
|
|
501
|
+
title: row.title
|
|
491
502
|
};
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
const dayCount = args.dayCount ?? 90;
|
|
496
|
-
const end = utcDate(args.nowMs ?? Date.now());
|
|
497
|
-
const endMs = Date.parse(`${end}T23:59:59.999Z`);
|
|
498
|
-
const startMs = Date.parse(`${end}T00:00:00.000Z`) - (dayCount - 1) * 864e5;
|
|
499
|
-
const executionDate = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD')`;
|
|
500
|
-
const rows = await readExecutionStatusBuckets({
|
|
501
|
-
automationId: args.automationId,
|
|
502
|
-
bucket: executionDate,
|
|
503
|
-
endMs,
|
|
504
|
-
startMs
|
|
503
|
+
const parsed = scheduledAutomationSchema.safeParse({
|
|
504
|
+
...row.record,
|
|
505
|
+
...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
|
|
505
506
|
});
|
|
506
|
-
|
|
507
|
-
for (let offset = 0; offset < dayCount; offset += 1) {
|
|
508
|
-
const date = utcDate(startMs + offset * 864e5);
|
|
509
|
-
byDate.set(date, emptyStatusDay(date));
|
|
510
|
-
}
|
|
511
|
-
for (const row of rows) {
|
|
512
|
-
const day = byDate.get(row.date);
|
|
513
|
-
if (!day) continue;
|
|
514
|
-
if (row.status === "completed") day.completed = row.count;
|
|
515
|
-
else if (row.status === "failed") day.failed = row.count;
|
|
516
|
-
else if (row.status === "blocked") day.blocked = row.count;
|
|
517
|
-
if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
|
|
518
|
-
}
|
|
519
|
-
return [...byDate.values()];
|
|
507
|
+
return parsed.success ? parsed.data : void 0;
|
|
520
508
|
}
|
|
521
|
-
/**
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
startMs
|
|
509
|
+
/** Keep scan paths from returning current or legacy tombstones. */
|
|
510
|
+
function isListedScheduledAutomation(task) {
|
|
511
|
+
return task !== void 0 && task.status !== "deleted";
|
|
512
|
+
}
|
|
513
|
+
/** Build the stable run id for one task occurrence. */
|
|
514
|
+
function scheduledRunId(taskId, scheduledForMs) {
|
|
515
|
+
return `${taskId}:${scheduledForMs}`;
|
|
516
|
+
}
|
|
517
|
+
/** Acquire the deployed advisory lock for one scheduled automation. */
|
|
518
|
+
function withScheduledAutomationLock(db, taskId, callback) {
|
|
519
|
+
return db.transaction(async (tx) => {
|
|
520
|
+
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
|
|
521
|
+
return await callback(tx);
|
|
535
522
|
});
|
|
536
|
-
const byHour = /* @__PURE__ */ new Map();
|
|
537
|
-
for (let offset = 0; offset < hourCount; offset += 1) {
|
|
538
|
-
const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
|
|
539
|
-
byHour.set(date, emptyStatusDay(date));
|
|
540
|
-
}
|
|
541
|
-
for (const row of rows) {
|
|
542
|
-
const hour = byHour.get(row.date);
|
|
543
|
-
if (!hour) continue;
|
|
544
|
-
if (row.status === "completed") hour.completed = row.count;
|
|
545
|
-
else if (row.status === "failed") hour.failed = row.count;
|
|
546
|
-
else if (row.status === "blocked") hour.blocked = row.count;
|
|
547
|
-
if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
|
|
548
|
-
}
|
|
549
|
-
return [...byHour.values()];
|
|
550
523
|
}
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
}
|
|
524
|
+
function requireStoredTask(task) {
|
|
525
|
+
const parsed = scheduledAutomationSchema.safeParse(task);
|
|
526
|
+
if (!parsed.success) throw new Error("Scheduled automation routing context is invalid.");
|
|
527
|
+
const { title, ...current } = parsed.data;
|
|
528
|
+
const normalizedTitle = title?.trim() || void 0;
|
|
529
|
+
return {
|
|
530
|
+
...current,
|
|
531
|
+
...normalizedTitle ? { title: normalizedTitle } : void 0
|
|
532
|
+
};
|
|
560
533
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
534
|
+
async function upsertScheduledAutomation(db, task) {
|
|
535
|
+
const { createdAtMs, creatorIdentityId, id, nextRunAtMs, runNowAtMs, status, statusReason, title, ...record } = task;
|
|
536
|
+
const columns = {
|
|
537
|
+
channelId: record.destination.channelId,
|
|
538
|
+
createdAtMs,
|
|
539
|
+
creatorIdentityId,
|
|
540
|
+
creatorSlackUserId: record.createdBy.slackUserId,
|
|
541
|
+
...automationTaskColumns(record.task),
|
|
542
|
+
nextRunAtMs: nextRunAtMs ?? null,
|
|
543
|
+
record,
|
|
544
|
+
runNowAtMs: runNowAtMs ?? null,
|
|
545
|
+
status,
|
|
546
|
+
statusReason: statusReason ?? null,
|
|
547
|
+
teamId: record.destination.teamId,
|
|
548
|
+
title: title?.trim() || null
|
|
549
|
+
};
|
|
550
|
+
await db.insert(juniorAutomations).values({
|
|
551
|
+
...columns,
|
|
552
|
+
id,
|
|
553
|
+
kind: "scheduled"
|
|
554
|
+
}).onConflictDoUpdate({
|
|
555
|
+
target: juniorAutomations.id,
|
|
556
|
+
set: columns
|
|
557
|
+
});
|
|
574
558
|
}
|
|
575
|
-
/**
|
|
576
|
-
function
|
|
577
|
-
|
|
559
|
+
/** Read and decode one scheduled automation. */
|
|
560
|
+
async function readScheduledAutomation(db, taskId) {
|
|
561
|
+
const rows = await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.id, taskId), eq(juniorAutomations.kind, "scheduled"))).limit(1);
|
|
562
|
+
return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
|
|
578
563
|
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
if (!task || automationRevision(task) !== revision) throw new AutomationConflictError();
|
|
564
|
+
async function readListedScheduledAutomations(db, teamId) {
|
|
565
|
+
return (await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.kind, "scheduled"), ne(juniorAutomations.status, "deleted"), teamId === void 0 ? void 0 : eq(juniorAutomations.teamId, teamId))).orderBy(asc(juniorAutomations.createdAtMs), asc(juniorAutomations.id))).map(parseScheduledAutomationRow).filter(isListedScheduledAutomation);
|
|
582
566
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
function automationDefinition(task) {
|
|
587
|
-
const common = {
|
|
588
|
-
title: task.title?.trim() || null,
|
|
589
|
-
task: task.task,
|
|
590
|
-
credentialMode: task.credentialMode,
|
|
591
|
-
destination: task.destination,
|
|
592
|
-
outcomes: task.outcomes
|
|
593
|
-
};
|
|
594
|
-
return "schedule" in task ? {
|
|
595
|
-
...common,
|
|
596
|
-
schedule: task.schedule
|
|
597
|
-
} : {
|
|
598
|
-
...common,
|
|
599
|
-
trigger: task.trigger
|
|
600
|
-
};
|
|
567
|
+
/** List decoded scheduled automations for one team in stable creation order. */
|
|
568
|
+
async function listScheduledAutomationsForTeam(db, teamId) {
|
|
569
|
+
return await readListedScheduledAutomations(db, teamId);
|
|
601
570
|
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
571
|
+
async function writeScheduledAutomation(db, task, current, editedBy) {
|
|
572
|
+
if (current?.status === "blocked" && task.status === "active" && typeof task.nextRunAtMs === "number" && Number.isFinite(task.nextRunAtMs)) await db.delete(juniorAutomationRuns).where(and(eq(juniorAutomationRuns.id, scheduledRunId(task.id, task.nextRunAtMs)), eq(juniorAutomationRuns.status, "blocked")));
|
|
573
|
+
if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
|
|
574
|
+
await upsertScheduledAutomation(db, task);
|
|
575
|
+
await recordAutomationVersion(db, task, current, editedBy);
|
|
605
576
|
}
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
createdAtMs: Date.now(),
|
|
622
|
-
editedBy: editedBy ?? (current ? null : task.createdBy),
|
|
623
|
-
definition
|
|
577
|
+
async function skipPendingRunsForDeletedTask(db, task) {
|
|
578
|
+
await db.update(juniorAutomationRuns).set({
|
|
579
|
+
completedAtMs: task.updatedAtMs,
|
|
580
|
+
errorMessage: `Scheduled automation ${task.id} was deleted before the run started.`,
|
|
581
|
+
status: "skipped"
|
|
582
|
+
}).where(and(eq(juniorAutomationRuns.automationId, task.id), eq(juniorAutomationRuns.status, "pending")));
|
|
583
|
+
}
|
|
584
|
+
/** Create a scheduled automation once under its retry-stable task lock. */
|
|
585
|
+
async function createScheduledAutomation(db, task) {
|
|
586
|
+
const next = requireStoredTask(task);
|
|
587
|
+
return await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
588
|
+
const current = await readScheduledAutomation(tx, task.id);
|
|
589
|
+
if (current) return current;
|
|
590
|
+
await writeScheduledAutomation(tx, next, void 0);
|
|
591
|
+
return next;
|
|
624
592
|
});
|
|
625
593
|
}
|
|
626
594
|
/**
|
|
627
|
-
*
|
|
628
|
-
*
|
|
629
|
-
* An Automation run stores this version so that a reader can see the
|
|
630
|
-
* instruction that ran after the definition changes. The value is null when
|
|
631
|
-
* no saved version has this definition.
|
|
595
|
+
* Save a scheduled automation and clear its blocked occurrence on reactivation.
|
|
596
|
+
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
632
597
|
*/
|
|
633
|
-
function
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
)`;
|
|
640
|
-
}
|
|
641
|
-
const versionColumns = {
|
|
642
|
-
createdAtMs: juniorAutomationVersions.createdAtMs,
|
|
643
|
-
definition: juniorAutomationVersions.definition,
|
|
644
|
-
editedBy: juniorAutomationVersions.editedBy,
|
|
645
|
-
kind: juniorAutomations.kind,
|
|
646
|
-
version: juniorAutomationVersions.version
|
|
647
|
-
};
|
|
648
|
-
function parseVersionRow(row) {
|
|
649
|
-
return automationVersionSchema.parse({
|
|
650
|
-
kind: row.kind,
|
|
651
|
-
version: row.version,
|
|
652
|
-
createdAt: new Date(row.createdAtMs).toISOString(),
|
|
653
|
-
editedBy: row.editedBy,
|
|
654
|
-
definition: row.definition
|
|
598
|
+
async function saveScheduledAutomation(db, task, expectedRevision, editedBy) {
|
|
599
|
+
const next = requireStoredTask(task);
|
|
600
|
+
await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
601
|
+
const current = await readScheduledAutomation(tx, task.id);
|
|
602
|
+
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
603
|
+
await writeScheduledAutomation(tx, next, current, editedBy);
|
|
655
604
|
});
|
|
605
|
+
return next;
|
|
656
606
|
}
|
|
657
|
-
/**
|
|
658
|
-
async function
|
|
659
|
-
|
|
660
|
-
return row ? parseVersionRow(row) : void 0;
|
|
661
|
-
}
|
|
662
|
-
/** Read saved definitions, newest first. */
|
|
663
|
-
async function listAutomationVersions(db, automationId, limit) {
|
|
664
|
-
return (await db.select(versionColumns).from(juniorAutomationVersions).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationVersions.automationId)).where(eq(juniorAutomationVersions.automationId, automationId)).orderBy(desc(juniorAutomationVersions.version)).limit(limit)).map(parseVersionRow);
|
|
665
|
-
}
|
|
666
|
-
// src/chat/event-automations/run-limit.ts
|
|
667
|
-
const RUN_LIST_PREFIX = "junior:event_automation_runs:v1";
|
|
668
|
-
const RUN_LIST_BURST_ROOM = 100;
|
|
669
|
-
const runEntrySchema = z.union([z.object({
|
|
670
|
-
atMs: z.number().finite(),
|
|
671
|
-
id: z.string().min(1)
|
|
672
|
-
}).strict(), z.object({ reset: z.literal(true) }).strict()]);
|
|
673
|
-
function runListKey(automationId) {
|
|
674
|
-
return `${RUN_LIST_PREFIX}:${automationId}`;
|
|
607
|
+
/** Save a scheduled automation inside a task lock already held by the caller. */
|
|
608
|
+
async function saveScheduledAutomationInLock(db, task, current) {
|
|
609
|
+
await writeScheduledAutomation(db, requireStoredTask(task), current);
|
|
675
610
|
}
|
|
676
|
-
|
|
677
|
-
|
|
611
|
+
/** Mark one live scheduled automation deleted while keeping its history. */
|
|
612
|
+
async function deleteScheduledAutomation(db, id, nowMs = Date.now()) {
|
|
613
|
+
return await withScheduledAutomationLock(db, id, async (tx) => {
|
|
614
|
+
const current = await readScheduledAutomation(tx, id);
|
|
615
|
+
if (!current || current.status === "deleted") return void 0;
|
|
616
|
+
const deleted = requireStoredTask({
|
|
617
|
+
...current,
|
|
618
|
+
nextRunAtMs: void 0,
|
|
619
|
+
runNowAtMs: void 0,
|
|
620
|
+
status: "deleted",
|
|
621
|
+
updatedAtMs: nowMs
|
|
622
|
+
});
|
|
623
|
+
await writeScheduledAutomation(tx, deleted, current);
|
|
624
|
+
return deleted;
|
|
625
|
+
});
|
|
678
626
|
}
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
627
|
+
/**
|
|
628
|
+
* Block a Scheduled automation outside the settle step of a run, such as from
|
|
629
|
+
* a Watch Event Turn of its run. An active automation becomes blocked. A
|
|
630
|
+
* paused automation stays paused and keeps the reason, so resume returns it
|
|
631
|
+
* to blocked. Returns true only when this call set it to blocked.
|
|
632
|
+
*/
|
|
633
|
+
async function blockScheduledAutomation(db, id, reason, nowMs = Date.now()) {
|
|
634
|
+
return await withScheduledAutomationLock(db, id, async (tx) => {
|
|
635
|
+
const current = await readScheduledAutomation(tx, id);
|
|
636
|
+
if (current?.status !== "active" && current?.status !== "paused") return false;
|
|
637
|
+
const blocked = current.status === "active";
|
|
638
|
+
await writeScheduledAutomation(tx, requireStoredTask({
|
|
639
|
+
...current,
|
|
640
|
+
...blocked ? {
|
|
641
|
+
nextRunAtMs: void 0,
|
|
642
|
+
runNowAtMs: void 0,
|
|
643
|
+
status: "blocked"
|
|
644
|
+
} : void 0,
|
|
645
|
+
statusReason: reason,
|
|
646
|
+
updatedAtMs: nowMs
|
|
647
|
+
}), current);
|
|
648
|
+
return blocked;
|
|
684
649
|
});
|
|
685
650
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
const count = windowMs / unitMs;
|
|
694
|
-
return count === 1 ? unit : `${count} ${unit}s`;
|
|
695
|
-
}
|
|
696
|
-
return `${windowMs} ms`;
|
|
697
|
-
}
|
|
698
|
-
/** Reason stored on an Event automation that the run limit blocked. */
|
|
699
|
-
function eventAutomationRunLimitReason() {
|
|
700
|
-
const window = describeRunWindow(botConfig.eventAutomationRunWindowMs);
|
|
701
|
-
return `This automation reached its limit of ${botConfig.maxEventAutomationRuns} runs per ${window}. Check that its trigger is not too broad, then resume it.`;
|
|
651
|
+
// src/api/conversations/aggregate.ts
|
|
652
|
+
function usageTokenValue(source, field) {
|
|
653
|
+
return sql`CASE
|
|
654
|
+
WHEN ${source.usage}->>${field} IS NOT NULL
|
|
655
|
+
THEN (${source.usage}->>${field})::double precision
|
|
656
|
+
ELSE NULL
|
|
657
|
+
END`;
|
|
702
658
|
}
|
|
703
|
-
function
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
659
|
+
function tokenValue(source) {
|
|
660
|
+
return sql`
|
|
661
|
+
CASE
|
|
662
|
+
WHEN COALESCE(
|
|
663
|
+
${source.usage}->>'inputTokens',
|
|
664
|
+
${source.usage}->>'outputTokens',
|
|
665
|
+
${source.usage}->>'cachedInputTokens',
|
|
666
|
+
${source.usage}->>'cacheCreationTokens'
|
|
667
|
+
) IS NOT NULL
|
|
668
|
+
THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
|
|
669
|
+
+ COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
|
|
670
|
+
+ COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
|
|
671
|
+
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
672
|
+
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
673
|
+
THEN (${source.usage}->>'totalTokens')::double precision
|
|
674
|
+
ELSE NULL
|
|
675
|
+
END
|
|
676
|
+
`;
|
|
710
677
|
}
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
*
|
|
714
|
-
* `runKey` is the dispatch idempotency key, so a provider retry of the same
|
|
715
|
-
* Event does not count again.
|
|
716
|
-
*/
|
|
717
|
-
async function admitEventAutomationRun(args) {
|
|
718
|
-
const state = args.state ?? getStateAdapter();
|
|
719
|
-
await state.connect();
|
|
720
|
-
const readEntries = async () => {
|
|
721
|
-
const values = await state.getList(runListKey(args.automationId));
|
|
722
|
-
return {
|
|
723
|
-
entries: values.flatMap((value) => {
|
|
724
|
-
const entry = runEntrySchema.safeParse(value);
|
|
725
|
-
return entry.success ? [entry.data] : [];
|
|
726
|
-
}),
|
|
727
|
-
length: values.length
|
|
728
|
-
};
|
|
729
|
-
};
|
|
730
|
-
if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
|
|
731
|
-
atMs: args.nowMs,
|
|
732
|
-
id: args.runKey
|
|
733
|
-
});
|
|
734
|
-
const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
|
|
735
|
-
const { entries, length } = await readEntries();
|
|
736
|
-
let lastReset = -1;
|
|
737
|
-
entries.forEach((entry, index) => {
|
|
738
|
-
if ("reset" in entry) lastReset = index;
|
|
739
|
-
});
|
|
740
|
-
const oldest = entries[0];
|
|
741
|
-
const full = lastReset === -1 && length >= runListMaxLength() && oldest !== void 0 && "atMs" in oldest && oldest.atMs > windowStartMs;
|
|
742
|
-
const runKeys = /* @__PURE__ */ new Set();
|
|
743
|
-
for (const entry of entries.slice(lastReset + 1)) {
|
|
744
|
-
if ("reset" in entry) continue;
|
|
745
|
-
if (entry.atMs > windowStartMs) runKeys.add(entry.id);
|
|
746
|
-
if (entry.id === args.runKey) return full || runKeys.size > botConfig.maxEventAutomationRuns ? "limited" : "allowed";
|
|
747
|
-
}
|
|
748
|
-
return "limited";
|
|
678
|
+
function costValue(source) {
|
|
679
|
+
return conversationUsageCostExpr(source.usage);
|
|
749
680
|
}
|
|
750
|
-
/**
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
681
|
+
/** Read one conversation row's usage cost as a SQL expression. */
|
|
682
|
+
function conversationUsageCostExpr(usage) {
|
|
683
|
+
return sql`
|
|
684
|
+
CASE
|
|
685
|
+
WHEN ${usage}->'cost'->>'total' IS NOT NULL
|
|
686
|
+
THEN (${usage}->'cost'->>'total')::double precision
|
|
687
|
+
WHEN COALESCE(
|
|
688
|
+
${usage}->'cost'->>'input',
|
|
689
|
+
${usage}->'cost'->>'output',
|
|
690
|
+
${usage}->'cost'->>'cacheRead',
|
|
691
|
+
${usage}->'cost'->>'cacheWrite'
|
|
692
|
+
) IS NOT NULL
|
|
693
|
+
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
694
|
+
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
695
|
+
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
696
|
+
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
697
|
+
ELSE NULL
|
|
698
|
+
END
|
|
699
|
+
`;
|
|
759
700
|
}
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
function eventAutomationColumns(task) {
|
|
766
|
-
const { status: _status, statusReason: _statusReason, title, ...definition } = task;
|
|
767
|
-
const { createdAtMs: _createdAtMs, creatorIdentityId, id: _id, ...record } = eventAutomationSchema.parse(definition);
|
|
701
|
+
/** Select complete conversation metrics inside the database instead of materializing source rows. */
|
|
702
|
+
function conversationAggregateColumns(sources) {
|
|
703
|
+
const metrics = sources?.metrics ?? juniorConversations;
|
|
704
|
+
const roots = sources?.roots ?? juniorConversations;
|
|
705
|
+
const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
|
|
768
706
|
return {
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
707
|
+
active: sql`${conversationCount} FILTER (
|
|
708
|
+
WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
|
|
709
|
+
)::integer`,
|
|
710
|
+
conversations: sql`${conversationCount}::integer`,
|
|
711
|
+
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
712
|
+
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
713
|
+
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
714
|
+
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
715
|
+
failed: sql`${conversationCount} FILTER (
|
|
716
|
+
WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
|
|
717
|
+
)::integer`,
|
|
718
|
+
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
719
|
+
tokens: sql`SUM(${tokenValue(metrics)})::double precision`
|
|
778
720
|
};
|
|
779
721
|
}
|
|
780
|
-
|
|
722
|
+
/** Select the complete first/last activity range for a grouped conversation aggregate. */
|
|
723
|
+
function conversationRangeColumns() {
|
|
781
724
|
return {
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
creatorIdentityId: row.creatorIdentityId,
|
|
785
|
-
id: row.id
|
|
725
|
+
firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
|
|
726
|
+
lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
|
|
786
727
|
};
|
|
787
728
|
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
729
|
+
// src/chat/automations/execution-stats.ts
|
|
730
|
+
const AUTOMATION_EXECUTION_STATUSES = [
|
|
731
|
+
"blocked",
|
|
732
|
+
"completed",
|
|
733
|
+
"failed"
|
|
734
|
+
];
|
|
735
|
+
/** An execution is a run with an outcome. Skipped runs are not executions. */
|
|
736
|
+
function isExecution() {
|
|
737
|
+
return and(inArray(juniorAutomationRuns.status, [...AUTOMATION_EXECUTION_STATUSES]), isNotNull(juniorAutomationRuns.completedAtMs));
|
|
791
738
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
* so one bad row cannot stop matching for its whole namespace.
|
|
795
|
-
*/
|
|
796
|
-
function readMatchableEventAutomationRow(row) {
|
|
797
|
-
const parsed = eventAutomationSchema.safeParse(eventAutomationRowInput(row));
|
|
798
|
-
if (parsed.success) return withRowFields(row, parsed.data);
|
|
799
|
-
logWarn("event_automation.row.invalid", {
|
|
800
|
-
"app.task.id": row.id,
|
|
801
|
-
"app.task.type": "event",
|
|
802
|
-
"error.message": parsed.error.message
|
|
803
|
-
});
|
|
739
|
+
function addUsd(current, next) {
|
|
740
|
+
return Math.round((current + next) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
804
741
|
}
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
742
|
+
const EMPTY_RUN_WINDOWS = {
|
|
743
|
+
1: 0,
|
|
744
|
+
7: 0,
|
|
745
|
+
30: 0,
|
|
746
|
+
90: 0
|
|
747
|
+
};
|
|
748
|
+
/** Empty run or cost windows for automations with no execution history. */
|
|
749
|
+
function emptyAutomationRunWindows() {
|
|
750
|
+
return { ...EMPTY_RUN_WINDOWS };
|
|
813
751
|
}
|
|
814
|
-
function
|
|
815
|
-
return
|
|
752
|
+
function utcDate(nowMs) {
|
|
753
|
+
return new Date(nowMs).toISOString().slice(0, 10);
|
|
816
754
|
}
|
|
817
|
-
function
|
|
818
|
-
return
|
|
755
|
+
function emptyStatusDay(date) {
|
|
756
|
+
return {
|
|
757
|
+
blocked: 0,
|
|
758
|
+
completed: 0,
|
|
759
|
+
costUsd: 0,
|
|
760
|
+
date,
|
|
761
|
+
failed: 0
|
|
762
|
+
};
|
|
819
763
|
}
|
|
820
|
-
/**
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
const columns = eventAutomationColumns(task);
|
|
828
|
-
if ((await getEventAutomation(db, task.id))?.status === "deleted") await clearEventAutomationRuns(task.id);
|
|
829
|
-
return db.transaction(async (tx) => {
|
|
830
|
-
const inserted = await tx.insert(juniorAutomations).values({
|
|
831
|
-
...columns,
|
|
832
|
-
createdAtMs: task.createdAtMs,
|
|
833
|
-
id: task.id,
|
|
834
|
-
kind: "event",
|
|
835
|
-
status: "active"
|
|
836
|
-
}).onConflictDoNothing().returning();
|
|
837
|
-
if (inserted[0]) {
|
|
838
|
-
const created = parseEventAutomationRow(inserted[0]);
|
|
839
|
-
await recordAutomationVersion(tx, created, void 0);
|
|
840
|
-
return created;
|
|
841
|
-
}
|
|
842
|
-
const existing = await getEventAutomation(tx, task.id);
|
|
843
|
-
if (!existing) throw new Error(`Automation ${task.id} already exists with another kind.`);
|
|
844
|
-
if (existing.status !== "deleted") return existing;
|
|
845
|
-
const rows = await tx.update(juniorAutomations).set({
|
|
846
|
-
...columns,
|
|
847
|
-
status: "active",
|
|
848
|
-
statusReason: null
|
|
849
|
-
}).where(and(eventAutomationWhere(task.id), eq(juniorAutomations.status, "deleted"))).returning();
|
|
850
|
-
if (!rows[0]) return await getEventAutomation(tx, task.id);
|
|
851
|
-
const revived = parseEventAutomationRow(rows[0]);
|
|
852
|
-
await recordAutomationVersion(tx, revived, void 0);
|
|
853
|
-
return revived;
|
|
854
|
-
});
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* Replace an existing non-deleted event automation under a row lock.
|
|
858
|
-
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
859
|
-
*/
|
|
860
|
-
async function saveEventAutomation(db, task, expectedRevision, editedBy) {
|
|
861
|
-
const columns = eventAutomationColumns(task);
|
|
862
|
-
return db.transaction(async (tx) => {
|
|
863
|
-
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(task.id)).for("update");
|
|
864
|
-
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
865
|
-
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
866
|
-
if (!current || current.status === "deleted") return void 0;
|
|
867
|
-
const saved = parseEventAutomationRow((await tx.update(juniorAutomations).set(columns).where(eventAutomationWhere(task.id)).returning())[0]);
|
|
868
|
-
await recordAutomationVersion(tx, saved, current, editedBy);
|
|
869
|
-
return saved;
|
|
870
|
-
});
|
|
871
|
-
}
|
|
872
|
-
/** Mark one existing event automation deleted while retaining the row for history. */
|
|
873
|
-
async function deleteEventAutomation(db, id) {
|
|
874
|
-
const rows = await db.update(juniorAutomations).set({ status: "deleted" }).where(and(eq(juniorAutomations.id, id), activeEventAutomationWhere())).returning();
|
|
875
|
-
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
876
|
-
}
|
|
877
|
-
/**
|
|
878
|
-
* List deleted event automations created by one user, newest first.
|
|
879
|
-
* Used only to keep historical runs after the live automation list drops the row.
|
|
880
|
-
*/
|
|
881
|
-
async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
|
|
882
|
-
const identityIds = user.identities.map((identity) => identity.id);
|
|
883
|
-
if (identityIds.length === 0) return [];
|
|
884
|
-
return (await db.select().from(juniorAutomations).where(and(inArray(juniorAutomations.creatorIdentityId, identityIds), eq(juniorAutomations.kind, "event"), eq(juniorAutomations.status, "deleted"))).orderBy(desc(juniorAutomations.createdAtMs), desc(juniorAutomations.id)).limit(limit)).map(parseEventAutomationRow);
|
|
885
|
-
}
|
|
886
|
-
/**
|
|
887
|
-
* Select live rows whose identifier is one of these, and rows with no
|
|
888
|
-
* identifier. A row with no identifier runs for every resource of its
|
|
889
|
-
* namespace, so it gets every copy of an Event.
|
|
890
|
-
*/
|
|
891
|
-
function eventIdentifierWhere(identifiers) {
|
|
892
|
-
return or(isNull(juniorAutomations.identifier), ...identifiers.length > 0 ? [inArray(juniorAutomations.identifier, [...identifiers])] : []);
|
|
893
|
-
}
|
|
894
|
-
/** SQL for rows whose trigger selects any of these event types. */
|
|
895
|
-
function eventTypesWhere(eventTypes) {
|
|
896
|
-
return or(...eventTypes.map((eventType) => sql`${juniorAutomations.record}->'trigger'->'events' @> ${JSON.stringify([eventType])}::jsonb`));
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
|
-
* Return why a row must not run for an Event with one of these identifiers,
|
|
900
|
-
* or nothing when it may.
|
|
901
|
-
*
|
|
902
|
-
* The identifier column and the saved trigger must agree. A row with no
|
|
903
|
-
* identifier must also have a trigger that the enabled `catalog` accepts. A
|
|
904
|
-
* plugin can later require a filter or stop letting an event run for every
|
|
905
|
-
* resource, and the row must not stay broad.
|
|
906
|
-
*/
|
|
907
|
-
function eventAutomationGateProblem(row, task, identifiers, catalog) {
|
|
908
|
-
const identifier = task.trigger.identifier;
|
|
909
|
-
if (identifier !== void 0) return identifier === row.identifier && identifiers.includes(identifier) ? void 0 : "The saved trigger has a different identifier from its row.";
|
|
910
|
-
if (row.identifier !== null) return "The saved trigger has no identifier, but its row has one.";
|
|
911
|
-
const problems = registeredEventTriggerProblems(catalog, task.trigger);
|
|
912
|
-
return problems.length > 0 ? problems.map((problem) => problem.message).join(" ") : void 0;
|
|
764
|
+
/**
|
|
765
|
+
* Return the Conversation id when that Conversation exists, else null. A
|
|
766
|
+
* dispatch can end before it creates its Conversation, and the run's
|
|
767
|
+
* `conversation_id` is a foreign key.
|
|
768
|
+
*/
|
|
769
|
+
function existingConversationId(conversationId) {
|
|
770
|
+
return sql`(select ${juniorConversations.conversationId} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
|
|
913
771
|
}
|
|
914
772
|
/**
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
918
|
-
* not parse or that the gate rejects.
|
|
773
|
+
* Record the outcome of one Automation run. A run that already has an outcome
|
|
774
|
+
* keeps it. A failed write is logged, and the heartbeat settles a started
|
|
775
|
+
* event run later.
|
|
919
776
|
*/
|
|
920
|
-
async function
|
|
921
|
-
const
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
777
|
+
async function recordAutomationExecution(automationId, options) {
|
|
778
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
779
|
+
const status = options.status ?? "completed";
|
|
780
|
+
const outcome = {
|
|
781
|
+
completedAtMs: nowMs,
|
|
782
|
+
errorMessage: options.errorMessage ?? null,
|
|
783
|
+
status
|
|
784
|
+
};
|
|
785
|
+
try {
|
|
786
|
+
await getDb().insert(juniorAutomationRuns).values({
|
|
787
|
+
id: options.executionId,
|
|
788
|
+
automationId,
|
|
789
|
+
conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
|
|
790
|
+
...outcome
|
|
791
|
+
}).onConflictDoUpdate({
|
|
792
|
+
target: juniorAutomationRuns.id,
|
|
793
|
+
set: {
|
|
794
|
+
...outcome,
|
|
795
|
+
conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`
|
|
796
|
+
},
|
|
797
|
+
setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
|
|
932
798
|
});
|
|
933
|
-
|
|
934
|
-
|
|
799
|
+
} catch (error) {
|
|
800
|
+
logWarn("task.execution.stat_failed", {
|
|
801
|
+
error,
|
|
802
|
+
"app.task.execution.id": options.executionId,
|
|
803
|
+
"app.task.execution.status": status,
|
|
804
|
+
"app.task.execution.task_id": automationId
|
|
805
|
+
});
|
|
806
|
+
}
|
|
935
807
|
}
|
|
936
|
-
/**
|
|
937
|
-
function
|
|
938
|
-
if (
|
|
939
|
-
|
|
808
|
+
/** Load usage analytics for the given automations. */
|
|
809
|
+
async function readAutomationExecutionSummaries(automationIds, options = {}) {
|
|
810
|
+
if (automationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
811
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
812
|
+
const oneDayAgoMs = nowMs - 864e5;
|
|
813
|
+
const sevenDaysAgoMs = nowMs - 6048e5;
|
|
814
|
+
const thirtyDaysAgoMs = nowMs - 2592e6;
|
|
815
|
+
const ninetyDaysAgoMs = nowMs - 7776e6;
|
|
816
|
+
const db = getDb();
|
|
817
|
+
const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
|
|
818
|
+
const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
|
|
819
|
+
status: juniorAutomationRuns.status,
|
|
820
|
+
conversationId: juniorAutomationRuns.conversationId,
|
|
821
|
+
automationId: juniorAutomationRuns.automationId
|
|
822
|
+
}).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
|
|
823
|
+
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
824
|
+
const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
|
|
825
|
+
const summaryRows = db.select({
|
|
826
|
+
costLast1Day: costSince(oneDayAgoMs),
|
|
827
|
+
costLast7Days: costSince(sevenDaysAgoMs),
|
|
828
|
+
costLast30Days: costSince(thirtyDaysAgoMs),
|
|
829
|
+
costLast90Days: costSince(ninetyDaysAgoMs),
|
|
830
|
+
lastRunStatus: latest.status,
|
|
831
|
+
lastConversationId: latest.conversationId,
|
|
832
|
+
lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
|
|
833
|
+
runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
|
|
834
|
+
runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
|
|
835
|
+
runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
|
|
836
|
+
runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
|
|
837
|
+
automationId: juniorAutomationRuns.automationId,
|
|
838
|
+
totalCostUsd: sql`coalesce(sum(${conversationCost}), 0)::double precision`,
|
|
839
|
+
totalRuns: sql`count(*)::int`
|
|
840
|
+
}).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
|
|
841
|
+
const [rows, recentRuns] = await Promise.all([summaryRows, readAutomationRecentRuns(automationIds)]);
|
|
842
|
+
return new Map(rows.map((row) => [row.automationId, {
|
|
843
|
+
costUsd: {
|
|
844
|
+
1: addUsd(0, row.costLast1Day),
|
|
845
|
+
7: addUsd(0, row.costLast7Days),
|
|
846
|
+
30: addUsd(0, row.costLast30Days),
|
|
847
|
+
90: addUsd(0, row.costLast90Days)
|
|
848
|
+
},
|
|
849
|
+
lastRunStatus: row.lastRunStatus,
|
|
850
|
+
...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
|
|
851
|
+
...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
|
|
852
|
+
recentRuns: recentRuns.get(row.automationId) ?? [],
|
|
853
|
+
runs: {
|
|
854
|
+
1: row.runsLast1Day,
|
|
855
|
+
7: row.runsLast7Days,
|
|
856
|
+
30: row.runsLast30Days,
|
|
857
|
+
90: row.runsLast90Days
|
|
858
|
+
},
|
|
859
|
+
totalCostUsd: addUsd(0, row.totalCostUsd),
|
|
860
|
+
totalRuns: row.totalRuns
|
|
861
|
+
}]));
|
|
940
862
|
}
|
|
941
863
|
/**
|
|
942
|
-
*
|
|
943
|
-
*
|
|
944
|
-
*
|
|
945
|
-
* filters on the keys in `data` fail adds no keys. So a broad trigger for
|
|
946
|
-
* one repository does not make every repository load its lazy data.
|
|
864
|
+
* Load the newest runs of each Automation, oldest first. A lateral limit
|
|
865
|
+
* reads at most `AUTOMATION_RECENT_RUN_LIMIT` rows per Automation from the
|
|
866
|
+
* (automation, completed) index, so long histories do not slow the list.
|
|
947
867
|
*/
|
|
948
|
-
async function
|
|
949
|
-
const
|
|
950
|
-
const
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
868
|
+
async function readAutomationRecentRuns(automationIds) {
|
|
869
|
+
const db = getDb();
|
|
870
|
+
const recent = db.select({
|
|
871
|
+
durationMs: juniorConversations.durationMs,
|
|
872
|
+
executedAtMs: juniorAutomationRuns.completedAtMs,
|
|
873
|
+
executionId: juniorAutomationRuns.id,
|
|
874
|
+
status: juniorAutomationRuns.status
|
|
875
|
+
}).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, juniorAutomations.id))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(20).as("recent_run");
|
|
876
|
+
const rows = await db.select({
|
|
877
|
+
automationId: juniorAutomations.id,
|
|
878
|
+
durationMs: recent.durationMs,
|
|
879
|
+
executedAtMs: recent.executedAtMs,
|
|
880
|
+
status: recent.status
|
|
881
|
+
}).from(juniorAutomations).innerJoinLateral(recent, sql`true`).where(inArray(juniorAutomations.id, automationIds)).orderBy(juniorAutomations.id, asc(recent.executedAtMs), asc(recent.executionId));
|
|
882
|
+
const byAutomation = /* @__PURE__ */ new Map();
|
|
883
|
+
for (const row of rows) {
|
|
884
|
+
const durationMs = positiveDuration(row.durationMs);
|
|
885
|
+
const runs = byAutomation.get(row.automationId) ?? [];
|
|
886
|
+
runs.push({
|
|
887
|
+
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
888
|
+
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
889
|
+
status: row.status
|
|
890
|
+
});
|
|
891
|
+
byAutomation.set(row.automationId, runs);
|
|
963
892
|
}
|
|
964
|
-
return
|
|
893
|
+
return byAutomation;
|
|
965
894
|
}
|
|
966
|
-
/**
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
* filters match. Returns one list per event, in order. The events must share
|
|
970
|
-
* one namespace. The gate skips a row whose trigger and identifier column
|
|
971
|
-
* disagree, and a row with no identifier whose trigger the enabled `catalog`
|
|
972
|
-
* rejects.
|
|
973
|
-
*/
|
|
974
|
-
async function findMatchingEventAutomations(db, events, teamId, catalog) {
|
|
975
|
-
const namespace = events[0]?.namespace;
|
|
976
|
-
if (namespace === void 0) return [];
|
|
977
|
-
if (events.some((event) => event.namespace !== namespace)) throw new Error("Events to match must share one namespace.");
|
|
978
|
-
const tasks = await readGatedEventAutomations(db, {
|
|
979
|
-
catalog,
|
|
980
|
-
eventTypes: [...new Set(events.map((event) => event.eventType))],
|
|
981
|
-
identifiers: [...new Set(events.map((event) => event.identifier))],
|
|
982
|
-
namespace,
|
|
983
|
-
teamId
|
|
984
|
-
});
|
|
985
|
-
return events.map((event) => tasks.filter((task) => (task.trigger.identifier === void 0 || task.trigger.identifier === event.identifier) && task.trigger.events.includes(event.eventType) && eventMatches(task.trigger.match, event.data)));
|
|
895
|
+
/** Keep a recorded runtime only when it is a real duration. */
|
|
896
|
+
function positiveDuration(value) {
|
|
897
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
986
898
|
}
|
|
987
|
-
/**
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
if (status === "active" && (await getEventAutomation(db, id))?.status !== "active") await clearEventAutomationRuns(id);
|
|
995
|
-
return db.transaction(async (tx) => {
|
|
996
|
-
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(id)).for("update");
|
|
997
|
-
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
998
|
-
requireAutomationRevision(current, revision);
|
|
999
|
-
if (!current || current.status === "deleted") throw new Error("Automation no longer exists.");
|
|
1000
|
-
const next = status === "paused" ? {
|
|
1001
|
-
status,
|
|
1002
|
-
statusReason: current.statusReason
|
|
1003
|
-
} : current.status === "paused" && current.statusReason ? {
|
|
1004
|
-
status: "blocked",
|
|
1005
|
-
statusReason: current.statusReason
|
|
1006
|
-
} : {
|
|
1007
|
-
status,
|
|
1008
|
-
statusReason: void 0
|
|
1009
|
-
};
|
|
1010
|
-
await tx.update(juniorAutomations).set({
|
|
1011
|
-
status: next.status,
|
|
1012
|
-
statusReason: next.statusReason ?? null
|
|
1013
|
-
}).where(eventAutomationWhere(id));
|
|
1014
|
-
const { statusReason: _statusReason, ...rest } = current;
|
|
1015
|
-
return {
|
|
1016
|
-
...rest,
|
|
1017
|
-
status: next.status,
|
|
1018
|
-
...next.statusReason ? { statusReason: next.statusReason } : void 0
|
|
1019
|
-
};
|
|
1020
|
-
});
|
|
899
|
+
/** Load the Automation run linked to one conversation, if any. */
|
|
900
|
+
async function readAutomationExecutionByConversationId(args) {
|
|
901
|
+
const [row] = await getDb().select({
|
|
902
|
+
kind: juniorAutomations.kind,
|
|
903
|
+
automationId: juniorAutomationRuns.automationId
|
|
904
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(eq(juniorAutomationRuns.conversationId, args.conversationId)).limit(1);
|
|
905
|
+
return row;
|
|
1021
906
|
}
|
|
1022
907
|
/**
|
|
1023
|
-
*
|
|
1024
|
-
*
|
|
1025
|
-
*
|
|
1026
|
-
*
|
|
1027
|
-
* the automation to blocked, so the creator notice goes once and never for
|
|
1028
|
-
* an automation that the dashboard shows as paused.
|
|
908
|
+
* Load the display name of the Automation linked to each untitled
|
|
909
|
+
* conversation. Like the Automation list, the name falls back to the first
|
|
910
|
+
* line of the instruction. Titled conversations and conversations without a
|
|
911
|
+
* linked Automation are absent from the result.
|
|
1029
912
|
*/
|
|
1030
|
-
async function
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
nextRunAtMs: row.nextRunAtMs,
|
|
1045
|
-
runNowAtMs: row.runNowAtMs,
|
|
1046
|
-
status: row.status,
|
|
1047
|
-
statusReason: row.statusReason,
|
|
1048
|
-
title: row.title
|
|
1049
|
-
};
|
|
1050
|
-
const parsed = scheduledAutomationSchema.safeParse({
|
|
1051
|
-
...row.record,
|
|
1052
|
-
...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
|
|
1053
|
-
});
|
|
1054
|
-
return parsed.success ? parsed.data : void 0;
|
|
1055
|
-
}
|
|
1056
|
-
/** Keep scan paths from returning current or legacy tombstones. */
|
|
1057
|
-
function isListedScheduledAutomation(task) {
|
|
1058
|
-
return task !== void 0 && task.status !== "deleted";
|
|
1059
|
-
}
|
|
1060
|
-
/** Build the stable run id for one task occurrence. */
|
|
1061
|
-
function scheduledRunId(taskId, scheduledForMs) {
|
|
1062
|
-
return `${taskId}:${scheduledForMs}`;
|
|
1063
|
-
}
|
|
1064
|
-
/** Acquire the deployed advisory lock for one scheduled automation. */
|
|
1065
|
-
function withScheduledAutomationLock(db, taskId, callback) {
|
|
1066
|
-
return db.transaction(async (tx) => {
|
|
1067
|
-
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
|
|
1068
|
-
return await callback(tx);
|
|
1069
|
-
});
|
|
1070
|
-
}
|
|
1071
|
-
function requireStoredTask(task) {
|
|
1072
|
-
const parsed = scheduledAutomationSchema.safeParse(task);
|
|
1073
|
-
if (!parsed.success) throw new Error("Scheduled automation routing context is invalid.");
|
|
1074
|
-
const { title, ...current } = parsed.data;
|
|
1075
|
-
const normalizedTitle = title?.trim() || void 0;
|
|
1076
|
-
return {
|
|
1077
|
-
...current,
|
|
1078
|
-
...normalizedTitle ? { title: normalizedTitle } : void 0
|
|
1079
|
-
};
|
|
1080
|
-
}
|
|
1081
|
-
async function upsertScheduledAutomation(db, task) {
|
|
1082
|
-
const { createdAtMs, creatorIdentityId, id, nextRunAtMs, runNowAtMs, status, statusReason, title, ...record } = task;
|
|
1083
|
-
const columns = {
|
|
1084
|
-
channelId: record.destination.channelId,
|
|
1085
|
-
createdAtMs,
|
|
1086
|
-
creatorIdentityId,
|
|
1087
|
-
creatorSlackUserId: record.createdBy.slackUserId,
|
|
1088
|
-
...automationTaskColumns(record.task),
|
|
1089
|
-
nextRunAtMs: nextRunAtMs ?? null,
|
|
1090
|
-
record,
|
|
1091
|
-
runNowAtMs: runNowAtMs ?? null,
|
|
1092
|
-
status,
|
|
1093
|
-
statusReason: statusReason ?? null,
|
|
1094
|
-
teamId: record.destination.teamId,
|
|
1095
|
-
title: title?.trim() || null
|
|
1096
|
-
};
|
|
1097
|
-
await db.insert(juniorAutomations).values({
|
|
1098
|
-
...columns,
|
|
1099
|
-
id,
|
|
1100
|
-
kind: "scheduled"
|
|
1101
|
-
}).onConflictDoUpdate({
|
|
1102
|
-
target: juniorAutomations.id,
|
|
1103
|
-
set: columns
|
|
1104
|
-
});
|
|
1105
|
-
}
|
|
1106
|
-
/** Read and decode one scheduled automation. */
|
|
1107
|
-
async function readScheduledAutomation(db, taskId) {
|
|
1108
|
-
const rows = await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.id, taskId), eq(juniorAutomations.kind, "scheduled"))).limit(1);
|
|
1109
|
-
return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
|
|
1110
|
-
}
|
|
1111
|
-
async function readListedScheduledAutomations(db, teamId) {
|
|
1112
|
-
return (await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.kind, "scheduled"), ne(juniorAutomations.status, "deleted"), teamId === void 0 ? void 0 : eq(juniorAutomations.teamId, teamId))).orderBy(asc(juniorAutomations.createdAtMs), asc(juniorAutomations.id))).map(parseScheduledAutomationRow).filter(isListedScheduledAutomation);
|
|
1113
|
-
}
|
|
1114
|
-
/** List decoded scheduled automations for one team in stable creation order. */
|
|
1115
|
-
async function listScheduledAutomationsForTeam(db, teamId) {
|
|
1116
|
-
return await readListedScheduledAutomations(db, teamId);
|
|
913
|
+
async function readAutomationTitlesByConversationId(conversations) {
|
|
914
|
+
const titles = /* @__PURE__ */ new Map();
|
|
915
|
+
const untitledIds = conversations.flatMap((conversation) => conversation.title ? [] : [conversation.conversationId]);
|
|
916
|
+
if (untitledIds.length === 0) return titles;
|
|
917
|
+
const rows = await getDb().select({
|
|
918
|
+
conversationId: juniorAutomationRuns.conversationId,
|
|
919
|
+
task: sql`${juniorAutomations.record}->'task'`,
|
|
920
|
+
title: juniorAutomations.title
|
|
921
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(inArray(juniorAutomationRuns.conversationId, untitledIds));
|
|
922
|
+
for (const row of rows) {
|
|
923
|
+
const title = row.title?.trim() || fallbackShortTitle(automationTaskDescription(automationTaskSchema.parse(row.task)), "");
|
|
924
|
+
if (row.conversationId && title) titles.set(row.conversationId, title);
|
|
925
|
+
}
|
|
926
|
+
return titles;
|
|
1117
927
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
await upsertScheduledAutomation(db, task);
|
|
1122
|
-
await recordAutomationVersion(db, task, current, editedBy);
|
|
928
|
+
/** Load newest-first executions for one automation, with conversation titles when present. */
|
|
929
|
+
async function readAutomationExecutions(args) {
|
|
930
|
+
return (await getDb().select(executionColumns).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).leftJoin(juniorAutomationVersions, executionVersion()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(args.limit)).map((row) => mapAutomationExecutionRecord(row));
|
|
1123
931
|
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
932
|
+
/** Load newest-first executions for the supplied viewer-visible automations. */
|
|
933
|
+
async function readAutomationRuns(args) {
|
|
934
|
+
if (args.automationIds.length === 0) return [];
|
|
935
|
+
return (await getDb().select({
|
|
936
|
+
...executionColumns,
|
|
937
|
+
kind: juniorAutomations.kind,
|
|
938
|
+
automationId: juniorAutomationRuns.automationId
|
|
939
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).leftJoin(juniorAutomationVersions, executionVersion()).where(and(isExecution(), inArray(juniorAutomationRuns.automationId, args.automationIds))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(args.limit)).map((row) => ({
|
|
940
|
+
...mapAutomationExecutionRecord(row),
|
|
941
|
+
kind: row.kind,
|
|
942
|
+
automationId: row.automationId
|
|
943
|
+
}));
|
|
1130
944
|
}
|
|
1131
|
-
/**
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
945
|
+
/** Columns that describe one execution, its Conversation, and its version. */
|
|
946
|
+
const executionColumns = {
|
|
947
|
+
automationVersion: juniorAutomationRuns.automationVersion,
|
|
948
|
+
conversationId: juniorAutomationRuns.conversationId,
|
|
949
|
+
credentialMode: sql`${juniorAutomationVersions.definition}->>'credentialMode'`,
|
|
950
|
+
durationMs: juniorConversations.durationMs,
|
|
951
|
+
errorMessage: juniorAutomationRuns.errorMessage,
|
|
952
|
+
executedAtMs: juniorAutomationRuns.completedAtMs,
|
|
953
|
+
executionId: juniorAutomationRuns.id,
|
|
954
|
+
scheduledForMs: juniorAutomationRuns.scheduledForMs,
|
|
955
|
+
startedAtMs: juniorAutomationRuns.startedAtMs,
|
|
956
|
+
status: juniorAutomationRuns.status,
|
|
957
|
+
title: juniorConversations.title,
|
|
958
|
+
usage: juniorConversations.usage
|
|
959
|
+
};
|
|
960
|
+
function executionConversation() {
|
|
961
|
+
return eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId);
|
|
1140
962
|
}
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
1144
|
-
*/
|
|
1145
|
-
async function saveScheduledAutomation(db, task, expectedRevision, editedBy) {
|
|
1146
|
-
const next = requireStoredTask(task);
|
|
1147
|
-
await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
1148
|
-
const current = await readScheduledAutomation(tx, task.id);
|
|
1149
|
-
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
1150
|
-
await writeScheduledAutomation(tx, next, current, editedBy);
|
|
1151
|
-
});
|
|
1152
|
-
return next;
|
|
963
|
+
function executionVersion() {
|
|
964
|
+
return and(eq(juniorAutomationVersions.automationId, juniorAutomationRuns.automationId), eq(juniorAutomationVersions.version, juniorAutomationRuns.automationVersion));
|
|
1153
965
|
}
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
await writeScheduledAutomation(db, requireStoredTask(task), current);
|
|
966
|
+
function isoTime(ms) {
|
|
967
|
+
return ms === null ? void 0 : new Date(ms).toISOString();
|
|
1157
968
|
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
|
|
969
|
+
function mapAutomationExecutionRecord(row) {
|
|
970
|
+
const title = row.title?.trim();
|
|
971
|
+
const costUsd = agentTurnCostUsd(row.usage ?? void 0);
|
|
972
|
+
const totalTokens = agentTurnTotalTokens(row.usage ?? void 0);
|
|
973
|
+
const durationMs = positiveDuration(row.durationMs);
|
|
974
|
+
const error = row.errorMessage?.trim();
|
|
975
|
+
const scheduledFor = isoTime(row.scheduledForMs);
|
|
976
|
+
const startedAt = isoTime(row.startedAtMs);
|
|
977
|
+
return {
|
|
978
|
+
...row.automationVersion !== null ? { automationVersion: row.automationVersion } : void 0,
|
|
979
|
+
...row.conversationId ? { conversationId: row.conversationId } : void 0,
|
|
980
|
+
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
981
|
+
...row.credentialMode === "creator" || row.credentialMode === "system" ? { credentialMode: row.credentialMode } : void 0,
|
|
982
|
+
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
983
|
+
...error ? { error } : void 0,
|
|
984
|
+
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
985
|
+
executionId: row.executionId,
|
|
986
|
+
...scheduledFor ? { scheduledFor } : void 0,
|
|
987
|
+
...startedAt ? { startedAt } : void 0,
|
|
988
|
+
status: row.status,
|
|
989
|
+
...title ? { title } : void 0,
|
|
990
|
+
...totalTokens !== void 0 ? { totalTokens } : void 0
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
/** Load a fixed trailing window of terminal executions for one automation by status. */
|
|
994
|
+
async function readAutomationExecutionStatusDays(args) {
|
|
995
|
+
const dayCount = args.dayCount ?? 90;
|
|
996
|
+
const end = utcDate(args.nowMs ?? Date.now());
|
|
997
|
+
const endMs = Date.parse(`${end}T23:59:59.999Z`);
|
|
998
|
+
const startMs = Date.parse(`${end}T00:00:00.000Z`) - (dayCount - 1) * 864e5;
|
|
999
|
+
const executionDate = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD')`;
|
|
1000
|
+
const rows = await readExecutionStatusBuckets({
|
|
1001
|
+
automationId: args.automationId,
|
|
1002
|
+
bucket: executionDate,
|
|
1003
|
+
endMs,
|
|
1004
|
+
startMs
|
|
1172
1005
|
});
|
|
1006
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
1007
|
+
for (let offset = 0; offset < dayCount; offset += 1) {
|
|
1008
|
+
const date = utcDate(startMs + offset * 864e5);
|
|
1009
|
+
byDate.set(date, emptyStatusDay(date));
|
|
1010
|
+
}
|
|
1011
|
+
for (const row of rows) {
|
|
1012
|
+
const day = byDate.get(row.date);
|
|
1013
|
+
if (!day) continue;
|
|
1014
|
+
if (row.status === "completed") day.completed = row.count;
|
|
1015
|
+
else if (row.status === "failed") day.failed = row.count;
|
|
1016
|
+
else if (row.status === "blocked") day.blocked = row.count;
|
|
1017
|
+
if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
|
|
1018
|
+
}
|
|
1019
|
+
return [...byDate.values()];
|
|
1173
1020
|
}
|
|
1174
|
-
/**
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
nextRunAtMs: void 0,
|
|
1189
|
-
runNowAtMs: void 0,
|
|
1190
|
-
status: "blocked"
|
|
1191
|
-
} : void 0,
|
|
1192
|
-
statusReason: reason,
|
|
1193
|
-
updatedAtMs: nowMs
|
|
1194
|
-
}), current);
|
|
1195
|
-
return blocked;
|
|
1021
|
+
/** Load a fixed trailing window of terminal executions for one automation by hour. */
|
|
1022
|
+
async function readAutomationExecutionStatusHours(args) {
|
|
1023
|
+
const hourCount = args.hourCount ?? 168;
|
|
1024
|
+
const nowMs = args.nowMs ?? Date.now();
|
|
1025
|
+
const end = new Date(nowMs);
|
|
1026
|
+
end.setUTCMinutes(0, 0, 0);
|
|
1027
|
+
const endMs = end.getTime() + 3599999;
|
|
1028
|
+
const startMs = end.getTime() - (hourCount - 1) * 36e5;
|
|
1029
|
+
const executionHour = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
|
|
1030
|
+
const rows = await readExecutionStatusBuckets({
|
|
1031
|
+
automationId: args.automationId,
|
|
1032
|
+
bucket: executionHour,
|
|
1033
|
+
endMs,
|
|
1034
|
+
startMs
|
|
1196
1035
|
});
|
|
1036
|
+
const byHour = /* @__PURE__ */ new Map();
|
|
1037
|
+
for (let offset = 0; offset < hourCount; offset += 1) {
|
|
1038
|
+
const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
|
|
1039
|
+
byHour.set(date, emptyStatusDay(date));
|
|
1040
|
+
}
|
|
1041
|
+
for (const row of rows) {
|
|
1042
|
+
const hour = byHour.get(row.date);
|
|
1043
|
+
if (!hour) continue;
|
|
1044
|
+
if (row.status === "completed") hour.completed = row.count;
|
|
1045
|
+
else if (row.status === "failed") hour.failed = row.count;
|
|
1046
|
+
else if (row.status === "blocked") hour.blocked = row.count;
|
|
1047
|
+
if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
|
|
1048
|
+
}
|
|
1049
|
+
return [...byHour.values()];
|
|
1050
|
+
}
|
|
1051
|
+
/** Count one automation's executions and their cost per time bucket and status. */
|
|
1052
|
+
async function readExecutionStatusBuckets(args) {
|
|
1053
|
+
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
1054
|
+
return await getDb().select({
|
|
1055
|
+
count: count(),
|
|
1056
|
+
costUsd: sql`SUM(${conversationCost})::double precision`,
|
|
1057
|
+
date: args.bucket,
|
|
1058
|
+
status: juniorAutomationRuns.status
|
|
1059
|
+
}).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId), gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs))).groupBy(args.bucket, juniorAutomationRuns.status).orderBy(asc(args.bucket), asc(juniorAutomationRuns.status));
|
|
1197
1060
|
}
|
|
1198
1061
|
// src/chat/automations/blocked-notice.ts
|
|
1199
1062
|
function buildBlockedNoticeText(automationId, title, reason) {
|
|
@@ -1555,521 +1418,4 @@ async function getPluginDispatchProjection(args) {
|
|
|
1555
1418
|
if (!record || record.plugin !== args.plugin) return;
|
|
1556
1419
|
return toDispatchProjection(record);
|
|
1557
1420
|
}
|
|
1558
|
-
|
|
1559
|
-
function defaultConversationState() {
|
|
1560
|
-
return {
|
|
1561
|
-
schemaVersion: 1,
|
|
1562
|
-
messages: [],
|
|
1563
|
-
processing: {},
|
|
1564
|
-
vision: { byFileId: {} }
|
|
1565
|
-
};
|
|
1566
|
-
}
|
|
1567
|
-
function coercePendingAuthState(value) {
|
|
1568
|
-
if (!isRecord$1(value)) return;
|
|
1569
|
-
const kind = value.kind;
|
|
1570
|
-
const provider = toOptionalString(value.provider);
|
|
1571
|
-
const actorId = toOptionalString(value.actorId);
|
|
1572
|
-
const authSessionId = toOptionalString(value.authSessionId);
|
|
1573
|
-
const scope = toOptionalString(value.scope);
|
|
1574
|
-
const sessionId = toOptionalString(value.sessionId);
|
|
1575
|
-
const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
|
|
1576
|
-
if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
|
|
1577
|
-
const base = {
|
|
1578
|
-
provider,
|
|
1579
|
-
actorId,
|
|
1580
|
-
...scope ? { scope } : void 0,
|
|
1581
|
-
sessionId,
|
|
1582
|
-
linkSentAtMs
|
|
1583
|
-
};
|
|
1584
|
-
return kind === "mcp" ? {
|
|
1585
|
-
...base,
|
|
1586
|
-
authSessionId,
|
|
1587
|
-
kind
|
|
1588
|
-
} : {
|
|
1589
|
-
...base,
|
|
1590
|
-
kind
|
|
1591
|
-
};
|
|
1592
|
-
}
|
|
1593
|
-
/** Safely coerce an unknown persisted value into a ThreadConversationState. */
|
|
1594
|
-
function coerceThreadConversationState(value) {
|
|
1595
|
-
if (!isRecord$1(value)) return defaultConversationState();
|
|
1596
|
-
const root = value;
|
|
1597
|
-
const rawConversation = isRecord$1(root.conversation) ? root.conversation : {};
|
|
1598
|
-
const messages = [];
|
|
1599
|
-
const rawProcessing = isRecord$1(rawConversation.processing) ? rawConversation.processing : {};
|
|
1600
|
-
const processing = {
|
|
1601
|
-
activeTurnId: toOptionalString(rawProcessing.activeTurnId),
|
|
1602
|
-
lastCompletedAtMs: toOptionalNumber(rawProcessing.lastCompletedAtMs),
|
|
1603
|
-
pendingAuth: coercePendingAuthState(rawProcessing.pendingAuth)
|
|
1604
|
-
};
|
|
1605
|
-
const rawVision = isRecord$1(rawConversation.vision) ? rawConversation.vision : {};
|
|
1606
|
-
const rawVisionByFileId = isRecord$1(rawVision.byFileId) ? rawVision.byFileId : {};
|
|
1607
|
-
const byFileId = {};
|
|
1608
|
-
for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
|
|
1609
|
-
if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
|
|
1610
|
-
if (!isRecord$1(value)) continue;
|
|
1611
|
-
const summary = toOptionalString(value.summary);
|
|
1612
|
-
const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
|
|
1613
|
-
if (!summary || !analyzedAtMs) continue;
|
|
1614
|
-
byFileId[fileId] = {
|
|
1615
|
-
summary,
|
|
1616
|
-
analyzedAtMs
|
|
1617
|
-
};
|
|
1618
|
-
}
|
|
1619
|
-
return {
|
|
1620
|
-
schemaVersion: 1,
|
|
1621
|
-
messages,
|
|
1622
|
-
processing,
|
|
1623
|
-
vision: {
|
|
1624
|
-
backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
|
|
1625
|
-
byFileId
|
|
1626
|
-
}
|
|
1627
|
-
};
|
|
1628
|
-
}
|
|
1629
|
-
/**
|
|
1630
|
-
* Wrap active conversation control into the thread scratch envelope.
|
|
1631
|
-
*
|
|
1632
|
-
* Visible history lives in SQL. Image summaries use a separate disposable
|
|
1633
|
-
* cache, so thread scratch does not retain them.
|
|
1634
|
-
*/
|
|
1635
|
-
function buildConversationStatePatch(conversation) {
|
|
1636
|
-
return { conversation: {
|
|
1637
|
-
schemaVersion: 1,
|
|
1638
|
-
processing: { ...conversation.processing }
|
|
1639
|
-
} };
|
|
1640
|
-
}
|
|
1641
|
-
// src/chat/runtime/thread-state.ts
|
|
1642
|
-
function threadStateKey(threadId) {
|
|
1643
|
-
return `thread-state:${threadId}`;
|
|
1644
|
-
}
|
|
1645
|
-
function channelStateKey(channelId) {
|
|
1646
|
-
return `channel-state:${channelId}`;
|
|
1647
|
-
}
|
|
1648
|
-
function buildThreadStatePayload(patch) {
|
|
1649
|
-
const payload = {};
|
|
1650
|
-
if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
|
|
1651
|
-
if (patch.sandboxRef !== void 0) {
|
|
1652
|
-
payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
|
|
1653
|
-
payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
|
|
1654
|
-
payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
|
|
1655
|
-
}
|
|
1656
|
-
return payload;
|
|
1657
|
-
}
|
|
1658
|
-
/**
|
|
1659
|
-
* Merge a payload into thread scratch with Junior's TTL.
|
|
1660
|
-
*
|
|
1661
|
-
* Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
|
|
1662
|
-
* shorter retention policy for the same scratch keys.
|
|
1663
|
-
*/
|
|
1664
|
-
async function mergePersistedState(key, payload) {
|
|
1665
|
-
if (Object.keys(payload).length === 0) return;
|
|
1666
|
-
const stateAdapter = getStateAdapter();
|
|
1667
|
-
await stateAdapter.connect();
|
|
1668
|
-
const existing = await stateAdapter.get(key) ?? {};
|
|
1669
|
-
await stateAdapter.set(key, {
|
|
1670
|
-
...existing,
|
|
1671
|
-
...payload
|
|
1672
|
-
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
1673
|
-
}
|
|
1674
|
-
/** Extract persisted sandbox metadata from thread state payload. */
|
|
1675
|
-
function getPersistedSandboxState(state) {
|
|
1676
|
-
const id = toOptionalString(state.app_sandbox_id);
|
|
1677
|
-
if (!id) return;
|
|
1678
|
-
const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
|
|
1679
|
-
const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
|
|
1680
|
-
return {
|
|
1681
|
-
id,
|
|
1682
|
-
...profileHash ? { profileHash } : void 0,
|
|
1683
|
-
...workspaceId ? { workspaceId } : void 0
|
|
1684
|
-
};
|
|
1685
|
-
}
|
|
1686
|
-
/** Persist only the Redis-backed runtime scratch in a thread-state patch. */
|
|
1687
|
-
async function persistThreadRuntimeState(conversationId, patch) {
|
|
1688
|
-
await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
|
|
1689
|
-
}
|
|
1690
|
-
/** Load the persisted state payload for a thread without requiring a Chat singleton. */
|
|
1691
|
-
async function getPersistedThreadState(threadId) {
|
|
1692
|
-
const stateAdapter = getStateAdapter();
|
|
1693
|
-
await stateAdapter.connect();
|
|
1694
|
-
return await stateAdapter.get(threadStateKey(threadId)) ?? {};
|
|
1695
|
-
}
|
|
1696
|
-
/** Persist a thread-state patch by thread id without constructing a Chat thread. */
|
|
1697
|
-
async function persistThreadStateById(threadId, patch) {
|
|
1698
|
-
if (patch.conversation) await persistConversationMessages({
|
|
1699
|
-
conversation: patch.conversation,
|
|
1700
|
-
conversationId: threadId
|
|
1701
|
-
});
|
|
1702
|
-
await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
|
|
1703
|
-
}
|
|
1704
|
-
/** Load legacy Redis-backed channel state during the SQL cutover. */
|
|
1705
|
-
async function getLegacyChannelState(channelId) {
|
|
1706
|
-
const stateAdapter = getStateAdapter();
|
|
1707
|
-
await stateAdapter.connect();
|
|
1708
|
-
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
1709
|
-
}
|
|
1710
|
-
/**
|
|
1711
|
-
* Resolve durable location configuration.
|
|
1712
|
-
*
|
|
1713
|
-
* Slack still reads the old channel-id Redis bag once during cutover.
|
|
1714
|
-
*/
|
|
1715
|
-
function getLocationConfigurationService(destination) {
|
|
1716
|
-
if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
|
|
1717
|
-
return createDurableLocationConfigurationService({
|
|
1718
|
-
destination,
|
|
1719
|
-
db: getDb(),
|
|
1720
|
-
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
1721
|
-
});
|
|
1722
|
-
}
|
|
1723
|
-
// src/chat/services/turn-session-routing.ts
|
|
1724
|
-
async function loadConversationChain(conversationId, conversationStore) {
|
|
1725
|
-
const chain = [];
|
|
1726
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1727
|
-
let cursor = conversationId;
|
|
1728
|
-
while (cursor && !seen.has(cursor)) {
|
|
1729
|
-
seen.add(cursor);
|
|
1730
|
-
const conversation = await conversationStore.get({ conversationId: cursor });
|
|
1731
|
-
if (!conversation) break;
|
|
1732
|
-
chain.push(conversation);
|
|
1733
|
-
cursor = conversation.parentConversationId;
|
|
1734
|
-
}
|
|
1735
|
-
return chain;
|
|
1736
|
-
}
|
|
1737
|
-
/**
|
|
1738
|
-
* Normalize a stored Slack session source against the conversation destination.
|
|
1739
|
-
*
|
|
1740
|
-
* Does not create channel or thread values from the conversation id.
|
|
1741
|
-
*/
|
|
1742
|
-
function slackSourceForDestination(args) {
|
|
1743
|
-
if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
|
|
1744
|
-
const threadTs = args.source.threadTs?.trim();
|
|
1745
|
-
return {
|
|
1746
|
-
kind: "slack",
|
|
1747
|
-
visibility: args.source.visibility ?? "public",
|
|
1748
|
-
teamId: args.source.teamId?.trim() || args.destination.teamId,
|
|
1749
|
-
channelId: args.source.channelId,
|
|
1750
|
-
...threadTs ? { threadTs } : void 0
|
|
1751
|
-
};
|
|
1752
|
-
}
|
|
1753
|
-
/**
|
|
1754
|
-
* Resolve the Conversation Location, Destination, and session Source.
|
|
1755
|
-
*
|
|
1756
|
-
* Reads parent Conversations when this Conversation has no Destination.
|
|
1757
|
-
*/
|
|
1758
|
-
async function resolveConversationRouting(args) {
|
|
1759
|
-
const conversationStore = args.conversationStore ?? (await import("./db-C1M1y-bh.js").then((n) => n.n)).getConversationStore();
|
|
1760
|
-
const chain = await loadConversationChain(args.conversationId, conversationStore);
|
|
1761
|
-
let destination;
|
|
1762
|
-
let source;
|
|
1763
|
-
let location;
|
|
1764
|
-
for (const conversation of chain) {
|
|
1765
|
-
destination ??= conversation.destination;
|
|
1766
|
-
source ??= conversation.sessionSource;
|
|
1767
|
-
location ??= conversation.location;
|
|
1768
|
-
if (destination && source) break;
|
|
1769
|
-
}
|
|
1770
|
-
if (!destination) return;
|
|
1771
|
-
if (destination.platform === "slack") {
|
|
1772
|
-
const slackSource = slackSourceForDestination({
|
|
1773
|
-
destination,
|
|
1774
|
-
source
|
|
1775
|
-
});
|
|
1776
|
-
return {
|
|
1777
|
-
destination,
|
|
1778
|
-
...location ? { location } : void 0,
|
|
1779
|
-
...slackSource ? { source: slackSource } : void 0
|
|
1780
|
-
};
|
|
1781
|
-
}
|
|
1782
|
-
return {
|
|
1783
|
-
destination,
|
|
1784
|
-
...location ? { location } : void 0,
|
|
1785
|
-
...source ? { source } : void 0
|
|
1786
|
-
};
|
|
1787
|
-
}
|
|
1788
|
-
/** Require the Conversation Destination and Source from SQL. */
|
|
1789
|
-
async function resolveTurnSessionRouting(args) {
|
|
1790
|
-
const routing = await resolveConversationRouting(args);
|
|
1791
|
-
if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
|
|
1792
|
-
return {
|
|
1793
|
-
destination: routing.destination,
|
|
1794
|
-
...routing.location ? { location: routing.location } : void 0,
|
|
1795
|
-
source: routing.source
|
|
1796
|
-
};
|
|
1797
|
-
}
|
|
1798
|
-
// src/chat/plugins/task-runner.ts
|
|
1799
|
-
/**
|
|
1800
|
-
* Plugin background-task orchestration.
|
|
1801
|
-
*
|
|
1802
|
-
* Core schedules tasks from completed sessions and exposes plugins only a
|
|
1803
|
-
* bounded run projection rather than live runtime internals or queue
|
|
1804
|
-
* payloads.
|
|
1805
|
-
*/
|
|
1806
|
-
var task_runner_exports = /* @__PURE__ */ __exportAll({
|
|
1807
|
-
processPluginTask: () => processPluginTask,
|
|
1808
|
-
scheduleSessionCompletedPluginTasks: () => scheduleSessionCompletedPluginTasks
|
|
1809
|
-
});
|
|
1810
|
-
const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
|
|
1811
|
-
function isRecord(value) {
|
|
1812
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
1813
|
-
}
|
|
1814
|
-
function textPart(value) {
|
|
1815
|
-
if (isRecord(value) && value.type === "text" && typeof value.text === "string") return value.text;
|
|
1816
|
-
}
|
|
1817
|
-
function messageText(message) {
|
|
1818
|
-
const content = message.content;
|
|
1819
|
-
if (typeof content === "string") return sanitizeText(content);
|
|
1820
|
-
if (!Array.isArray(content)) return "";
|
|
1821
|
-
return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
|
|
1822
|
-
}
|
|
1823
|
-
function toolResultText(message) {
|
|
1824
|
-
const record = message;
|
|
1825
|
-
return sanitizeText([
|
|
1826
|
-
messageText(message),
|
|
1827
|
-
record.output,
|
|
1828
|
-
record.result,
|
|
1829
|
-
record.stdout,
|
|
1830
|
-
record.stderr,
|
|
1831
|
-
record.toolResult
|
|
1832
|
-
].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
|
|
1833
|
-
}
|
|
1834
|
-
function sanitizeText(text) {
|
|
1835
|
-
return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
|
|
1836
|
-
}
|
|
1837
|
-
/** Build the transcript provenance for a user message from its Pi provenance. */
|
|
1838
|
-
function messageProvenance(provenance) {
|
|
1839
|
-
return {
|
|
1840
|
-
authority: provenance.authority,
|
|
1841
|
-
...provenance.actor ? { actor: provenance.actor } : void 0
|
|
1842
|
-
};
|
|
1843
|
-
}
|
|
1844
|
-
function runTranscriptEntry(message, provenance, runActor) {
|
|
1845
|
-
const role = getPiMessageRole(message);
|
|
1846
|
-
if (role === "user" || role === "assistant") {
|
|
1847
|
-
const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
|
|
1848
|
-
if (!text) return;
|
|
1849
|
-
if (role === "assistant") return {
|
|
1850
|
-
type: "message",
|
|
1851
|
-
role,
|
|
1852
|
-
text
|
|
1853
|
-
};
|
|
1854
|
-
return {
|
|
1855
|
-
type: "message",
|
|
1856
|
-
role,
|
|
1857
|
-
text,
|
|
1858
|
-
provenance: messageProvenance(provenance),
|
|
1859
|
-
isRunActor: sameActorIdentity(provenance.actor, runActor)
|
|
1860
|
-
};
|
|
1861
|
-
}
|
|
1862
|
-
if (!isToolResultMessage(message)) return;
|
|
1863
|
-
const toolName = normalizeToolNameFromResult(message);
|
|
1864
|
-
if (!toolName) return;
|
|
1865
|
-
const text = toolResultText(message);
|
|
1866
|
-
return {
|
|
1867
|
-
type: "toolResult",
|
|
1868
|
-
toolName,
|
|
1869
|
-
isError: isToolResultError(message),
|
|
1870
|
-
...text ? { text } : void 0
|
|
1871
|
-
};
|
|
1872
|
-
}
|
|
1873
|
-
/**
|
|
1874
|
-
* Slice the current turn's Pi messages with their aligned provenance and strip
|
|
1875
|
-
* runtime turn context, keeping each surviving message paired with the exact
|
|
1876
|
-
* provenance recorded for it. Stripping can drop or rewrite messages, so the
|
|
1877
|
-
* pairing is applied per message rather than by post-strip index.
|
|
1878
|
-
*/
|
|
1879
|
-
function turnMessagesWithProvenance(record) {
|
|
1880
|
-
const startIndex = record.turnStartMessageIndex ?? 0;
|
|
1881
|
-
const messages = record.piMessages.slice(startIndex);
|
|
1882
|
-
const provenance = record.piMessageProvenance.slice(startIndex);
|
|
1883
|
-
const paired = [];
|
|
1884
|
-
for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
|
|
1885
|
-
message: stripped,
|
|
1886
|
-
provenance: provenance[index] ?? { authority: "context" }
|
|
1887
|
-
});
|
|
1888
|
-
return paired;
|
|
1889
|
-
}
|
|
1890
|
-
/** Recover the Slack context author identity from a persisted thread message. */
|
|
1891
|
-
function slackContextAuthor(location, message) {
|
|
1892
|
-
const userId = message.author?.userId?.trim();
|
|
1893
|
-
if (!userId) return;
|
|
1894
|
-
return {
|
|
1895
|
-
platform: "slack",
|
|
1896
|
-
teamId: location.teamId,
|
|
1897
|
-
userId,
|
|
1898
|
-
...message.author?.userName ? { userName: message.author.userName } : void 0,
|
|
1899
|
-
...message.author?.fullName ? { fullName: message.author.fullName } : void 0
|
|
1900
|
-
};
|
|
1901
|
-
}
|
|
1902
|
-
function slackTimestampMs(value) {
|
|
1903
|
-
const timestamp = parseSlackMessageTs(value);
|
|
1904
|
-
if (!timestamp) return;
|
|
1905
|
-
const timestampMs = Number(timestamp) * 1e3;
|
|
1906
|
-
return Number.isFinite(timestampMs) ? timestampMs : void 0;
|
|
1907
|
-
}
|
|
1908
|
-
function conversationMessageTimestampMs(message) {
|
|
1909
|
-
if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
|
|
1910
|
-
return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
|
|
1911
|
-
}
|
|
1912
|
-
function messageExistedAtRunCompletion(message, completedAtMs) {
|
|
1913
|
-
const messageTimestampMs = conversationMessageTimestampMs(message);
|
|
1914
|
-
return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
|
|
1915
|
-
}
|
|
1916
|
-
/**
|
|
1917
|
-
* Project bounded public-thread context into the run transcript.
|
|
1918
|
-
*
|
|
1919
|
-
* Prior public Slack messages from the current Conversation are durable
|
|
1920
|
-
* evidence a completed run may have acted on, so passive consumers can cite
|
|
1921
|
-
* them. They are always context authority (never instruction), and private or
|
|
1922
|
-
* local Conversations add nothing here.
|
|
1923
|
-
*/
|
|
1924
|
-
async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
|
|
1925
|
-
if (location?.provider !== "slack" || visibility !== "public") return [];
|
|
1926
|
-
const conversation = coerceThreadConversationState(await getPersistedThreadState(record.conversationId));
|
|
1927
|
-
await hydrateConversationMessages({
|
|
1928
|
-
conversation,
|
|
1929
|
-
conversationId: record.conversationId
|
|
1930
|
-
});
|
|
1931
|
-
const entries = [];
|
|
1932
|
-
for (const message of conversation.messages) {
|
|
1933
|
-
if (message.role !== "user") continue;
|
|
1934
|
-
if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
|
|
1935
|
-
const text = sanitizeText(message.text);
|
|
1936
|
-
if (!text) continue;
|
|
1937
|
-
const author = slackContextAuthor(location, message);
|
|
1938
|
-
entries.push({
|
|
1939
|
-
type: "message",
|
|
1940
|
-
role: "user",
|
|
1941
|
-
text,
|
|
1942
|
-
provenance: {
|
|
1943
|
-
authority: "context",
|
|
1944
|
-
...author ? { actor: author } : void 0
|
|
1945
|
-
},
|
|
1946
|
-
isRunActor: sameActorIdentity(author, runActor)
|
|
1947
|
-
});
|
|
1948
|
-
}
|
|
1949
|
-
return entries;
|
|
1950
|
-
}
|
|
1951
|
-
async function withPluginTaskLock(taskId, callback) {
|
|
1952
|
-
const state = getStateAdapter();
|
|
1953
|
-
await state.connect();
|
|
1954
|
-
const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
|
|
1955
|
-
if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
|
|
1956
|
-
try {
|
|
1957
|
-
return await callback();
|
|
1958
|
-
} finally {
|
|
1959
|
-
await state.releaseLock(lock);
|
|
1960
|
-
}
|
|
1961
|
-
}
|
|
1962
|
-
/** Load the bounded completed-run projection exposed to plugin tasks. */
|
|
1963
|
-
async function loadPluginRun(params) {
|
|
1964
|
-
const record = await getTurnRecord(params.conversationId, params.sessionId);
|
|
1965
|
-
if (!record) throw new Error("Completed plugin task session record is unavailable");
|
|
1966
|
-
if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
|
|
1967
|
-
const conversationStore = getConversationStore();
|
|
1968
|
-
const routing = await resolveConversationRouting({
|
|
1969
|
-
conversationId: params.conversationId,
|
|
1970
|
-
conversationStore
|
|
1971
|
-
});
|
|
1972
|
-
if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
|
|
1973
|
-
const source = record.source ?? routing.source;
|
|
1974
|
-
if (!source) throw new Error("Completed plugin task session record is missing Source");
|
|
1975
|
-
const conversation = await conversationStore.get({ conversationId: params.conversationId });
|
|
1976
|
-
const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
|
|
1977
|
-
const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
|
|
1978
|
-
const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
|
|
1979
|
-
const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
|
|
1980
|
-
const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
|
|
1981
|
-
return pluginRunContextSchema.parse({
|
|
1982
|
-
...actorUser ? { actorUserId: actorUser.id } : void 0,
|
|
1983
|
-
completedAtMs: record.updatedAtMs,
|
|
1984
|
-
conversationId: record.conversationId,
|
|
1985
|
-
destination: routing.destination,
|
|
1986
|
-
...routing.location ? { locationId: routing.location.id } : void 0,
|
|
1987
|
-
actors: record.actors,
|
|
1988
|
-
...runActor ? { actor: runActor } : void 0,
|
|
1989
|
-
runId: record.turnId,
|
|
1990
|
-
source,
|
|
1991
|
-
transcript: [...contextEntries, ...runEntries]
|
|
1992
|
-
});
|
|
1993
|
-
}
|
|
1994
|
-
/** Build the plugin-facing context for one claimed task attempt. */
|
|
1995
|
-
function taskPluginContext(plugin, message, options = {}) {
|
|
1996
|
-
const pluginName = plugin.manifest.name;
|
|
1997
|
-
const sessionParams = pluginTaskParamsSchema.parse(message.params);
|
|
1998
|
-
const onCost = createPluginModelCostRecorder({
|
|
1999
|
-
conversationId: sessionParams.conversationId,
|
|
2000
|
-
pluginName,
|
|
2001
|
-
source: "task",
|
|
2002
|
-
turnId: sessionParams.sessionId
|
|
2003
|
-
});
|
|
2004
|
-
return {
|
|
2005
|
-
db: getDb(),
|
|
2006
|
-
embedder: createPluginEmbedder(pluginName, {
|
|
2007
|
-
onCost,
|
|
2008
|
-
signal: options.signal
|
|
2009
|
-
}),
|
|
2010
|
-
events: createPluginConversationEvents({
|
|
2011
|
-
conversationId: sessionParams.conversationId,
|
|
2012
|
-
operationId: pluginTaskId(message),
|
|
2013
|
-
plugin,
|
|
2014
|
-
turnId: sessionParams.sessionId
|
|
2015
|
-
}),
|
|
2016
|
-
id: pluginTaskId(message),
|
|
2017
|
-
log: createPluginLogger(pluginName),
|
|
2018
|
-
model: createPluginModel(pluginName, plugin.model, {
|
|
2019
|
-
onCost,
|
|
2020
|
-
signal: options.signal
|
|
2021
|
-
}),
|
|
2022
|
-
name: message.name,
|
|
2023
|
-
plugin: { name: pluginName },
|
|
2024
|
-
cache: createPluginCache(pluginName),
|
|
2025
|
-
run: { async load() {
|
|
2026
|
-
return await loadPluginRun(sessionParams);
|
|
2027
|
-
} },
|
|
2028
|
-
state: createPluginState(pluginName)
|
|
2029
|
-
};
|
|
2030
|
-
}
|
|
2031
|
-
function findPluginTask(message) {
|
|
2032
|
-
const plugin = [...coreTaskRegistrations(), ...getPlugins()].find((candidate) => candidate.manifest.name === message.plugin);
|
|
2033
|
-
if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
|
|
2034
|
-
return {
|
|
2035
|
-
plugin,
|
|
2036
|
-
task: plugin.tasks[message.name]
|
|
2037
|
-
};
|
|
2038
|
-
}
|
|
2039
|
-
/** Schedule all plugin tasks interested in a completed agent-run session. */
|
|
2040
|
-
async function scheduleSessionCompletedPluginTasks(params, options = {}) {
|
|
2041
|
-
const coreParams = pluginTaskParamsSchema.parse(params);
|
|
2042
|
-
const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
|
|
2043
|
-
name,
|
|
2044
|
-
plugin
|
|
2045
|
-
})));
|
|
2046
|
-
if (taskRegistrations.length === 0) return;
|
|
2047
|
-
const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
|
|
2048
|
-
if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
|
|
2049
|
-
const send = options.send ?? sendVercelPluginTask;
|
|
2050
|
-
const messages = taskRegistrations.map(({ name, plugin }) => ({
|
|
2051
|
-
name,
|
|
2052
|
-
params: coreParams,
|
|
2053
|
-
plugin: plugin.manifest.name
|
|
2054
|
-
}));
|
|
2055
|
-
await Promise.all(messages.map(async (message) => {
|
|
2056
|
-
await send(message);
|
|
2057
|
-
}));
|
|
2058
|
-
}
|
|
2059
|
-
/**
|
|
2060
|
-
* Execute one parsed plugin task request in a `plugin.task` span. The span
|
|
2061
|
-
* includes the lock wait, because both delay the work that runs the task.
|
|
2062
|
-
*/
|
|
2063
|
-
async function processPluginTask(message, options = {}) {
|
|
2064
|
-
const params = pluginTaskParamsSchema.parse(message.params);
|
|
2065
|
-
await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
|
|
2066
|
-
const resolved = findPluginTask(message);
|
|
2067
|
-
if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
|
|
2068
|
-
await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
|
|
2069
|
-
}), {
|
|
2070
|
-
"app.ai.turn.session_id": params.sessionId,
|
|
2071
|
-
"app.plugin.name": message.plugin,
|
|
2072
|
-
"app.plugin.task": message.name
|
|
2073
|
-
});
|
|
2074
|
-
}
|
|
2075
|
-
export { automationVersionOf as $, blockScheduledAutomation as A, registeredResourceTypeSchema as At, blockEventAutomation as B, listPendingDispatchMailboxAppends as C, eventGuidance as Ct, markDispatchFailed as D, registeredEventMatchSchema as Dt, markDispatchCompleted as E, hasEventCatalogEntries as Et, readScheduledAutomation as F, getEventAutomation as G, createEventAutomation as H, saveScheduledAutomation as I, saveEventAutomation as J, listDeletedEventAutomationsCreatedBy as K, saveScheduledAutomationInLock as L, deleteScheduledAutomation as M, requireValidEventTrigger as Mt, listScheduledAutomationsForTeam as N, markDispatchRunning as O, registeredEventTriggerProblems as Ot, parseScheduledAutomationRow as P, automationDefinition as Q, scheduledRunId as R, isTerminalDispatchStatus as S, eventCatalogEntry as St, markDispatchBlocked as T, eventWatchUnavailable as Tt, deleteEventAutomation as U, collectEventAutomationMatchKeys as V, findMatchingEventAutomations as W, admitEventAutomationRun as X, setEventAutomationStatus as Y, eventAutomationRunLimitReason as Z, getDispatchIdForConversation as _, conversationRangeColumns as _t, resolveTurnSessionRouting as a, requireAutomationRevision as at, getDispatchTurnId as b, automationEventCatalog as bt, getPersistedThreadState as c, readAutomationExecutionByConversationId as ct, coerceThreadConversationState as d, readAutomationExecutionSummaries as dt, listAutomationVersions as et, buildDispatchId as f, readAutomationExecutions as ft, getDispatchConversationId as g, conversationAggregateColumns as gt, createOrGetDispatch as h, recordAutomationExecution as ht, resolveConversationRouting as i, automationRevision as it, createScheduledAutomation as j, requireEventIdentifier as jt, notifyAutomationBlocked as k, registeredEventTypeSchema as kt, persistThreadRuntimeState as l, readAutomationExecutionStatusDays as lt, confirmDispatchMailboxAppend as m, readAutomationTitlesByConversationId as mt, scheduleSessionCompletedPluginTasks as n, sameDefinitionValue as nt, getLocationConfigurationService as o, emptyAutomationRunWindows as ot, claimDispatchMailboxAppend as p, readAutomationRuns as pt, parseEventAutomationRow as q, task_runner_exports as r, AutomationConflictError as rt, getPersistedSandboxState as s, existingConversationId as st, processPluginTask as t, readAutomationVersion as tt, persistThreadStateById as u, readAutomationExecutionStatusHours as ut, getDispatchInputMessageId as v, conversationUsageCostExpr as vt, markDispatchAwaitingResume as w, eventNamespaceSchema as wt, getPluginDispatchProjection as x, describeRegisteredEventTrigger as xt, getDispatchRecord as y, CORE_EVENT_NAMESPACE as yt, withScheduledAutomationLock as z };
|
|
1421
|
+
export { eventAutomationRunLimitReason as $, conversationRangeColumns as A, scheduledRunId as B, readAutomationExecutionStatusHours as C, readAutomationTitlesByConversationId as D, readAutomationRuns as E, listScheduledAutomationsForTeam as F, deleteEventAutomation as G, blockEventAutomation as H, parseScheduledAutomationRow as I, listDeletedEventAutomationsCreatedBy as J, findMatchingEventAutomations as K, readScheduledAutomation as L, blockScheduledAutomation as M, createScheduledAutomation as N, recordAutomationExecution as O, deleteScheduledAutomation as P, admitEventAutomationRun as Q, saveScheduledAutomation as R, readAutomationExecutionStatusDays as S, readAutomationExecutions as T, collectEventAutomationMatchKeys as U, withScheduledAutomationLock as V, createEventAutomation as W, saveEventAutomation as X, parseEventAutomationRow as Y, setEventAutomationStatus as Z, markDispatchRunning as _, getDispatchConversationId as a, AutomationConflictError as at, existingConversationId as b, getDispatchRecord as c, isTerminalDispatchStatus as d, automationDefinition as et, listPendingDispatchMailboxAppends as f, markDispatchFailed as g, markDispatchCompleted as h, createOrGetDispatch as i, sameDefinitionValue as it, conversationUsageCostExpr as j, conversationAggregateColumns as k, getDispatchTurnId as l, markDispatchBlocked as m, claimDispatchMailboxAppend as n, listAutomationVersions as nt, getDispatchIdForConversation as o, automationRevision as ot, markDispatchAwaitingResume as p, getEventAutomation as q, confirmDispatchMailboxAppend as r, readAutomationVersion as rt, getDispatchInputMessageId as s, requireAutomationRevision as st, buildDispatchId as t, automationVersionOf as tt, getPluginDispatchProjection as u, notifyAutomationBlocked as v, readAutomationExecutionSummaries as w, readAutomationExecutionByConversationId as x, emptyAutomationRunWindows as y, saveScheduledAutomationInLock as z };
|