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