@sentry/junior 0.284.0 → 0.286.0

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