@sentry/junior 0.295.0 → 0.297.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-ifgjyfpF.js → admin-tmGIw4KS.js} +2 -2
- package/dist/{agent-runner-DjMTPWEO.js → agent-runner-CneTquAE.js} +468 -1947
- 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 +306 -569
- package/dist/{app-uiTzRbvq.d.ts → app-BJojZ7HL.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-BrP6ImrC.js} +1 -1
- package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-CwfJy3Cd.js} +4 -88
- package/dist/{briefs-CbNYM-q2.js → briefs-uFTuhMqA.js} +3 -3
- package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-0kuQqYL4.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-DvnTPCfp.js → config-Dj9M_nqB.js} +18 -2
- package/dist/{connections-CWaIVl_1.js → connections-B96JUM5o.js} +6 -6
- package/dist/{conversation-CMkSmi02.js → conversation-CvcBU1z2.js} +2 -16
- package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-BSMlGZnS.js} +1 -1
- package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-DI29jbZV.js} +1 -1
- package/dist/conversation-turn-CZWBr091.js +805 -0
- package/dist/{credential-sync-BhbaZfmO.js → credential-sync-Blhx4_xf.js} +14 -13
- package/dist/{db-Dts2XvLu.js → db-Br0tfAo7.js} +54 -32
- package/dist/{db-CCUqQe0E.d.ts → db-CrtyFRz7.d.ts} +13 -1
- package/dist/{executor-Ck73J0wP.js → executor-BMPipFVA.js} +19 -5
- package/dist/instrumentation.js +19 -2
- package/dist/{logging-9OAq-fdg.js → logging-CQjlDQYX.js} +1 -1
- package/dist/{message-CtaPzC7m.js → message-BOZEIuxy.js} +15 -13
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -2
- package/dist/{session-stop-DkxI5vc3.js → notification-gusCgdQ6.js} +14 -933
- package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-V_DuMuNX.js} +2 -2
- package/dist/{projection-BzJQncZV.js → projection-B08mfi0u.js} +479 -145
- package/dist/{prompt-Cbq5b4SO.js → prompt-BlutWLNt.js} +4 -4
- package/dist/prompt-input-Dxn8cDC0.js +1424 -0
- package/dist/{registry-cbpOxO4M.js → registry-BDWgCJDf.js} +1 -1
- package/dist/reporting-window-DopzcOHh.js +137 -0
- package/dist/{resolve-t-pmRdwS.js → resolve-2Z_o_SsI.js} +3 -3
- package/dist/result-CAujiaci.js +463 -0
- package/dist/{runner-CHv9X9TH.js → runner-D2Chc02N.js} +9 -8
- package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-CFoJduFj.js} +1 -1
- package/dist/{schema-BhneuGYv.js → schema-Bqa5NbcP.js} +22 -48
- package/dist/{schema-TSEisVJR.d.ts → schema-Ce2XCS7O.d.ts} +24 -107
- package/dist/{service-account-DjPIwCMj.js → service-account-C9kRQEb_.js} +3 -3
- package/dist/{service-account-C4rBP8ne.js → service-account-CERfXEVU.js} +3 -3
- package/dist/session-stop-B-I1rAS1.js +181 -0
- package/dist/{skills-BZE2DP8I.js → skills-B0m1nZ_j.js} +3 -3
- package/dist/{spawn-BvULxIiu.js → spawn-CwMjRRtn.js} +6 -5
- package/dist/{state-CO9ETDzk.js → state-DFnmLmfn.js} +2 -2
- package/dist/{stop-CL-rdtQb.js → stop-BCH9VNGf.js} +329 -382
- package/dist/{store-DgD78_NK.js → store-B59rOYbS.js} +11 -4
- package/dist/{task-runner-CKOj6xla.js → store-m5bmdmsP.js} +929 -1559
- package/dist/task-queue-N0kuCknH.js +89 -0
- package/dist/task-runner-COOwR8qm.js +291 -0
- package/dist/thread-context-Cd44z_W5.js +248 -0
- package/dist/turn-cancel-DDu8TOwt.js +201 -0
- package/dist/turn-session-routing-BlCtVFRN.js +380 -0
- package/dist/{turn-failure-response-BTSo6SMJ.js → turn-user-message-ygLG3ylQ.js} +183 -358
- package/dist/turn-wake-DmQec4AG.js +161 -0
- package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
- package/dist/{validation-CXeYgBzq.js → validation-Ba2OcUse.js} +1 -1
- package/dist/{version-AQa7Fr2H.js → version-KNDzIAh6.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-Bqkb678l.js → viewer-BPpuN2f9.js} +3 -3
- package/dist/warmup-Bskrwmk1.js +2697 -0
- package/dist/{worker-Hl7N292I.js → worker-B1skZlit.js} +20 -8
- package/migrations/0101_drop_legacy_columns.sql +12 -0
- package/migrations/0102_code_change_last_activity.sql +1 -0
- package/migrations/0103_agent_invocation_fork.sql +8 -0
- package/migrations/meta/0101_snapshot.json +4496 -0
- package/migrations/meta/0102_snapshot.json +4502 -0
- package/migrations/meta/0103_snapshot.json +4509 -0
- package/migrations/meta/_journal.json +21 -0
- package/package.json +5 -4
- package/dist/result-DhgjR3nQ.js +0 -305
- package/dist/result-event-type-DD6BAgT7.js +0 -11
- package/dist/warmup-h6u1e9n0.js +0 -1869
- package/dist/work-yN_GAuXY.js +0 -768
|
@@ -1,1415 +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-Bqkb678l.js";
|
|
11
|
-
import { a as getStateAdapter } from "./state-CO9ETDzk.js";
|
|
12
|
-
import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-DUkHZjmL.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-B08mfi0u.js";
|
|
2
|
+
import { n as botConfig } from "./config-Dj9M_nqB.js";
|
|
3
|
+
import { _ as runBestEffort, h as logWarn } from "./logging-CQjlDQYX.js";
|
|
4
|
+
import { J as agentTurnTotalTokens, o as getDb, q as agentTurnCostUsd } from "./db-Br0tfAo7.js";
|
|
5
|
+
import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-BMPipFVA.js";
|
|
6
|
+
import { h as credentialSubjectSchema } from "./registry-BDWgCJDf.js";
|
|
7
|
+
import { a as getStateAdapter } from "./state-DFnmLmfn.js";
|
|
8
|
+
import { u as automationEventCatalog, v as registeredEventTriggerProblems } from "./turn-session-routing-BlCtVFRN.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-BrP6ImrC.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
|
-
function eventCatalogEntry(registration) {
|
|
31
|
-
return {
|
|
32
|
-
...registration,
|
|
33
|
-
anyResourceFields: anyResourceMatchFields(registration.resourceTypes)
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
/** Core-owned event namespace. Not a plugin publisher. */
|
|
37
|
-
const CORE_EVENT_NAMESPACE = "junior";
|
|
38
|
-
/** True when the catalog has any enabled registration. */
|
|
39
|
-
function hasEventCatalogEntries(catalog) {
|
|
40
|
-
return Object.keys(catalog).length > 0;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Catalog entries that durable event automations may select.
|
|
44
|
-
*
|
|
45
|
-
* Resource types with `automation: false` stay out of create/update schemas
|
|
46
|
-
* and trigger availability. A namespace with no such resource type left is
|
|
47
|
-
* removed.
|
|
48
|
-
*/
|
|
49
|
-
function automationEventCatalog(catalog) {
|
|
50
|
-
return Object.fromEntries(Object.entries(catalog).flatMap(([namespace, registration]) => {
|
|
51
|
-
const resourceTypes = registration.resourceTypes.filter((resourceType) => registration.limits?.[resourceType.type]?.automation !== false);
|
|
52
|
-
if (resourceTypes.length === 0) return [];
|
|
53
|
-
if (resourceTypes.length === registration.resourceTypes.length) return [[namespace, registration]];
|
|
54
|
-
const supported = new Set(resourceTypes.flatMap((resourceType) => resourceType.supportedEvents));
|
|
55
|
-
return [[namespace, eventCatalogEntry({
|
|
56
|
-
...registration,
|
|
57
|
-
resourceTypes,
|
|
58
|
-
events: Object.fromEntries(Object.entries(registration.events).filter(([eventType]) => supported.has(eventType)))
|
|
59
|
-
})]];
|
|
60
|
-
}));
|
|
61
|
-
}
|
|
62
|
-
/** Return why watchEvents cannot watch one resource type, if it cannot. */
|
|
63
|
-
function eventWatchUnavailable(catalog, namespace, resourceType) {
|
|
64
|
-
const limits = catalog[namespace]?.limits?.[resourceType];
|
|
65
|
-
return limits?.watch === false ? limits.watchUnavailableMessage : void 0;
|
|
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;
|
|
66
27
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
return
|
|
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");
|
|
70
31
|
}
|
|
71
|
-
/**
|
|
72
|
-
function
|
|
73
|
-
|
|
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();
|
|
74
35
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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
|
|
53
|
+
};
|
|
78
54
|
}
|
|
79
|
-
/**
|
|
80
|
-
function
|
|
81
|
-
return
|
|
55
|
+
/** Compare definition values after key sorting. */
|
|
56
|
+
function sameDefinitionValue(left, right) {
|
|
57
|
+
return JSON.stringify(canonicalJson(left)) === JSON.stringify(canonicalJson(right));
|
|
82
58
|
}
|
|
83
59
|
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
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.
|
|
87
63
|
*/
|
|
88
|
-
function
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
+
});
|
|
94
78
|
}
|
|
95
79
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
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.
|
|
99
85
|
*/
|
|
100
|
-
function
|
|
101
|
-
return
|
|
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
|
+
)`;
|
|
102
93
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
+
});
|
|
109
109
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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;
|
|
113
114
|
}
|
|
114
|
-
/**
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
* each text value in the case that its plugin declares, with no repeated
|
|
118
|
-
* list values. The dashboard clears `inputKeys` so messages name the filters
|
|
119
|
-
* as its plugin declares them.
|
|
120
|
-
*/
|
|
121
|
-
function requireValidEventTrigger(catalog, selection, target, options = { inputKeys: true }) {
|
|
122
|
-
const fields = eventTriggerChoices(catalog[selection.namespace] ?? NO_SOURCE, selection)?.fields ?? {};
|
|
123
|
-
const normalized = {
|
|
124
|
-
...selection,
|
|
125
|
-
match: normalizeEventMatch(fields, selection.match)
|
|
126
|
-
};
|
|
127
|
-
const problems = registeredEventTriggerProblems(catalog, normalized, options);
|
|
128
|
-
if (problems.length > 0) {
|
|
129
|
-
const source = catalog[selection.namespace]?.displayName ?? selection.namespace;
|
|
130
|
-
const resource = selection.resourceType ? `${source} ${selection.resourceType.replaceAll("_", " ")}` : source;
|
|
131
|
-
throw new ToolInputError([target === "watch" ? `This ${resource} watch cannot be created.` : `This ${resource} trigger cannot be saved.`, ...problems.map((problem) => problem.message)].join(" "));
|
|
132
|
-
}
|
|
133
|
-
return uniqueMatchValues(normalized.match);
|
|
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);
|
|
134
118
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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(" "));
|
|
150
|
-
}
|
|
151
|
-
// src/chat/state/conversation.ts
|
|
152
|
-
function defaultConversationState() {
|
|
153
|
-
return {
|
|
154
|
-
schemaVersion: 1,
|
|
155
|
-
messages: [],
|
|
156
|
-
processing: {},
|
|
157
|
-
vision: { byFileId: {} }
|
|
158
|
-
};
|
|
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}`;
|
|
159
128
|
}
|
|
160
|
-
function
|
|
161
|
-
|
|
162
|
-
const kind = value.kind;
|
|
163
|
-
const provider = toOptionalString(value.provider);
|
|
164
|
-
const actorId = toOptionalString(value.actorId);
|
|
165
|
-
const authSessionId = toOptionalString(value.authSessionId);
|
|
166
|
-
const scope = toOptionalString(value.scope);
|
|
167
|
-
const sessionId = toOptionalString(value.sessionId);
|
|
168
|
-
const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
|
|
169
|
-
if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
|
|
170
|
-
const base = {
|
|
171
|
-
provider,
|
|
172
|
-
actorId,
|
|
173
|
-
...scope ? { scope } : void 0,
|
|
174
|
-
sessionId,
|
|
175
|
-
linkSentAtMs
|
|
176
|
-
};
|
|
177
|
-
return kind === "mcp" ? {
|
|
178
|
-
...base,
|
|
179
|
-
authSessionId,
|
|
180
|
-
kind
|
|
181
|
-
} : {
|
|
182
|
-
...base,
|
|
183
|
-
kind
|
|
184
|
-
};
|
|
129
|
+
function runListMaxLength() {
|
|
130
|
+
return botConfig.maxEventAutomationRuns + RUN_LIST_BURST_ROOM;
|
|
185
131
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
|
|
203
|
-
if (!isRecord$1(value)) continue;
|
|
204
|
-
const summary = toOptionalString(value.summary);
|
|
205
|
-
const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
|
|
206
|
-
if (!summary || !analyzedAtMs) continue;
|
|
207
|
-
byFileId[fileId] = {
|
|
208
|
-
summary,
|
|
209
|
-
analyzedAtMs
|
|
210
|
-
};
|
|
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
|
+
});
|
|
138
|
+
}
|
|
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`;
|
|
211
148
|
}
|
|
212
|
-
return {
|
|
213
|
-
schemaVersion: 1,
|
|
214
|
-
messages,
|
|
215
|
-
processing,
|
|
216
|
-
vision: {
|
|
217
|
-
backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
|
|
218
|
-
byFileId
|
|
219
|
-
}
|
|
220
|
-
};
|
|
149
|
+
return `${windowMs} ms`;
|
|
221
150
|
}
|
|
222
|
-
/**
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
} };
|
|
233
|
-
}
|
|
234
|
-
// src/chat/runtime/thread-state.ts
|
|
235
|
-
function threadStateKey(threadId) {
|
|
236
|
-
return `thread-state:${threadId}`;
|
|
237
|
-
}
|
|
238
|
-
function channelStateKey(channelId) {
|
|
239
|
-
return `channel-state:${channelId}`;
|
|
240
|
-
}
|
|
241
|
-
function buildThreadStatePayload(patch) {
|
|
242
|
-
const payload = {};
|
|
243
|
-
if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
|
|
244
|
-
if (patch.sandboxRef !== void 0) {
|
|
245
|
-
payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
|
|
246
|
-
payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
|
|
247
|
-
payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
|
|
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.`;
|
|
155
|
+
}
|
|
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;
|
|
248
161
|
}
|
|
249
|
-
return
|
|
162
|
+
return false;
|
|
250
163
|
}
|
|
251
164
|
/**
|
|
252
|
-
*
|
|
165
|
+
* Count one run of an Event automation, or refuse when its window is full.
|
|
253
166
|
*
|
|
254
|
-
*
|
|
255
|
-
*
|
|
167
|
+
* `runKey` is the dispatch idempotency key, so a provider retry of the same
|
|
168
|
+
* Event does not count again.
|
|
256
169
|
*/
|
|
257
|
-
async function
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
const id = toOptionalString(state.app_sandbox_id);
|
|
270
|
-
if (!id) return;
|
|
271
|
-
const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
|
|
272
|
-
const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
|
|
273
|
-
return {
|
|
274
|
-
id,
|
|
275
|
-
...profileHash ? { profileHash } : void 0,
|
|
276
|
-
...workspaceId ? { workspaceId } : void 0
|
|
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
|
+
};
|
|
277
182
|
};
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
|
|
282
|
-
}
|
|
283
|
-
/** Load the persisted state payload for a thread without requiring a Chat singleton. */
|
|
284
|
-
async function getPersistedThreadState(threadId) {
|
|
285
|
-
const stateAdapter = getStateAdapter();
|
|
286
|
-
await stateAdapter.connect();
|
|
287
|
-
return await stateAdapter.get(threadStateKey(threadId)) ?? {};
|
|
288
|
-
}
|
|
289
|
-
/** Persist a thread-state patch by thread id without constructing a Chat thread. */
|
|
290
|
-
async function persistThreadStateById(threadId, patch) {
|
|
291
|
-
if (patch.conversation) await persistConversationMessages({
|
|
292
|
-
conversation: patch.conversation,
|
|
293
|
-
conversationId: threadId
|
|
183
|
+
if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
|
|
184
|
+
atMs: args.nowMs,
|
|
185
|
+
id: args.runKey
|
|
294
186
|
});
|
|
295
|
-
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
await stateAdapter.connect();
|
|
301
|
-
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
302
|
-
}
|
|
303
|
-
/**
|
|
304
|
-
* Resolve durable location configuration.
|
|
305
|
-
*
|
|
306
|
-
* Slack still reads the old channel-id Redis bag once during cutover.
|
|
307
|
-
*/
|
|
308
|
-
function getLocationConfigurationService(destination) {
|
|
309
|
-
if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
|
|
310
|
-
return createDurableLocationConfigurationService({
|
|
311
|
-
destination,
|
|
312
|
-
db: getDb(),
|
|
313
|
-
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
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;
|
|
314
192
|
});
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
const
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
seen.add(cursor);
|
|
323
|
-
const conversation = await conversationStore.get({ conversationId: cursor });
|
|
324
|
-
if (!conversation) break;
|
|
325
|
-
chain.push(conversation);
|
|
326
|
-
cursor = conversation.parentConversationId;
|
|
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";
|
|
327
200
|
}
|
|
328
|
-
return
|
|
201
|
+
return "limited";
|
|
329
202
|
}
|
|
330
203
|
/**
|
|
331
|
-
*
|
|
204
|
+
* Forget the runs counted for one Event automation.
|
|
332
205
|
*
|
|
333
|
-
*
|
|
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.
|
|
334
209
|
*/
|
|
335
|
-
function
|
|
336
|
-
|
|
337
|
-
const threadTs = args.source.threadTs?.trim();
|
|
338
|
-
return {
|
|
339
|
-
kind: "slack",
|
|
340
|
-
visibility: args.source.visibility ?? "public",
|
|
341
|
-
teamId: args.source.teamId?.trim() || args.destination.teamId,
|
|
342
|
-
channelId: args.source.channelId,
|
|
343
|
-
...threadTs ? { threadTs } : void 0
|
|
344
|
-
};
|
|
210
|
+
async function clearEventAutomationRuns(automationId, state = getStateAdapter()) {
|
|
211
|
+
await appendRunEntry(state, automationId, { reset: true });
|
|
345
212
|
}
|
|
213
|
+
// src/chat/event-automations/store.ts
|
|
346
214
|
/**
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
* Reads parent Conversations when this Conversation has no Destination.
|
|
215
|
+
* Validate an event automation and split it into its SQL columns. Lifecycle
|
|
216
|
+
* columns are written separately.
|
|
350
217
|
*/
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
const
|
|
354
|
-
let destination;
|
|
355
|
-
let source;
|
|
356
|
-
let location;
|
|
357
|
-
for (const conversation of chain) {
|
|
358
|
-
destination ??= conversation.destination;
|
|
359
|
-
source ??= conversation.sessionSource;
|
|
360
|
-
location ??= conversation.location;
|
|
361
|
-
if (destination && source) break;
|
|
362
|
-
}
|
|
363
|
-
if (!destination) return;
|
|
364
|
-
if (destination.platform === "slack") {
|
|
365
|
-
const slackSource = slackSourceForDestination({
|
|
366
|
-
destination,
|
|
367
|
-
source
|
|
368
|
-
});
|
|
369
|
-
return {
|
|
370
|
-
destination,
|
|
371
|
-
...location ? { location } : void 0,
|
|
372
|
-
...slackSource ? { source: slackSource } : void 0
|
|
373
|
-
};
|
|
374
|
-
}
|
|
218
|
+
function eventAutomationColumns(task) {
|
|
219
|
+
const { status: _status, statusReason: _statusReason, title, ...definition } = task;
|
|
220
|
+
const { createdAtMs: _createdAtMs, creatorIdentityId, id: _id, ...record } = eventAutomationSchema.parse(definition);
|
|
375
221
|
return {
|
|
376
|
-
destination,
|
|
377
|
-
|
|
378
|
-
|
|
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
|
|
379
231
|
};
|
|
380
232
|
}
|
|
381
|
-
|
|
382
|
-
async function resolveTurnSessionRouting(args) {
|
|
383
|
-
const routing = await resolveConversationRouting(args);
|
|
384
|
-
if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
|
|
233
|
+
function eventAutomationRowInput(row) {
|
|
385
234
|
return {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
235
|
+
...row.record,
|
|
236
|
+
createdAtMs: row.createdAtMs,
|
|
237
|
+
creatorIdentityId: row.creatorIdentityId,
|
|
238
|
+
id: row.id
|
|
389
239
|
};
|
|
390
240
|
}
|
|
391
|
-
|
|
392
|
-
function
|
|
393
|
-
return
|
|
394
|
-
WHEN ${source.usage}->>${field} IS NOT NULL
|
|
395
|
-
THEN (${source.usage}->>${field})::double precision
|
|
396
|
-
ELSE NULL
|
|
397
|
-
END`;
|
|
241
|
+
/** Decode an event Automation row with its SQL-backed fields. */
|
|
242
|
+
function parseEventAutomationRow(row) {
|
|
243
|
+
return withRowFields(row, eventAutomationSchema.parse(eventAutomationRowInput(row)));
|
|
398
244
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
412
|
-
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
413
|
-
THEN (${source.usage}->>'totalTokens')::double precision
|
|
414
|
-
ELSE NULL
|
|
415
|
-
END
|
|
416
|
-
`;
|
|
417
|
-
}
|
|
418
|
-
function costValue(source) {
|
|
419
|
-
return conversationUsageCostExpr(source.usage);
|
|
420
|
-
}
|
|
421
|
-
/** Read one conversation row's usage cost as a SQL expression. */
|
|
422
|
-
function conversationUsageCostExpr(usage) {
|
|
423
|
-
return sql`
|
|
424
|
-
CASE
|
|
425
|
-
WHEN ${usage}->'cost'->>'total' IS NOT NULL
|
|
426
|
-
THEN (${usage}->'cost'->>'total')::double precision
|
|
427
|
-
WHEN COALESCE(
|
|
428
|
-
${usage}->'cost'->>'input',
|
|
429
|
-
${usage}->'cost'->>'output',
|
|
430
|
-
${usage}->'cost'->>'cacheRead',
|
|
431
|
-
${usage}->'cost'->>'cacheWrite'
|
|
432
|
-
) IS NOT NULL
|
|
433
|
-
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
434
|
-
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
435
|
-
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
436
|
-
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
437
|
-
ELSE NULL
|
|
438
|
-
END
|
|
439
|
-
`;
|
|
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
|
+
});
|
|
440
257
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
const metrics = sources?.metrics ?? juniorConversations;
|
|
444
|
-
const roots = sources?.roots ?? juniorConversations;
|
|
445
|
-
const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
|
|
258
|
+
function withRowFields(row, task) {
|
|
259
|
+
const title = row.title?.trim();
|
|
446
260
|
return {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
452
|
-
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
453
|
-
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
454
|
-
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
455
|
-
failed: sql`${conversationCount} FILTER (
|
|
456
|
-
WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
|
|
457
|
-
)::integer`,
|
|
458
|
-
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
459
|
-
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
|
|
460
265
|
};
|
|
461
266
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
return {
|
|
465
|
-
firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
|
|
466
|
-
lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
|
|
467
|
-
};
|
|
267
|
+
function eventAutomationWhere(id) {
|
|
268
|
+
return and(eq(juniorAutomations.id, id), eq(juniorAutomations.kind, "event"));
|
|
468
269
|
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
"blocked",
|
|
472
|
-
"completed",
|
|
473
|
-
"failed"
|
|
474
|
-
];
|
|
475
|
-
/** An execution is a run with an outcome. Skipped runs are not executions. */
|
|
476
|
-
function isExecution() {
|
|
477
|
-
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"));
|
|
478
272
|
}
|
|
479
|
-
|
|
480
|
-
|
|
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;
|
|
481
277
|
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
+
});
|
|
491
308
|
}
|
|
492
|
-
|
|
493
|
-
|
|
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
|
+
});
|
|
494
324
|
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
costUsd: 0,
|
|
500
|
-
date,
|
|
501
|
-
failed: 0
|
|
502
|
-
};
|
|
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;
|
|
503
329
|
}
|
|
504
330
|
/**
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
* `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.
|
|
508
333
|
*/
|
|
509
|
-
function
|
|
510
|
-
|
|
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);
|
|
511
338
|
}
|
|
512
339
|
/**
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
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.
|
|
516
343
|
*/
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
344
|
+
function eventIdentifierWhere(identifiers) {
|
|
345
|
+
return or(isNull(juniorAutomations.identifier), ...identifiers.length > 0 ? [inArray(juniorAutomations.identifier, [...identifiers])] : []);
|
|
346
|
+
}
|
|
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`));
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
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.
|
|
359
|
+
*/
|
|
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;
|
|
366
|
+
}
|
|
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
|
|
545
385
|
});
|
|
546
|
-
|
|
386
|
+
return [];
|
|
387
|
+
});
|
|
547
388
|
}
|
|
548
|
-
/**
|
|
549
|
-
|
|
550
|
-
if (
|
|
551
|
-
|
|
552
|
-
const oneDayAgoMs = nowMs - 864e5;
|
|
553
|
-
const sevenDaysAgoMs = nowMs - 6048e5;
|
|
554
|
-
const thirtyDaysAgoMs = nowMs - 2592e6;
|
|
555
|
-
const ninetyDaysAgoMs = nowMs - 7776e6;
|
|
556
|
-
const db = getDb();
|
|
557
|
-
const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
|
|
558
|
-
const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
|
|
559
|
-
status: juniorAutomationRuns.status,
|
|
560
|
-
conversationId: juniorAutomationRuns.conversationId,
|
|
561
|
-
automationId: juniorAutomationRuns.automationId
|
|
562
|
-
}).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
|
|
563
|
-
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
564
|
-
const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
|
|
565
|
-
const summaryRows = db.select({
|
|
566
|
-
costLast1Day: costSince(oneDayAgoMs),
|
|
567
|
-
costLast7Days: costSince(sevenDaysAgoMs),
|
|
568
|
-
costLast30Days: costSince(thirtyDaysAgoMs),
|
|
569
|
-
costLast90Days: costSince(ninetyDaysAgoMs),
|
|
570
|
-
lastRunStatus: latest.status,
|
|
571
|
-
lastConversationId: latest.conversationId,
|
|
572
|
-
lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
|
|
573
|
-
runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
|
|
574
|
-
runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
|
|
575
|
-
runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
|
|
576
|
-
runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
|
|
577
|
-
automationId: juniorAutomationRuns.automationId,
|
|
578
|
-
totalCostUsd: sql`coalesce(sum(${conversationCost}), 0)::double precision`,
|
|
579
|
-
totalRuns: sql`count(*)::int`
|
|
580
|
-
}).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
|
|
581
|
-
const [rows, recentRuns] = await Promise.all([summaryRows, readAutomationRecentRuns(automationIds)]);
|
|
582
|
-
return new Map(rows.map((row) => [row.automationId, {
|
|
583
|
-
costUsd: {
|
|
584
|
-
1: addUsd(0, row.costLast1Day),
|
|
585
|
-
7: addUsd(0, row.costLast7Days),
|
|
586
|
-
30: addUsd(0, row.costLast30Days),
|
|
587
|
-
90: addUsd(0, row.costLast90Days)
|
|
588
|
-
},
|
|
589
|
-
lastRunStatus: row.lastRunStatus,
|
|
590
|
-
...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
|
|
591
|
-
...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
|
|
592
|
-
recentRuns: recentRuns.get(row.automationId) ?? [],
|
|
593
|
-
runs: {
|
|
594
|
-
1: row.runsLast1Day,
|
|
595
|
-
7: row.runsLast7Days,
|
|
596
|
-
30: row.runsLast30Days,
|
|
597
|
-
90: row.runsLast90Days
|
|
598
|
-
},
|
|
599
|
-
totalCostUsd: addUsd(0, row.totalCostUsd),
|
|
600
|
-
totalRuns: row.totalRuns
|
|
601
|
-
}]));
|
|
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));
|
|
602
393
|
}
|
|
603
394
|
/**
|
|
604
|
-
*
|
|
605
|
-
*
|
|
606
|
-
*
|
|
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.
|
|
607
400
|
*/
|
|
608
|
-
async function
|
|
609
|
-
const
|
|
610
|
-
const
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
for (const row of rows) {
|
|
624
|
-
const durationMs = positiveDuration(row.durationMs);
|
|
625
|
-
const runs = byAutomation.get(row.automationId) ?? [];
|
|
626
|
-
runs.push({
|
|
627
|
-
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
628
|
-
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
629
|
-
status: row.status
|
|
630
|
-
});
|
|
631
|
-
byAutomation.set(row.automationId, runs);
|
|
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);
|
|
632
416
|
}
|
|
633
|
-
return
|
|
634
|
-
}
|
|
635
|
-
/** Keep a recorded runtime only when it is a real duration. */
|
|
636
|
-
function positiveDuration(value) {
|
|
637
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
417
|
+
return [...keys].sort();
|
|
638
418
|
}
|
|
639
|
-
/**
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
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)));
|
|
646
439
|
}
|
|
647
440
|
/**
|
|
648
|
-
*
|
|
649
|
-
*
|
|
650
|
-
*
|
|
651
|
-
*
|
|
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.
|
|
652
445
|
*/
|
|
653
|
-
async function
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
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
|
+
});
|
|
667
474
|
}
|
|
668
|
-
/**
|
|
669
|
-
|
|
670
|
-
|
|
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";
|
|
671
488
|
}
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
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,
|
|
499
|
+
status: row.status,
|
|
500
|
+
statusReason: row.statusReason,
|
|
501
|
+
title: row.title
|
|
502
|
+
};
|
|
503
|
+
const parsed = scheduledAutomationSchema.safeParse({
|
|
504
|
+
...row.record,
|
|
505
|
+
...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
|
|
506
|
+
});
|
|
507
|
+
return parsed.success ? parsed.data : void 0;
|
|
684
508
|
}
|
|
685
|
-
/**
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
conversationId: juniorAutomationRuns.conversationId,
|
|
689
|
-
credentialMode: sql`${juniorAutomationVersions.definition}->>'credentialMode'`,
|
|
690
|
-
durationMs: juniorConversations.durationMs,
|
|
691
|
-
errorMessage: juniorAutomationRuns.errorMessage,
|
|
692
|
-
executedAtMs: juniorAutomationRuns.completedAtMs,
|
|
693
|
-
executionId: juniorAutomationRuns.id,
|
|
694
|
-
scheduledForMs: juniorAutomationRuns.scheduledForMs,
|
|
695
|
-
startedAtMs: juniorAutomationRuns.startedAtMs,
|
|
696
|
-
status: juniorAutomationRuns.status,
|
|
697
|
-
title: juniorConversations.title,
|
|
698
|
-
usage: juniorConversations.usage
|
|
699
|
-
};
|
|
700
|
-
function executionConversation() {
|
|
701
|
-
return eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId);
|
|
509
|
+
/** Keep scan paths from returning current or legacy tombstones. */
|
|
510
|
+
function isListedScheduledAutomation(task) {
|
|
511
|
+
return task !== void 0 && task.status !== "deleted";
|
|
702
512
|
}
|
|
703
|
-
|
|
704
|
-
|
|
513
|
+
/** Build the stable run id for one task occurrence. */
|
|
514
|
+
function scheduledRunId(taskId, scheduledForMs) {
|
|
515
|
+
return `${taskId}:${scheduledForMs}`;
|
|
705
516
|
}
|
|
706
|
-
|
|
707
|
-
|
|
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);
|
|
522
|
+
});
|
|
708
523
|
}
|
|
709
|
-
function
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
const
|
|
713
|
-
const
|
|
714
|
-
const error = row.errorMessage?.trim();
|
|
715
|
-
const scheduledFor = isoTime(row.scheduledForMs);
|
|
716
|
-
const startedAt = isoTime(row.startedAtMs);
|
|
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;
|
|
717
529
|
return {
|
|
718
|
-
...
|
|
719
|
-
...
|
|
720
|
-
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
721
|
-
...row.credentialMode === "creator" || row.credentialMode === "system" ? { credentialMode: row.credentialMode } : void 0,
|
|
722
|
-
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
723
|
-
...error ? { error } : void 0,
|
|
724
|
-
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
725
|
-
executionId: row.executionId,
|
|
726
|
-
...scheduledFor ? { scheduledFor } : void 0,
|
|
727
|
-
...startedAt ? { startedAt } : void 0,
|
|
728
|
-
status: row.status,
|
|
729
|
-
...title ? { title } : void 0,
|
|
730
|
-
...totalTokens !== void 0 ? { totalTokens } : void 0
|
|
530
|
+
...current,
|
|
531
|
+
...normalizedTitle ? { title: normalizedTitle } : void 0
|
|
731
532
|
};
|
|
732
533
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
const
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
else if (row.status === "blocked") day.blocked = row.count;
|
|
757
|
-
if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
|
|
758
|
-
}
|
|
759
|
-
return [...byDate.values()];
|
|
760
|
-
}
|
|
761
|
-
/** Load a fixed trailing window of terminal executions for one automation by hour. */
|
|
762
|
-
async function readAutomationExecutionStatusHours(args) {
|
|
763
|
-
const hourCount = args.hourCount ?? 168;
|
|
764
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
765
|
-
const end = new Date(nowMs);
|
|
766
|
-
end.setUTCMinutes(0, 0, 0);
|
|
767
|
-
const endMs = end.getTime() + 3599999;
|
|
768
|
-
const startMs = end.getTime() - (hourCount - 1) * 36e5;
|
|
769
|
-
const executionHour = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
|
|
770
|
-
const rows = await readExecutionStatusBuckets({
|
|
771
|
-
automationId: args.automationId,
|
|
772
|
-
bucket: executionHour,
|
|
773
|
-
endMs,
|
|
774
|
-
startMs
|
|
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
|
|
775
557
|
});
|
|
776
|
-
const byHour = /* @__PURE__ */ new Map();
|
|
777
|
-
for (let offset = 0; offset < hourCount; offset += 1) {
|
|
778
|
-
const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
|
|
779
|
-
byHour.set(date, emptyStatusDay(date));
|
|
780
|
-
}
|
|
781
|
-
for (const row of rows) {
|
|
782
|
-
const hour = byHour.get(row.date);
|
|
783
|
-
if (!hour) continue;
|
|
784
|
-
if (row.status === "completed") hour.completed = row.count;
|
|
785
|
-
else if (row.status === "failed") hour.failed = row.count;
|
|
786
|
-
else if (row.status === "blocked") hour.blocked = row.count;
|
|
787
|
-
if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
|
|
788
|
-
}
|
|
789
|
-
return [...byHour.values()];
|
|
790
558
|
}
|
|
791
|
-
/**
|
|
792
|
-
async function
|
|
793
|
-
const
|
|
794
|
-
return
|
|
795
|
-
count: count(),
|
|
796
|
-
costUsd: sql`SUM(${conversationCost})::double precision`,
|
|
797
|
-
date: args.bucket,
|
|
798
|
-
status: juniorAutomationRuns.status
|
|
799
|
-
}).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));
|
|
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;
|
|
800
563
|
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
var AutomationConflictError = class extends ToolInputError {
|
|
804
|
-
constructor() {
|
|
805
|
-
super("This Automation changed after it was loaded. Reload it before saving.");
|
|
806
|
-
this.name = "AutomationConflictError";
|
|
807
|
-
}
|
|
808
|
-
};
|
|
809
|
-
/** Sort object keys so equal values produce equal JSON. */
|
|
810
|
-
function canonicalJson(value) {
|
|
811
|
-
if (Array.isArray(value)) return value.map(canonicalJson);
|
|
812
|
-
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalJson(child)]));
|
|
813
|
-
return value;
|
|
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);
|
|
814
566
|
}
|
|
815
|
-
/**
|
|
816
|
-
function
|
|
817
|
-
return
|
|
567
|
+
/** List decoded scheduled automations for one team in stable creation order. */
|
|
568
|
+
async function listScheduledAutomationsForTeam(db, teamId) {
|
|
569
|
+
return await readListedScheduledAutomations(db, teamId);
|
|
818
570
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
if (
|
|
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);
|
|
822
576
|
}
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
task: task.task,
|
|
830
|
-
credentialMode: task.credentialMode,
|
|
831
|
-
destination: task.destination,
|
|
832
|
-
outcomes: task.outcomes
|
|
833
|
-
};
|
|
834
|
-
return "schedule" in task ? {
|
|
835
|
-
...common,
|
|
836
|
-
schedule: task.schedule
|
|
837
|
-
} : {
|
|
838
|
-
...common,
|
|
839
|
-
trigger: task.trigger
|
|
840
|
-
};
|
|
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")));
|
|
841
583
|
}
|
|
842
|
-
/**
|
|
843
|
-
function
|
|
844
|
-
|
|
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;
|
|
592
|
+
});
|
|
845
593
|
}
|
|
846
594
|
/**
|
|
847
|
-
* Save a
|
|
848
|
-
*
|
|
849
|
-
* Automation is new, so the creator saves version 1.
|
|
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.
|
|
850
597
|
*/
|
|
851
|
-
async function
|
|
852
|
-
const
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
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);
|
|
604
|
+
});
|
|
605
|
+
return next;
|
|
606
|
+
}
|
|
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);
|
|
610
|
+
}
|
|
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;
|
|
864
625
|
});
|
|
865
626
|
}
|
|
866
627
|
/**
|
|
867
|
-
*
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
871
|
-
* no saved version has this definition.
|
|
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.
|
|
872
632
|
*/
|
|
873
|
-
function
|
|
874
|
-
return
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
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;
|
|
649
|
+
});
|
|
880
650
|
}
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
function parseVersionRow(row) {
|
|
889
|
-
return automationVersionSchema.parse({
|
|
890
|
-
kind: row.kind,
|
|
891
|
-
version: row.version,
|
|
892
|
-
createdAt: new Date(row.createdAtMs).toISOString(),
|
|
893
|
-
editedBy: row.editedBy,
|
|
894
|
-
definition: row.definition
|
|
895
|
-
});
|
|
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`;
|
|
896
658
|
}
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
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
|
+
`;
|
|
901
677
|
}
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
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);
|
|
678
|
+
function costValue(source) {
|
|
679
|
+
return conversationUsageCostExpr(source.usage);
|
|
905
680
|
}
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
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
|
+
`;
|
|
915
700
|
}
|
|
916
|
-
|
|
917
|
-
|
|
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(*)`;
|
|
706
|
+
return {
|
|
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`
|
|
720
|
+
};
|
|
918
721
|
}
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
}
|
|
722
|
+
/** Select the complete first/last activity range for a grouped conversation aggregate. */
|
|
723
|
+
function conversationRangeColumns() {
|
|
724
|
+
return {
|
|
725
|
+
firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
|
|
726
|
+
lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
|
|
727
|
+
};
|
|
925
728
|
}
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
}
|
|
936
|
-
return `${windowMs} ms`;
|
|
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));
|
|
937
738
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
const window = describeRunWindow(botConfig.eventAutomationRunWindowMs);
|
|
941
|
-
return `This automation reached its limit of ${botConfig.maxEventAutomationRuns} runs per ${window}. Check that its trigger is not too broad, then resume it.`;
|
|
739
|
+
function addUsd(current, next) {
|
|
740
|
+
return Math.round((current + next) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
942
741
|
}
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
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 };
|
|
950
751
|
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
const values = await state.getList(runListKey(args.automationId));
|
|
962
|
-
return {
|
|
963
|
-
entries: values.flatMap((value) => {
|
|
964
|
-
const entry = runEntrySchema.safeParse(value);
|
|
965
|
-
return entry.success ? [entry.data] : [];
|
|
966
|
-
}),
|
|
967
|
-
length: values.length
|
|
968
|
-
};
|
|
752
|
+
function utcDate(nowMs) {
|
|
753
|
+
return new Date(nowMs).toISOString().slice(0, 10);
|
|
754
|
+
}
|
|
755
|
+
function emptyStatusDay(date) {
|
|
756
|
+
return {
|
|
757
|
+
blocked: 0,
|
|
758
|
+
completed: 0,
|
|
759
|
+
costUsd: 0,
|
|
760
|
+
date,
|
|
761
|
+
failed: 0
|
|
969
762
|
};
|
|
970
|
-
if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
|
|
971
|
-
atMs: args.nowMs,
|
|
972
|
-
id: args.runKey
|
|
973
|
-
});
|
|
974
|
-
const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
|
|
975
|
-
const { entries, length } = await readEntries();
|
|
976
|
-
let lastReset = -1;
|
|
977
|
-
entries.forEach((entry, index) => {
|
|
978
|
-
if ("reset" in entry) lastReset = index;
|
|
979
|
-
});
|
|
980
|
-
const oldest = entries[0];
|
|
981
|
-
const full = lastReset === -1 && length >= runListMaxLength() && oldest !== void 0 && "atMs" in oldest && oldest.atMs > windowStartMs;
|
|
982
|
-
const runKeys = /* @__PURE__ */ new Set();
|
|
983
|
-
for (const entry of entries.slice(lastReset + 1)) {
|
|
984
|
-
if ("reset" in entry) continue;
|
|
985
|
-
if (entry.atMs > windowStartMs) runKeys.add(entry.id);
|
|
986
|
-
if (entry.id === args.runKey) return full || runKeys.size > botConfig.maxEventAutomationRuns ? "limited" : "allowed";
|
|
987
|
-
}
|
|
988
|
-
return "limited";
|
|
989
763
|
}
|
|
990
764
|
/**
|
|
991
|
-
*
|
|
992
|
-
*
|
|
993
|
-
*
|
|
994
|
-
* Call it before the automation becomes active, so an Event cannot see the
|
|
995
|
-
* old full count and block it again.
|
|
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.
|
|
996
768
|
*/
|
|
997
|
-
|
|
998
|
-
|
|
769
|
+
function existingConversationId(conversationId) {
|
|
770
|
+
return sql`(select ${juniorConversations.conversationId} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
|
|
999
771
|
}
|
|
1000
|
-
// src/chat/event-automations/store.ts
|
|
1001
772
|
/**
|
|
1002
|
-
*
|
|
1003
|
-
*
|
|
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.
|
|
1004
776
|
*/
|
|
1005
|
-
function
|
|
1006
|
-
const
|
|
1007
|
-
const
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
identifier: record.trigger.identifier ?? null,
|
|
1013
|
-
...automationTaskColumns(record.task),
|
|
1014
|
-
namespace: record.trigger.namespace,
|
|
1015
|
-
record,
|
|
1016
|
-
teamId: record.destination.teamId,
|
|
1017
|
-
title: title?.trim() || null
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
1020
|
-
function eventAutomationRowInput(row) {
|
|
1021
|
-
return {
|
|
1022
|
-
...row.record,
|
|
1023
|
-
createdAtMs: row.createdAtMs,
|
|
1024
|
-
creatorIdentityId: row.creatorIdentityId,
|
|
1025
|
-
id: row.id
|
|
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
|
|
1026
784
|
};
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
"app.task.id": row.id,
|
|
1041
|
-
"app.task.type": "event",
|
|
1042
|
-
"error.message": parsed.error.message
|
|
1043
|
-
});
|
|
1044
|
-
}
|
|
1045
|
-
function withRowFields(row, task) {
|
|
1046
|
-
const title = row.title?.trim();
|
|
1047
|
-
return {
|
|
1048
|
-
...task,
|
|
1049
|
-
status: row.status,
|
|
1050
|
-
...row.statusReason ? { statusReason: row.statusReason } : void 0,
|
|
1051
|
-
...title ? { title } : void 0
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
function eventAutomationWhere(id) {
|
|
1055
|
-
return and(eq(juniorAutomations.id, id), eq(juniorAutomations.kind, "event"));
|
|
1056
|
-
}
|
|
1057
|
-
function activeEventAutomationWhere() {
|
|
1058
|
-
return and(eq(juniorAutomations.kind, "event"), ne(juniorAutomations.status, "deleted"));
|
|
1059
|
-
}
|
|
1060
|
-
/** Read one event automation by id, including deleted rows when present. */
|
|
1061
|
-
async function getEventAutomation(db, id) {
|
|
1062
|
-
const rows = await db.select().from(juniorAutomations).where(eventAutomationWhere(id)).limit(1);
|
|
1063
|
-
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
1064
|
-
}
|
|
1065
|
-
/** Create one retry-stable event automation, or revive a deleted row with the new payload. */
|
|
1066
|
-
async function createEventAutomation(db, task) {
|
|
1067
|
-
const columns = eventAutomationColumns(task);
|
|
1068
|
-
if ((await getEventAutomation(db, task.id))?.status === "deleted") await clearEventAutomationRuns(task.id);
|
|
1069
|
-
return db.transaction(async (tx) => {
|
|
1070
|
-
const inserted = await tx.insert(juniorAutomations).values({
|
|
1071
|
-
...columns,
|
|
1072
|
-
createdAtMs: task.createdAtMs,
|
|
1073
|
-
id: task.id,
|
|
1074
|
-
kind: "event",
|
|
1075
|
-
status: "active"
|
|
1076
|
-
}).onConflictDoNothing().returning();
|
|
1077
|
-
if (inserted[0]) {
|
|
1078
|
-
const created = parseEventAutomationRow(inserted[0]);
|
|
1079
|
-
await recordAutomationVersion(tx, created, void 0);
|
|
1080
|
-
return created;
|
|
1081
|
-
}
|
|
1082
|
-
const existing = await getEventAutomation(tx, task.id);
|
|
1083
|
-
if (!existing) throw new Error(`Automation ${task.id} already exists with another kind.`);
|
|
1084
|
-
if (existing.status !== "deleted") return existing;
|
|
1085
|
-
const rows = await tx.update(juniorAutomations).set({
|
|
1086
|
-
...columns,
|
|
1087
|
-
status: "active",
|
|
1088
|
-
statusReason: null
|
|
1089
|
-
}).where(and(eventAutomationWhere(task.id), eq(juniorAutomations.status, "deleted"))).returning();
|
|
1090
|
-
if (!rows[0]) return await getEventAutomation(tx, task.id);
|
|
1091
|
-
const revived = parseEventAutomationRow(rows[0]);
|
|
1092
|
-
await recordAutomationVersion(tx, revived, void 0);
|
|
1093
|
-
return revived;
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
/**
|
|
1097
|
-
* Replace an existing non-deleted event automation under a row lock.
|
|
1098
|
-
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
1099
|
-
*/
|
|
1100
|
-
async function saveEventAutomation(db, task, expectedRevision, editedBy) {
|
|
1101
|
-
const columns = eventAutomationColumns(task);
|
|
1102
|
-
return db.transaction(async (tx) => {
|
|
1103
|
-
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(task.id)).for("update");
|
|
1104
|
-
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
1105
|
-
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
1106
|
-
if (!current || current.status === "deleted") return void 0;
|
|
1107
|
-
const saved = parseEventAutomationRow((await tx.update(juniorAutomations).set(columns).where(eventAutomationWhere(task.id)).returning())[0]);
|
|
1108
|
-
await recordAutomationVersion(tx, saved, current, editedBy);
|
|
1109
|
-
return saved;
|
|
1110
|
-
});
|
|
1111
|
-
}
|
|
1112
|
-
/** Mark one existing event automation deleted while retaining the row for history. */
|
|
1113
|
-
async function deleteEventAutomation(db, id) {
|
|
1114
|
-
const rows = await db.update(juniorAutomations).set({ status: "deleted" }).where(and(eq(juniorAutomations.id, id), activeEventAutomationWhere())).returning();
|
|
1115
|
-
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
1116
|
-
}
|
|
1117
|
-
/**
|
|
1118
|
-
* List deleted event automations created by one user, newest first.
|
|
1119
|
-
* Used only to keep historical runs after the live automation list drops the row.
|
|
1120
|
-
*/
|
|
1121
|
-
async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
|
|
1122
|
-
const identityIds = user.identities.map((identity) => identity.id);
|
|
1123
|
-
if (identityIds.length === 0) return [];
|
|
1124
|
-
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);
|
|
1125
|
-
}
|
|
1126
|
-
/**
|
|
1127
|
-
* Select live rows whose identifier is one of these, and rows with no
|
|
1128
|
-
* identifier. A row with no identifier runs for every resource of its
|
|
1129
|
-
* namespace, so it gets every copy of an Event.
|
|
1130
|
-
*/
|
|
1131
|
-
function eventIdentifierWhere(identifiers) {
|
|
1132
|
-
return or(isNull(juniorAutomations.identifier), ...identifiers.length > 0 ? [inArray(juniorAutomations.identifier, [...identifiers])] : []);
|
|
1133
|
-
}
|
|
1134
|
-
/** SQL for rows whose trigger selects any of these event types. */
|
|
1135
|
-
function eventTypesWhere(eventTypes) {
|
|
1136
|
-
return or(...eventTypes.map((eventType) => sql`${juniorAutomations.record}->'trigger'->'events' @> ${JSON.stringify([eventType])}::jsonb`));
|
|
1137
|
-
}
|
|
1138
|
-
/**
|
|
1139
|
-
* Return why a row must not run for an Event with one of these identifiers,
|
|
1140
|
-
* or nothing when it may.
|
|
1141
|
-
*
|
|
1142
|
-
* The identifier column and the saved trigger must agree. A row with no
|
|
1143
|
-
* identifier must also have a trigger that the enabled `catalog` accepts. A
|
|
1144
|
-
* plugin can later require a filter or stop letting an event run for every
|
|
1145
|
-
* resource, and the row must not stay broad.
|
|
1146
|
-
*/
|
|
1147
|
-
function eventAutomationGateProblem(row, task, identifiers, catalog) {
|
|
1148
|
-
const identifier = task.trigger.identifier;
|
|
1149
|
-
if (identifier !== void 0) return identifier === row.identifier && identifiers.includes(identifier) ? void 0 : "The saved trigger has a different identifier from its row.";
|
|
1150
|
-
if (row.identifier !== null) return "The saved trigger has no identifier, but its row has one.";
|
|
1151
|
-
const problems = registeredEventTriggerProblems(catalog, task.trigger);
|
|
1152
|
-
return problems.length > 0 ? problems.map((problem) => problem.message).join(" ") : void 0;
|
|
1153
|
-
}
|
|
1154
|
-
/**
|
|
1155
|
-
* Read the rows that can match an Event: live rows of one team and
|
|
1156
|
-
* namespace whose identifier is one of these, or that have no identifier,
|
|
1157
|
-
* and that select one of these event types. Skip and log a row that does
|
|
1158
|
-
* not parse or that the gate rejects.
|
|
1159
|
-
*/
|
|
1160
|
-
async function readGatedEventAutomations(db, input) {
|
|
1161
|
-
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));
|
|
1162
|
-
const plugins = automationEventCatalog(input.catalog);
|
|
1163
|
-
return rows.flatMap((row) => {
|
|
1164
|
-
const task = readMatchableEventAutomationRow(row);
|
|
1165
|
-
if (!task) return [];
|
|
1166
|
-
const problem = eventAutomationGateProblem(row, task, input.identifiers, plugins);
|
|
1167
|
-
if (problem === void 0) return [task];
|
|
1168
|
-
logWarn("event_automation.gate.rejected", {
|
|
1169
|
-
"app.task.id": task.id,
|
|
1170
|
-
"app.task.type": "event",
|
|
1171
|
-
"app.event_automation.skip_reason": problem
|
|
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"])
|
|
1172
798
|
});
|
|
1173
|
-
|
|
1174
|
-
|
|
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
|
+
}
|
|
1175
807
|
}
|
|
1176
|
-
/**
|
|
1177
|
-
function
|
|
1178
|
-
if (
|
|
1179
|
-
|
|
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
|
+
}]));
|
|
1180
862
|
}
|
|
1181
863
|
/**
|
|
1182
|
-
*
|
|
1183
|
-
*
|
|
1184
|
-
*
|
|
1185
|
-
* filters on the keys in `data` fail adds no keys. So a broad trigger for
|
|
1186
|
-
* 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.
|
|
1187
867
|
*/
|
|
1188
|
-
async function
|
|
1189
|
-
const
|
|
1190
|
-
const
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
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);
|
|
1203
892
|
}
|
|
1204
|
-
return
|
|
893
|
+
return byAutomation;
|
|
1205
894
|
}
|
|
1206
|
-
/**
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
* filters match. Returns one list per event, in order. The events must share
|
|
1210
|
-
* one namespace. The gate skips a row whose trigger and identifier column
|
|
1211
|
-
* disagree, and a row with no identifier whose trigger the enabled `catalog`
|
|
1212
|
-
* rejects.
|
|
1213
|
-
*/
|
|
1214
|
-
async function findMatchingEventAutomations(db, events, teamId, catalog) {
|
|
1215
|
-
const namespace = events[0]?.namespace;
|
|
1216
|
-
if (namespace === void 0) return [];
|
|
1217
|
-
if (events.some((event) => event.namespace !== namespace)) throw new Error("Events to match must share one namespace.");
|
|
1218
|
-
const tasks = await readGatedEventAutomations(db, {
|
|
1219
|
-
catalog,
|
|
1220
|
-
eventTypes: [...new Set(events.map((event) => event.eventType))],
|
|
1221
|
-
identifiers: [...new Set(events.map((event) => event.identifier))],
|
|
1222
|
-
namespace,
|
|
1223
|
-
teamId
|
|
1224
|
-
});
|
|
1225
|
-
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;
|
|
1226
898
|
}
|
|
1227
|
-
/**
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
if (status === "active" && (await getEventAutomation(db, id))?.status !== "active") await clearEventAutomationRuns(id);
|
|
1235
|
-
return db.transaction(async (tx) => {
|
|
1236
|
-
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(id)).for("update");
|
|
1237
|
-
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
1238
|
-
requireAutomationRevision(current, revision);
|
|
1239
|
-
if (!current || current.status === "deleted") throw new Error("Automation no longer exists.");
|
|
1240
|
-
const next = status === "paused" ? {
|
|
1241
|
-
status,
|
|
1242
|
-
statusReason: current.statusReason
|
|
1243
|
-
} : current.status === "paused" && current.statusReason ? {
|
|
1244
|
-
status: "blocked",
|
|
1245
|
-
statusReason: current.statusReason
|
|
1246
|
-
} : {
|
|
1247
|
-
status,
|
|
1248
|
-
statusReason: void 0
|
|
1249
|
-
};
|
|
1250
|
-
await tx.update(juniorAutomations).set({
|
|
1251
|
-
status: next.status,
|
|
1252
|
-
statusReason: next.statusReason ?? null
|
|
1253
|
-
}).where(eventAutomationWhere(id));
|
|
1254
|
-
const { statusReason: _statusReason, ...rest } = current;
|
|
1255
|
-
return {
|
|
1256
|
-
...rest,
|
|
1257
|
-
status: next.status,
|
|
1258
|
-
...next.statusReason ? { statusReason: next.statusReason } : void 0
|
|
1259
|
-
};
|
|
1260
|
-
});
|
|
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;
|
|
1261
906
|
}
|
|
1262
907
|
/**
|
|
1263
|
-
*
|
|
1264
|
-
*
|
|
1265
|
-
*
|
|
1266
|
-
*
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
*/
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
const
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
creatorIdentityId: row.creatorIdentityId,
|
|
1283
|
-
id: row.id,
|
|
1284
|
-
nextRunAtMs: row.nextRunAtMs,
|
|
1285
|
-
runNowAtMs: row.runNowAtMs,
|
|
1286
|
-
status: row.status,
|
|
1287
|
-
statusReason: row.statusReason,
|
|
1288
|
-
title: row.title
|
|
1289
|
-
};
|
|
1290
|
-
const parsed = scheduledAutomationSchema.safeParse({
|
|
1291
|
-
...row.record,
|
|
1292
|
-
...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
|
|
1293
|
-
});
|
|
1294
|
-
return parsed.success ? parsed.data : void 0;
|
|
1295
|
-
}
|
|
1296
|
-
/** Keep scan paths from returning current or legacy tombstones. */
|
|
1297
|
-
function isListedScheduledAutomation(task) {
|
|
1298
|
-
return task !== void 0 && task.status !== "deleted";
|
|
1299
|
-
}
|
|
1300
|
-
/** Build the stable run id for one task occurrence. */
|
|
1301
|
-
function scheduledRunId(taskId, scheduledForMs) {
|
|
1302
|
-
return `${taskId}:${scheduledForMs}`;
|
|
1303
|
-
}
|
|
1304
|
-
/** Acquire the deployed advisory lock for one scheduled automation. */
|
|
1305
|
-
function withScheduledAutomationLock(db, taskId, callback) {
|
|
1306
|
-
return db.transaction(async (tx) => {
|
|
1307
|
-
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
|
|
1308
|
-
return await callback(tx);
|
|
1309
|
-
});
|
|
1310
|
-
}
|
|
1311
|
-
function requireStoredTask(task) {
|
|
1312
|
-
const parsed = scheduledAutomationSchema.safeParse(task);
|
|
1313
|
-
if (!parsed.success) throw new Error("Scheduled automation routing context is invalid.");
|
|
1314
|
-
const { title, ...current } = parsed.data;
|
|
1315
|
-
const normalizedTitle = title?.trim() || void 0;
|
|
1316
|
-
return {
|
|
1317
|
-
...current,
|
|
1318
|
-
...normalizedTitle ? { title: normalizedTitle } : void 0
|
|
1319
|
-
};
|
|
1320
|
-
}
|
|
1321
|
-
async function upsertScheduledAutomation(db, task) {
|
|
1322
|
-
const { createdAtMs, creatorIdentityId, id, nextRunAtMs, runNowAtMs, status, statusReason, title, ...record } = task;
|
|
1323
|
-
const columns = {
|
|
1324
|
-
channelId: record.destination.channelId,
|
|
1325
|
-
createdAtMs,
|
|
1326
|
-
creatorIdentityId,
|
|
1327
|
-
creatorSlackUserId: record.createdBy.slackUserId,
|
|
1328
|
-
...automationTaskColumns(record.task),
|
|
1329
|
-
nextRunAtMs: nextRunAtMs ?? null,
|
|
1330
|
-
record,
|
|
1331
|
-
runNowAtMs: runNowAtMs ?? null,
|
|
1332
|
-
status,
|
|
1333
|
-
statusReason: statusReason ?? null,
|
|
1334
|
-
teamId: record.destination.teamId,
|
|
1335
|
-
title: title?.trim() || null
|
|
1336
|
-
};
|
|
1337
|
-
await db.insert(juniorAutomations).values({
|
|
1338
|
-
...columns,
|
|
1339
|
-
id,
|
|
1340
|
-
kind: "scheduled"
|
|
1341
|
-
}).onConflictDoUpdate({
|
|
1342
|
-
target: juniorAutomations.id,
|
|
1343
|
-
set: columns
|
|
1344
|
-
});
|
|
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.
|
|
912
|
+
*/
|
|
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;
|
|
1345
927
|
}
|
|
1346
|
-
/**
|
|
1347
|
-
async function
|
|
1348
|
-
|
|
1349
|
-
return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
|
|
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));
|
|
1350
931
|
}
|
|
1351
|
-
|
|
1352
|
-
|
|
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
|
+
}));
|
|
1353
944
|
}
|
|
1354
|
-
/**
|
|
1355
|
-
|
|
1356
|
-
|
|
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);
|
|
1357
962
|
}
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
|
|
1361
|
-
await upsertScheduledAutomation(db, task);
|
|
1362
|
-
await recordAutomationVersion(db, task, current, editedBy);
|
|
963
|
+
function executionVersion() {
|
|
964
|
+
return and(eq(juniorAutomationVersions.automationId, juniorAutomationRuns.automationId), eq(juniorAutomationVersions.version, juniorAutomationRuns.automationVersion));
|
|
1363
965
|
}
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
completedAtMs: task.updatedAtMs,
|
|
1367
|
-
errorMessage: `Scheduled automation ${task.id} was deleted before the run started.`,
|
|
1368
|
-
status: "skipped"
|
|
1369
|
-
}).where(and(eq(juniorAutomationRuns.automationId, task.id), eq(juniorAutomationRuns.status, "pending")));
|
|
966
|
+
function isoTime(ms) {
|
|
967
|
+
return ms === null ? void 0 : new Date(ms).toISOString();
|
|
1370
968
|
}
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
const
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
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
|
+
};
|
|
1380
992
|
}
|
|
1381
|
-
/**
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
const
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
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
|
|
1391
1005
|
});
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
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()];
|
|
1397
1020
|
}
|
|
1398
|
-
/**
|
|
1399
|
-
async function
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
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
|
|
1412
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));
|
|
1413
1060
|
}
|
|
1414
1061
|
// src/chat/automations/blocked-notice.ts
|
|
1415
1062
|
function buildBlockedNoticeText(automationId, title, reason) {
|
|
@@ -1771,281 +1418,4 @@ async function getPluginDispatchProjection(args) {
|
|
|
1771
1418
|
if (!record || record.plugin !== args.plugin) return;
|
|
1772
1419
|
return toDispatchProjection(record);
|
|
1773
1420
|
}
|
|
1774
|
-
|
|
1775
|
-
/**
|
|
1776
|
-
* Plugin background-task orchestration.
|
|
1777
|
-
*
|
|
1778
|
-
* Core schedules tasks from completed sessions and exposes plugins only a
|
|
1779
|
-
* bounded run projection rather than live runtime internals or queue
|
|
1780
|
-
* payloads.
|
|
1781
|
-
*/
|
|
1782
|
-
var task_runner_exports = /* @__PURE__ */ __exportAll({
|
|
1783
|
-
processPluginTask: () => processPluginTask,
|
|
1784
|
-
scheduleSessionCompletedPluginTasks: () => scheduleSessionCompletedPluginTasks
|
|
1785
|
-
});
|
|
1786
|
-
const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
|
|
1787
|
-
function isRecord(value) {
|
|
1788
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
1789
|
-
}
|
|
1790
|
-
function textPart(value) {
|
|
1791
|
-
if (isRecord(value) && value.type === "text" && typeof value.text === "string") return value.text;
|
|
1792
|
-
}
|
|
1793
|
-
function messageText(message) {
|
|
1794
|
-
const content = message.content;
|
|
1795
|
-
if (typeof content === "string") return sanitizeText(content);
|
|
1796
|
-
if (!Array.isArray(content)) return "";
|
|
1797
|
-
return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
|
|
1798
|
-
}
|
|
1799
|
-
function toolResultText(message) {
|
|
1800
|
-
const record = message;
|
|
1801
|
-
return sanitizeText([
|
|
1802
|
-
messageText(message),
|
|
1803
|
-
record.output,
|
|
1804
|
-
record.result,
|
|
1805
|
-
record.stdout,
|
|
1806
|
-
record.stderr,
|
|
1807
|
-
record.toolResult
|
|
1808
|
-
].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
|
|
1809
|
-
}
|
|
1810
|
-
function sanitizeText(text) {
|
|
1811
|
-
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();
|
|
1812
|
-
}
|
|
1813
|
-
/** Build the transcript provenance for a user message from its Pi provenance. */
|
|
1814
|
-
function messageProvenance(provenance) {
|
|
1815
|
-
return {
|
|
1816
|
-
authority: provenance.authority,
|
|
1817
|
-
...provenance.actor ? { actor: provenance.actor } : void 0
|
|
1818
|
-
};
|
|
1819
|
-
}
|
|
1820
|
-
function runTranscriptEntry(message, provenance, runActor) {
|
|
1821
|
-
const role = getPiMessageRole(message);
|
|
1822
|
-
if (role === "user" || role === "assistant") {
|
|
1823
|
-
const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
|
|
1824
|
-
if (!text) return;
|
|
1825
|
-
if (role === "assistant") return {
|
|
1826
|
-
type: "message",
|
|
1827
|
-
role,
|
|
1828
|
-
text
|
|
1829
|
-
};
|
|
1830
|
-
return {
|
|
1831
|
-
type: "message",
|
|
1832
|
-
role,
|
|
1833
|
-
text,
|
|
1834
|
-
provenance: messageProvenance(provenance),
|
|
1835
|
-
isRunActor: sameActorIdentity(provenance.actor, runActor)
|
|
1836
|
-
};
|
|
1837
|
-
}
|
|
1838
|
-
if (!isToolResultMessage(message)) return;
|
|
1839
|
-
const toolName = normalizeToolNameFromResult(message);
|
|
1840
|
-
if (!toolName) return;
|
|
1841
|
-
const text = toolResultText(message);
|
|
1842
|
-
return {
|
|
1843
|
-
type: "toolResult",
|
|
1844
|
-
toolName,
|
|
1845
|
-
isError: isToolResultError(message),
|
|
1846
|
-
...text ? { text } : void 0
|
|
1847
|
-
};
|
|
1848
|
-
}
|
|
1849
|
-
/**
|
|
1850
|
-
* Slice the current turn's Pi messages with their aligned provenance and strip
|
|
1851
|
-
* runtime turn context, keeping each surviving message paired with the exact
|
|
1852
|
-
* provenance recorded for it. Stripping can drop or rewrite messages, so the
|
|
1853
|
-
* pairing is applied per message rather than by post-strip index.
|
|
1854
|
-
*/
|
|
1855
|
-
function turnMessagesWithProvenance(record) {
|
|
1856
|
-
const startIndex = record.turnStartMessageIndex ?? 0;
|
|
1857
|
-
const messages = record.piMessages.slice(startIndex);
|
|
1858
|
-
const provenance = record.piMessageProvenance.slice(startIndex);
|
|
1859
|
-
const paired = [];
|
|
1860
|
-
for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
|
|
1861
|
-
message: stripped,
|
|
1862
|
-
provenance: provenance[index] ?? { authority: "context" }
|
|
1863
|
-
});
|
|
1864
|
-
return paired;
|
|
1865
|
-
}
|
|
1866
|
-
/** Recover the Slack context author identity from a persisted thread message. */
|
|
1867
|
-
function slackContextAuthor(location, message) {
|
|
1868
|
-
const userId = message.author?.userId?.trim();
|
|
1869
|
-
if (!userId) return;
|
|
1870
|
-
return {
|
|
1871
|
-
platform: "slack",
|
|
1872
|
-
teamId: location.teamId,
|
|
1873
|
-
userId,
|
|
1874
|
-
...message.author?.userName ? { userName: message.author.userName } : void 0,
|
|
1875
|
-
...message.author?.fullName ? { fullName: message.author.fullName } : void 0
|
|
1876
|
-
};
|
|
1877
|
-
}
|
|
1878
|
-
function slackTimestampMs(value) {
|
|
1879
|
-
const timestamp = parseSlackMessageTs(value);
|
|
1880
|
-
if (!timestamp) return;
|
|
1881
|
-
const timestampMs = Number(timestamp) * 1e3;
|
|
1882
|
-
return Number.isFinite(timestampMs) ? timestampMs : void 0;
|
|
1883
|
-
}
|
|
1884
|
-
function conversationMessageTimestampMs(message) {
|
|
1885
|
-
if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
|
|
1886
|
-
return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
|
|
1887
|
-
}
|
|
1888
|
-
function messageExistedAtRunCompletion(message, completedAtMs) {
|
|
1889
|
-
const messageTimestampMs = conversationMessageTimestampMs(message);
|
|
1890
|
-
return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
|
|
1891
|
-
}
|
|
1892
|
-
/**
|
|
1893
|
-
* Project bounded public-thread context into the run transcript.
|
|
1894
|
-
*
|
|
1895
|
-
* Prior public Slack messages from the current Conversation are durable
|
|
1896
|
-
* evidence a completed run may have acted on, so passive consumers can cite
|
|
1897
|
-
* them. They are always context authority (never instruction), and private or
|
|
1898
|
-
* local Conversations add nothing here.
|
|
1899
|
-
*/
|
|
1900
|
-
async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
|
|
1901
|
-
if (location?.provider !== "slack" || visibility !== "public") return [];
|
|
1902
|
-
const conversation = coerceThreadConversationState(await getPersistedThreadState(record.conversationId));
|
|
1903
|
-
await hydrateConversationMessages({
|
|
1904
|
-
conversation,
|
|
1905
|
-
conversationId: record.conversationId
|
|
1906
|
-
});
|
|
1907
|
-
const entries = [];
|
|
1908
|
-
for (const message of conversation.messages) {
|
|
1909
|
-
if (message.role !== "user") continue;
|
|
1910
|
-
if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
|
|
1911
|
-
const text = sanitizeText(message.text);
|
|
1912
|
-
if (!text) continue;
|
|
1913
|
-
const author = slackContextAuthor(location, message);
|
|
1914
|
-
entries.push({
|
|
1915
|
-
type: "message",
|
|
1916
|
-
role: "user",
|
|
1917
|
-
text,
|
|
1918
|
-
provenance: {
|
|
1919
|
-
authority: "context",
|
|
1920
|
-
...author ? { actor: author } : void 0
|
|
1921
|
-
},
|
|
1922
|
-
isRunActor: sameActorIdentity(author, runActor)
|
|
1923
|
-
});
|
|
1924
|
-
}
|
|
1925
|
-
return entries;
|
|
1926
|
-
}
|
|
1927
|
-
async function withPluginTaskLock(taskId, callback) {
|
|
1928
|
-
const state = getStateAdapter();
|
|
1929
|
-
await state.connect();
|
|
1930
|
-
const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
|
|
1931
|
-
if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
|
|
1932
|
-
try {
|
|
1933
|
-
return await callback();
|
|
1934
|
-
} finally {
|
|
1935
|
-
await state.releaseLock(lock);
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
/** Load the bounded completed-run projection exposed to plugin tasks. */
|
|
1939
|
-
async function loadPluginRun(params) {
|
|
1940
|
-
const record = await getTurnRecord(params.conversationId, params.sessionId);
|
|
1941
|
-
if (!record) throw new Error("Completed plugin task session record is unavailable");
|
|
1942
|
-
if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
|
|
1943
|
-
const conversationStore = getConversationStore();
|
|
1944
|
-
const routing = await resolveConversationRouting({
|
|
1945
|
-
conversationId: params.conversationId,
|
|
1946
|
-
conversationStore
|
|
1947
|
-
});
|
|
1948
|
-
if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
|
|
1949
|
-
const source = record.source ?? routing.source;
|
|
1950
|
-
if (!source) throw new Error("Completed plugin task session record is missing Source");
|
|
1951
|
-
const conversation = await conversationStore.get({ conversationId: params.conversationId });
|
|
1952
|
-
const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
|
|
1953
|
-
const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
|
|
1954
|
-
const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
|
|
1955
|
-
const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
|
|
1956
|
-
const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
|
|
1957
|
-
return pluginRunContextSchema.parse({
|
|
1958
|
-
...actorUser ? { actorUserId: actorUser.id } : void 0,
|
|
1959
|
-
completedAtMs: record.updatedAtMs,
|
|
1960
|
-
conversationId: record.conversationId,
|
|
1961
|
-
destination: routing.destination,
|
|
1962
|
-
...routing.location ? { locationId: routing.location.id } : void 0,
|
|
1963
|
-
actors: record.actors,
|
|
1964
|
-
...runActor ? { actor: runActor } : void 0,
|
|
1965
|
-
runId: record.turnId,
|
|
1966
|
-
source,
|
|
1967
|
-
transcript: [...contextEntries, ...runEntries]
|
|
1968
|
-
});
|
|
1969
|
-
}
|
|
1970
|
-
/** Build the plugin-facing context for one claimed task attempt. */
|
|
1971
|
-
function taskPluginContext(plugin, message, options = {}) {
|
|
1972
|
-
const pluginName = plugin.manifest.name;
|
|
1973
|
-
const sessionParams = pluginTaskParamsSchema.parse(message.params);
|
|
1974
|
-
const onCost = createPluginModelCostRecorder({
|
|
1975
|
-
conversationId: sessionParams.conversationId,
|
|
1976
|
-
pluginName,
|
|
1977
|
-
source: "task",
|
|
1978
|
-
turnId: sessionParams.sessionId
|
|
1979
|
-
});
|
|
1980
|
-
return {
|
|
1981
|
-
db: getDb(),
|
|
1982
|
-
embedder: createPluginEmbedder(pluginName, {
|
|
1983
|
-
onCost,
|
|
1984
|
-
signal: options.signal
|
|
1985
|
-
}),
|
|
1986
|
-
events: createPluginConversationEvents({
|
|
1987
|
-
conversationId: sessionParams.conversationId,
|
|
1988
|
-
operationId: pluginTaskId(message),
|
|
1989
|
-
plugin,
|
|
1990
|
-
turnId: sessionParams.sessionId
|
|
1991
|
-
}),
|
|
1992
|
-
id: pluginTaskId(message),
|
|
1993
|
-
log: createPluginLogger(pluginName),
|
|
1994
|
-
model: createPluginModel(pluginName, plugin.model, {
|
|
1995
|
-
onCost,
|
|
1996
|
-
signal: options.signal
|
|
1997
|
-
}),
|
|
1998
|
-
name: message.name,
|
|
1999
|
-
plugin: { name: pluginName },
|
|
2000
|
-
cache: createPluginCache(pluginName),
|
|
2001
|
-
run: { async load() {
|
|
2002
|
-
return await loadPluginRun(sessionParams);
|
|
2003
|
-
} },
|
|
2004
|
-
state: createPluginState(pluginName)
|
|
2005
|
-
};
|
|
2006
|
-
}
|
|
2007
|
-
function findPluginTask(message) {
|
|
2008
|
-
const plugin = [...coreTaskRegistrations(), ...getPlugins()].find((candidate) => candidate.manifest.name === message.plugin);
|
|
2009
|
-
if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
|
|
2010
|
-
return {
|
|
2011
|
-
plugin,
|
|
2012
|
-
task: plugin.tasks[message.name]
|
|
2013
|
-
};
|
|
2014
|
-
}
|
|
2015
|
-
/** Schedule all plugin tasks interested in a completed agent-run session. */
|
|
2016
|
-
async function scheduleSessionCompletedPluginTasks(params, options = {}) {
|
|
2017
|
-
const coreParams = pluginTaskParamsSchema.parse(params);
|
|
2018
|
-
const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
|
|
2019
|
-
name,
|
|
2020
|
-
plugin
|
|
2021
|
-
})));
|
|
2022
|
-
if (taskRegistrations.length === 0) return;
|
|
2023
|
-
const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
|
|
2024
|
-
if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
|
|
2025
|
-
const send = options.send ?? sendVercelPluginTask;
|
|
2026
|
-
const messages = taskRegistrations.map(({ name, plugin }) => ({
|
|
2027
|
-
name,
|
|
2028
|
-
params: coreParams,
|
|
2029
|
-
plugin: plugin.manifest.name
|
|
2030
|
-
}));
|
|
2031
|
-
await Promise.all(messages.map(async (message) => {
|
|
2032
|
-
await send(message);
|
|
2033
|
-
}));
|
|
2034
|
-
}
|
|
2035
|
-
/**
|
|
2036
|
-
* Execute one parsed plugin task request in a `plugin.task` span. The span
|
|
2037
|
-
* includes the lock wait, because both delay the work that runs the task.
|
|
2038
|
-
*/
|
|
2039
|
-
async function processPluginTask(message, options = {}) {
|
|
2040
|
-
const params = pluginTaskParamsSchema.parse(message.params);
|
|
2041
|
-
await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
|
|
2042
|
-
const resolved = findPluginTask(message);
|
|
2043
|
-
if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
|
|
2044
|
-
await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
|
|
2045
|
-
}), {
|
|
2046
|
-
"app.ai.turn.session_id": params.sessionId,
|
|
2047
|
-
"app.plugin.name": message.plugin,
|
|
2048
|
-
"app.plugin.task": message.name
|
|
2049
|
-
});
|
|
2050
|
-
}
|
|
2051
|
-
export { readAutomationExecutionByConversationId as $, withScheduledAutomationLock as A, requireValidEventTrigger as At, setEventAutomationStatus as B, deleteScheduledAutomation as C, eventWatchUnavailable as Ct, saveScheduledAutomation as D, registeredEventTypeSchema as Dt, readScheduledAutomation as E, registeredEventTriggerProblems as Et, findMatchingEventAutomations as F, listAutomationVersions as G, eventAutomationRunLimitReason as H, getEventAutomation as I, AutomationConflictError as J, readAutomationVersion as K, listDeletedEventAutomationsCreatedBy as L, collectEventAutomationMatchKeys as M, createEventAutomation as N, saveScheduledAutomationInLock as O, registeredResourceTypeSchema as Ot, deleteEventAutomation as P, existingConversationId as Q, parseEventAutomationRow as R, createScheduledAutomation as S, eventNamespaceSchema as St, parseScheduledAutomationRow as T, registeredEventMatchSchema as Tt, automationDefinition as U, admitEventAutomationRun as V, automationVersionOf as W, requireAutomationRevision as X, automationRevision as Y, emptyAutomationRunWindows as Z, markDispatchBlocked as _, CORE_EVENT_NAMESPACE as _t, claimDispatchMailboxAppend as a, readAutomationTitlesByConversationId as at, markDispatchRunning as b, eventCatalogEntry as bt, getDispatchConversationId as c, conversationRangeColumns as ct, getDispatchRecord as d, getLocationConfigurationService as dt, readAutomationExecutionStatusDays as et, getDispatchTurnId as f, getPersistedSandboxState as ft, markDispatchAwaitingResume as g, coerceThreadConversationState as gt, listPendingDispatchMailboxAppends as h, persistThreadStateById as ht, buildDispatchId as i, readAutomationRuns as it, blockEventAutomation as j, scheduledRunId as k, requireEventIdentifier as kt, getDispatchIdForConversation as l, resolveConversationRouting as lt, isTerminalDispatchStatus as m, persistThreadRuntimeState as mt, scheduleSessionCompletedPluginTasks as n, readAutomationExecutionSummaries as nt, confirmDispatchMailboxAppend as o, recordAutomationExecution as ot, getPluginDispatchProjection as p, getPersistedThreadState as pt, sameDefinitionValue as q, task_runner_exports as r, readAutomationExecutions as rt, createOrGetDispatch as s, conversationAggregateColumns as st, processPluginTask as t, readAutomationExecutionStatusHours as tt, getDispatchInputMessageId as u, resolveTurnSessionRouting as ut, markDispatchCompleted as v, automationEventCatalog as vt, listScheduledAutomationsForTeam as w, hasEventCatalogEntries as wt, notifyAutomationBlocked as x, eventGuidance as xt, markDispatchFailed as y, describeRegisteredEventTrigger as yt, saveEventAutomation 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 };
|