@sentry/junior 0.285.0 → 0.286.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/{adapter-DN5AB4VU.js → adapter-JQZaJ-B_.js} +1 -1
- package/dist/{admin-DOITMKnn.js → admin-Dm2bimJ-.js} +1 -1
- package/dist/{agent-runner-BsWhHe4N.js → agent-runner-DGCwOEyL.js} +1567 -1048
- package/dist/api/schema.d.ts +1 -1
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +70 -92
- package/dist/{app-DyMs9330.d.ts → app-BKq0JzWx.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +37 -40
- package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-CAPafcUY.js} +1 -1
- package/dist/{automation-Mk8aaHzy.js → automation-B-jJN_gM.js} +1 -1
- package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-Btu2oab_.js} +137 -3
- package/dist/{briefs-Cl8-nK9B.js → briefs-UMeYehUe.js} +4 -4
- package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-Bym8GVdh.js} +1 -1
- package/dist/cli/chat.js +14 -14
- 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 +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{client-DDbBucBw.js → client-B0aAs7wC.js} +2 -2
- package/dist/{config-DqFnykQT.js → config-B9f9Lqo5.js} +1 -1
- package/dist/{connections-DA4LT9LL.js → connections-CQ7p0aNJ.js} +16 -50
- package/dist/{conversation-D8kVoCrP.js → conversation-BusI2uzj.js} +15 -6
- package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
- package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-Cd_nZZBM.js} +1 -1
- package/dist/{credential-sync-hcsYatw-.js → credential-sync-DmiJi_At.js} +13 -13
- package/dist/{db-BhHZSuFw.d.ts → db-C5zi4ecs.d.ts} +4 -4
- package/dist/{executor-BLEMIgIZ.js → executor-Dipi2Ixl.js} +11 -17
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BfORLKoq.js → logging-CMFhLLj4.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
- package/dist/{message-DqjuKzUx.js → message-D1xLljUF.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-DCAFIUQr.js} +2 -2
- package/dist/{projection-DliWYrnT.js → projection-CoeMNxJ4.js} +286 -212
- package/dist/{prompt-BvIUzY4y.js → prompt-C9OQEfan.js} +1 -1
- package/dist/{registry-rC7MCxu8.js → registry-u-sFYtx_.js} +1 -1
- package/dist/{resolve-Biu8Qw3u.js → resolve-DYqgL3Eo.js} +3 -3
- package/dist/{result-DxJMCX47.js → result-CescSwAw.js} +8 -8
- package/dist/{runner-BQJSFLKg.js → runner-Cr67a8TB.js} +16 -12
- package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
- package/dist/{schema-BasXTvi2.js → schema-BUSi3sgv.js} +5 -5
- package/dist/{schema-BUviRAs8.d.ts → schema-Ih60j59-.d.ts} +44 -7
- package/dist/{service-account-BI5Wgx22.js → service-account-CGEqz9wG.js} +3 -3
- package/dist/{service-account-CAE-_1dR.js → service-account-CsKxktLk.js} +3 -3
- package/dist/{session-stop-CA-jOJ84.js → session-stop-CGz5DByb.js} +22 -20
- package/dist/{skills-B22duVJU.js → skills-COCqf61f.js} +2 -2
- package/dist/{spawn-BB2_4VYn.js → spawn-C8F_iXWO.js} +13 -2
- package/dist/{stop-DioIcEAu.js → stop-GyFZkHuQ.js} +242 -952
- package/dist/{store-Dn4W7qgH.js → store-D0-8plWp.js} +3 -3
- package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-xPuQmEot.js} +1439 -993
- package/dist/{store-B26LV6UP.js → turn-failure-response-BOviBdT-.js} +331 -5
- package/dist/{validation-TzhfQABF.js → validation-DZDKorGz.js} +1 -1
- package/dist/{version-DSk8CFvA.js → version-BTIz7fGi.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-1Ea81s0b.js → viewer-CH-ASQzh.js} +39 -36
- package/dist/{work-ybG4_q5C.js → work-C75_IM5e.js} +92 -87
- package/dist/{worker-ccSyZRNz.js → worker-Dl47I729.js} +6 -6
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +5 -4
- package/dist/task-queue-Bt0IoR2i.js +0 -139
- package/dist/task-runner-D8lddjzp.js +0 -290
- package/dist/thread-state-CrFk3K_7.js +0 -173
- package/dist/turn-failure-response-DaJ04qVj.js +0 -224
- package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
|
@@ -1,15 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
1
|
+
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
+
import { Bi as formatSlackLink, Ji as openSlackDirectMessage, La as createPluginEmbedder, Mo as createPluginCache, No as createDurableLocationConfigurationService, Qn as coreTaskRegistrations, Ra as createPluginModel, T as fallbackShortTitle, Xa as createPluginModelCostRecorder, Yn as getPlugins, Za as createPluginLogger, Zi as postSlackMessage, Zt as getPiMessageRole, ai as JUNIOR_THREAD_STATE_TTL_MS, b as persistConversationMessages, cn as normalizeToolNameFromResult, fi as ToolInputError, it as getTurnRecord, nn as instructionTextForProjection, on as isToolResultError, pi as createPluginState, sn as isToolResultMessage, so as createPluginConversationEvents, ui as getDashboardTaskLink, un as stripRuntimeTurnContext, v as hydrateConversationMessages, zi as escapeSlackMrkdwnText } from "./projection-CoeMNxJ4.js";
|
|
3
|
+
import { n as botConfig } from "./config-B9f9Lqo5.js";
|
|
4
|
+
import { E as withSpan, G as toOptionalNumber, K as toOptionalString, W as isRecord$1, _ as runBestEffort, h as logWarn } from "./logging-CMFhLLj4.js";
|
|
5
|
+
import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
|
|
6
|
+
import { S as getDb, i as readActorIdentity, it as agentTurnTotalTokens, rt as agentTurnCostUsd, x as getConversationStore } from "./viewer-CH-ASQzh.js";
|
|
7
|
+
import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-Dipi2Ixl.js";
|
|
8
|
+
import { v as sameActorIdentity } from "./media-B-BpXo41.js";
|
|
9
|
+
import { h as credentialSubjectSchema } from "./registry-u-sFYtx_.js";
|
|
10
|
+
import { r as getStateAdapter } from "./adapter-JQZaJ-B_.js";
|
|
11
|
+
import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-Btu2oab_.js";
|
|
12
|
+
import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-B-jJN_gM.js";
|
|
9
13
|
import { createHash } from "node:crypto";
|
|
10
14
|
import * as z from "zod";
|
|
11
15
|
import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
|
|
12
|
-
import { agentEventMatchSchema, anyResourceMatchFields, describeEventTrigger, destinationSchema, destinationVisibilitySchema, eventMatches, eventTriggerChoices, eventTriggerProblems, isSlackDestination, normalizeEventIdentifier, normalizeEventMatch, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
|
|
16
|
+
import { agentEventMatchSchema, anyResourceMatchFields, describeEventTrigger, destinationSchema, destinationVisibilitySchema, eventMatches, eventTriggerChoices, eventTriggerProblems, isSlackDestination, normalizeEventIdentifier, normalizeEventMatch, pluginRunContextSchema, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
|
|
13
17
|
// src/chat/events/catalog.ts
|
|
14
18
|
/** A source with nothing enabled, for a namespace that the catalog lacks. */
|
|
15
19
|
const NO_SOURCE = {
|
|
@@ -143,1053 +147,1293 @@ function requireEventIdentifier(catalog, input) {
|
|
|
143
147
|
const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
|
|
144
148
|
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(" "));
|
|
145
149
|
}
|
|
146
|
-
// src/chat/
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
};
|
|
154
|
-
/** Sort object keys so equal values produce equal JSON. */
|
|
155
|
-
function canonicalJson(value) {
|
|
156
|
-
if (Array.isArray(value)) return value.map(canonicalJson);
|
|
157
|
-
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalJson(child)]));
|
|
158
|
-
return value;
|
|
159
|
-
}
|
|
160
|
-
/** Identify the stored values being edited, including lifecycle and creator authority. */
|
|
161
|
-
function automationRevision(task) {
|
|
162
|
-
return createHash("sha256").update(JSON.stringify(canonicalJson(task))).digest("hex");
|
|
163
|
-
}
|
|
164
|
-
/** Reject a stale edit while the storage owner holds the write lock. */
|
|
165
|
-
function requireAutomationRevision(task, revision) {
|
|
166
|
-
if (!task || automationRevision(task) !== revision) throw new AutomationConflictError();
|
|
150
|
+
// src/chat/state/conversation.ts
|
|
151
|
+
function defaultConversationState() {
|
|
152
|
+
return {
|
|
153
|
+
schemaVersion: 1,
|
|
154
|
+
messages: [],
|
|
155
|
+
processing: {},
|
|
156
|
+
vision: { byFileId: {} }
|
|
157
|
+
};
|
|
167
158
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
159
|
+
function coercePendingAuthState(value) {
|
|
160
|
+
if (!isRecord$1(value)) return;
|
|
161
|
+
const kind = value.kind;
|
|
162
|
+
const provider = toOptionalString(value.provider);
|
|
163
|
+
const actorId = toOptionalString(value.actorId);
|
|
164
|
+
const authSessionId = toOptionalString(value.authSessionId);
|
|
165
|
+
const scope = toOptionalString(value.scope);
|
|
166
|
+
const sessionId = toOptionalString(value.sessionId);
|
|
167
|
+
const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
|
|
168
|
+
if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
|
|
169
|
+
const base = {
|
|
170
|
+
provider,
|
|
171
|
+
actorId,
|
|
172
|
+
...scope ? { scope } : void 0,
|
|
173
|
+
sessionId,
|
|
174
|
+
linkSentAtMs
|
|
178
175
|
};
|
|
179
|
-
return "
|
|
180
|
-
...
|
|
181
|
-
|
|
176
|
+
return kind === "mcp" ? {
|
|
177
|
+
...base,
|
|
178
|
+
authSessionId,
|
|
179
|
+
kind
|
|
182
180
|
} : {
|
|
183
|
-
...
|
|
184
|
-
|
|
181
|
+
...base,
|
|
182
|
+
kind
|
|
185
183
|
};
|
|
186
184
|
}
|
|
187
|
-
/**
|
|
188
|
-
function
|
|
189
|
-
|
|
185
|
+
/** Safely coerce an unknown persisted value into a ThreadConversationState. */
|
|
186
|
+
function coerceThreadConversationState(value) {
|
|
187
|
+
if (!isRecord$1(value)) return defaultConversationState();
|
|
188
|
+
const root = value;
|
|
189
|
+
const rawConversation = isRecord$1(root.conversation) ? root.conversation : {};
|
|
190
|
+
const messages = [];
|
|
191
|
+
const rawProcessing = isRecord$1(rawConversation.processing) ? rawConversation.processing : {};
|
|
192
|
+
const processing = {
|
|
193
|
+
activeTurnId: toOptionalString(rawProcessing.activeTurnId),
|
|
194
|
+
lastCompletedAtMs: toOptionalNumber(rawProcessing.lastCompletedAtMs),
|
|
195
|
+
pendingAuth: coercePendingAuthState(rawProcessing.pendingAuth)
|
|
196
|
+
};
|
|
197
|
+
const rawVision = isRecord$1(rawConversation.vision) ? rawConversation.vision : {};
|
|
198
|
+
const rawVisionByFileId = isRecord$1(rawVision.byFileId) ? rawVision.byFileId : {};
|
|
199
|
+
const byFileId = {};
|
|
200
|
+
for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
|
|
201
|
+
if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
|
|
202
|
+
if (!isRecord$1(value)) continue;
|
|
203
|
+
const summary = toOptionalString(value.summary);
|
|
204
|
+
const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
|
|
205
|
+
if (!summary || !analyzedAtMs) continue;
|
|
206
|
+
byFileId[fileId] = {
|
|
207
|
+
summary,
|
|
208
|
+
analyzedAtMs
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
schemaVersion: 1,
|
|
213
|
+
messages,
|
|
214
|
+
processing,
|
|
215
|
+
vision: {
|
|
216
|
+
backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
|
|
217
|
+
byFileId
|
|
218
|
+
}
|
|
219
|
+
};
|
|
190
220
|
}
|
|
191
221
|
/**
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
222
|
+
* Wrap active conversation control into the thread scratch envelope.
|
|
223
|
+
*
|
|
224
|
+
* Visible history lives in SQL. Image summaries use a separate disposable
|
|
225
|
+
* cache, so thread scratch does not retain them.
|
|
195
226
|
*/
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
227
|
+
function buildConversationStatePatch(conversation) {
|
|
228
|
+
return { conversation: {
|
|
229
|
+
schemaVersion: 1,
|
|
230
|
+
processing: { ...conversation.processing }
|
|
231
|
+
} };
|
|
232
|
+
}
|
|
233
|
+
// src/chat/runtime/thread-state.ts
|
|
234
|
+
function threadStateKey(threadId) {
|
|
235
|
+
return `thread-state:${threadId}`;
|
|
236
|
+
}
|
|
237
|
+
function channelStateKey(channelId) {
|
|
238
|
+
return `channel-state:${channelId}`;
|
|
239
|
+
}
|
|
240
|
+
function buildThreadStatePayload(patch) {
|
|
241
|
+
const payload = {};
|
|
242
|
+
if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
|
|
243
|
+
if (patch.sandboxRef !== void 0) {
|
|
244
|
+
payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
|
|
245
|
+
payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
|
|
246
|
+
payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
|
|
247
|
+
}
|
|
248
|
+
return payload;
|
|
210
249
|
}
|
|
211
250
|
/**
|
|
212
|
-
*
|
|
251
|
+
* Merge a payload into thread scratch with Junior's TTL.
|
|
213
252
|
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
* no saved version has this definition.
|
|
253
|
+
* Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
|
|
254
|
+
* shorter retention policy for the same scratch keys.
|
|
217
255
|
*/
|
|
218
|
-
function
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
return
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
definition: row.definition
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
/** Read one saved definition. */
|
|
243
|
-
async function readAutomationVersion(db, automationId, version) {
|
|
244
|
-
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);
|
|
245
|
-
return row ? parseVersionRow(row) : void 0;
|
|
246
|
-
}
|
|
247
|
-
/** Read saved definitions, newest first. */
|
|
248
|
-
async function listAutomationVersions(db, automationId, limit) {
|
|
249
|
-
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);
|
|
250
|
-
}
|
|
251
|
-
// src/chat/event-automations/run-limit.ts
|
|
252
|
-
const RUN_LIST_PREFIX = "junior:event_automation_runs:v1";
|
|
253
|
-
const RUN_LIST_BURST_ROOM = 100;
|
|
254
|
-
const runEntrySchema = z.union([z.object({
|
|
255
|
-
atMs: z.number().finite(),
|
|
256
|
-
id: z.string().min(1)
|
|
257
|
-
}).strict(), z.object({ reset: z.literal(true) }).strict()]);
|
|
258
|
-
function runListKey(automationId) {
|
|
259
|
-
return `${RUN_LIST_PREFIX}:${automationId}`;
|
|
260
|
-
}
|
|
261
|
-
function runListMaxLength() {
|
|
262
|
-
return botConfig.maxEventAutomationRuns + RUN_LIST_BURST_ROOM;
|
|
256
|
+
async function mergePersistedState(key, payload) {
|
|
257
|
+
if (Object.keys(payload).length === 0) return;
|
|
258
|
+
const stateAdapter = getStateAdapter();
|
|
259
|
+
await stateAdapter.connect();
|
|
260
|
+
const existing = await stateAdapter.get(key) ?? {};
|
|
261
|
+
await stateAdapter.set(key, {
|
|
262
|
+
...existing,
|
|
263
|
+
...payload
|
|
264
|
+
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
265
|
+
}
|
|
266
|
+
/** Extract persisted sandbox metadata from thread state payload. */
|
|
267
|
+
function getPersistedSandboxState(state) {
|
|
268
|
+
const id = toOptionalString(state.app_sandbox_id);
|
|
269
|
+
if (!id) return;
|
|
270
|
+
const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
|
|
271
|
+
const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
|
|
272
|
+
return {
|
|
273
|
+
id,
|
|
274
|
+
...profileHash ? { profileHash } : void 0,
|
|
275
|
+
...workspaceId ? { workspaceId } : void 0
|
|
276
|
+
};
|
|
263
277
|
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
await
|
|
267
|
-
|
|
268
|
-
|
|
278
|
+
/** Persist only the Redis-backed runtime scratch in a thread-state patch. */
|
|
279
|
+
async function persistThreadRuntimeState(conversationId, patch) {
|
|
280
|
+
await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
|
|
281
|
+
}
|
|
282
|
+
/** Load the persisted state payload for a thread without requiring a Chat singleton. */
|
|
283
|
+
async function getPersistedThreadState(threadId) {
|
|
284
|
+
const stateAdapter = getStateAdapter();
|
|
285
|
+
await stateAdapter.connect();
|
|
286
|
+
return await stateAdapter.get(threadStateKey(threadId)) ?? {};
|
|
287
|
+
}
|
|
288
|
+
/** Persist a thread-state patch by thread id without constructing a Chat thread. */
|
|
289
|
+
async function persistThreadStateById(threadId, patch) {
|
|
290
|
+
if (patch.conversation) await persistConversationMessages({
|
|
291
|
+
conversation: patch.conversation,
|
|
292
|
+
conversationId: threadId
|
|
269
293
|
});
|
|
294
|
+
await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
|
|
270
295
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
["second", 1e3]
|
|
277
|
-
]) if (windowMs % unitMs === 0) {
|
|
278
|
-
const count = windowMs / unitMs;
|
|
279
|
-
return count === 1 ? unit : `${count} ${unit}s`;
|
|
280
|
-
}
|
|
281
|
-
return `${windowMs} ms`;
|
|
282
|
-
}
|
|
283
|
-
/** Reason stored on an Event automation that the run limit blocked. */
|
|
284
|
-
function eventAutomationRunLimitReason() {
|
|
285
|
-
const window = describeRunWindow(botConfig.eventAutomationRunWindowMs);
|
|
286
|
-
return `This automation reached its limit of ${botConfig.maxEventAutomationRuns} runs per ${window}. Check that its trigger is not too broad, then resume it.`;
|
|
287
|
-
}
|
|
288
|
-
function hasRunKey(entries, runKey) {
|
|
289
|
-
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
290
|
-
const entry = entries[index];
|
|
291
|
-
if ("reset" in entry) return false;
|
|
292
|
-
if (entry.id === runKey) return true;
|
|
293
|
-
}
|
|
294
|
-
return false;
|
|
296
|
+
/** Load legacy Redis-backed channel state during the SQL cutover. */
|
|
297
|
+
async function getLegacyChannelState(channelId) {
|
|
298
|
+
const stateAdapter = getStateAdapter();
|
|
299
|
+
await stateAdapter.connect();
|
|
300
|
+
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
295
301
|
}
|
|
296
302
|
/**
|
|
297
|
-
*
|
|
303
|
+
* Resolve durable location configuration.
|
|
298
304
|
*
|
|
299
|
-
*
|
|
300
|
-
* Event does not count again.
|
|
305
|
+
* Slack still reads the old channel-id Redis bag once during cutover.
|
|
301
306
|
*/
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
entries: values.flatMap((value) => {
|
|
309
|
-
const entry = runEntrySchema.safeParse(value);
|
|
310
|
-
return entry.success ? [entry.data] : [];
|
|
311
|
-
}),
|
|
312
|
-
length: values.length
|
|
313
|
-
};
|
|
314
|
-
};
|
|
315
|
-
if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
|
|
316
|
-
atMs: args.nowMs,
|
|
317
|
-
id: args.runKey
|
|
318
|
-
});
|
|
319
|
-
const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
|
|
320
|
-
const { entries, length } = await readEntries();
|
|
321
|
-
let lastReset = -1;
|
|
322
|
-
entries.forEach((entry, index) => {
|
|
323
|
-
if ("reset" in entry) lastReset = index;
|
|
307
|
+
function getLocationConfigurationService(destination) {
|
|
308
|
+
if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
|
|
309
|
+
return createDurableLocationConfigurationService({
|
|
310
|
+
destination,
|
|
311
|
+
db: getDb(),
|
|
312
|
+
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
324
313
|
});
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
314
|
+
}
|
|
315
|
+
// src/chat/services/turn-session-routing.ts
|
|
316
|
+
async function loadConversationChain(conversationId, conversationStore) {
|
|
317
|
+
const chain = [];
|
|
318
|
+
const seen = /* @__PURE__ */ new Set();
|
|
319
|
+
let cursor = conversationId;
|
|
320
|
+
while (cursor && !seen.has(cursor)) {
|
|
321
|
+
seen.add(cursor);
|
|
322
|
+
const conversation = await conversationStore.get({ conversationId: cursor });
|
|
323
|
+
if (!conversation) break;
|
|
324
|
+
chain.push(conversation);
|
|
325
|
+
cursor = conversation.parentConversationId;
|
|
332
326
|
}
|
|
333
|
-
return
|
|
327
|
+
return chain;
|
|
334
328
|
}
|
|
335
329
|
/**
|
|
336
|
-
*
|
|
330
|
+
* Normalize a stored Slack session source against the conversation destination.
|
|
337
331
|
*
|
|
338
|
-
*
|
|
339
|
-
* Call it before the automation becomes active, so an Event cannot see the
|
|
340
|
-
* old full count and block it again.
|
|
332
|
+
* Does not create channel or thread values from the conversation id.
|
|
341
333
|
*/
|
|
342
|
-
|
|
343
|
-
|
|
334
|
+
function slackSourceForDestination(args) {
|
|
335
|
+
if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
|
|
336
|
+
const threadTs = args.source.threadTs?.trim();
|
|
337
|
+
return {
|
|
338
|
+
kind: "slack",
|
|
339
|
+
visibility: args.source.visibility ?? "public",
|
|
340
|
+
teamId: args.source.teamId?.trim() || args.destination.teamId,
|
|
341
|
+
channelId: args.source.channelId,
|
|
342
|
+
...threadTs ? { threadTs } : void 0
|
|
343
|
+
};
|
|
344
344
|
}
|
|
345
|
-
// src/chat/event-automations/store.ts
|
|
346
345
|
/**
|
|
347
|
-
*
|
|
348
|
-
*
|
|
346
|
+
* Resolve the Conversation Location, Destination, and session Source.
|
|
347
|
+
*
|
|
348
|
+
* Reads parent Conversations when this Conversation has no Destination.
|
|
349
349
|
*/
|
|
350
|
-
function
|
|
351
|
-
const
|
|
352
|
-
const
|
|
350
|
+
async function resolveConversationRouting(args) {
|
|
351
|
+
const conversationStore = args.conversationStore ?? (await import("./viewer-CH-ASQzh.js").then((n) => n.v)).getConversationStore();
|
|
352
|
+
const chain = await loadConversationChain(args.conversationId, conversationStore);
|
|
353
|
+
let destination;
|
|
354
|
+
let source;
|
|
355
|
+
let location;
|
|
356
|
+
for (const conversation of chain) {
|
|
357
|
+
destination ??= conversation.destination;
|
|
358
|
+
source ??= conversation.sessionSource;
|
|
359
|
+
location ??= conversation.location;
|
|
360
|
+
if (destination && source) break;
|
|
361
|
+
}
|
|
362
|
+
if (!destination) return;
|
|
363
|
+
if (destination.platform === "slack") {
|
|
364
|
+
const slackSource = slackSourceForDestination({
|
|
365
|
+
destination,
|
|
366
|
+
source
|
|
367
|
+
});
|
|
368
|
+
return {
|
|
369
|
+
destination,
|
|
370
|
+
...location ? { location } : void 0,
|
|
371
|
+
...slackSource ? { source: slackSource } : void 0
|
|
372
|
+
};
|
|
373
|
+
}
|
|
353
374
|
return {
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
identifier: record.trigger.identifier ?? null,
|
|
358
|
-
instruction: record.task.text,
|
|
359
|
-
namespace: record.trigger.namespace,
|
|
360
|
-
record,
|
|
361
|
-
teamId: record.destination.teamId,
|
|
362
|
-
title: title?.trim() || null
|
|
375
|
+
destination,
|
|
376
|
+
...location ? { location } : void 0,
|
|
377
|
+
...source ? { source } : void 0
|
|
363
378
|
};
|
|
364
379
|
}
|
|
365
|
-
|
|
380
|
+
/** Require the Conversation Destination and Source from SQL. */
|
|
381
|
+
async function resolveTurnSessionRouting(args) {
|
|
382
|
+
const routing = await resolveConversationRouting(args);
|
|
383
|
+
if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
|
|
366
384
|
return {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
id: row.id
|
|
385
|
+
destination: routing.destination,
|
|
386
|
+
...routing.location ? { location: routing.location } : void 0,
|
|
387
|
+
source: routing.source
|
|
371
388
|
};
|
|
372
389
|
}
|
|
373
|
-
|
|
374
|
-
function
|
|
375
|
-
return
|
|
390
|
+
// src/api/conversations/aggregate.ts
|
|
391
|
+
function usageTokenValue(source, field) {
|
|
392
|
+
return sql`CASE
|
|
393
|
+
WHEN ${source.usage}->>${field} IS NOT NULL
|
|
394
|
+
THEN (${source.usage}->>${field})::double precision
|
|
395
|
+
ELSE NULL
|
|
396
|
+
END`;
|
|
376
397
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
398
|
+
function tokenValue(source) {
|
|
399
|
+
return sql`
|
|
400
|
+
CASE
|
|
401
|
+
WHEN COALESCE(
|
|
402
|
+
${source.usage}->>'inputTokens',
|
|
403
|
+
${source.usage}->>'outputTokens',
|
|
404
|
+
${source.usage}->>'cachedInputTokens',
|
|
405
|
+
${source.usage}->>'cacheCreationTokens'
|
|
406
|
+
) IS NOT NULL
|
|
407
|
+
THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
|
|
408
|
+
+ COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
|
|
409
|
+
+ COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
|
|
410
|
+
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
411
|
+
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
412
|
+
THEN (${source.usage}->>'totalTokens')::double precision
|
|
413
|
+
ELSE NULL
|
|
414
|
+
END
|
|
415
|
+
`;
|
|
389
416
|
}
|
|
390
|
-
function
|
|
391
|
-
|
|
417
|
+
function costValue(source) {
|
|
418
|
+
return conversationUsageCostExpr(source.usage);
|
|
419
|
+
}
|
|
420
|
+
/** Read one conversation row's usage cost as a SQL expression. */
|
|
421
|
+
function conversationUsageCostExpr(usage) {
|
|
422
|
+
return sql`
|
|
423
|
+
CASE
|
|
424
|
+
WHEN ${usage}->'cost'->>'total' IS NOT NULL
|
|
425
|
+
THEN (${usage}->'cost'->>'total')::double precision
|
|
426
|
+
WHEN COALESCE(
|
|
427
|
+
${usage}->'cost'->>'input',
|
|
428
|
+
${usage}->'cost'->>'output',
|
|
429
|
+
${usage}->'cost'->>'cacheRead',
|
|
430
|
+
${usage}->'cost'->>'cacheWrite'
|
|
431
|
+
) IS NOT NULL
|
|
432
|
+
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
433
|
+
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
434
|
+
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
435
|
+
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
436
|
+
ELSE NULL
|
|
437
|
+
END
|
|
438
|
+
`;
|
|
439
|
+
}
|
|
440
|
+
/** Select complete conversation metrics inside the database instead of materializing source rows. */
|
|
441
|
+
function conversationAggregateColumns(sources) {
|
|
442
|
+
const metrics = sources?.metrics ?? juniorConversations;
|
|
443
|
+
const roots = sources?.roots ?? juniorConversations;
|
|
444
|
+
const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
|
|
392
445
|
return {
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
446
|
+
active: sql`${conversationCount} FILTER (
|
|
447
|
+
WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
|
|
448
|
+
)::integer`,
|
|
449
|
+
conversations: sql`${conversationCount}::integer`,
|
|
450
|
+
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
451
|
+
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
452
|
+
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
453
|
+
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
454
|
+
failed: sql`${conversationCount} FILTER (
|
|
455
|
+
WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
|
|
456
|
+
)::integer`,
|
|
457
|
+
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
458
|
+
tokens: sql`SUM(${tokenValue(metrics)})::double precision`
|
|
397
459
|
};
|
|
398
460
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
461
|
+
/** Select the complete first/last activity range for a grouped conversation aggregate. */
|
|
462
|
+
function conversationRangeColumns() {
|
|
463
|
+
return {
|
|
464
|
+
firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
|
|
465
|
+
lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
|
|
466
|
+
};
|
|
404
467
|
}
|
|
405
|
-
/**
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
468
|
+
/** Count distinct UTC activity dates without loading conversation timestamps into the app. */
|
|
469
|
+
function conversationActiveDaysColumn() {
|
|
470
|
+
return sql`COUNT(DISTINCT (${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC')::date)::integer`;
|
|
409
471
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
kind: "event",
|
|
420
|
-
status: "active"
|
|
421
|
-
}).onConflictDoNothing().returning();
|
|
422
|
-
if (inserted[0]) {
|
|
423
|
-
const created = parseEventAutomationRow(inserted[0]);
|
|
424
|
-
await recordAutomationVersion(tx, created, void 0);
|
|
425
|
-
return created;
|
|
426
|
-
}
|
|
427
|
-
const existing = await getEventAutomation(tx, task.id);
|
|
428
|
-
if (!existing) throw new Error(`Automation ${task.id} already exists with another kind.`);
|
|
429
|
-
if (existing.status !== "deleted") return existing;
|
|
430
|
-
const rows = await tx.update(juniorAutomations).set({
|
|
431
|
-
...columns,
|
|
432
|
-
status: "active",
|
|
433
|
-
statusReason: null
|
|
434
|
-
}).where(and(eventAutomationWhere(task.id), eq(juniorAutomations.status, "deleted"))).returning();
|
|
435
|
-
if (!rows[0]) return await getEventAutomation(tx, task.id);
|
|
436
|
-
const revived = parseEventAutomationRow(rows[0]);
|
|
437
|
-
await recordAutomationVersion(tx, revived, void 0);
|
|
438
|
-
return revived;
|
|
439
|
-
});
|
|
472
|
+
// src/chat/automations/execution-stats.ts
|
|
473
|
+
const AUTOMATION_EXECUTION_STATUSES = [
|
|
474
|
+
"blocked",
|
|
475
|
+
"completed",
|
|
476
|
+
"failed"
|
|
477
|
+
];
|
|
478
|
+
/** An execution is a run with an outcome. Skipped runs are not executions. */
|
|
479
|
+
function isExecution() {
|
|
480
|
+
return and(inArray(juniorAutomationRuns.status, [...AUTOMATION_EXECUTION_STATUSES]), isNotNull(juniorAutomationRuns.completedAtMs));
|
|
440
481
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
444
|
-
*/
|
|
445
|
-
async function saveEventAutomation(db, task, expectedRevision, editedBy) {
|
|
446
|
-
const columns = eventAutomationColumns(task);
|
|
447
|
-
return db.transaction(async (tx) => {
|
|
448
|
-
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(task.id)).for("update");
|
|
449
|
-
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
450
|
-
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
451
|
-
if (!current || current.status === "deleted") return void 0;
|
|
452
|
-
const saved = parseEventAutomationRow((await tx.update(juniorAutomations).set(columns).where(eventAutomationWhere(task.id)).returning())[0]);
|
|
453
|
-
await recordAutomationVersion(tx, saved, current, editedBy);
|
|
454
|
-
return saved;
|
|
455
|
-
});
|
|
482
|
+
function addUsd(current, next) {
|
|
483
|
+
return Math.round((current + next) * 0xe8d4a51000) / 0xe8d4a51000;
|
|
456
484
|
}
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
485
|
+
const EMPTY_RUN_WINDOWS = {
|
|
486
|
+
1: 0,
|
|
487
|
+
7: 0,
|
|
488
|
+
30: 0,
|
|
489
|
+
90: 0
|
|
490
|
+
};
|
|
491
|
+
/** Empty run or cost windows for automations with no execution history. */
|
|
492
|
+
function emptyAutomationRunWindows() {
|
|
493
|
+
return { ...EMPTY_RUN_WINDOWS };
|
|
461
494
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
* Used only to keep historical runs after the live automation list drops the row.
|
|
465
|
-
*/
|
|
466
|
-
async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
|
|
467
|
-
const identityIds = user.identities.map((identity) => identity.id);
|
|
468
|
-
if (identityIds.length === 0) return [];
|
|
469
|
-
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);
|
|
495
|
+
function utcDate(nowMs) {
|
|
496
|
+
return new Date(nowMs).toISOString().slice(0, 10);
|
|
470
497
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
498
|
+
function emptyDay(date) {
|
|
499
|
+
return {
|
|
500
|
+
costUsd: 0,
|
|
501
|
+
date,
|
|
502
|
+
event: 0,
|
|
503
|
+
scheduled: 0
|
|
504
|
+
};
|
|
478
505
|
}
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
506
|
+
function emptyStatusDay(date) {
|
|
507
|
+
return {
|
|
508
|
+
blocked: 0,
|
|
509
|
+
completed: 0,
|
|
510
|
+
date,
|
|
511
|
+
failed: 0
|
|
512
|
+
};
|
|
482
513
|
}
|
|
483
514
|
/**
|
|
484
|
-
* Return
|
|
485
|
-
*
|
|
486
|
-
*
|
|
487
|
-
* The identifier column and the saved trigger must agree. A row with no
|
|
488
|
-
* identifier must also have a trigger that the enabled `catalog` accepts. A
|
|
489
|
-
* plugin can later require a filter or stop letting an event run for every
|
|
490
|
-
* resource, and the row must not stay broad.
|
|
515
|
+
* Return the Conversation id when that Conversation exists, else null. A
|
|
516
|
+
* dispatch can end before it creates its Conversation, and the run's
|
|
517
|
+
* `conversation_id` is a foreign key.
|
|
491
518
|
*/
|
|
492
|
-
function
|
|
493
|
-
|
|
494
|
-
if (identifier !== void 0) return identifier === row.identifier && identifiers.includes(identifier) ? void 0 : "The saved trigger has a different identifier from its row.";
|
|
495
|
-
if (row.identifier !== null) return "The saved trigger has no identifier, but its row has one.";
|
|
496
|
-
const problems = registeredEventTriggerProblems(catalog, task.trigger);
|
|
497
|
-
return problems.length > 0 ? problems.map((problem) => problem.message).join(" ") : void 0;
|
|
519
|
+
function existingConversationId(conversationId) {
|
|
520
|
+
return sql`(select ${juniorConversations.conversationId} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
|
|
498
521
|
}
|
|
499
522
|
/**
|
|
500
|
-
*
|
|
501
|
-
*
|
|
502
|
-
*
|
|
503
|
-
* not parse or that the gate rejects.
|
|
523
|
+
* Record the outcome of one Automation run. A run that already has an outcome
|
|
524
|
+
* keeps it. A failed write is logged, and the heartbeat settles a started
|
|
525
|
+
* event run later.
|
|
504
526
|
*/
|
|
505
|
-
async function
|
|
506
|
-
const
|
|
507
|
-
const
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
527
|
+
async function recordAutomationExecution(automationId, options) {
|
|
528
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
529
|
+
const status = options.status ?? "completed";
|
|
530
|
+
const outcome = {
|
|
531
|
+
completedAtMs: nowMs,
|
|
532
|
+
errorMessage: options.errorMessage ?? null,
|
|
533
|
+
status
|
|
534
|
+
};
|
|
535
|
+
try {
|
|
536
|
+
await getDb().insert(juniorAutomationRuns).values({
|
|
537
|
+
id: options.executionId,
|
|
538
|
+
automationId,
|
|
539
|
+
conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
|
|
540
|
+
...outcome
|
|
541
|
+
}).onConflictDoUpdate({
|
|
542
|
+
target: juniorAutomationRuns.id,
|
|
543
|
+
set: {
|
|
544
|
+
...outcome,
|
|
545
|
+
conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`
|
|
546
|
+
},
|
|
547
|
+
setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
|
|
517
548
|
});
|
|
518
|
-
|
|
549
|
+
} catch (error) {
|
|
550
|
+
logWarn("task.execution.stat_failed", {
|
|
551
|
+
error,
|
|
552
|
+
"app.task.execution.id": options.executionId,
|
|
553
|
+
"app.task.execution.status": status,
|
|
554
|
+
"app.task.execution.task_id": automationId
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
/** Load usage analytics for the given automations. */
|
|
559
|
+
async function readAutomationExecutionSummaries(automationIds, options = {}) {
|
|
560
|
+
if (automationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
561
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
562
|
+
const oneDayAgoMs = nowMs - 864e5;
|
|
563
|
+
const sevenDaysAgoMs = nowMs - 6048e5;
|
|
564
|
+
const thirtyDaysAgoMs = nowMs - 2592e6;
|
|
565
|
+
const ninetyDaysAgoMs = nowMs - 7776e6;
|
|
566
|
+
const db = getDb();
|
|
567
|
+
const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
|
|
568
|
+
const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
|
|
569
|
+
status: juniorAutomationRuns.status,
|
|
570
|
+
conversationId: juniorAutomationRuns.conversationId,
|
|
571
|
+
automationId: juniorAutomationRuns.automationId
|
|
572
|
+
}).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
|
|
573
|
+
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
574
|
+
const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
|
|
575
|
+
const rows = await db.select({
|
|
576
|
+
costLast1Day: costSince(oneDayAgoMs),
|
|
577
|
+
costLast7Days: costSince(sevenDaysAgoMs),
|
|
578
|
+
costLast30Days: costSince(thirtyDaysAgoMs),
|
|
579
|
+
costLast90Days: costSince(ninetyDaysAgoMs),
|
|
580
|
+
lastRunStatus: latest.status,
|
|
581
|
+
lastConversationId: latest.conversationId,
|
|
582
|
+
lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
|
|
583
|
+
runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
|
|
584
|
+
runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
|
|
585
|
+
runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
|
|
586
|
+
runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
|
|
587
|
+
automationId: juniorAutomationRuns.automationId,
|
|
588
|
+
totalRuns: sql`count(*)::int`
|
|
589
|
+
}).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
|
|
590
|
+
return new Map(rows.map((row) => [row.automationId, {
|
|
591
|
+
costUsd: {
|
|
592
|
+
1: addUsd(0, row.costLast1Day),
|
|
593
|
+
7: addUsd(0, row.costLast7Days),
|
|
594
|
+
30: addUsd(0, row.costLast30Days),
|
|
595
|
+
90: addUsd(0, row.costLast90Days)
|
|
596
|
+
},
|
|
597
|
+
lastRunStatus: row.lastRunStatus,
|
|
598
|
+
...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
|
|
599
|
+
...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
|
|
600
|
+
runs: {
|
|
601
|
+
1: row.runsLast1Day,
|
|
602
|
+
7: row.runsLast7Days,
|
|
603
|
+
30: row.runsLast30Days,
|
|
604
|
+
90: row.runsLast90Days
|
|
605
|
+
},
|
|
606
|
+
totalRuns: row.totalRuns
|
|
607
|
+
}]));
|
|
608
|
+
}
|
|
609
|
+
/** Load a fixed trailing window of completed executions stacked by task type. */
|
|
610
|
+
async function readAutomationExecutionDays(dayCount = 90, options = {}) {
|
|
611
|
+
const end = utcDate(options.nowMs ?? Date.now());
|
|
612
|
+
const endMs = Date.parse(`${end}T23:59:59.999Z`);
|
|
613
|
+
const startMs = Date.parse(`${end}T00:00:00.000Z`) - (dayCount - 1) * 864e5;
|
|
614
|
+
const executionDate = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD')`;
|
|
615
|
+
const rows = await readCompletedExecutionBuckets({
|
|
616
|
+
access: options.access,
|
|
617
|
+
bucket: executionDate,
|
|
618
|
+
endMs,
|
|
619
|
+
startMs
|
|
620
|
+
});
|
|
621
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
622
|
+
for (let offset = 0; offset < dayCount; offset += 1) {
|
|
623
|
+
const date = utcDate(startMs + offset * 864e5);
|
|
624
|
+
byDate.set(date, emptyDay(date));
|
|
625
|
+
}
|
|
626
|
+
for (const row of rows) {
|
|
627
|
+
const day = byDate.get(row.date);
|
|
628
|
+
if (!day) continue;
|
|
629
|
+
if (row.kind === "scheduled") day.scheduled = row.count;
|
|
630
|
+
else if (row.kind === "event") day.event = row.count;
|
|
631
|
+
if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
|
|
632
|
+
}
|
|
633
|
+
return [...byDate.values()];
|
|
634
|
+
}
|
|
635
|
+
/** Load a fixed trailing window of completed executions stacked by hour. */
|
|
636
|
+
async function readAutomationExecutionHours(hourCount = 168, options = {}) {
|
|
637
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
638
|
+
const end = new Date(nowMs);
|
|
639
|
+
end.setUTCMinutes(0, 0, 0);
|
|
640
|
+
const endMs = end.getTime() + 3599999;
|
|
641
|
+
const startMs = end.getTime() - (hourCount - 1) * 36e5;
|
|
642
|
+
const executionHour = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
|
|
643
|
+
const rows = await readCompletedExecutionBuckets({
|
|
644
|
+
access: options.access,
|
|
645
|
+
bucket: executionHour,
|
|
646
|
+
endMs,
|
|
647
|
+
startMs
|
|
648
|
+
});
|
|
649
|
+
const byHour = /* @__PURE__ */ new Map();
|
|
650
|
+
for (let offset = 0; offset < hourCount; offset += 1) {
|
|
651
|
+
const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
|
|
652
|
+
byHour.set(date, emptyDay(date));
|
|
653
|
+
}
|
|
654
|
+
for (const row of rows) {
|
|
655
|
+
const hour = byHour.get(row.date);
|
|
656
|
+
if (!hour) continue;
|
|
657
|
+
if (row.kind === "scheduled") hour.scheduled = row.count;
|
|
658
|
+
else if (row.kind === "event") hour.event = row.count;
|
|
659
|
+
if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
|
|
660
|
+
}
|
|
661
|
+
return [...byHour.values()];
|
|
662
|
+
}
|
|
663
|
+
/** Count completed executions and their cost per time bucket and kind. */
|
|
664
|
+
async function readCompletedExecutionBuckets(args) {
|
|
665
|
+
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
666
|
+
return await getDb().select({
|
|
667
|
+
count: count(),
|
|
668
|
+
costUsd: sql`SUM(${conversationCost})::double precision`,
|
|
669
|
+
date: args.bucket,
|
|
670
|
+
kind: juniorAutomations.kind
|
|
671
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId)).where(and(gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs), eq(juniorAutomationRuns.status, "completed"), args.access)).groupBy(args.bucket, juniorAutomations.kind).orderBy(asc(args.bucket), asc(juniorAutomations.kind));
|
|
672
|
+
}
|
|
673
|
+
/** Load the Automation run linked to one conversation, if any. */
|
|
674
|
+
async function readAutomationExecutionByConversationId(args) {
|
|
675
|
+
const [row] = await getDb().select({
|
|
676
|
+
kind: juniorAutomations.kind,
|
|
677
|
+
automationId: juniorAutomationRuns.automationId
|
|
678
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(eq(juniorAutomationRuns.conversationId, args.conversationId)).limit(1);
|
|
679
|
+
return row;
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Load the display name of the Automation linked to each untitled
|
|
683
|
+
* conversation. Like the Automation list, the name falls back to the first
|
|
684
|
+
* line of the instruction. Titled conversations and conversations without a
|
|
685
|
+
* linked Automation are absent from the result.
|
|
686
|
+
*/
|
|
687
|
+
async function readAutomationTitlesByConversationId(conversations) {
|
|
688
|
+
const titles = /* @__PURE__ */ new Map();
|
|
689
|
+
const untitledIds = conversations.flatMap((conversation) => conversation.title ? [] : [conversation.conversationId]);
|
|
690
|
+
if (untitledIds.length === 0) return titles;
|
|
691
|
+
const rows = await getDb().select({
|
|
692
|
+
conversationId: juniorAutomationRuns.conversationId,
|
|
693
|
+
instruction: juniorAutomations.instruction,
|
|
694
|
+
title: juniorAutomations.title
|
|
695
|
+
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(inArray(juniorAutomationRuns.conversationId, untitledIds));
|
|
696
|
+
for (const row of rows) {
|
|
697
|
+
const title = row.title?.trim() || fallbackShortTitle(row.instruction, "");
|
|
698
|
+
if (row.conversationId && title) titles.set(row.conversationId, title);
|
|
699
|
+
}
|
|
700
|
+
return titles;
|
|
701
|
+
}
|
|
702
|
+
/** Load newest-first executions for one automation, with conversation titles when present. */
|
|
703
|
+
async function readAutomationExecutions(args) {
|
|
704
|
+
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));
|
|
705
|
+
}
|
|
706
|
+
/** Load newest-first executions for the supplied viewer-visible automations. */
|
|
707
|
+
async function readAutomationRuns(args) {
|
|
708
|
+
if (args.automationIds.length === 0) return [];
|
|
709
|
+
return (await getDb().select({
|
|
710
|
+
...executionColumns,
|
|
711
|
+
kind: juniorAutomations.kind,
|
|
712
|
+
automationId: juniorAutomationRuns.automationId
|
|
713
|
+
}).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) => ({
|
|
714
|
+
...mapAutomationExecutionRecord(row),
|
|
715
|
+
kind: row.kind,
|
|
716
|
+
automationId: row.automationId
|
|
717
|
+
}));
|
|
718
|
+
}
|
|
719
|
+
/** Columns that describe one execution, its Conversation, and its version. */
|
|
720
|
+
const executionColumns = {
|
|
721
|
+
automationVersion: juniorAutomationRuns.automationVersion,
|
|
722
|
+
conversationId: juniorAutomationRuns.conversationId,
|
|
723
|
+
credentialMode: sql`${juniorAutomationVersions.definition}->>'credentialMode'`,
|
|
724
|
+
durationMs: juniorConversations.durationMs,
|
|
725
|
+
errorMessage: juniorAutomationRuns.errorMessage,
|
|
726
|
+
executedAtMs: juniorAutomationRuns.completedAtMs,
|
|
727
|
+
executionId: juniorAutomationRuns.id,
|
|
728
|
+
scheduledForMs: juniorAutomationRuns.scheduledForMs,
|
|
729
|
+
startedAtMs: juniorAutomationRuns.startedAtMs,
|
|
730
|
+
status: juniorAutomationRuns.status,
|
|
731
|
+
title: juniorConversations.title,
|
|
732
|
+
usage: juniorConversations.usage
|
|
733
|
+
};
|
|
734
|
+
function executionConversation() {
|
|
735
|
+
return eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId);
|
|
736
|
+
}
|
|
737
|
+
function executionVersion() {
|
|
738
|
+
return and(eq(juniorAutomationVersions.automationId, juniorAutomationRuns.automationId), eq(juniorAutomationVersions.version, juniorAutomationRuns.automationVersion));
|
|
739
|
+
}
|
|
740
|
+
function isoTime(ms) {
|
|
741
|
+
return ms === null ? void 0 : new Date(ms).toISOString();
|
|
742
|
+
}
|
|
743
|
+
function mapAutomationExecutionRecord(row) {
|
|
744
|
+
const title = row.title?.trim();
|
|
745
|
+
const costUsd = agentTurnCostUsd(row.usage ?? void 0);
|
|
746
|
+
const totalTokens = agentTurnTotalTokens(row.usage ?? void 0);
|
|
747
|
+
const durationMs = typeof row.durationMs === "number" && Number.isFinite(row.durationMs) && row.durationMs > 0 ? row.durationMs : void 0;
|
|
748
|
+
const error = row.errorMessage?.trim();
|
|
749
|
+
const scheduledFor = isoTime(row.scheduledForMs);
|
|
750
|
+
const startedAt = isoTime(row.startedAtMs);
|
|
751
|
+
return {
|
|
752
|
+
...row.automationVersion !== null ? { automationVersion: row.automationVersion } : void 0,
|
|
753
|
+
...row.conversationId ? { conversationId: row.conversationId } : void 0,
|
|
754
|
+
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
755
|
+
...row.credentialMode === "creator" || row.credentialMode === "system" ? { credentialMode: row.credentialMode } : void 0,
|
|
756
|
+
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
757
|
+
...error ? { error } : void 0,
|
|
758
|
+
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
759
|
+
executionId: row.executionId,
|
|
760
|
+
...scheduledFor ? { scheduledFor } : void 0,
|
|
761
|
+
...startedAt ? { startedAt } : void 0,
|
|
762
|
+
status: row.status,
|
|
763
|
+
...title ? { title } : void 0,
|
|
764
|
+
...totalTokens !== void 0 ? { totalTokens } : void 0
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
/** Load a fixed trailing window of terminal executions for one automation by status. */
|
|
768
|
+
async function readAutomationExecutionStatusDays(args) {
|
|
769
|
+
const dayCount = args.dayCount ?? 90;
|
|
770
|
+
const end = utcDate(args.nowMs ?? Date.now());
|
|
771
|
+
const endMs = Date.parse(`${end}T23:59:59.999Z`);
|
|
772
|
+
const startMs = Date.parse(`${end}T00:00:00.000Z`) - (dayCount - 1) * 864e5;
|
|
773
|
+
const executionDate = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD')`;
|
|
774
|
+
const rows = await readExecutionStatusBuckets({
|
|
775
|
+
automationId: args.automationId,
|
|
776
|
+
bucket: executionDate,
|
|
777
|
+
endMs,
|
|
778
|
+
startMs
|
|
779
|
+
});
|
|
780
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
781
|
+
for (let offset = 0; offset < dayCount; offset += 1) {
|
|
782
|
+
const date = utcDate(startMs + offset * 864e5);
|
|
783
|
+
byDate.set(date, emptyStatusDay(date));
|
|
784
|
+
}
|
|
785
|
+
for (const row of rows) {
|
|
786
|
+
const day = byDate.get(row.date);
|
|
787
|
+
if (!day) continue;
|
|
788
|
+
if (row.status === "completed") day.completed = row.count;
|
|
789
|
+
else if (row.status === "failed") day.failed = row.count;
|
|
790
|
+
else if (row.status === "blocked") day.blocked = row.count;
|
|
791
|
+
}
|
|
792
|
+
return [...byDate.values()];
|
|
793
|
+
}
|
|
794
|
+
/** Load a fixed trailing window of terminal executions for one automation by hour. */
|
|
795
|
+
async function readAutomationExecutionStatusHours(args) {
|
|
796
|
+
const hourCount = args.hourCount ?? 168;
|
|
797
|
+
const nowMs = args.nowMs ?? Date.now();
|
|
798
|
+
const end = new Date(nowMs);
|
|
799
|
+
end.setUTCMinutes(0, 0, 0);
|
|
800
|
+
const endMs = end.getTime() + 3599999;
|
|
801
|
+
const startMs = end.getTime() - (hourCount - 1) * 36e5;
|
|
802
|
+
const executionHour = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
|
|
803
|
+
const rows = await readExecutionStatusBuckets({
|
|
804
|
+
automationId: args.automationId,
|
|
805
|
+
bucket: executionHour,
|
|
806
|
+
endMs,
|
|
807
|
+
startMs
|
|
519
808
|
});
|
|
809
|
+
const byHour = /* @__PURE__ */ new Map();
|
|
810
|
+
for (let offset = 0; offset < hourCount; offset += 1) {
|
|
811
|
+
const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
|
|
812
|
+
byHour.set(date, emptyStatusDay(date));
|
|
813
|
+
}
|
|
814
|
+
for (const row of rows) {
|
|
815
|
+
const hour = byHour.get(row.date);
|
|
816
|
+
if (!hour) continue;
|
|
817
|
+
if (row.status === "completed") hour.completed = row.count;
|
|
818
|
+
else if (row.status === "failed") hour.failed = row.count;
|
|
819
|
+
else if (row.status === "blocked") hour.blocked = row.count;
|
|
820
|
+
}
|
|
821
|
+
return [...byHour.values()];
|
|
520
822
|
}
|
|
521
|
-
/**
|
|
522
|
-
function
|
|
523
|
-
|
|
524
|
-
|
|
823
|
+
/** Count one automation's executions per time bucket and status. */
|
|
824
|
+
async function readExecutionStatusBuckets(args) {
|
|
825
|
+
return await getDb().select({
|
|
826
|
+
count: count(),
|
|
827
|
+
date: args.bucket,
|
|
828
|
+
status: juniorAutomationRuns.status
|
|
829
|
+
}).from(juniorAutomationRuns).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));
|
|
830
|
+
}
|
|
831
|
+
// src/chat/automations/revision.ts
|
|
832
|
+
/** Storage revisions prevent stale edits from replacing newer values. */
|
|
833
|
+
var AutomationConflictError = class extends ToolInputError {
|
|
834
|
+
constructor() {
|
|
835
|
+
super("This Automation changed after it was loaded. Reload it before saving.");
|
|
836
|
+
this.name = "AutomationConflictError";
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
/** Sort object keys so equal values produce equal JSON. */
|
|
840
|
+
function canonicalJson(value) {
|
|
841
|
+
if (Array.isArray(value)) return value.map(canonicalJson);
|
|
842
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalJson(child)]));
|
|
843
|
+
return value;
|
|
844
|
+
}
|
|
845
|
+
/** Identify the stored values being edited, including lifecycle and creator authority. */
|
|
846
|
+
function automationRevision(task) {
|
|
847
|
+
return createHash("sha256").update(JSON.stringify(canonicalJson(task))).digest("hex");
|
|
848
|
+
}
|
|
849
|
+
/** Reject a stale edit while the storage owner holds the write lock. */
|
|
850
|
+
function requireAutomationRevision(task, revision) {
|
|
851
|
+
if (!task || automationRevision(task) !== revision) throw new AutomationConflictError();
|
|
852
|
+
}
|
|
853
|
+
// src/chat/automations/versions.ts
|
|
854
|
+
/** Automation versions keep each saved definition so people can see how it changed. */
|
|
855
|
+
/** Return the versioned part of an Automation. Lifecycle and run state are excluded. */
|
|
856
|
+
function automationDefinition(task) {
|
|
857
|
+
const common = {
|
|
858
|
+
title: task.title?.trim() || null,
|
|
859
|
+
instruction: task.task.text,
|
|
860
|
+
credentialMode: task.credentialMode,
|
|
861
|
+
destination: task.destination,
|
|
862
|
+
outcomes: task.outcomes
|
|
863
|
+
};
|
|
864
|
+
return "schedule" in task ? {
|
|
865
|
+
...common,
|
|
866
|
+
schedule: task.schedule
|
|
867
|
+
} : {
|
|
868
|
+
...common,
|
|
869
|
+
trigger: task.trigger
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
/** Compare definition values after key sorting. */
|
|
873
|
+
function sameDefinitionValue(left, right) {
|
|
874
|
+
return JSON.stringify(canonicalJson(left)) === JSON.stringify(canonicalJson(right));
|
|
525
875
|
}
|
|
526
876
|
/**
|
|
527
|
-
*
|
|
528
|
-
*
|
|
529
|
-
*
|
|
530
|
-
* filters on the keys in `data` fail adds no keys. So a broad trigger for
|
|
531
|
-
* one repository does not make every repository load its lazy data.
|
|
877
|
+
* Save a version when the definition changed. Call this in the same
|
|
878
|
+
* transaction and lock as the Automation write. Without `current`, the
|
|
879
|
+
* Automation is new, so the creator saves version 1.
|
|
532
880
|
*/
|
|
533
|
-
async function
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
881
|
+
async function recordAutomationVersion(db, task, current, editedBy) {
|
|
882
|
+
const definition = automationDefinition(task);
|
|
883
|
+
if (current && sameDefinitionValue(automationDefinition(current), definition)) return;
|
|
884
|
+
await db.insert(juniorAutomationVersions).values({
|
|
885
|
+
automationId: task.id,
|
|
886
|
+
version: sql`(
|
|
887
|
+
SELECT coalesce(max(${juniorAutomationVersions.version}), 0) + 1
|
|
888
|
+
FROM ${juniorAutomationVersions}
|
|
889
|
+
WHERE ${juniorAutomationVersions.automationId} = ${task.id}
|
|
890
|
+
)`,
|
|
891
|
+
createdAtMs: Date.now(),
|
|
892
|
+
editedBy: editedBy ?? (current ? null : task.createdBy),
|
|
893
|
+
definition
|
|
543
894
|
});
|
|
544
|
-
const keys = /* @__PURE__ */ new Set();
|
|
545
|
-
for (const task of tasks) {
|
|
546
|
-
if (task.trigger.identifier === void 0 && input.data && !eventMatches(knownMatch(task.trigger.match, input.data), input.data)) continue;
|
|
547
|
-
for (const key of Object.keys(task.trigger.match ?? {})) keys.add(key);
|
|
548
|
-
}
|
|
549
|
-
return [...keys].sort();
|
|
550
895
|
}
|
|
551
896
|
/**
|
|
552
|
-
*
|
|
553
|
-
*
|
|
554
|
-
*
|
|
555
|
-
*
|
|
897
|
+
* Select the newest saved version with the same definition as `task`.
|
|
898
|
+
*
|
|
899
|
+
* An Automation run stores this version so that a reader can see the
|
|
900
|
+
* instruction that ran after the definition changes. The value is null when
|
|
901
|
+
* no saved version has this definition.
|
|
556
902
|
*/
|
|
557
|
-
|
|
558
|
-
return (
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
903
|
+
function automationVersionOf(task) {
|
|
904
|
+
return sql`(
|
|
905
|
+
SELECT max(${juniorAutomationVersions.version})
|
|
906
|
+
FROM ${juniorAutomationVersions}
|
|
907
|
+
WHERE ${juniorAutomationVersions.automationId} = ${task.id}
|
|
908
|
+
AND ${juniorAutomationVersions.definition} = ${JSON.stringify(automationDefinition(task))}::jsonb
|
|
909
|
+
)`;
|
|
910
|
+
}
|
|
911
|
+
const versionColumns = {
|
|
912
|
+
createdAtMs: juniorAutomationVersions.createdAtMs,
|
|
913
|
+
definition: juniorAutomationVersions.definition,
|
|
914
|
+
editedBy: juniorAutomationVersions.editedBy,
|
|
915
|
+
kind: juniorAutomations.kind,
|
|
916
|
+
version: juniorAutomationVersions.version
|
|
917
|
+
};
|
|
918
|
+
function parseVersionRow(row) {
|
|
919
|
+
return automationVersionSchema.parse({
|
|
920
|
+
kind: row.kind,
|
|
921
|
+
version: row.version,
|
|
922
|
+
createdAt: new Date(row.createdAtMs).toISOString(),
|
|
923
|
+
editedBy: row.editedBy,
|
|
924
|
+
definition: row.definition
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
/** Read one saved definition. */
|
|
928
|
+
async function readAutomationVersion(db, automationId, version) {
|
|
929
|
+
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);
|
|
930
|
+
return row ? parseVersionRow(row) : void 0;
|
|
931
|
+
}
|
|
932
|
+
/** Read saved definitions, newest first. */
|
|
933
|
+
async function listAutomationVersions(db, automationId, limit) {
|
|
934
|
+
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);
|
|
935
|
+
}
|
|
936
|
+
// src/chat/event-automations/run-limit.ts
|
|
937
|
+
const RUN_LIST_PREFIX = "junior:event_automation_runs:v1";
|
|
938
|
+
const RUN_LIST_BURST_ROOM = 100;
|
|
939
|
+
const runEntrySchema = z.union([z.object({
|
|
940
|
+
atMs: z.number().finite(),
|
|
941
|
+
id: z.string().min(1)
|
|
942
|
+
}).strict(), z.object({ reset: z.literal(true) }).strict()]);
|
|
943
|
+
function runListKey(automationId) {
|
|
944
|
+
return `${RUN_LIST_PREFIX}:${automationId}`;
|
|
945
|
+
}
|
|
946
|
+
function runListMaxLength() {
|
|
947
|
+
return botConfig.maxEventAutomationRuns + RUN_LIST_BURST_ROOM;
|
|
948
|
+
}
|
|
949
|
+
async function appendRunEntry(state, automationId, entry) {
|
|
950
|
+
await state.connect();
|
|
951
|
+
await state.appendToList(runListKey(automationId), entry, {
|
|
952
|
+
maxLength: runListMaxLength(),
|
|
953
|
+
ttlMs: botConfig.eventAutomationRunWindowMs
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
function describeRunWindow(windowMs) {
|
|
957
|
+
for (const [unit, unitMs] of [
|
|
958
|
+
["day", 864e5],
|
|
959
|
+
["hour", 36e5],
|
|
960
|
+
["minute", 6e4],
|
|
961
|
+
["second", 1e3]
|
|
962
|
+
]) if (windowMs % unitMs === 0) {
|
|
963
|
+
const count = windowMs / unitMs;
|
|
964
|
+
return count === 1 ? unit : `${count} ${unit}s`;
|
|
965
|
+
}
|
|
966
|
+
return `${windowMs} ms`;
|
|
967
|
+
}
|
|
968
|
+
/** Reason stored on an Event automation that the run limit blocked. */
|
|
969
|
+
function eventAutomationRunLimitReason() {
|
|
970
|
+
const window = describeRunWindow(botConfig.eventAutomationRunWindowMs);
|
|
971
|
+
return `This automation reached its limit of ${botConfig.maxEventAutomationRuns} runs per ${window}. Check that its trigger is not too broad, then resume it.`;
|
|
972
|
+
}
|
|
973
|
+
function hasRunKey(entries, runKey) {
|
|
974
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
975
|
+
const entry = entries[index];
|
|
976
|
+
if ("reset" in entry) return false;
|
|
977
|
+
if (entry.id === runKey) return true;
|
|
978
|
+
}
|
|
979
|
+
return false;
|
|
565
980
|
}
|
|
566
981
|
/**
|
|
567
|
-
*
|
|
568
|
-
*
|
|
569
|
-
*
|
|
570
|
-
*
|
|
982
|
+
* Count one run of an Event automation, or refuse when its window is full.
|
|
983
|
+
*
|
|
984
|
+
* `runKey` is the dispatch idempotency key, so a provider retry of the same
|
|
985
|
+
* Event does not count again.
|
|
571
986
|
*/
|
|
572
|
-
async function
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
const
|
|
577
|
-
requireAutomationRevision(current, revision);
|
|
578
|
-
if (!current || current.status === "deleted") throw new Error("Automation no longer exists.");
|
|
579
|
-
const next = status === "paused" ? {
|
|
580
|
-
status,
|
|
581
|
-
statusReason: current.statusReason
|
|
582
|
-
} : current.status === "paused" && current.statusReason ? {
|
|
583
|
-
status: "blocked",
|
|
584
|
-
statusReason: current.statusReason
|
|
585
|
-
} : {
|
|
586
|
-
status,
|
|
587
|
-
statusReason: void 0
|
|
588
|
-
};
|
|
589
|
-
await tx.update(juniorAutomations).set({
|
|
590
|
-
status: next.status,
|
|
591
|
-
statusReason: next.statusReason ?? null
|
|
592
|
-
}).where(eventAutomationWhere(id));
|
|
593
|
-
const { statusReason: _statusReason, ...rest } = current;
|
|
987
|
+
async function admitEventAutomationRun(args) {
|
|
988
|
+
const state = args.state ?? getStateAdapter();
|
|
989
|
+
await state.connect();
|
|
990
|
+
const readEntries = async () => {
|
|
991
|
+
const values = await state.getList(runListKey(args.automationId));
|
|
594
992
|
return {
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
993
|
+
entries: values.flatMap((value) => {
|
|
994
|
+
const entry = runEntrySchema.safeParse(value);
|
|
995
|
+
return entry.success ? [entry.data] : [];
|
|
996
|
+
}),
|
|
997
|
+
length: values.length
|
|
598
998
|
};
|
|
999
|
+
};
|
|
1000
|
+
if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
|
|
1001
|
+
atMs: args.nowMs,
|
|
1002
|
+
id: args.runKey
|
|
1003
|
+
});
|
|
1004
|
+
const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
|
|
1005
|
+
const { entries, length } = await readEntries();
|
|
1006
|
+
let lastReset = -1;
|
|
1007
|
+
entries.forEach((entry, index) => {
|
|
1008
|
+
if ("reset" in entry) lastReset = index;
|
|
599
1009
|
});
|
|
1010
|
+
const oldest = entries[0];
|
|
1011
|
+
const full = lastReset === -1 && length >= runListMaxLength() && oldest !== void 0 && "atMs" in oldest && oldest.atMs > windowStartMs;
|
|
1012
|
+
const runKeys = /* @__PURE__ */ new Set();
|
|
1013
|
+
for (const entry of entries.slice(lastReset + 1)) {
|
|
1014
|
+
if ("reset" in entry) continue;
|
|
1015
|
+
if (entry.atMs > windowStartMs) runKeys.add(entry.id);
|
|
1016
|
+
if (entry.id === args.runKey) return full || runKeys.size > botConfig.maxEventAutomationRuns ? "limited" : "allowed";
|
|
1017
|
+
}
|
|
1018
|
+
return "limited";
|
|
600
1019
|
}
|
|
601
1020
|
/**
|
|
602
|
-
*
|
|
603
|
-
*
|
|
604
|
-
*
|
|
605
|
-
*
|
|
606
|
-
*
|
|
607
|
-
* an automation that the dashboard shows as paused.
|
|
1021
|
+
* Forget the runs counted for one Event automation.
|
|
1022
|
+
*
|
|
1023
|
+
* Resume and revive call this so the automation starts with a new window.
|
|
1024
|
+
* Call it before the automation becomes active, so an Event cannot see the
|
|
1025
|
+
* old full count and block it again.
|
|
608
1026
|
*/
|
|
609
|
-
async function
|
|
610
|
-
|
|
611
|
-
status: sql`case when ${juniorAutomations.status} = 'active' then 'blocked' else ${juniorAutomations.status} end`,
|
|
612
|
-
statusReason: reason
|
|
613
|
-
}).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";
|
|
614
|
-
}
|
|
615
|
-
// src/chat/scheduled-automations/tasks.ts
|
|
616
|
-
const SCHEDULER_KEY_PREFIX = "junior:scheduler";
|
|
617
|
-
/** Decode a Scheduled automation row. Returns undefined for an invalid row. */
|
|
618
|
-
function parseScheduledAutomationRow(row) {
|
|
619
|
-
const columns = {
|
|
620
|
-
createdAtMs: row.createdAtMs,
|
|
621
|
-
creatorIdentityId: row.creatorIdentityId,
|
|
622
|
-
id: row.id,
|
|
623
|
-
nextRunAtMs: row.nextRunAtMs,
|
|
624
|
-
runNowAtMs: row.runNowAtMs,
|
|
625
|
-
status: row.status,
|
|
626
|
-
statusReason: row.statusReason,
|
|
627
|
-
title: row.title
|
|
628
|
-
};
|
|
629
|
-
const parsed = scheduledAutomationSchema.safeParse({
|
|
630
|
-
...row.record,
|
|
631
|
-
...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
|
|
632
|
-
});
|
|
633
|
-
return parsed.success ? parsed.data : void 0;
|
|
634
|
-
}
|
|
635
|
-
/** Keep scan paths from returning current or legacy tombstones. */
|
|
636
|
-
function isListedScheduledAutomation(task) {
|
|
637
|
-
return task !== void 0 && task.status !== "deleted";
|
|
638
|
-
}
|
|
639
|
-
/** Build the stable run id for one task occurrence. */
|
|
640
|
-
function scheduledRunId(taskId, scheduledForMs) {
|
|
641
|
-
return `${taskId}:${scheduledForMs}`;
|
|
642
|
-
}
|
|
643
|
-
/** Acquire the deployed advisory lock for one scheduled automation. */
|
|
644
|
-
function withScheduledAutomationLock(db, taskId, callback) {
|
|
645
|
-
return db.transaction(async (tx) => {
|
|
646
|
-
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
|
|
647
|
-
return await callback(tx);
|
|
648
|
-
});
|
|
1027
|
+
async function clearEventAutomationRuns(automationId, state = getStateAdapter()) {
|
|
1028
|
+
await appendRunEntry(state, automationId, { reset: true });
|
|
649
1029
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
1030
|
+
// src/chat/event-automations/store.ts
|
|
1031
|
+
/**
|
|
1032
|
+
* Validate an event automation and split it into its SQL columns. Lifecycle
|
|
1033
|
+
* columns are written separately.
|
|
1034
|
+
*/
|
|
1035
|
+
function eventAutomationColumns(task) {
|
|
1036
|
+
const { status: _status, statusReason: _statusReason, title, ...definition } = task;
|
|
1037
|
+
const { createdAtMs: _createdAtMs, creatorIdentityId, id: _id, ...record } = eventAutomationSchema.parse(definition);
|
|
655
1038
|
return {
|
|
656
|
-
...current,
|
|
657
|
-
...normalizedTitle ? { title: normalizedTitle } : void 0
|
|
658
|
-
};
|
|
659
|
-
}
|
|
660
|
-
async function upsertScheduledAutomation(db, task) {
|
|
661
|
-
const { createdAtMs, creatorIdentityId, id, nextRunAtMs, runNowAtMs, status, statusReason, title, ...record } = task;
|
|
662
|
-
const columns = {
|
|
663
1039
|
channelId: record.destination.channelId,
|
|
664
|
-
createdAtMs,
|
|
665
1040
|
creatorIdentityId,
|
|
666
1041
|
creatorSlackUserId: record.createdBy.slackUserId,
|
|
1042
|
+
identifier: record.trigger.identifier ?? null,
|
|
667
1043
|
instruction: record.task.text,
|
|
668
|
-
|
|
1044
|
+
namespace: record.trigger.namespace,
|
|
669
1045
|
record,
|
|
670
|
-
runNowAtMs: runNowAtMs ?? null,
|
|
671
|
-
status,
|
|
672
|
-
statusReason: statusReason ?? null,
|
|
673
1046
|
teamId: record.destination.teamId,
|
|
674
1047
|
title: title?.trim() || null
|
|
675
1048
|
};
|
|
676
|
-
await db.insert(juniorAutomations).values({
|
|
677
|
-
...columns,
|
|
678
|
-
id,
|
|
679
|
-
kind: "scheduled"
|
|
680
|
-
}).onConflictDoUpdate({
|
|
681
|
-
target: juniorAutomations.id,
|
|
682
|
-
set: columns
|
|
683
|
-
});
|
|
684
|
-
}
|
|
685
|
-
/** Read and decode one scheduled automation. */
|
|
686
|
-
async function readScheduledAutomation(db, taskId) {
|
|
687
|
-
const rows = await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.id, taskId), eq(juniorAutomations.kind, "scheduled"))).limit(1);
|
|
688
|
-
return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
|
|
689
|
-
}
|
|
690
|
-
async function readListedScheduledAutomations(db, teamId) {
|
|
691
|
-
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);
|
|
692
|
-
}
|
|
693
|
-
/** List decoded scheduled automations for one team in stable creation order. */
|
|
694
|
-
async function listScheduledAutomationsForTeam(db, teamId) {
|
|
695
|
-
return await readListedScheduledAutomations(db, teamId);
|
|
696
|
-
}
|
|
697
|
-
async function writeScheduledAutomation(db, task, current, editedBy) {
|
|
698
|
-
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")));
|
|
699
|
-
if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
|
|
700
|
-
await upsertScheduledAutomation(db, task);
|
|
701
|
-
await recordAutomationVersion(db, task, current, editedBy);
|
|
702
|
-
}
|
|
703
|
-
async function skipPendingRunsForDeletedTask(db, task) {
|
|
704
|
-
await db.update(juniorAutomationRuns).set({
|
|
705
|
-
completedAtMs: task.updatedAtMs,
|
|
706
|
-
errorMessage: `Scheduled automation ${task.id} was deleted before the run started.`,
|
|
707
|
-
status: "skipped"
|
|
708
|
-
}).where(and(eq(juniorAutomationRuns.automationId, task.id), eq(juniorAutomationRuns.status, "pending")));
|
|
709
|
-
}
|
|
710
|
-
/** Create a scheduled automation once under its retry-stable task lock. */
|
|
711
|
-
async function createScheduledAutomation(db, task) {
|
|
712
|
-
const next = requireStoredTask(task);
|
|
713
|
-
return await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
714
|
-
const current = await readScheduledAutomation(tx, task.id);
|
|
715
|
-
if (current) return current;
|
|
716
|
-
await writeScheduledAutomation(tx, next, void 0);
|
|
717
|
-
return next;
|
|
718
|
-
});
|
|
719
|
-
}
|
|
720
|
-
/**
|
|
721
|
-
* Save a scheduled automation and clear its blocked occurrence on reactivation.
|
|
722
|
-
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
723
|
-
*/
|
|
724
|
-
async function saveScheduledAutomation(db, task, expectedRevision, editedBy) {
|
|
725
|
-
const next = requireStoredTask(task);
|
|
726
|
-
await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
727
|
-
const current = await readScheduledAutomation(tx, task.id);
|
|
728
|
-
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
729
|
-
await writeScheduledAutomation(tx, next, current, editedBy);
|
|
730
|
-
});
|
|
731
|
-
return next;
|
|
732
|
-
}
|
|
733
|
-
/** Save a scheduled automation inside a task lock already held by the caller. */
|
|
734
|
-
async function saveScheduledAutomationInLock(db, task, current) {
|
|
735
|
-
await writeScheduledAutomation(db, requireStoredTask(task), current);
|
|
736
|
-
}
|
|
737
|
-
/** Mark one live scheduled automation deleted while keeping its history. */
|
|
738
|
-
async function deleteScheduledAutomation(db, id, nowMs = Date.now()) {
|
|
739
|
-
return await withScheduledAutomationLock(db, id, async (tx) => {
|
|
740
|
-
const current = await readScheduledAutomation(tx, id);
|
|
741
|
-
if (!current || current.status === "deleted") return void 0;
|
|
742
|
-
const deleted = requireStoredTask({
|
|
743
|
-
...current,
|
|
744
|
-
nextRunAtMs: void 0,
|
|
745
|
-
runNowAtMs: void 0,
|
|
746
|
-
status: "deleted",
|
|
747
|
-
updatedAtMs: nowMs
|
|
748
|
-
});
|
|
749
|
-
await writeScheduledAutomation(tx, deleted, current);
|
|
750
|
-
return deleted;
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
// src/api/conversations/aggregate.ts
|
|
754
|
-
function usageTokenValue(source, field) {
|
|
755
|
-
return sql`CASE
|
|
756
|
-
WHEN ${source.usage}->>${field} IS NOT NULL
|
|
757
|
-
THEN (${source.usage}->>${field})::double precision
|
|
758
|
-
ELSE NULL
|
|
759
|
-
END`;
|
|
760
|
-
}
|
|
761
|
-
function tokenValue(source) {
|
|
762
|
-
return sql`
|
|
763
|
-
CASE
|
|
764
|
-
WHEN COALESCE(
|
|
765
|
-
${source.usage}->>'inputTokens',
|
|
766
|
-
${source.usage}->>'outputTokens',
|
|
767
|
-
${source.usage}->>'cachedInputTokens',
|
|
768
|
-
${source.usage}->>'cacheCreationTokens'
|
|
769
|
-
) IS NOT NULL
|
|
770
|
-
THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
|
|
771
|
-
+ COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
|
|
772
|
-
+ COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
|
|
773
|
-
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
774
|
-
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
775
|
-
THEN (${source.usage}->>'totalTokens')::double precision
|
|
776
|
-
ELSE NULL
|
|
777
|
-
END
|
|
778
|
-
`;
|
|
779
|
-
}
|
|
780
|
-
function costValue(source) {
|
|
781
|
-
return conversationUsageCostExpr(source.usage);
|
|
782
|
-
}
|
|
783
|
-
/** Read one conversation row's usage cost as a SQL expression. */
|
|
784
|
-
function conversationUsageCostExpr(usage) {
|
|
785
|
-
return sql`
|
|
786
|
-
CASE
|
|
787
|
-
WHEN ${usage}->'cost'->>'total' IS NOT NULL
|
|
788
|
-
THEN (${usage}->'cost'->>'total')::double precision
|
|
789
|
-
WHEN COALESCE(
|
|
790
|
-
${usage}->'cost'->>'input',
|
|
791
|
-
${usage}->'cost'->>'output',
|
|
792
|
-
${usage}->'cost'->>'cacheRead',
|
|
793
|
-
${usage}->'cost'->>'cacheWrite'
|
|
794
|
-
) IS NOT NULL
|
|
795
|
-
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
796
|
-
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
797
|
-
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
798
|
-
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
799
|
-
ELSE NULL
|
|
800
|
-
END
|
|
801
|
-
`;
|
|
802
1049
|
}
|
|
803
|
-
|
|
804
|
-
function conversationAggregateColumns(sources) {
|
|
805
|
-
const metrics = sources?.metrics ?? juniorConversations;
|
|
806
|
-
const roots = sources?.roots ?? juniorConversations;
|
|
807
|
-
const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
|
|
1050
|
+
function eventAutomationRowInput(row) {
|
|
808
1051
|
return {
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
814
|
-
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
815
|
-
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
816
|
-
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
817
|
-
failed: sql`${conversationCount} FILTER (
|
|
818
|
-
WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
|
|
819
|
-
)::integer`,
|
|
820
|
-
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
821
|
-
tokens: sql`SUM(${tokenValue(metrics)})::double precision`
|
|
1052
|
+
...row.record,
|
|
1053
|
+
createdAtMs: row.createdAtMs,
|
|
1054
|
+
creatorIdentityId: row.creatorIdentityId,
|
|
1055
|
+
id: row.id
|
|
822
1056
|
};
|
|
823
1057
|
}
|
|
824
|
-
/**
|
|
825
|
-
function
|
|
1058
|
+
/** Decode an event Automation row with its SQL-backed fields. */
|
|
1059
|
+
function parseEventAutomationRow(row) {
|
|
1060
|
+
return withRowFields(row, eventAutomationSchema.parse(eventAutomationRowInput(row)));
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Decode a row for Event matching. Log and skip a row that does not parse,
|
|
1064
|
+
* so one bad row cannot stop matching for its whole namespace.
|
|
1065
|
+
*/
|
|
1066
|
+
function readMatchableEventAutomationRow(row) {
|
|
1067
|
+
const parsed = eventAutomationSchema.safeParse(eventAutomationRowInput(row));
|
|
1068
|
+
if (parsed.success) return withRowFields(row, parsed.data);
|
|
1069
|
+
logWarn("event_automation.row.invalid", {
|
|
1070
|
+
"app.task.id": row.id,
|
|
1071
|
+
"app.task.type": "event",
|
|
1072
|
+
"error.message": parsed.error.message
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
function withRowFields(row, task) {
|
|
1076
|
+
const title = row.title?.trim();
|
|
826
1077
|
return {
|
|
827
|
-
|
|
828
|
-
|
|
1078
|
+
...task,
|
|
1079
|
+
status: row.status,
|
|
1080
|
+
...row.statusReason ? { statusReason: row.statusReason } : void 0,
|
|
1081
|
+
...title ? { title } : void 0
|
|
829
1082
|
};
|
|
830
1083
|
}
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
return sql`COUNT(DISTINCT (${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC')::date)::integer`;
|
|
834
|
-
}
|
|
835
|
-
// src/chat/automations/execution-stats.ts
|
|
836
|
-
const AUTOMATION_EXECUTION_STATUSES = [
|
|
837
|
-
"blocked",
|
|
838
|
-
"completed",
|
|
839
|
-
"failed"
|
|
840
|
-
];
|
|
841
|
-
/** An execution is a run with an outcome. Skipped runs are not executions. */
|
|
842
|
-
function isExecution() {
|
|
843
|
-
return and(inArray(juniorAutomationRuns.status, [...AUTOMATION_EXECUTION_STATUSES]), isNotNull(juniorAutomationRuns.completedAtMs));
|
|
1084
|
+
function eventAutomationWhere(id) {
|
|
1085
|
+
return and(eq(juniorAutomations.id, id), eq(juniorAutomations.kind, "event"));
|
|
844
1086
|
}
|
|
845
|
-
function
|
|
846
|
-
return
|
|
1087
|
+
function activeEventAutomationWhere() {
|
|
1088
|
+
return and(eq(juniorAutomations.kind, "event"), ne(juniorAutomations.status, "deleted"));
|
|
847
1089
|
}
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
90: 0
|
|
853
|
-
};
|
|
854
|
-
/** Empty run or cost windows for automations with no execution history. */
|
|
855
|
-
function emptyAutomationRunWindows() {
|
|
856
|
-
return { ...EMPTY_RUN_WINDOWS };
|
|
1090
|
+
/** Read one event automation by id, including deleted rows when present. */
|
|
1091
|
+
async function getEventAutomation(db, id) {
|
|
1092
|
+
const rows = await db.select().from(juniorAutomations).where(eventAutomationWhere(id)).limit(1);
|
|
1093
|
+
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
857
1094
|
}
|
|
858
|
-
|
|
859
|
-
|
|
1095
|
+
/** Create one retry-stable event automation, or revive a deleted row with the new payload. */
|
|
1096
|
+
async function createEventAutomation(db, task) {
|
|
1097
|
+
const columns = eventAutomationColumns(task);
|
|
1098
|
+
if ((await getEventAutomation(db, task.id))?.status === "deleted") await clearEventAutomationRuns(task.id);
|
|
1099
|
+
return db.transaction(async (tx) => {
|
|
1100
|
+
const inserted = await tx.insert(juniorAutomations).values({
|
|
1101
|
+
...columns,
|
|
1102
|
+
createdAtMs: task.createdAtMs,
|
|
1103
|
+
id: task.id,
|
|
1104
|
+
kind: "event",
|
|
1105
|
+
status: "active"
|
|
1106
|
+
}).onConflictDoNothing().returning();
|
|
1107
|
+
if (inserted[0]) {
|
|
1108
|
+
const created = parseEventAutomationRow(inserted[0]);
|
|
1109
|
+
await recordAutomationVersion(tx, created, void 0);
|
|
1110
|
+
return created;
|
|
1111
|
+
}
|
|
1112
|
+
const existing = await getEventAutomation(tx, task.id);
|
|
1113
|
+
if (!existing) throw new Error(`Automation ${task.id} already exists with another kind.`);
|
|
1114
|
+
if (existing.status !== "deleted") return existing;
|
|
1115
|
+
const rows = await tx.update(juniorAutomations).set({
|
|
1116
|
+
...columns,
|
|
1117
|
+
status: "active",
|
|
1118
|
+
statusReason: null
|
|
1119
|
+
}).where(and(eventAutomationWhere(task.id), eq(juniorAutomations.status, "deleted"))).returning();
|
|
1120
|
+
if (!rows[0]) return await getEventAutomation(tx, task.id);
|
|
1121
|
+
const revived = parseEventAutomationRow(rows[0]);
|
|
1122
|
+
await recordAutomationVersion(tx, revived, void 0);
|
|
1123
|
+
return revived;
|
|
1124
|
+
});
|
|
860
1125
|
}
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
1126
|
+
/**
|
|
1127
|
+
* Replace an existing non-deleted event automation under a row lock.
|
|
1128
|
+
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
1129
|
+
*/
|
|
1130
|
+
async function saveEventAutomation(db, task, expectedRevision, editedBy) {
|
|
1131
|
+
const columns = eventAutomationColumns(task);
|
|
1132
|
+
return db.transaction(async (tx) => {
|
|
1133
|
+
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(task.id)).for("update");
|
|
1134
|
+
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
1135
|
+
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
1136
|
+
if (!current || current.status === "deleted") return void 0;
|
|
1137
|
+
const saved = parseEventAutomationRow((await tx.update(juniorAutomations).set(columns).where(eventAutomationWhere(task.id)).returning())[0]);
|
|
1138
|
+
await recordAutomationVersion(tx, saved, current, editedBy);
|
|
1139
|
+
return saved;
|
|
1140
|
+
});
|
|
868
1141
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
date,
|
|
874
|
-
failed: 0
|
|
875
|
-
};
|
|
1142
|
+
/** Mark one existing event automation deleted while retaining the row for history. */
|
|
1143
|
+
async function deleteEventAutomation(db, id) {
|
|
1144
|
+
const rows = await db.update(juniorAutomations).set({ status: "deleted" }).where(and(eq(juniorAutomations.id, id), activeEventAutomationWhere())).returning();
|
|
1145
|
+
return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
876
1146
|
}
|
|
877
1147
|
/**
|
|
878
|
-
*
|
|
879
|
-
*
|
|
880
|
-
* `conversation_id` is a foreign key.
|
|
1148
|
+
* List deleted event automations created by one user, newest first.
|
|
1149
|
+
* Used only to keep historical runs after the live automation list drops the row.
|
|
881
1150
|
*/
|
|
882
|
-
function
|
|
883
|
-
|
|
1151
|
+
async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
|
|
1152
|
+
const identityIds = user.identities.map((identity) => identity.id);
|
|
1153
|
+
if (identityIds.length === 0) return [];
|
|
1154
|
+
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);
|
|
884
1155
|
}
|
|
885
1156
|
/**
|
|
886
|
-
*
|
|
887
|
-
*
|
|
888
|
-
*
|
|
1157
|
+
* Select live rows whose identifier is one of these, and rows with no
|
|
1158
|
+
* identifier. A row with no identifier runs for every resource of its
|
|
1159
|
+
* namespace, so it gets every copy of an Event.
|
|
889
1160
|
*/
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
const status = options.status ?? "completed";
|
|
893
|
-
const outcome = {
|
|
894
|
-
completedAtMs: nowMs,
|
|
895
|
-
errorMessage: options.errorMessage ?? null,
|
|
896
|
-
status
|
|
897
|
-
};
|
|
898
|
-
try {
|
|
899
|
-
await getDb().insert(juniorAutomationRuns).values({
|
|
900
|
-
id: options.executionId,
|
|
901
|
-
automationId,
|
|
902
|
-
conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
|
|
903
|
-
...outcome
|
|
904
|
-
}).onConflictDoUpdate({
|
|
905
|
-
target: juniorAutomationRuns.id,
|
|
906
|
-
set: {
|
|
907
|
-
...outcome,
|
|
908
|
-
conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`
|
|
909
|
-
},
|
|
910
|
-
setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
|
|
911
|
-
});
|
|
912
|
-
} catch (error) {
|
|
913
|
-
logWarn("task.execution.stat_failed", {
|
|
914
|
-
error,
|
|
915
|
-
"app.task.execution.id": options.executionId,
|
|
916
|
-
"app.task.execution.status": status,
|
|
917
|
-
"app.task.execution.task_id": automationId
|
|
918
|
-
});
|
|
919
|
-
}
|
|
1161
|
+
function eventIdentifierWhere(identifiers) {
|
|
1162
|
+
return or(isNull(juniorAutomations.identifier), ...identifiers.length > 0 ? [inArray(juniorAutomations.identifier, [...identifiers])] : []);
|
|
920
1163
|
}
|
|
921
|
-
/**
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
925
|
-
const oneDayAgoMs = nowMs - 864e5;
|
|
926
|
-
const sevenDaysAgoMs = nowMs - 6048e5;
|
|
927
|
-
const thirtyDaysAgoMs = nowMs - 2592e6;
|
|
928
|
-
const ninetyDaysAgoMs = nowMs - 7776e6;
|
|
929
|
-
const db = getDb();
|
|
930
|
-
const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
|
|
931
|
-
const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
|
|
932
|
-
status: juniorAutomationRuns.status,
|
|
933
|
-
conversationId: juniorAutomationRuns.conversationId,
|
|
934
|
-
automationId: juniorAutomationRuns.automationId
|
|
935
|
-
}).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
|
|
936
|
-
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
|
|
937
|
-
const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
|
|
938
|
-
const rows = await db.select({
|
|
939
|
-
costLast1Day: costSince(oneDayAgoMs),
|
|
940
|
-
costLast7Days: costSince(sevenDaysAgoMs),
|
|
941
|
-
costLast30Days: costSince(thirtyDaysAgoMs),
|
|
942
|
-
costLast90Days: costSince(ninetyDaysAgoMs),
|
|
943
|
-
lastRunStatus: latest.status,
|
|
944
|
-
lastConversationId: latest.conversationId,
|
|
945
|
-
lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
|
|
946
|
-
runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
|
|
947
|
-
runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
|
|
948
|
-
runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
|
|
949
|
-
runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
|
|
950
|
-
automationId: juniorAutomationRuns.automationId,
|
|
951
|
-
totalRuns: sql`count(*)::int`
|
|
952
|
-
}).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
|
|
953
|
-
return new Map(rows.map((row) => [row.automationId, {
|
|
954
|
-
costUsd: {
|
|
955
|
-
1: addUsd(0, row.costLast1Day),
|
|
956
|
-
7: addUsd(0, row.costLast7Days),
|
|
957
|
-
30: addUsd(0, row.costLast30Days),
|
|
958
|
-
90: addUsd(0, row.costLast90Days)
|
|
959
|
-
},
|
|
960
|
-
lastRunStatus: row.lastRunStatus,
|
|
961
|
-
...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
|
|
962
|
-
...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
|
|
963
|
-
runs: {
|
|
964
|
-
1: row.runsLast1Day,
|
|
965
|
-
7: row.runsLast7Days,
|
|
966
|
-
30: row.runsLast30Days,
|
|
967
|
-
90: row.runsLast90Days
|
|
968
|
-
},
|
|
969
|
-
totalRuns: row.totalRuns
|
|
970
|
-
}]));
|
|
1164
|
+
/** SQL for rows whose trigger selects any of these event types. */
|
|
1165
|
+
function eventTypesWhere(eventTypes) {
|
|
1166
|
+
return or(...eventTypes.map((eventType) => sql`${juniorAutomations.record}->'trigger'->'events' @> ${JSON.stringify([eventType])}::jsonb`));
|
|
971
1167
|
}
|
|
972
|
-
/**
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
1168
|
+
/**
|
|
1169
|
+
* Return why a row must not run for an Event with one of these identifiers,
|
|
1170
|
+
* or nothing when it may.
|
|
1171
|
+
*
|
|
1172
|
+
* The identifier column and the saved trigger must agree. A row with no
|
|
1173
|
+
* identifier must also have a trigger that the enabled `catalog` accepts. A
|
|
1174
|
+
* plugin can later require a filter or stop letting an event run for every
|
|
1175
|
+
* resource, and the row must not stay broad.
|
|
1176
|
+
*/
|
|
1177
|
+
function eventAutomationGateProblem(row, task, identifiers, catalog) {
|
|
1178
|
+
const identifier = task.trigger.identifier;
|
|
1179
|
+
if (identifier !== void 0) return identifier === row.identifier && identifiers.includes(identifier) ? void 0 : "The saved trigger has a different identifier from its row.";
|
|
1180
|
+
if (row.identifier !== null) return "The saved trigger has no identifier, but its row has one.";
|
|
1181
|
+
const problems = registeredEventTriggerProblems(catalog, task.trigger);
|
|
1182
|
+
return problems.length > 0 ? problems.map((problem) => problem.message).join(" ") : void 0;
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Read the rows that can match an Event: live rows of one team and
|
|
1186
|
+
* namespace whose identifier is one of these, or that have no identifier,
|
|
1187
|
+
* and that select one of these event types. Skip and log a row that does
|
|
1188
|
+
* not parse or that the gate rejects.
|
|
1189
|
+
*/
|
|
1190
|
+
async function readGatedEventAutomations(db, input) {
|
|
1191
|
+
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));
|
|
1192
|
+
const plugins = automationEventCatalog(input.catalog);
|
|
1193
|
+
return rows.flatMap((row) => {
|
|
1194
|
+
const task = readMatchableEventAutomationRow(row);
|
|
1195
|
+
if (!task) return [];
|
|
1196
|
+
const problem = eventAutomationGateProblem(row, task, input.identifiers, plugins);
|
|
1197
|
+
if (problem === void 0) return [task];
|
|
1198
|
+
logWarn("event_automation.gate.rejected", {
|
|
1199
|
+
"app.task.id": task.id,
|
|
1200
|
+
"app.task.type": "event",
|
|
1201
|
+
"app.event_automation.skip_reason": problem
|
|
1202
|
+
});
|
|
1203
|
+
return [];
|
|
983
1204
|
});
|
|
984
|
-
const byDate = /* @__PURE__ */ new Map();
|
|
985
|
-
for (let offset = 0; offset < dayCount; offset += 1) {
|
|
986
|
-
const date = utcDate(startMs + offset * 864e5);
|
|
987
|
-
byDate.set(date, emptyDay(date));
|
|
988
|
-
}
|
|
989
|
-
for (const row of rows) {
|
|
990
|
-
const day = byDate.get(row.date);
|
|
991
|
-
if (!day) continue;
|
|
992
|
-
if (row.kind === "scheduled") day.scheduled = row.count;
|
|
993
|
-
else if (row.kind === "event") day.event = row.count;
|
|
994
|
-
if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
|
|
995
|
-
}
|
|
996
|
-
return [...byDate.values()];
|
|
997
1205
|
}
|
|
998
|
-
/**
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1206
|
+
/** The filters of a match whose keys are in this data. */
|
|
1207
|
+
function knownMatch(match, data) {
|
|
1208
|
+
if (!match) return void 0;
|
|
1209
|
+
return Object.fromEntries(Object.entries(match).filter(([key]) => data[key] !== void 0));
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Collect match keys from live event automations for these identifiers and
|
|
1213
|
+
* event types, and from automations with no identifier. Does not evaluate
|
|
1214
|
+
* match values, except for automations with no identifier: one whose
|
|
1215
|
+
* filters on the keys in `data` fail adds no keys. So a broad trigger for
|
|
1216
|
+
* one repository does not make every repository load its lazy data.
|
|
1217
|
+
*/
|
|
1218
|
+
async function collectEventAutomationMatchKeys(db, input) {
|
|
1219
|
+
const eventTypes = [...new Set(input.eventTypes.map((eventType) => eventType.trim()).filter(Boolean))];
|
|
1220
|
+
const identifiers = [...new Set(input.identifiers.map((value) => value.trim()).filter(Boolean))];
|
|
1221
|
+
if (eventTypes.length === 0) return [];
|
|
1222
|
+
const tasks = await readGatedEventAutomations(db, {
|
|
1223
|
+
catalog: input.catalog,
|
|
1224
|
+
eventTypes,
|
|
1225
|
+
identifiers,
|
|
1226
|
+
namespace: input.namespace,
|
|
1227
|
+
teamId: input.teamId
|
|
1011
1228
|
});
|
|
1012
|
-
const
|
|
1013
|
-
for (
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
}
|
|
1017
|
-
for (const row of rows) {
|
|
1018
|
-
const hour = byHour.get(row.date);
|
|
1019
|
-
if (!hour) continue;
|
|
1020
|
-
if (row.kind === "scheduled") hour.scheduled = row.count;
|
|
1021
|
-
else if (row.kind === "event") hour.event = row.count;
|
|
1022
|
-
if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
|
|
1229
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1230
|
+
for (const task of tasks) {
|
|
1231
|
+
if (task.trigger.identifier === void 0 && input.data && !eventMatches(knownMatch(task.trigger.match, input.data), input.data)) continue;
|
|
1232
|
+
for (const key of Object.keys(task.trigger.match ?? {})) keys.add(key);
|
|
1023
1233
|
}
|
|
1024
|
-
return [...
|
|
1234
|
+
return [...keys].sort();
|
|
1025
1235
|
}
|
|
1026
|
-
/**
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1236
|
+
/**
|
|
1237
|
+
* Find every live task matching one normalized event: tasks for its exact
|
|
1238
|
+
* identifier, and tasks with no identifier whose filters match. The gate
|
|
1239
|
+
* skips a row whose trigger and identifier column disagree, and a row with
|
|
1240
|
+
* no identifier whose trigger the enabled `catalog` rejects.
|
|
1241
|
+
*/
|
|
1242
|
+
async function findMatchingEventAutomations(db, event, teamId, catalog) {
|
|
1243
|
+
return (await readGatedEventAutomations(db, {
|
|
1244
|
+
catalog,
|
|
1245
|
+
eventTypes: [event.eventType],
|
|
1246
|
+
identifiers: [event.identifier],
|
|
1247
|
+
namespace: event.namespace,
|
|
1248
|
+
teamId
|
|
1249
|
+
})).filter((task) => task.trigger.events.includes(event.eventType) && eventMatches(task.trigger.match, event.data));
|
|
1035
1250
|
}
|
|
1036
|
-
/**
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1251
|
+
/**
|
|
1252
|
+
* Change lifecycle under the same row lock as edits, without changing
|
|
1253
|
+
* credentials. A pause keeps an unresolved block reason, so resuming a paused
|
|
1254
|
+
* blocked automation returns it to blocked. Resume a blocked automation to
|
|
1255
|
+
* clear the reason. A resume also clears the run-limit count first.
|
|
1256
|
+
*/
|
|
1257
|
+
async function setEventAutomationStatus(db, id, status, revision) {
|
|
1258
|
+
if (status === "active" && (await getEventAutomation(db, id))?.status !== "active") await clearEventAutomationRuns(id);
|
|
1259
|
+
return db.transaction(async (tx) => {
|
|
1260
|
+
const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(id)).for("update");
|
|
1261
|
+
const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
|
|
1262
|
+
requireAutomationRevision(current, revision);
|
|
1263
|
+
if (!current || current.status === "deleted") throw new Error("Automation no longer exists.");
|
|
1264
|
+
const next = status === "paused" ? {
|
|
1265
|
+
status,
|
|
1266
|
+
statusReason: current.statusReason
|
|
1267
|
+
} : current.status === "paused" && current.statusReason ? {
|
|
1268
|
+
status: "blocked",
|
|
1269
|
+
statusReason: current.statusReason
|
|
1270
|
+
} : {
|
|
1271
|
+
status,
|
|
1272
|
+
statusReason: void 0
|
|
1273
|
+
};
|
|
1274
|
+
await tx.update(juniorAutomations).set({
|
|
1275
|
+
status: next.status,
|
|
1276
|
+
statusReason: next.statusReason ?? null
|
|
1277
|
+
}).where(eventAutomationWhere(id));
|
|
1278
|
+
const { statusReason: _statusReason, ...rest } = current;
|
|
1279
|
+
return {
|
|
1280
|
+
...rest,
|
|
1281
|
+
status: next.status,
|
|
1282
|
+
...next.statusReason ? { statusReason: next.statusReason } : void 0
|
|
1283
|
+
};
|
|
1284
|
+
});
|
|
1043
1285
|
}
|
|
1044
1286
|
/**
|
|
1045
|
-
*
|
|
1046
|
-
*
|
|
1047
|
-
*
|
|
1048
|
-
*
|
|
1287
|
+
* Stop an event automation after a run reports a problem that only its
|
|
1288
|
+
* creator can fix. An active automation becomes blocked. A paused automation
|
|
1289
|
+
* stays paused and keeps the reason, so resume returns it to blocked.
|
|
1290
|
+
* Deleted automations do not change. Returns true only when this call set
|
|
1291
|
+
* the automation to blocked, so the creator notice goes once and never for
|
|
1292
|
+
* an automation that the dashboard shows as paused.
|
|
1049
1293
|
*/
|
|
1050
|
-
async function
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
conversationId: juniorAutomationRuns.conversationId,
|
|
1056
|
-
instruction: juniorAutomations.instruction,
|
|
1057
|
-
title: juniorAutomations.title
|
|
1058
|
-
}).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(inArray(juniorAutomationRuns.conversationId, untitledIds));
|
|
1059
|
-
for (const row of rows) {
|
|
1060
|
-
const title = row.title?.trim() || fallbackShortTitle(row.instruction, "");
|
|
1061
|
-
if (row.conversationId && title) titles.set(row.conversationId, title);
|
|
1062
|
-
}
|
|
1063
|
-
return titles;
|
|
1294
|
+
async function blockEventAutomation(db, id, reason) {
|
|
1295
|
+
return (await db.update(juniorAutomations).set({
|
|
1296
|
+
status: sql`case when ${juniorAutomations.status} = 'active' then 'blocked' else ${juniorAutomations.status} end`,
|
|
1297
|
+
statusReason: reason
|
|
1298
|
+
}).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";
|
|
1064
1299
|
}
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1300
|
+
// src/chat/scheduled-automations/tasks.ts
|
|
1301
|
+
const SCHEDULER_KEY_PREFIX = "junior:scheduler";
|
|
1302
|
+
/** Decode a Scheduled automation row. Returns undefined for an invalid row. */
|
|
1303
|
+
function parseScheduledAutomationRow(row) {
|
|
1304
|
+
const columns = {
|
|
1305
|
+
createdAtMs: row.createdAtMs,
|
|
1306
|
+
creatorIdentityId: row.creatorIdentityId,
|
|
1307
|
+
id: row.id,
|
|
1308
|
+
nextRunAtMs: row.nextRunAtMs,
|
|
1309
|
+
runNowAtMs: row.runNowAtMs,
|
|
1310
|
+
status: row.status,
|
|
1311
|
+
statusReason: row.statusReason,
|
|
1312
|
+
title: row.title
|
|
1313
|
+
};
|
|
1314
|
+
const parsed = scheduledAutomationSchema.safeParse({
|
|
1315
|
+
...row.record,
|
|
1316
|
+
...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
|
|
1317
|
+
});
|
|
1318
|
+
return parsed.success ? parsed.data : void 0;
|
|
1068
1319
|
}
|
|
1069
|
-
/**
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1320
|
+
/** Keep scan paths from returning current or legacy tombstones. */
|
|
1321
|
+
function isListedScheduledAutomation(task) {
|
|
1322
|
+
return task !== void 0 && task.status !== "deleted";
|
|
1323
|
+
}
|
|
1324
|
+
/** Build the stable run id for one task occurrence. */
|
|
1325
|
+
function scheduledRunId(taskId, scheduledForMs) {
|
|
1326
|
+
return `${taskId}:${scheduledForMs}`;
|
|
1327
|
+
}
|
|
1328
|
+
/** Acquire the deployed advisory lock for one scheduled automation. */
|
|
1329
|
+
function withScheduledAutomationLock(db, taskId, callback) {
|
|
1330
|
+
return db.transaction(async (tx) => {
|
|
1331
|
+
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
|
|
1332
|
+
return await callback(tx);
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
function requireStoredTask(task) {
|
|
1336
|
+
const parsed = scheduledAutomationSchema.safeParse(task);
|
|
1337
|
+
if (!parsed.success) throw new Error("Scheduled automation routing context is invalid.");
|
|
1338
|
+
const { title, ...current } = parsed.data;
|
|
1339
|
+
const normalizedTitle = title?.trim() || void 0;
|
|
1340
|
+
return {
|
|
1341
|
+
...current,
|
|
1342
|
+
...normalizedTitle ? { title: normalizedTitle } : void 0
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
async function upsertScheduledAutomation(db, task) {
|
|
1346
|
+
const { createdAtMs, creatorIdentityId, id, nextRunAtMs, runNowAtMs, status, statusReason, title, ...record } = task;
|
|
1347
|
+
const columns = {
|
|
1348
|
+
channelId: record.destination.channelId,
|
|
1349
|
+
createdAtMs,
|
|
1350
|
+
creatorIdentityId,
|
|
1351
|
+
creatorSlackUserId: record.createdBy.slackUserId,
|
|
1352
|
+
instruction: record.task.text,
|
|
1353
|
+
nextRunAtMs: nextRunAtMs ?? null,
|
|
1354
|
+
record,
|
|
1355
|
+
runNowAtMs: runNowAtMs ?? null,
|
|
1356
|
+
status,
|
|
1357
|
+
statusReason: statusReason ?? null,
|
|
1358
|
+
teamId: record.destination.teamId,
|
|
1359
|
+
title: title?.trim() || null
|
|
1360
|
+
};
|
|
1361
|
+
await db.insert(juniorAutomations).values({
|
|
1362
|
+
...columns,
|
|
1363
|
+
id,
|
|
1364
|
+
kind: "scheduled"
|
|
1365
|
+
}).onConflictDoUpdate({
|
|
1366
|
+
target: juniorAutomations.id,
|
|
1367
|
+
set: columns
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
/** Read and decode one scheduled automation. */
|
|
1371
|
+
async function readScheduledAutomation(db, taskId) {
|
|
1372
|
+
const rows = await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.id, taskId), eq(juniorAutomations.kind, "scheduled"))).limit(1);
|
|
1373
|
+
return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
|
|
1081
1374
|
}
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
automationVersion: juniorAutomationRuns.automationVersion,
|
|
1085
|
-
conversationId: juniorAutomationRuns.conversationId,
|
|
1086
|
-
credentialMode: sql`${juniorAutomationVersions.definition}->>'credentialMode'`,
|
|
1087
|
-
durationMs: juniorConversations.durationMs,
|
|
1088
|
-
errorMessage: juniorAutomationRuns.errorMessage,
|
|
1089
|
-
executedAtMs: juniorAutomationRuns.completedAtMs,
|
|
1090
|
-
executionId: juniorAutomationRuns.id,
|
|
1091
|
-
scheduledForMs: juniorAutomationRuns.scheduledForMs,
|
|
1092
|
-
startedAtMs: juniorAutomationRuns.startedAtMs,
|
|
1093
|
-
status: juniorAutomationRuns.status,
|
|
1094
|
-
title: juniorConversations.title,
|
|
1095
|
-
usage: juniorConversations.usage
|
|
1096
|
-
};
|
|
1097
|
-
function executionConversation() {
|
|
1098
|
-
return eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId);
|
|
1375
|
+
async function readListedScheduledAutomations(db, teamId) {
|
|
1376
|
+
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);
|
|
1099
1377
|
}
|
|
1100
|
-
|
|
1101
|
-
|
|
1378
|
+
/** List decoded scheduled automations for one team in stable creation order. */
|
|
1379
|
+
async function listScheduledAutomationsForTeam(db, teamId) {
|
|
1380
|
+
return await readListedScheduledAutomations(db, teamId);
|
|
1102
1381
|
}
|
|
1103
|
-
function
|
|
1104
|
-
|
|
1382
|
+
async function writeScheduledAutomation(db, task, current, editedBy) {
|
|
1383
|
+
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")));
|
|
1384
|
+
if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
|
|
1385
|
+
await upsertScheduledAutomation(db, task);
|
|
1386
|
+
await recordAutomationVersion(db, task, current, editedBy);
|
|
1105
1387
|
}
|
|
1106
|
-
function
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
const scheduledFor = isoTime(row.scheduledForMs);
|
|
1113
|
-
const startedAt = isoTime(row.startedAtMs);
|
|
1114
|
-
return {
|
|
1115
|
-
...row.automationVersion !== null ? { automationVersion: row.automationVersion } : void 0,
|
|
1116
|
-
...row.conversationId ? { conversationId: row.conversationId } : void 0,
|
|
1117
|
-
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
1118
|
-
...row.credentialMode === "creator" || row.credentialMode === "system" ? { credentialMode: row.credentialMode } : void 0,
|
|
1119
|
-
...durationMs !== void 0 ? { durationMs } : void 0,
|
|
1120
|
-
...error ? { error } : void 0,
|
|
1121
|
-
executedAt: new Date(row.executedAtMs).toISOString(),
|
|
1122
|
-
executionId: row.executionId,
|
|
1123
|
-
...scheduledFor ? { scheduledFor } : void 0,
|
|
1124
|
-
...startedAt ? { startedAt } : void 0,
|
|
1125
|
-
status: row.status,
|
|
1126
|
-
...title ? { title } : void 0,
|
|
1127
|
-
...totalTokens !== void 0 ? { totalTokens } : void 0
|
|
1128
|
-
};
|
|
1388
|
+
async function skipPendingRunsForDeletedTask(db, task) {
|
|
1389
|
+
await db.update(juniorAutomationRuns).set({
|
|
1390
|
+
completedAtMs: task.updatedAtMs,
|
|
1391
|
+
errorMessage: `Scheduled automation ${task.id} was deleted before the run started.`,
|
|
1392
|
+
status: "skipped"
|
|
1393
|
+
}).where(and(eq(juniorAutomationRuns.automationId, task.id), eq(juniorAutomationRuns.status, "pending")));
|
|
1129
1394
|
}
|
|
1130
|
-
/**
|
|
1131
|
-
async function
|
|
1132
|
-
const
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
automationId: args.automationId,
|
|
1139
|
-
bucket: executionDate,
|
|
1140
|
-
endMs,
|
|
1141
|
-
startMs
|
|
1395
|
+
/** Create a scheduled automation once under its retry-stable task lock. */
|
|
1396
|
+
async function createScheduledAutomation(db, task) {
|
|
1397
|
+
const next = requireStoredTask(task);
|
|
1398
|
+
return await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
1399
|
+
const current = await readScheduledAutomation(tx, task.id);
|
|
1400
|
+
if (current) return current;
|
|
1401
|
+
await writeScheduledAutomation(tx, next, void 0);
|
|
1402
|
+
return next;
|
|
1142
1403
|
});
|
|
1143
|
-
const byDate = /* @__PURE__ */ new Map();
|
|
1144
|
-
for (let offset = 0; offset < dayCount; offset += 1) {
|
|
1145
|
-
const date = utcDate(startMs + offset * 864e5);
|
|
1146
|
-
byDate.set(date, emptyStatusDay(date));
|
|
1147
|
-
}
|
|
1148
|
-
for (const row of rows) {
|
|
1149
|
-
const day = byDate.get(row.date);
|
|
1150
|
-
if (!day) continue;
|
|
1151
|
-
if (row.status === "completed") day.completed = row.count;
|
|
1152
|
-
else if (row.status === "failed") day.failed = row.count;
|
|
1153
|
-
else if (row.status === "blocked") day.blocked = row.count;
|
|
1154
|
-
}
|
|
1155
|
-
return [...byDate.values()];
|
|
1156
1404
|
}
|
|
1157
|
-
/**
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
automationId: args.automationId,
|
|
1168
|
-
bucket: executionHour,
|
|
1169
|
-
endMs,
|
|
1170
|
-
startMs
|
|
1405
|
+
/**
|
|
1406
|
+
* Save a scheduled automation and clear its blocked occurrence on reactivation.
|
|
1407
|
+
* Pass `editedBy` when a person changes the definition so its version names them.
|
|
1408
|
+
*/
|
|
1409
|
+
async function saveScheduledAutomation(db, task, expectedRevision, editedBy) {
|
|
1410
|
+
const next = requireStoredTask(task);
|
|
1411
|
+
await withScheduledAutomationLock(db, task.id, async (tx) => {
|
|
1412
|
+
const current = await readScheduledAutomation(tx, task.id);
|
|
1413
|
+
if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
|
|
1414
|
+
await writeScheduledAutomation(tx, next, current, editedBy);
|
|
1171
1415
|
});
|
|
1172
|
-
|
|
1173
|
-
for (let offset = 0; offset < hourCount; offset += 1) {
|
|
1174
|
-
const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
|
|
1175
|
-
byHour.set(date, emptyStatusDay(date));
|
|
1176
|
-
}
|
|
1177
|
-
for (const row of rows) {
|
|
1178
|
-
const hour = byHour.get(row.date);
|
|
1179
|
-
if (!hour) continue;
|
|
1180
|
-
if (row.status === "completed") hour.completed = row.count;
|
|
1181
|
-
else if (row.status === "failed") hour.failed = row.count;
|
|
1182
|
-
else if (row.status === "blocked") hour.blocked = row.count;
|
|
1183
|
-
}
|
|
1184
|
-
return [...byHour.values()];
|
|
1416
|
+
return next;
|
|
1185
1417
|
}
|
|
1186
|
-
/**
|
|
1187
|
-
async function
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1418
|
+
/** Save a scheduled automation inside a task lock already held by the caller. */
|
|
1419
|
+
async function saveScheduledAutomationInLock(db, task, current) {
|
|
1420
|
+
await writeScheduledAutomation(db, requireStoredTask(task), current);
|
|
1421
|
+
}
|
|
1422
|
+
/** Mark one live scheduled automation deleted while keeping its history. */
|
|
1423
|
+
async function deleteScheduledAutomation(db, id, nowMs = Date.now()) {
|
|
1424
|
+
return await withScheduledAutomationLock(db, id, async (tx) => {
|
|
1425
|
+
const current = await readScheduledAutomation(tx, id);
|
|
1426
|
+
if (!current || current.status === "deleted") return void 0;
|
|
1427
|
+
const deleted = requireStoredTask({
|
|
1428
|
+
...current,
|
|
1429
|
+
nextRunAtMs: void 0,
|
|
1430
|
+
runNowAtMs: void 0,
|
|
1431
|
+
status: "deleted",
|
|
1432
|
+
updatedAtMs: nowMs
|
|
1433
|
+
});
|
|
1434
|
+
await writeScheduledAutomation(tx, deleted, current);
|
|
1435
|
+
return deleted;
|
|
1436
|
+
});
|
|
1193
1437
|
}
|
|
1194
1438
|
// src/chat/automations/blocked-notice.ts
|
|
1195
1439
|
function buildBlockedNoticeText(automationId, title, reason) {
|
|
@@ -1547,79 +1791,281 @@ async function getPluginDispatchProjection(args) {
|
|
|
1547
1791
|
if (!record || record.plugin !== args.plugin) return;
|
|
1548
1792
|
return toDispatchProjection(record);
|
|
1549
1793
|
}
|
|
1550
|
-
// src/chat/
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1794
|
+
// src/chat/plugins/task-runner.ts
|
|
1795
|
+
/**
|
|
1796
|
+
* Plugin background-task orchestration.
|
|
1797
|
+
*
|
|
1798
|
+
* Core schedules tasks from completed sessions and exposes plugins only a
|
|
1799
|
+
* bounded run projection rather than live runtime internals or queue
|
|
1800
|
+
* payloads.
|
|
1801
|
+
*/
|
|
1802
|
+
var task_runner_exports = /* @__PURE__ */ __exportAll({
|
|
1803
|
+
processPluginTask: () => processPluginTask,
|
|
1804
|
+
scheduleSessionCompletedPluginTasks: () => scheduleSessionCompletedPluginTasks
|
|
1805
|
+
});
|
|
1806
|
+
const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
|
|
1807
|
+
function isRecord(value) {
|
|
1808
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
1809
|
+
}
|
|
1810
|
+
function textPart(value) {
|
|
1811
|
+
if (isRecord(value) && value.type === "text" && typeof value.text === "string") return value.text;
|
|
1812
|
+
}
|
|
1813
|
+
function messageText(message) {
|
|
1814
|
+
const content = message.content;
|
|
1815
|
+
if (typeof content === "string") return sanitizeText(content);
|
|
1816
|
+
if (!Array.isArray(content)) return "";
|
|
1817
|
+
return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
|
|
1818
|
+
}
|
|
1819
|
+
function toolResultText(message) {
|
|
1820
|
+
const record = message;
|
|
1821
|
+
return sanitizeText([
|
|
1822
|
+
messageText(message),
|
|
1823
|
+
record.output,
|
|
1824
|
+
record.result,
|
|
1825
|
+
record.stdout,
|
|
1826
|
+
record.stderr,
|
|
1827
|
+
record.toolResult
|
|
1828
|
+
].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
|
|
1829
|
+
}
|
|
1830
|
+
function sanitizeText(text) {
|
|
1831
|
+
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();
|
|
1832
|
+
}
|
|
1833
|
+
/** Build the transcript provenance for a user message from its Pi provenance. */
|
|
1834
|
+
function messageProvenance(provenance) {
|
|
1835
|
+
return {
|
|
1836
|
+
authority: provenance.authority,
|
|
1837
|
+
...provenance.actor ? { actor: provenance.actor } : void 0
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
function runTranscriptEntry(message, provenance, runActor) {
|
|
1841
|
+
const role = getPiMessageRole(message);
|
|
1842
|
+
if (role === "user" || role === "assistant") {
|
|
1843
|
+
const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
|
|
1844
|
+
if (!text) return;
|
|
1845
|
+
if (role === "assistant") return {
|
|
1846
|
+
type: "message",
|
|
1847
|
+
role,
|
|
1848
|
+
text
|
|
1849
|
+
};
|
|
1850
|
+
return {
|
|
1851
|
+
type: "message",
|
|
1852
|
+
role,
|
|
1853
|
+
text,
|
|
1854
|
+
provenance: messageProvenance(provenance),
|
|
1855
|
+
isRunActor: sameActorIdentity(provenance.actor, runActor)
|
|
1856
|
+
};
|
|
1561
1857
|
}
|
|
1562
|
-
return
|
|
1858
|
+
if (!isToolResultMessage(message)) return;
|
|
1859
|
+
const toolName = normalizeToolNameFromResult(message);
|
|
1860
|
+
if (!toolName) return;
|
|
1861
|
+
const text = toolResultText(message);
|
|
1862
|
+
return {
|
|
1863
|
+
type: "toolResult",
|
|
1864
|
+
toolName,
|
|
1865
|
+
isError: isToolResultError(message),
|
|
1866
|
+
...text ? { text } : void 0
|
|
1867
|
+
};
|
|
1563
1868
|
}
|
|
1564
1869
|
/**
|
|
1565
|
-
*
|
|
1566
|
-
*
|
|
1567
|
-
*
|
|
1870
|
+
* Slice the current turn's Pi messages with their aligned provenance and strip
|
|
1871
|
+
* runtime turn context, keeping each surviving message paired with the exact
|
|
1872
|
+
* provenance recorded for it. Stripping can drop or rewrite messages, so the
|
|
1873
|
+
* pairing is applied per message rather than by post-strip index.
|
|
1568
1874
|
*/
|
|
1569
|
-
function
|
|
1570
|
-
|
|
1571
|
-
const
|
|
1875
|
+
function turnMessagesWithProvenance(record) {
|
|
1876
|
+
const startIndex = record.turnStartMessageIndex ?? 0;
|
|
1877
|
+
const messages = record.piMessages.slice(startIndex);
|
|
1878
|
+
const provenance = record.piMessageProvenance.slice(startIndex);
|
|
1879
|
+
const paired = [];
|
|
1880
|
+
for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
|
|
1881
|
+
message: stripped,
|
|
1882
|
+
provenance: provenance[index] ?? { authority: "context" }
|
|
1883
|
+
});
|
|
1884
|
+
return paired;
|
|
1885
|
+
}
|
|
1886
|
+
/** Recover the Slack context author identity from a persisted thread message. */
|
|
1887
|
+
function slackContextAuthor(location, message) {
|
|
1888
|
+
const userId = message.author?.userId?.trim();
|
|
1889
|
+
if (!userId) return;
|
|
1572
1890
|
return {
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
...
|
|
1891
|
+
platform: "slack",
|
|
1892
|
+
teamId: location.teamId,
|
|
1893
|
+
userId,
|
|
1894
|
+
...message.author?.userName ? { userName: message.author.userName } : void 0,
|
|
1895
|
+
...message.author?.fullName ? { fullName: message.author.fullName } : void 0
|
|
1578
1896
|
};
|
|
1579
1897
|
}
|
|
1898
|
+
function slackTimestampMs(value) {
|
|
1899
|
+
const timestamp = parseSlackMessageTs(value);
|
|
1900
|
+
if (!timestamp) return;
|
|
1901
|
+
const timestampMs = Number(timestamp) * 1e3;
|
|
1902
|
+
return Number.isFinite(timestampMs) ? timestampMs : void 0;
|
|
1903
|
+
}
|
|
1904
|
+
function conversationMessageTimestampMs(message) {
|
|
1905
|
+
if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
|
|
1906
|
+
return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
|
|
1907
|
+
}
|
|
1908
|
+
function messageExistedAtRunCompletion(message, completedAtMs) {
|
|
1909
|
+
const messageTimestampMs = conversationMessageTimestampMs(message);
|
|
1910
|
+
return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
|
|
1911
|
+
}
|
|
1580
1912
|
/**
|
|
1581
|
-
*
|
|
1913
|
+
* Project bounded public-thread context into the run transcript.
|
|
1582
1914
|
*
|
|
1583
|
-
*
|
|
1915
|
+
* Prior public Slack messages from the current Conversation are durable
|
|
1916
|
+
* evidence a completed run may have acted on, so passive consumers can cite
|
|
1917
|
+
* them. They are always context authority (never instruction), and private or
|
|
1918
|
+
* local Conversations add nothing here.
|
|
1584
1919
|
*/
|
|
1585
|
-
async function
|
|
1586
|
-
|
|
1587
|
-
const
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
if (
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1920
|
+
async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
|
|
1921
|
+
if (location?.provider !== "slack" || visibility !== "public") return [];
|
|
1922
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(record.conversationId));
|
|
1923
|
+
await hydrateConversationMessages({
|
|
1924
|
+
conversation,
|
|
1925
|
+
conversationId: record.conversationId
|
|
1926
|
+
});
|
|
1927
|
+
const entries = [];
|
|
1928
|
+
for (const message of conversation.messages) {
|
|
1929
|
+
if (message.role !== "user") continue;
|
|
1930
|
+
if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
|
|
1931
|
+
const text = sanitizeText(message.text);
|
|
1932
|
+
if (!text) continue;
|
|
1933
|
+
const author = slackContextAuthor(location, message);
|
|
1934
|
+
entries.push({
|
|
1935
|
+
type: "message",
|
|
1936
|
+
role: "user",
|
|
1937
|
+
text,
|
|
1938
|
+
provenance: {
|
|
1939
|
+
authority: "context",
|
|
1940
|
+
...author ? { actor: author } : void 0
|
|
1941
|
+
},
|
|
1942
|
+
isRunActor: sameActorIdentity(author, runActor)
|
|
1602
1943
|
});
|
|
1603
|
-
return {
|
|
1604
|
-
destination,
|
|
1605
|
-
...location ? { location } : void 0,
|
|
1606
|
-
...slackSource ? { source: slackSource } : void 0
|
|
1607
|
-
};
|
|
1608
1944
|
}
|
|
1945
|
+
return entries;
|
|
1946
|
+
}
|
|
1947
|
+
async function withPluginTaskLock(taskId, callback) {
|
|
1948
|
+
const state = getStateAdapter();
|
|
1949
|
+
await state.connect();
|
|
1950
|
+
const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
|
|
1951
|
+
if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
|
|
1952
|
+
try {
|
|
1953
|
+
return await callback();
|
|
1954
|
+
} finally {
|
|
1955
|
+
await state.releaseLock(lock);
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
/** Load the bounded completed-run projection exposed to plugin tasks. */
|
|
1959
|
+
async function loadPluginRun(params) {
|
|
1960
|
+
const record = await getTurnRecord(params.conversationId, params.sessionId);
|
|
1961
|
+
if (!record) throw new Error("Completed plugin task session record is unavailable");
|
|
1962
|
+
if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
|
|
1963
|
+
const conversationStore = getConversationStore();
|
|
1964
|
+
const routing = await resolveConversationRouting({
|
|
1965
|
+
conversationId: params.conversationId,
|
|
1966
|
+
conversationStore
|
|
1967
|
+
});
|
|
1968
|
+
if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
|
|
1969
|
+
const source = record.source ?? routing.source;
|
|
1970
|
+
if (!source) throw new Error("Completed plugin task session record is missing Source");
|
|
1971
|
+
const conversation = await conversationStore.get({ conversationId: params.conversationId });
|
|
1972
|
+
const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
|
|
1973
|
+
const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
|
|
1974
|
+
const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
|
|
1975
|
+
const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
|
|
1976
|
+
const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
|
|
1977
|
+
return pluginRunContextSchema.parse({
|
|
1978
|
+
...actorUser ? { actorUserId: actorUser.id } : void 0,
|
|
1979
|
+
completedAtMs: record.updatedAtMs,
|
|
1980
|
+
conversationId: record.conversationId,
|
|
1981
|
+
destination: routing.destination,
|
|
1982
|
+
...routing.location ? { locationId: routing.location.id } : void 0,
|
|
1983
|
+
actors: record.actors,
|
|
1984
|
+
...runActor ? { actor: runActor } : void 0,
|
|
1985
|
+
runId: record.turnId,
|
|
1986
|
+
source,
|
|
1987
|
+
transcript: [...contextEntries, ...runEntries]
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
/** Build the plugin-facing context for one claimed task attempt. */
|
|
1991
|
+
function taskPluginContext(plugin, message, options = {}) {
|
|
1992
|
+
const pluginName = plugin.manifest.name;
|
|
1993
|
+
const sessionParams = pluginTaskParamsSchema.parse(message.params);
|
|
1994
|
+
const onCost = createPluginModelCostRecorder({
|
|
1995
|
+
conversationId: sessionParams.conversationId,
|
|
1996
|
+
pluginName,
|
|
1997
|
+
source: "task",
|
|
1998
|
+
turnId: sessionParams.sessionId
|
|
1999
|
+
});
|
|
1609
2000
|
return {
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
2001
|
+
db: getDb(),
|
|
2002
|
+
embedder: createPluginEmbedder(pluginName, {
|
|
2003
|
+
onCost,
|
|
2004
|
+
signal: options.signal
|
|
2005
|
+
}),
|
|
2006
|
+
events: createPluginConversationEvents({
|
|
2007
|
+
conversationId: sessionParams.conversationId,
|
|
2008
|
+
operationId: pluginTaskId(message),
|
|
2009
|
+
plugin,
|
|
2010
|
+
turnId: sessionParams.sessionId
|
|
2011
|
+
}),
|
|
2012
|
+
id: pluginTaskId(message),
|
|
2013
|
+
log: createPluginLogger(pluginName),
|
|
2014
|
+
model: createPluginModel(pluginName, plugin.model, {
|
|
2015
|
+
onCost,
|
|
2016
|
+
signal: options.signal
|
|
2017
|
+
}),
|
|
2018
|
+
name: message.name,
|
|
2019
|
+
plugin: { name: pluginName },
|
|
2020
|
+
cache: createPluginCache(pluginName),
|
|
2021
|
+
run: { async load() {
|
|
2022
|
+
return await loadPluginRun(sessionParams);
|
|
2023
|
+
} },
|
|
2024
|
+
state: createPluginState(pluginName)
|
|
1613
2025
|
};
|
|
1614
2026
|
}
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
|
|
2027
|
+
function findPluginTask(message) {
|
|
2028
|
+
const plugin = [...coreTaskRegistrations(), ...getPlugins()].find((candidate) => candidate.manifest.name === message.plugin);
|
|
2029
|
+
if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
|
|
1619
2030
|
return {
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
source: routing.source
|
|
2031
|
+
plugin,
|
|
2032
|
+
task: plugin.tasks[message.name]
|
|
1623
2033
|
};
|
|
1624
2034
|
}
|
|
1625
|
-
|
|
2035
|
+
/** Schedule all plugin tasks interested in a completed agent-run session. */
|
|
2036
|
+
async function scheduleSessionCompletedPluginTasks(params, options = {}) {
|
|
2037
|
+
const coreParams = pluginTaskParamsSchema.parse(params);
|
|
2038
|
+
const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
|
|
2039
|
+
name,
|
|
2040
|
+
plugin
|
|
2041
|
+
})));
|
|
2042
|
+
if (taskRegistrations.length === 0) return;
|
|
2043
|
+
const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
|
|
2044
|
+
if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
|
|
2045
|
+
const send = options.send ?? sendVercelPluginTask;
|
|
2046
|
+
const messages = taskRegistrations.map(({ name, plugin }) => ({
|
|
2047
|
+
name,
|
|
2048
|
+
params: coreParams,
|
|
2049
|
+
plugin: plugin.manifest.name
|
|
2050
|
+
}));
|
|
2051
|
+
await Promise.all(messages.map(async (message) => {
|
|
2052
|
+
await send(message);
|
|
2053
|
+
}));
|
|
2054
|
+
}
|
|
2055
|
+
/**
|
|
2056
|
+
* Execute one parsed plugin task request in a `plugin.task` span. The span
|
|
2057
|
+
* includes the lock wait, because both delay the work that runs the task.
|
|
2058
|
+
*/
|
|
2059
|
+
async function processPluginTask(message, options = {}) {
|
|
2060
|
+
const params = pluginTaskParamsSchema.parse(message.params);
|
|
2061
|
+
await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
|
|
2062
|
+
const resolved = findPluginTask(message);
|
|
2063
|
+
if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
|
|
2064
|
+
await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
|
|
2065
|
+
}), {
|
|
2066
|
+
"app.ai.turn.session_id": params.sessionId,
|
|
2067
|
+
"app.plugin.name": message.plugin,
|
|
2068
|
+
"app.plugin.task": message.name
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
export { readAutomationExecutionByConversationId as $, withScheduledAutomationLock as A, registeredEventTriggerProblems as At, setEventAutomationStatus as B, deleteScheduledAutomation as C, describeRegisteredEventTrigger as Ct, saveScheduledAutomation as D, eventWatchUnavailable as Dt, readScheduledAutomation as E, eventNamespaceSchema 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, registeredResourceTypeSchema as Mt, createEventAutomation as N, requireEventIdentifier as Nt, saveScheduledAutomationInLock as O, hasEventCatalogEntries as Ot, deleteEventAutomation as P, requireValidEventTrigger as Pt, existingConversationId as Q, parseEventAutomationRow as R, createScheduledAutomation as S, automationEventCatalog as St, parseScheduledAutomationRow as T, eventGuidance as Tt, automationDefinition as U, admitEventAutomationRun as V, automationVersionOf as W, requireAutomationRevision as X, automationRevision as Y, emptyAutomationRunWindows as Z, markDispatchBlocked as _, getPersistedThreadState as _t, claimDispatchMailboxAppend as a, readAutomationExecutions as at, markDispatchRunning as b, coerceThreadConversationState as bt, getDispatchConversationId as c, recordAutomationExecution as ct, getDispatchRecord as d, conversationRangeColumns as dt, readAutomationExecutionDays as et, getDispatchTurnId as f, conversationUsageCostExpr as ft, markDispatchAwaitingResume as g, getPersistedSandboxState as gt, listPendingDispatchMailboxAppends as h, getLocationConfigurationService as ht, buildDispatchId as i, readAutomationExecutionSummaries as it, blockEventAutomation as j, registeredEventTypeSchema as jt, scheduledRunId as k, registeredEventMatchSchema as kt, getDispatchIdForConversation as l, conversationActiveDaysColumn as lt, isTerminalDispatchStatus as m, resolveTurnSessionRouting as mt, scheduleSessionCompletedPluginTasks as n, readAutomationExecutionStatusDays as nt, confirmDispatchMailboxAppend as o, readAutomationRuns as ot, getPluginDispatchProjection as p, resolveConversationRouting as pt, sameDefinitionValue as q, task_runner_exports as r, readAutomationExecutionStatusHours as rt, createOrGetDispatch as s, readAutomationTitlesByConversationId as st, processPluginTask as t, readAutomationExecutionHours as tt, getDispatchInputMessageId as u, conversationAggregateColumns as ut, markDispatchCompleted as v, persistThreadRuntimeState as vt, listScheduledAutomationsForTeam as w, eventCatalogEntry as wt, notifyAutomationBlocked as x, CORE_EVENT_NAMESPACE as xt, markDispatchFailed as y, persistThreadStateById as yt, saveEventAutomation as z };
|