@sentry/junior 0.295.0 → 0.297.0

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