@sentry/junior 0.305.0 → 0.306.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 (80) hide show
  1. package/dist/{adapter-context-BpvbUki8.js → adapter-context-CnY-i32r.js} +2 -2
  2. package/dist/{admin-CoDt35ny.js → admin-BLLdLnXh.js} +2 -2
  3. package/dist/{agent-runner-C5d6rY5g.js → agent-runner-BaLjEjPR.js} +261 -190
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +19 -4
  7. package/dist/api.js +137 -40
  8. package/dist/{app-Cs157Zc5.d.ts → app-DvYbM9UD.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +487 -434
  11. package/dist/{background-compaction-queue-BTqMIfTA.js → background-compaction-queue-D2wzxtGU.js} +2 -2
  12. package/dist/{briefs-BRdznF7c.js → briefs-DvyzXfrF.js} +3 -3
  13. package/dist/{catalog-runtime-J52Tej47.js → catalog-runtime-B1R-nHd3.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +5 -5
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-CBZp0udd.js → config-DUD-zMvp.js} +111 -13
  22. package/dist/{connections-BYmuJ6Vm.js → connections-CDhsqPcC.js} +6 -6
  23. package/dist/{continue-in-slack-Cvot6S38.js → continue-in-slack-BXQizz9o.js} +5 -5
  24. package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
  25. package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
  26. package/dist/{conversation-privacy-D2pOzBNl.js → conversation-privacy-YE54gMN8.js} +1 -1
  27. package/dist/{conversation-turn-CI8WDpnK.js → conversation-turn-BzdmrHb0.js} +22 -40
  28. package/dist/{credential-sync-COqnZ1Dx.js → credential-sync-Cdm-e1vJ.js} +14 -13
  29. package/dist/{db-DU84dCVu.js → db-DV2ZUb1Y.js} +90 -11
  30. package/dist/{db-zbN5ZV_o.d.ts → db-pH357Dkt.d.ts} +1 -1
  31. package/dist/{executor-CFyrgOu1.js → executor-CjNhwwnj.js} +47 -4
  32. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  33. package/dist/{install-CQ76CfRw.js → install-DbD7C5td.js} +2 -2
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{lineage-DLd2UxVP.js → lineage-BFdIPb3o.js} +2 -2
  36. package/dist/{logging-BPNTQVFu.js → logging-oYpJYr-S.js} +1 -1
  37. package/dist/{message-BWJLeQ5e.js → message-BBPcMKJY.js} +8 -8
  38. package/dist/{model-input-DoM9Ht-d.js → model-input-DYYF3a8B.js} +3 -3
  39. package/dist/nitro.d.ts +1 -1
  40. package/dist/nitro.js +4 -4
  41. package/dist/{oauth-callback-server-DeHbnAQl.js → oauth-callback-server-C7Q987su.js} +2 -2
  42. package/dist/{projection-CcFBVFUo.js → projection-CWXDE0f6.js} +7738 -6166
  43. package/dist/{prompt-C5LREK2p.js → prompt-P3eRqO8C.js} +15 -7
  44. package/dist/{queue-B2AAL3ym.js → queue-7FSijgqG.js} +4 -4
  45. package/dist/{registry-BjZZqKqi.js → registry-1pzXmplY.js} +1 -1
  46. package/dist/{resolve-CeJgXuH1.js → resolve-n87oXY-d.js} +3 -3
  47. package/dist/{result-icDrueyB.js → result-BmF9v9bv.js} +9 -9
  48. package/dist/{runner-nVfMkMMB.js → runner-4j7ZsxP5.js} +13 -15
  49. package/dist/{sandbox-egress-signals-H9vQ5qRf.js → sandbox-egress-signals-BRQI8HvT.js} +1 -1
  50. package/dist/{automation-CuA3yEcD.js → schedule-CHPWQn-x.js} +347 -5
  51. package/dist/{schema-CKcu-IK6.d.ts → schema-CVbIjrF3.d.ts} +71 -1
  52. package/dist/{schema-Bx0Mlo32.js → schema-D7iIEh6t.js} +52 -6
  53. package/dist/{service-account-Dw06p3zm.js → service-account-BDQ9xzta.js} +3 -3
  54. package/dist/{service-account-DU5865XA.js → service-account-DzQiOmqa.js} +5 -5
  55. package/dist/{session-stop-uotLtp4g.js → session-stop-BQxgHR4X.js} +854 -160
  56. package/dist/{skills-Bex1EaO5.js → skills-CPf4vNuC.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-EPG3riWF.js → slack-conversation-unfurl-B1KEptUg.js} +10 -9
  58. package/dist/{spawn-CoD3vDuS.js → spawn-CjGddiAU.js} +6 -6
  59. package/dist/{state-nCR4Muhn.js → state-9wfj6aSD.js} +4 -4
  60. package/dist/{stop-BFVd0P0m.js → stop-CsQGuN5n.js} +62 -117
  61. package/dist/{store-Ca6G962n.js → store-Dz3YZ7gQ.js} +5 -5
  62. package/dist/{task-queue-BLPZU6kC.js → task-queue-CFlrJguF.js} +3 -3
  63. package/dist/{task-runner-xsOPIxCZ.js → task-runner-frzlUvFD.js} +8 -9
  64. package/dist/{thread-context-BOvZhsKK.js → thread-context-C4QuZlM8.js} +8 -91
  65. package/dist/turn-session-routing-BXaubz2w.js +244 -0
  66. package/dist/{turn-user-message-BrhuyYrH.js → turn-user-message-DNC0eRZ7.js} +3 -3
  67. package/dist/users-XCCKn3xW.js +181 -0
  68. package/dist/{validation-BnY9K5WB.js → validation-L5fdjmFX.js} +1 -1
  69. package/dist/{version-qROlRQGF.js → version-BFmuwgxP.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-CxUiOraX.js → viewer-DKOeHpv3.js} +3 -3
  72. package/dist/{warmup--Gkz7iB-.js → warmup-mTMIatCV.js} +267 -272
  73. package/dist/{web-message-id-lNodcCOI.js → web-message-id-CUaSiGme.js} +16 -1
  74. package/dist/{worker-DJ8d9fmD.js → worker-Bz4KNxjI.js} +7 -7
  75. package/migrations/0114_plan_items.sql +22 -0
  76. package/migrations/meta/0114_snapshot.json +5203 -0
  77. package/migrations/meta/_journal.json +7 -0
  78. package/package.json +6 -6
  79. package/dist/schedule-cP0AACm1.js +0 -344
  80. package/dist/turn-session-routing-2bW2qfeb.js +0 -1792
@@ -1,1792 +0,0 @@
1
- import { As as createDurableLocationConfigurationService, Da as postSlackMessage, Fi as getDashboardTaskLink, Oi as JUNIOR_THREAD_STATE_TTL_MS, b as persistConversationMessages, eo as ToolInputError, ma as formatSlackLink, pa as escapeSlackMrkdwnText, w as fallbackShortTitle, wa as openSlackDirectMessage } from "./projection-CcFBVFUo.js";
2
- import { n as botConfig } from "./config-CBZp0udd.js";
3
- import { J as toOptionalString, K as isRecord, _ as runBestEffort, h as logWarn, q as toOptionalNumber } from "./logging-BPNTQVFu.js";
4
- import { X as getStateAdapter, ct as agentTurnTotalTokens, o as getDb, st as agentTurnCostUsd } from "./db-DU84dCVu.js";
5
- import { N as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-CFyrgOu1.js";
6
- import { h as credentialSubjectSchema } from "./registry-BjZZqKqi.js";
7
- import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-CuA3yEcD.js";
8
- import * as z from "zod";
9
- import { createHash } from "node:crypto";
10
- import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
11
- import { agentEventMatchSchema, anyResourceMatchFields, describeEventTrigger, destinationSchema, destinationVisibilitySchema, eventMatches, eventTriggerChoices, eventTriggerProblems, isSlackDestination, normalizeEventIdentifier, normalizeEventMatch, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
12
- // src/chat/events/catalog.ts
13
- /** A source with nothing enabled, for a namespace that the catalog lacks. */
14
- const NO_SOURCE = {
15
- resourceTypes: [],
16
- events: {},
17
- anyResourceFields: {}
18
- };
19
- /**
20
- * Build one catalog entry. It merges the filters of every resource type here,
21
- * once, so trigger checks for each event copy and each row do not merge them
22
- * again.
23
- */
24
- function eventCatalogEntry(registration) {
25
- return {
26
- ...registration,
27
- anyResourceFields: anyResourceMatchFields(registration.resourceTypes)
28
- };
29
- }
30
- /** Core-owned event namespace. Not a plugin publisher. */
31
- const CORE_EVENT_NAMESPACE = "junior";
32
- /** True when the catalog has any enabled registration. */
33
- function hasEventCatalogEntries(catalog) {
34
- return Object.keys(catalog).length > 0;
35
- }
36
- /**
37
- * Catalog entries that durable event automations may select.
38
- *
39
- * Resource types with `automation: false` stay out of create/update schemas
40
- * and trigger availability. A namespace with no such resource type left is
41
- * removed.
42
- */
43
- function automationEventCatalog(catalog) {
44
- return Object.fromEntries(Object.entries(catalog).flatMap(([namespace, registration]) => {
45
- const resourceTypes = registration.resourceTypes.filter((resourceType) => registration.limits?.[resourceType.type]?.automation !== false);
46
- if (resourceTypes.length === 0) return [];
47
- if (resourceTypes.length === registration.resourceTypes.length) return [[namespace, registration]];
48
- const supported = new Set(resourceTypes.flatMap((resourceType) => resourceType.supportedEvents));
49
- return [[namespace, eventCatalogEntry({
50
- ...registration,
51
- resourceTypes,
52
- events: Object.fromEntries(Object.entries(registration.events).filter(([eventType]) => supported.has(eventType)))
53
- })]];
54
- }));
55
- }
56
- /** Return why watchEvents cannot watch one resource type, if it cannot. */
57
- function eventWatchUnavailable(catalog, namespace, resourceType) {
58
- const limits = catalog[namespace]?.limits?.[resourceType];
59
- return limits?.watch === false ? limits.watchUnavailableMessage : void 0;
60
- }
61
- function enumSchema(values, unavailableMessage) {
62
- if (values.length === 0) return z.string().refine(() => false, unavailableMessage);
63
- return z.enum(values);
64
- }
65
- /** Build the model-facing namespace enum from enabled event plugins. */
66
- function eventNamespaceSchema(catalog) {
67
- return enumSchema(Object.keys(catalog).sort(), "No event namespaces are enabled.");
68
- }
69
- /** Build the model-facing event enum from enabled plugin registrations. */
70
- function registeredEventTypeSchema(catalog) {
71
- return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.flatMap((resourceType) => resourceType.supportedEvents)))].sort(), "No event types are enabled.");
72
- }
73
- /** Build the model-facing resource type enum from enabled plugin registrations. */
74
- function registeredResourceTypeSchema(catalog) {
75
- return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.map((resourceType) => resourceType.type)))].sort(), "No resource types are enabled.");
76
- }
77
- /**
78
- * Return app guidance for one event of a namespace. The source declares it
79
- * once for the event, so every resource type and a trigger with no resource
80
- * type get the same guidance.
81
- */
82
- function eventGuidance(catalog, namespace, eventType) {
83
- return catalog[namespace]?.events[eventType]?.guidance;
84
- }
85
- /** Build the match object the tools accept for one resource type. */
86
- function registeredEventMatchSchema() {
87
- 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.");
88
- }
89
- /**
90
- * List why a selection cannot work with the enabled plugins. Use it for new
91
- * selections and for saved triggers, which can go stale after a plugin renames
92
- * or removes a resource type, event, or filter.
93
- */
94
- function registeredEventTriggerProblems(catalog, selection, options) {
95
- return eventTriggerProblems(catalog[selection.namespace] ?? NO_SOURCE, selection, options);
96
- }
97
- /**
98
- * Describe a selection with the enabled plugins, for the dashboard and Slack.
99
- * Its problems are the same as `registeredEventTriggerProblems`.
100
- */
101
- function describeRegisteredEventTrigger(catalog, selection) {
102
- return describeEventTrigger(catalog[selection.namespace] ?? NO_SOURCE, selection);
103
- }
104
- function uniqueMatchValues(match) {
105
- if (!match || Object.keys(match).length === 0) return void 0;
106
- return Object.fromEntries(Object.entries(match).map(([key, value]) => [key, Array.isArray(value) ? [...new Set(value)] : value]));
107
- }
108
- /**
109
- * Reject an event automation trigger or a Watch that cannot work, with every
110
- * problem in one message for the agent. Return its match as it is saved:
111
- * each text value in the case that its plugin declares, with no repeated
112
- * list values. The dashboard clears `inputKeys` so messages name the filters
113
- * as its plugin declares them.
114
- */
115
- function requireValidEventTrigger(catalog, selection, target, options = { inputKeys: true }) {
116
- const fields = eventTriggerChoices(catalog[selection.namespace] ?? NO_SOURCE, selection)?.fields ?? {};
117
- const normalized = {
118
- ...selection,
119
- match: normalizeEventMatch(fields, selection.match)
120
- };
121
- const problems = registeredEventTriggerProblems(catalog, normalized, options);
122
- if (problems.length > 0) {
123
- const source = catalog[selection.namespace]?.displayName ?? selection.namespace;
124
- const resource = selection.resourceType ? `${source} ${selection.resourceType.replaceAll("_", " ")}` : source;
125
- throw new ToolInputError([target === "watch" ? `This ${resource} watch cannot be created.` : `This ${resource} trigger cannot be saved.`, ...problems.map((problem) => problem.message)].join(" "));
126
- }
127
- return uniqueMatchValues(normalized.match);
128
- }
129
- /**
130
- * Normalize one selector with the convention declared by its plugin.
131
- *
132
- * Reject a selector that does not fit its resource type. Resource types can
133
- * share event types, so only the identifier shows which one a selector names.
134
- */
135
- function requireEventIdentifier(catalog, input) {
136
- const registration = catalog[input.namespace];
137
- const identifier = normalizeEventIdentifier(registration, input.identifier);
138
- const resourceTypes = registration?.resourceTypes ?? [];
139
- const fits = (resourceType) => resourceType.identifier !== void 0 && new RegExp(resourceType.identifier.pattern).test(identifier);
140
- const resourceType = resourceTypes.find((candidate) => candidate.type === input.resourceType);
141
- if (!resourceType?.identifier || fits(resourceType)) return identifier;
142
- const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
143
- 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(" "));
144
- }
145
- // src/chat/automations/revision.ts
146
- /** Storage revisions prevent stale edits from replacing newer values. */
147
- var AutomationConflictError = class extends ToolInputError {
148
- constructor() {
149
- super("This Automation changed after it was loaded. Reload it before saving.");
150
- this.name = "AutomationConflictError";
151
- }
152
- };
153
- /** Sort object keys so equal values produce equal JSON. */
154
- function canonicalJson(value) {
155
- if (Array.isArray(value)) return value.map(canonicalJson);
156
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonicalJson(child)]));
157
- return value;
158
- }
159
- /** Identify the stored values being edited, including lifecycle and creator authority. */
160
- function automationRevision(task) {
161
- return createHash("sha256").update(JSON.stringify(canonicalJson(task))).digest("hex");
162
- }
163
- /** Reject a stale edit while the storage owner holds the write lock. */
164
- function requireAutomationRevision(task, revision) {
165
- if (!task || automationRevision(task) !== revision) throw new AutomationConflictError();
166
- }
167
- // src/chat/automations/versions.ts
168
- /** Automation versions keep each saved definition so people can see how it changed. */
169
- /** Return the versioned part of an Automation. Lifecycle and run state are excluded. */
170
- function automationDefinition(task) {
171
- const common = {
172
- title: task.title?.trim() || null,
173
- task: task.task,
174
- credentialMode: task.credentialMode,
175
- destination: task.destination,
176
- outcomes: task.outcomes
177
- };
178
- return "schedule" in task ? {
179
- ...common,
180
- schedule: task.schedule
181
- } : {
182
- ...common,
183
- trigger: task.trigger
184
- };
185
- }
186
- /** Compare definition values after key sorting. */
187
- function sameDefinitionValue(left, right) {
188
- return JSON.stringify(canonicalJson(left)) === JSON.stringify(canonicalJson(right));
189
- }
190
- /**
191
- * Save a version when the definition changed. Call this in the same
192
- * transaction and lock as the Automation write. Without `current`, the
193
- * Automation is new, so the creator saves version 1.
194
- */
195
- async function recordAutomationVersion(db, task, current, editedBy) {
196
- const definition = automationDefinition(task);
197
- if (current && sameDefinitionValue(automationDefinition(current), definition)) return;
198
- await db.insert(juniorAutomationVersions).values({
199
- automationId: task.id,
200
- version: sql`(
201
- SELECT coalesce(max(${juniorAutomationVersions.version}), 0) + 1
202
- FROM ${juniorAutomationVersions}
203
- WHERE ${juniorAutomationVersions.automationId} = ${task.id}
204
- )`,
205
- createdAtMs: Date.now(),
206
- editedBy: editedBy ?? (current ? null : task.createdBy),
207
- definition
208
- });
209
- }
210
- /**
211
- * Select the newest saved version with the same definition as `task`.
212
- *
213
- * An Automation run stores this version so that a reader can see the
214
- * instruction that ran after the definition changes. The value is null when
215
- * no saved version has this definition.
216
- */
217
- function automationVersionOf(task) {
218
- return sql`(
219
- SELECT max(${juniorAutomationVersions.version})
220
- FROM ${juniorAutomationVersions}
221
- WHERE ${juniorAutomationVersions.automationId} = ${task.id}
222
- AND ${juniorAutomationVersions.definition} = ${JSON.stringify(automationDefinition(task))}::jsonb
223
- )`;
224
- }
225
- const versionColumns = {
226
- createdAtMs: juniorAutomationVersions.createdAtMs,
227
- definition: juniorAutomationVersions.definition,
228
- editedBy: juniorAutomationVersions.editedBy,
229
- kind: juniorAutomations.kind,
230
- version: juniorAutomationVersions.version
231
- };
232
- function parseVersionRow(row) {
233
- return automationVersionSchema.parse({
234
- kind: row.kind,
235
- version: row.version,
236
- createdAt: new Date(row.createdAtMs).toISOString(),
237
- editedBy: row.editedBy,
238
- definition: row.definition
239
- });
240
- }
241
- /** Read one saved definition. */
242
- async function readAutomationVersion(db, automationId, version) {
243
- 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);
244
- return row ? parseVersionRow(row) : void 0;
245
- }
246
- /** Read saved definitions, newest first. */
247
- async function listAutomationVersions(db, automationId, limit) {
248
- 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);
249
- }
250
- // src/chat/event-automations/run-limit.ts
251
- const RUN_LIST_PREFIX = "junior:event_automation_runs:v1";
252
- const RUN_LIST_BURST_ROOM = 100;
253
- const runEntrySchema = z.union([z.object({
254
- atMs: z.number().finite(),
255
- id: z.string().min(1)
256
- }).strict(), z.object({ reset: z.literal(true) }).strict()]);
257
- function runListKey(automationId) {
258
- return `${RUN_LIST_PREFIX}:${automationId}`;
259
- }
260
- function runListMaxLength() {
261
- return botConfig.maxEventAutomationRuns + RUN_LIST_BURST_ROOM;
262
- }
263
- async function appendRunEntry(state, automationId, entry) {
264
- await state.connect();
265
- await state.appendToList(runListKey(automationId), entry, {
266
- maxLength: runListMaxLength(),
267
- ttlMs: botConfig.eventAutomationRunWindowMs
268
- });
269
- }
270
- function describeRunWindow(windowMs) {
271
- for (const [unit, unitMs] of [
272
- ["day", 864e5],
273
- ["hour", 36e5],
274
- ["minute", 6e4],
275
- ["second", 1e3]
276
- ]) if (windowMs % unitMs === 0) {
277
- const count = windowMs / unitMs;
278
- return count === 1 ? unit : `${count} ${unit}s`;
279
- }
280
- return `${windowMs} ms`;
281
- }
282
- /** Reason stored on an Event automation that the run limit blocked. */
283
- function eventAutomationRunLimitReason() {
284
- const window = describeRunWindow(botConfig.eventAutomationRunWindowMs);
285
- return `This automation reached its limit of ${botConfig.maxEventAutomationRuns} runs per ${window}. Check that its trigger is not too broad, then resume it.`;
286
- }
287
- function hasRunKey(entries, runKey) {
288
- for (let index = entries.length - 1; index >= 0; index -= 1) {
289
- const entry = entries[index];
290
- if ("reset" in entry) return false;
291
- if (entry.id === runKey) return true;
292
- }
293
- return false;
294
- }
295
- /**
296
- * Count one run of an Event automation, or refuse when its window is full.
297
- *
298
- * `runKey` is the dispatch idempotency key, so a provider retry of the same
299
- * Event does not count again.
300
- */
301
- async function admitEventAutomationRun(args) {
302
- const state = args.state ?? getStateAdapter();
303
- await state.connect();
304
- const readEntries = async () => {
305
- const values = await state.getList(runListKey(args.automationId));
306
- return {
307
- entries: values.flatMap((value) => {
308
- const entry = runEntrySchema.safeParse(value);
309
- return entry.success ? [entry.data] : [];
310
- }),
311
- length: values.length
312
- };
313
- };
314
- if (!hasRunKey((await readEntries()).entries, args.runKey)) await appendRunEntry(state, args.automationId, {
315
- atMs: args.nowMs,
316
- id: args.runKey
317
- });
318
- const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
319
- const { entries, length } = await readEntries();
320
- let lastReset = -1;
321
- entries.forEach((entry, index) => {
322
- if ("reset" in entry) lastReset = index;
323
- });
324
- const oldest = entries[0];
325
- const full = lastReset === -1 && length >= runListMaxLength() && oldest !== void 0 && "atMs" in oldest && oldest.atMs > windowStartMs;
326
- const runKeys = /* @__PURE__ */ new Set();
327
- for (const entry of entries.slice(lastReset + 1)) {
328
- if ("reset" in entry) continue;
329
- if (entry.atMs > windowStartMs) runKeys.add(entry.id);
330
- if (entry.id === args.runKey) return full || runKeys.size > botConfig.maxEventAutomationRuns ? "limited" : "allowed";
331
- }
332
- return "limited";
333
- }
334
- /**
335
- * Forget the runs counted for one Event automation.
336
- *
337
- * Resume and revive call this so the automation starts with a new window.
338
- * Call it before the automation becomes active, so an Event cannot see the
339
- * old full count and block it again.
340
- */
341
- async function clearEventAutomationRuns(automationId, state = getStateAdapter()) {
342
- await appendRunEntry(state, automationId, { reset: true });
343
- }
344
- // src/chat/event-automations/store.ts
345
- /**
346
- * Validate an event automation and split it into its SQL columns. Lifecycle
347
- * columns are written separately.
348
- */
349
- function eventAutomationColumns(task) {
350
- const { status: _status, statusReason: _statusReason, title, ...definition } = task;
351
- const { createdAtMs: _createdAtMs, creatorIdentityId, id: _id, ...record } = eventAutomationSchema.parse(definition);
352
- return {
353
- channelId: record.destination.channelId,
354
- creatorIdentityId,
355
- creatorSlackUserId: record.createdBy.slackUserId,
356
- identifier: record.trigger.identifier ?? null,
357
- ...automationTaskColumns(record.task),
358
- namespace: record.trigger.namespace,
359
- record,
360
- teamId: record.destination.teamId,
361
- title: title?.trim() || null
362
- };
363
- }
364
- function eventAutomationRowInput(row) {
365
- return {
366
- ...row.record,
367
- createdAtMs: row.createdAtMs,
368
- creatorIdentityId: row.creatorIdentityId,
369
- id: row.id
370
- };
371
- }
372
- /** Decode an event Automation row with its SQL-backed fields. */
373
- function parseEventAutomationRow(row) {
374
- return withRowFields(row, eventAutomationSchema.parse(eventAutomationRowInput(row)));
375
- }
376
- /**
377
- * Decode a row for Event matching. Log and skip a row that does not parse,
378
- * so one bad row cannot stop matching for its whole namespace.
379
- */
380
- function readMatchableEventAutomationRow(row) {
381
- const parsed = eventAutomationSchema.safeParse(eventAutomationRowInput(row));
382
- if (parsed.success) return withRowFields(row, parsed.data);
383
- logWarn("event_automation.row.invalid", {
384
- "app.task.id": row.id,
385
- "app.task.type": "event",
386
- "error.message": parsed.error.message
387
- });
388
- }
389
- function withRowFields(row, task) {
390
- const title = row.title?.trim();
391
- return {
392
- ...task,
393
- status: row.status,
394
- ...row.statusReason ? { statusReason: row.statusReason } : void 0,
395
- ...title ? { title } : void 0
396
- };
397
- }
398
- function eventAutomationWhere(id) {
399
- return and(eq(juniorAutomations.id, id), eq(juniorAutomations.kind, "event"));
400
- }
401
- function activeEventAutomationWhere() {
402
- return and(eq(juniorAutomations.kind, "event"), ne(juniorAutomations.status, "deleted"));
403
- }
404
- /** Read one event automation by id, including deleted rows when present. */
405
- async function getEventAutomation(db, id) {
406
- const rows = await db.select().from(juniorAutomations).where(eventAutomationWhere(id)).limit(1);
407
- return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
408
- }
409
- /** Create one retry-stable event automation, or revive a deleted row with the new payload. */
410
- async function createEventAutomation(db, task) {
411
- const columns = eventAutomationColumns(task);
412
- if ((await getEventAutomation(db, task.id))?.status === "deleted") await clearEventAutomationRuns(task.id);
413
- return db.transaction(async (tx) => {
414
- const inserted = await tx.insert(juniorAutomations).values({
415
- ...columns,
416
- createdAtMs: task.createdAtMs,
417
- id: task.id,
418
- kind: "event",
419
- status: "active"
420
- }).onConflictDoNothing().returning();
421
- if (inserted[0]) {
422
- const created = parseEventAutomationRow(inserted[0]);
423
- await recordAutomationVersion(tx, created, void 0);
424
- return created;
425
- }
426
- const existing = await getEventAutomation(tx, task.id);
427
- if (!existing) throw new Error(`Automation ${task.id} already exists with another kind.`);
428
- if (existing.status !== "deleted") return existing;
429
- const rows = await tx.update(juniorAutomations).set({
430
- ...columns,
431
- status: "active",
432
- statusReason: null
433
- }).where(and(eventAutomationWhere(task.id), eq(juniorAutomations.status, "deleted"))).returning();
434
- if (!rows[0]) return await getEventAutomation(tx, task.id);
435
- const revived = parseEventAutomationRow(rows[0]);
436
- await recordAutomationVersion(tx, revived, void 0);
437
- return revived;
438
- });
439
- }
440
- /**
441
- * Replace an existing non-deleted event automation under a row lock.
442
- * Pass `editedBy` when a person changes the definition so its version names them.
443
- */
444
- async function saveEventAutomation(db, task, expectedRevision, editedBy) {
445
- const columns = eventAutomationColumns(task);
446
- return db.transaction(async (tx) => {
447
- const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(task.id)).for("update");
448
- const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
449
- if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
450
- if (!current || current.status === "deleted") return void 0;
451
- const saved = parseEventAutomationRow((await tx.update(juniorAutomations).set(columns).where(eventAutomationWhere(task.id)).returning())[0]);
452
- await recordAutomationVersion(tx, saved, current, editedBy);
453
- return saved;
454
- });
455
- }
456
- /** Mark one existing event automation deleted while retaining the row for history. */
457
- async function deleteEventAutomation(db, id) {
458
- const rows = await db.update(juniorAutomations).set({ status: "deleted" }).where(and(eq(juniorAutomations.id, id), activeEventAutomationWhere())).returning();
459
- return rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
460
- }
461
- /**
462
- * List deleted event automations created by one user, newest first.
463
- * Used only to keep historical runs after the live automation list drops the row.
464
- */
465
- async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
466
- const identityIds = user.identities.map((identity) => identity.id);
467
- if (identityIds.length === 0) return [];
468
- 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);
469
- }
470
- /**
471
- * Select live rows whose identifier is one of these, and rows with no
472
- * identifier. A row with no identifier runs for every resource of its
473
- * namespace, so it gets every copy of an Event.
474
- */
475
- function eventIdentifierWhere(identifiers) {
476
- return or(isNull(juniorAutomations.identifier), ...identifiers.length > 0 ? [inArray(juniorAutomations.identifier, [...identifiers])] : []);
477
- }
478
- /** SQL for rows whose trigger selects any of these event types. */
479
- function eventTypesWhere(eventTypes) {
480
- return or(...eventTypes.map((eventType) => sql`${juniorAutomations.record}->'trigger'->'events' @> ${JSON.stringify([eventType])}::jsonb`));
481
- }
482
- /**
483
- * Return why a row must not run for an Event with one of these identifiers,
484
- * or nothing when it may.
485
- *
486
- * The identifier column and the saved trigger must agree. A row with no
487
- * identifier must also have a trigger that the enabled `catalog` accepts. A
488
- * plugin can later require a filter or stop letting an event run for every
489
- * resource, and the row must not stay broad.
490
- */
491
- function eventAutomationGateProblem(row, task, identifiers, catalog) {
492
- const identifier = task.trigger.identifier;
493
- if (identifier !== void 0) return identifier === row.identifier && identifiers.includes(identifier) ? void 0 : "The saved trigger has a different identifier from its row.";
494
- if (row.identifier !== null) return "The saved trigger has no identifier, but its row has one.";
495
- const problems = registeredEventTriggerProblems(catalog, task.trigger);
496
- return problems.length > 0 ? problems.map((problem) => problem.message).join(" ") : void 0;
497
- }
498
- /**
499
- * Read the rows that can match an Event: live rows of one team and
500
- * namespace whose identifier is one of these, or that have no identifier,
501
- * and that select one of these event types. Skip and log a row that does
502
- * not parse or that the gate rejects.
503
- */
504
- async function readGatedEventAutomations(db, input) {
505
- 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));
506
- const plugins = automationEventCatalog(input.catalog);
507
- return rows.flatMap((row) => {
508
- const task = readMatchableEventAutomationRow(row);
509
- if (!task) return [];
510
- const problem = eventAutomationGateProblem(row, task, input.identifiers, plugins);
511
- if (problem === void 0) return [task];
512
- logWarn("event_automation.gate.rejected", {
513
- "app.task.id": task.id,
514
- "app.task.type": "event",
515
- "app.event_automation.skip_reason": problem
516
- });
517
- return [];
518
- });
519
- }
520
- /** The filters of a match whose keys are in this data. */
521
- function knownMatch(match, data) {
522
- if (!match) return void 0;
523
- return Object.fromEntries(Object.entries(match).filter(([key]) => data[key] !== void 0));
524
- }
525
- /**
526
- * Collect match keys from live event automations for these identifiers and
527
- * event types, and from automations with no identifier. Does not evaluate
528
- * match values, except for automations with no identifier: one whose
529
- * filters on the keys in `data` fail adds no keys. So a broad trigger for
530
- * one repository does not make every repository load its lazy data.
531
- */
532
- async function collectEventAutomationMatchKeys(db, input) {
533
- const eventTypes = [...new Set(input.eventTypes.map((eventType) => eventType.trim()).filter(Boolean))];
534
- const identifiers = [...new Set(input.identifiers.map((value) => value.trim()).filter(Boolean))];
535
- if (eventTypes.length === 0) return [];
536
- const tasks = await readGatedEventAutomations(db, {
537
- catalog: input.catalog,
538
- eventTypes,
539
- identifiers,
540
- namespace: input.namespace,
541
- teamId: input.teamId
542
- });
543
- const keys = /* @__PURE__ */ new Set();
544
- for (const task of tasks) {
545
- if (task.trigger.identifier === void 0 && input.data && !eventMatches(knownMatch(task.trigger.match, input.data), input.data)) continue;
546
- for (const key of Object.keys(task.trigger.match ?? {})) keys.add(key);
547
- }
548
- return [...keys].sort();
549
- }
550
- /**
551
- * Find every live task matching each normalized event, with one read for all
552
- * of them: tasks for its exact identifier, and tasks with no identifier whose
553
- * filters match. Returns one list per event, in order. The events must share
554
- * one namespace. The gate skips a row whose trigger and identifier column
555
- * disagree, and a row with no identifier whose trigger the enabled `catalog`
556
- * rejects.
557
- */
558
- async function findMatchingEventAutomations(db, events, teamId, catalog) {
559
- const namespace = events[0]?.namespace;
560
- if (namespace === void 0) return [];
561
- if (events.some((event) => event.namespace !== namespace)) throw new Error("Events to match must share one namespace.");
562
- const tasks = await readGatedEventAutomations(db, {
563
- catalog,
564
- eventTypes: [...new Set(events.map((event) => event.eventType))],
565
- identifiers: [...new Set(events.map((event) => event.identifier))],
566
- namespace,
567
- teamId
568
- });
569
- 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)));
570
- }
571
- /**
572
- * Change lifecycle under the same row lock as edits, without changing
573
- * credentials. A pause keeps an unresolved block reason, so resuming a paused
574
- * blocked automation returns it to blocked. Resume a blocked automation to
575
- * clear the reason. A resume also clears the run-limit count first.
576
- */
577
- async function setEventAutomationStatus(db, id, status, revision) {
578
- if (status === "active" && (await getEventAutomation(db, id))?.status !== "active") await clearEventAutomationRuns(id);
579
- return db.transaction(async (tx) => {
580
- const rows = await tx.select().from(juniorAutomations).where(eventAutomationWhere(id)).for("update");
581
- const current = rows[0] ? parseEventAutomationRow(rows[0]) : void 0;
582
- requireAutomationRevision(current, revision);
583
- if (!current || current.status === "deleted") throw new Error("Automation no longer exists.");
584
- const next = status === "paused" ? {
585
- status,
586
- statusReason: current.statusReason
587
- } : current.status === "paused" && current.statusReason ? {
588
- status: "blocked",
589
- statusReason: current.statusReason
590
- } : {
591
- status,
592
- statusReason: void 0
593
- };
594
- await tx.update(juniorAutomations).set({
595
- status: next.status,
596
- statusReason: next.statusReason ?? null
597
- }).where(eventAutomationWhere(id));
598
- const { statusReason: _statusReason, ...rest } = current;
599
- return {
600
- ...rest,
601
- status: next.status,
602
- ...next.statusReason ? { statusReason: next.statusReason } : void 0
603
- };
604
- });
605
- }
606
- /**
607
- * Stop an event automation after a run reports a problem that only its
608
- * creator can fix. An active automation becomes blocked. A paused automation
609
- * stays paused and keeps the reason, so resume returns it to blocked.
610
- * Deleted automations do not change. Returns true only when this call set
611
- * the automation to blocked, so the creator notice goes once and never for
612
- * an automation that the dashboard shows as paused.
613
- */
614
- async function blockEventAutomation(db, id, reason) {
615
- return (await db.update(juniorAutomations).set({
616
- status: sql`case when ${juniorAutomations.status} = 'active' then 'blocked' else ${juniorAutomations.status} end`,
617
- statusReason: reason
618
- }).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";
619
- }
620
- // src/chat/scheduled-automations/tasks.ts
621
- const SCHEDULER_KEY_PREFIX = "junior:scheduler";
622
- /** Decode a Scheduled automation row. Returns undefined for an invalid row. */
623
- function parseScheduledAutomationRow(row) {
624
- const columns = {
625
- createdAtMs: row.createdAtMs,
626
- creatorIdentityId: row.creatorIdentityId,
627
- id: row.id,
628
- nextRunAtMs: row.nextRunAtMs,
629
- runNowAtMs: row.runNowAtMs,
630
- status: row.status,
631
- statusReason: row.statusReason,
632
- title: row.title
633
- };
634
- const parsed = scheduledAutomationSchema.safeParse({
635
- ...row.record,
636
- ...Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== null))
637
- });
638
- return parsed.success ? parsed.data : void 0;
639
- }
640
- /** Keep scan paths from returning current or legacy tombstones. */
641
- function isListedScheduledAutomation(task) {
642
- return task !== void 0 && task.status !== "deleted";
643
- }
644
- /** Build the stable run id for one task occurrence. */
645
- function scheduledRunId(taskId, scheduledForMs) {
646
- return `${taskId}:${scheduledForMs}`;
647
- }
648
- /** Acquire the deployed advisory lock for one scheduled automation. */
649
- function withScheduledAutomationLock(db, taskId, callback) {
650
- return db.transaction(async (tx) => {
651
- await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
652
- return await callback(tx);
653
- });
654
- }
655
- function requireStoredTask(task) {
656
- const parsed = scheduledAutomationSchema.safeParse(task);
657
- if (!parsed.success) throw new Error("Scheduled automation routing context is invalid.");
658
- const { title, ...current } = parsed.data;
659
- const normalizedTitle = title?.trim() || void 0;
660
- return {
661
- ...current,
662
- ...normalizedTitle ? { title: normalizedTitle } : void 0
663
- };
664
- }
665
- async function upsertScheduledAutomation(db, task) {
666
- const { createdAtMs, creatorIdentityId, id, nextRunAtMs, runNowAtMs, status, statusReason, title, ...record } = task;
667
- const columns = {
668
- channelId: record.destination.channelId,
669
- createdAtMs,
670
- creatorIdentityId,
671
- creatorSlackUserId: record.createdBy.slackUserId,
672
- ...automationTaskColumns(record.task),
673
- nextRunAtMs: nextRunAtMs ?? null,
674
- record,
675
- runNowAtMs: runNowAtMs ?? null,
676
- status,
677
- statusReason: statusReason ?? null,
678
- teamId: record.destination.teamId,
679
- title: title?.trim() || null
680
- };
681
- await db.insert(juniorAutomations).values({
682
- ...columns,
683
- id,
684
- kind: "scheduled"
685
- }).onConflictDoUpdate({
686
- target: juniorAutomations.id,
687
- set: columns
688
- });
689
- }
690
- /** Read and decode one scheduled automation. */
691
- async function readScheduledAutomation(db, taskId) {
692
- const rows = await db.select().from(juniorAutomations).where(and(eq(juniorAutomations.id, taskId), eq(juniorAutomations.kind, "scheduled"))).limit(1);
693
- return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
694
- }
695
- async function readListedScheduledAutomations(db, teamId) {
696
- 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);
697
- }
698
- /** List decoded scheduled automations for one team in stable creation order. */
699
- async function listScheduledAutomationsForTeam(db, teamId) {
700
- return await readListedScheduledAutomations(db, teamId);
701
- }
702
- async function writeScheduledAutomation(db, task, current, editedBy) {
703
- 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")));
704
- if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
705
- await upsertScheduledAutomation(db, task);
706
- await recordAutomationVersion(db, task, current, editedBy);
707
- }
708
- async function skipPendingRunsForDeletedTask(db, task) {
709
- await db.update(juniorAutomationRuns).set({
710
- completedAtMs: task.updatedAtMs,
711
- errorMessage: `Scheduled automation ${task.id} was deleted before the run started.`,
712
- status: "skipped"
713
- }).where(and(eq(juniorAutomationRuns.automationId, task.id), eq(juniorAutomationRuns.status, "pending")));
714
- }
715
- /** Create a scheduled automation once under its retry-stable task lock. */
716
- async function createScheduledAutomation(db, task) {
717
- const next = requireStoredTask(task);
718
- return await withScheduledAutomationLock(db, task.id, async (tx) => {
719
- const current = await readScheduledAutomation(tx, task.id);
720
- if (current) return current;
721
- await writeScheduledAutomation(tx, next, void 0);
722
- return next;
723
- });
724
- }
725
- /**
726
- * Save a scheduled automation and clear its blocked occurrence on reactivation.
727
- * Pass `editedBy` when a person changes the definition so its version names them.
728
- */
729
- async function saveScheduledAutomation(db, task, expectedRevision, editedBy) {
730
- const next = requireStoredTask(task);
731
- await withScheduledAutomationLock(db, task.id, async (tx) => {
732
- const current = await readScheduledAutomation(tx, task.id);
733
- if (expectedRevision !== void 0) requireAutomationRevision(current, expectedRevision);
734
- await writeScheduledAutomation(tx, next, current, editedBy);
735
- });
736
- return next;
737
- }
738
- /** Save a scheduled automation inside a task lock already held by the caller. */
739
- async function saveScheduledAutomationInLock(db, task, current) {
740
- await writeScheduledAutomation(db, requireStoredTask(task), current);
741
- }
742
- /** Mark one live scheduled automation deleted while keeping its history. */
743
- async function deleteScheduledAutomation(db, id, nowMs = Date.now()) {
744
- return await withScheduledAutomationLock(db, id, async (tx) => {
745
- const current = await readScheduledAutomation(tx, id);
746
- if (!current || current.status === "deleted") return void 0;
747
- const deleted = requireStoredTask({
748
- ...current,
749
- nextRunAtMs: void 0,
750
- runNowAtMs: void 0,
751
- status: "deleted",
752
- updatedAtMs: nowMs
753
- });
754
- await writeScheduledAutomation(tx, deleted, current);
755
- return deleted;
756
- });
757
- }
758
- /**
759
- * Block a Scheduled automation outside the settle step of a run, such as from
760
- * a Watch Event Turn of its run. An active automation becomes blocked. A
761
- * paused automation stays paused and keeps the reason, so resume returns it
762
- * to blocked. Returns true only when this call set it to blocked.
763
- */
764
- async function blockScheduledAutomation(db, id, reason, nowMs = Date.now()) {
765
- return await withScheduledAutomationLock(db, id, async (tx) => {
766
- const current = await readScheduledAutomation(tx, id);
767
- if (current?.status !== "active" && current?.status !== "paused") return false;
768
- const blocked = current.status === "active";
769
- await writeScheduledAutomation(tx, requireStoredTask({
770
- ...current,
771
- ...blocked ? {
772
- nextRunAtMs: void 0,
773
- runNowAtMs: void 0,
774
- status: "blocked"
775
- } : void 0,
776
- statusReason: reason,
777
- updatedAtMs: nowMs
778
- }), current);
779
- return blocked;
780
- });
781
- }
782
- // src/api/conversations/aggregate.ts
783
- function usageTokenValue(source, field) {
784
- return sql`CASE
785
- WHEN ${source.usage}->>${field} IS NOT NULL
786
- THEN (${source.usage}->>${field})::double precision
787
- ELSE NULL
788
- END`;
789
- }
790
- function tokenValue(source) {
791
- return sql`
792
- CASE
793
- WHEN COALESCE(
794
- ${source.usage}->>'inputTokens',
795
- ${source.usage}->>'outputTokens',
796
- ${source.usage}->>'cachedInputTokens',
797
- ${source.usage}->>'cacheCreationTokens'
798
- ) IS NOT NULL
799
- THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
800
- + COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
801
- + COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
802
- + COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
803
- WHEN ${source.usage}->>'totalTokens' IS NOT NULL
804
- THEN (${source.usage}->>'totalTokens')::double precision
805
- ELSE NULL
806
- END
807
- `;
808
- }
809
- function costValue(source) {
810
- return conversationUsageCostExpr(source.usage);
811
- }
812
- /** Read one conversation row's usage cost as a SQL expression. */
813
- function conversationUsageCostExpr(usage) {
814
- return sql`
815
- CASE
816
- WHEN ${usage}->'cost'->>'total' IS NOT NULL
817
- THEN (${usage}->'cost'->>'total')::double precision
818
- WHEN COALESCE(
819
- ${usage}->'cost'->>'input',
820
- ${usage}->'cost'->>'output',
821
- ${usage}->'cost'->>'cacheRead',
822
- ${usage}->'cost'->>'cacheWrite'
823
- ) IS NOT NULL
824
- THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
825
- + COALESCE((${usage}->'cost'->>'output')::double precision, 0)
826
- + COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
827
- + COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
828
- ELSE NULL
829
- END
830
- `;
831
- }
832
- /** Select complete conversation metrics inside the database instead of materializing source rows. */
833
- function conversationAggregateColumns(sources) {
834
- const metrics = sources?.metrics ?? juniorConversations;
835
- const roots = sources?.roots ?? juniorConversations;
836
- const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
837
- return {
838
- active: sql`${conversationCount} FILTER (
839
- WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
840
- )::integer`,
841
- conversations: sql`${conversationCount}::integer`,
842
- cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
843
- cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
844
- costUsd: sql`SUM(${costValue(metrics)})::double precision`,
845
- durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
846
- failed: sql`${conversationCount} FILTER (
847
- WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
848
- )::integer`,
849
- inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
850
- tokens: sql`SUM(${tokenValue(metrics)})::double precision`
851
- };
852
- }
853
- /** Select the complete first/last activity range for a grouped conversation aggregate. */
854
- function conversationRangeColumns() {
855
- return {
856
- firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
857
- lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
858
- };
859
- }
860
- // src/chat/automations/execution-stats.ts
861
- const AUTOMATION_EXECUTION_STATUSES = [
862
- "blocked",
863
- "completed",
864
- "failed"
865
- ];
866
- /** An execution is a run with an outcome. Skipped runs are not executions. */
867
- function isExecution() {
868
- return and(inArray(juniorAutomationRuns.status, [...AUTOMATION_EXECUTION_STATUSES]), isNotNull(juniorAutomationRuns.completedAtMs));
869
- }
870
- function addUsd(current, next) {
871
- return Math.round((current + next) * 0xe8d4a51000) / 0xe8d4a51000;
872
- }
873
- const EMPTY_RUN_WINDOWS = {
874
- 1: 0,
875
- 7: 0,
876
- 30: 0,
877
- 90: 0
878
- };
879
- /** Empty run or cost windows for automations with no execution history. */
880
- function emptyAutomationRunWindows() {
881
- return { ...EMPTY_RUN_WINDOWS };
882
- }
883
- function utcDate(nowMs) {
884
- return new Date(nowMs).toISOString().slice(0, 10);
885
- }
886
- function emptyStatusDay(date) {
887
- return {
888
- blocked: 0,
889
- completed: 0,
890
- costUsd: 0,
891
- date,
892
- failed: 0
893
- };
894
- }
895
- /**
896
- * Return the Conversation id when that Conversation exists, else null. A
897
- * dispatch can end before it creates its Conversation, and the run's
898
- * `conversation_id` is a foreign key.
899
- */
900
- function existingConversationId(conversationId) {
901
- return sql`(select ${juniorConversations.conversationId} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
902
- }
903
- /**
904
- * Record the outcome of one Automation run. A run that already has an outcome
905
- * keeps it. A failed write is logged, and the heartbeat settles a started
906
- * event run later.
907
- */
908
- async function recordAutomationExecution(automationId, options) {
909
- const nowMs = options.nowMs ?? Date.now();
910
- const status = options.status ?? "completed";
911
- const outcome = {
912
- completedAtMs: nowMs,
913
- errorMessage: options.errorMessage ?? null,
914
- status
915
- };
916
- try {
917
- await getDb().insert(juniorAutomationRuns).values({
918
- id: options.executionId,
919
- automationId,
920
- conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
921
- ...outcome
922
- }).onConflictDoUpdate({
923
- target: juniorAutomationRuns.id,
924
- set: {
925
- ...outcome,
926
- conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`
927
- },
928
- setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
929
- });
930
- } catch (error) {
931
- logWarn("task.execution.stat_failed", {
932
- error,
933
- "app.task.execution.id": options.executionId,
934
- "app.task.execution.status": status,
935
- "app.task.execution.task_id": automationId
936
- });
937
- }
938
- }
939
- /** Load usage analytics for the given automations. */
940
- async function readAutomationExecutionSummaries(automationIds, options = {}) {
941
- if (automationIds.length === 0) return /* @__PURE__ */ new Map();
942
- const nowMs = options.nowMs ?? Date.now();
943
- const oneDayAgoMs = nowMs - 864e5;
944
- const sevenDaysAgoMs = nowMs - 6048e5;
945
- const thirtyDaysAgoMs = nowMs - 2592e6;
946
- const ninetyDaysAgoMs = nowMs - 7776e6;
947
- const db = getDb();
948
- const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
949
- const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
950
- status: juniorAutomationRuns.status,
951
- conversationId: juniorAutomationRuns.conversationId,
952
- automationId: juniorAutomationRuns.automationId
953
- }).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
954
- const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
955
- const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
956
- const summaryRows = db.select({
957
- costLast1Day: costSince(oneDayAgoMs),
958
- costLast7Days: costSince(sevenDaysAgoMs),
959
- costLast30Days: costSince(thirtyDaysAgoMs),
960
- costLast90Days: costSince(ninetyDaysAgoMs),
961
- lastRunStatus: latest.status,
962
- lastConversationId: latest.conversationId,
963
- lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
964
- runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
965
- runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
966
- runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
967
- runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
968
- automationId: juniorAutomationRuns.automationId,
969
- totalCostUsd: sql`coalesce(sum(${conversationCost}), 0)::double precision`,
970
- totalRuns: sql`count(*)::int`
971
- }).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
972
- const [rows, recentRuns] = await Promise.all([summaryRows, readAutomationRecentRuns(automationIds)]);
973
- return new Map(rows.map((row) => [row.automationId, {
974
- costUsd: {
975
- 1: addUsd(0, row.costLast1Day),
976
- 7: addUsd(0, row.costLast7Days),
977
- 30: addUsd(0, row.costLast30Days),
978
- 90: addUsd(0, row.costLast90Days)
979
- },
980
- lastRunStatus: row.lastRunStatus,
981
- ...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
982
- ...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
983
- recentRuns: recentRuns.get(row.automationId) ?? [],
984
- runs: {
985
- 1: row.runsLast1Day,
986
- 7: row.runsLast7Days,
987
- 30: row.runsLast30Days,
988
- 90: row.runsLast90Days
989
- },
990
- totalCostUsd: addUsd(0, row.totalCostUsd),
991
- totalRuns: row.totalRuns
992
- }]));
993
- }
994
- /**
995
- * Load the newest runs of each Automation, oldest first. A lateral limit
996
- * reads at most `AUTOMATION_RECENT_RUN_LIMIT` rows per Automation from the
997
- * (automation, completed) index, so long histories do not slow the list.
998
- */
999
- async function readAutomationRecentRuns(automationIds) {
1000
- const db = getDb();
1001
- const recent = db.select({
1002
- durationMs: juniorConversations.durationMs,
1003
- executedAtMs: juniorAutomationRuns.completedAtMs,
1004
- executionId: juniorAutomationRuns.id,
1005
- status: juniorAutomationRuns.status
1006
- }).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");
1007
- const rows = await db.select({
1008
- automationId: juniorAutomations.id,
1009
- durationMs: recent.durationMs,
1010
- executedAtMs: recent.executedAtMs,
1011
- status: recent.status
1012
- }).from(juniorAutomations).innerJoinLateral(recent, sql`true`).where(inArray(juniorAutomations.id, automationIds)).orderBy(juniorAutomations.id, asc(recent.executedAtMs), asc(recent.executionId));
1013
- const byAutomation = /* @__PURE__ */ new Map();
1014
- for (const row of rows) {
1015
- const durationMs = positiveDuration(row.durationMs);
1016
- const runs = byAutomation.get(row.automationId) ?? [];
1017
- runs.push({
1018
- ...durationMs !== void 0 ? { durationMs } : void 0,
1019
- executedAt: new Date(row.executedAtMs).toISOString(),
1020
- status: row.status
1021
- });
1022
- byAutomation.set(row.automationId, runs);
1023
- }
1024
- return byAutomation;
1025
- }
1026
- /** Keep a recorded runtime only when it is a real duration. */
1027
- function positiveDuration(value) {
1028
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
1029
- }
1030
- /** Load the Automation run linked to one conversation, if any. */
1031
- async function readAutomationExecutionByConversationId(args) {
1032
- const [row] = await getDb().select({
1033
- kind: juniorAutomations.kind,
1034
- automationId: juniorAutomationRuns.automationId
1035
- }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(eq(juniorAutomationRuns.conversationId, args.conversationId)).limit(1);
1036
- return row;
1037
- }
1038
- /**
1039
- * Load the display name of the Automation linked to each untitled
1040
- * conversation. Like the Automation list, the name falls back to the first
1041
- * line of the instruction. Titled conversations and conversations without a
1042
- * linked Automation are absent from the result.
1043
- */
1044
- async function readAutomationTitlesByConversationId(conversations) {
1045
- const titles = /* @__PURE__ */ new Map();
1046
- const untitledIds = conversations.flatMap((conversation) => conversation.title ? [] : [conversation.conversationId]);
1047
- if (untitledIds.length === 0) return titles;
1048
- const rows = await getDb().select({
1049
- conversationId: juniorAutomationRuns.conversationId,
1050
- task: sql`${juniorAutomations.record}->'task'`,
1051
- title: juniorAutomations.title
1052
- }).from(juniorAutomationRuns).innerJoin(juniorAutomations, eq(juniorAutomations.id, juniorAutomationRuns.automationId)).where(inArray(juniorAutomationRuns.conversationId, untitledIds));
1053
- for (const row of rows) {
1054
- const title = row.title?.trim() || fallbackShortTitle(automationTaskDescription(automationTaskSchema.parse(row.task)), "");
1055
- if (row.conversationId && title) titles.set(row.conversationId, title);
1056
- }
1057
- return titles;
1058
- }
1059
- /** Load newest-first executions for one automation, with conversation titles when present. */
1060
- async function readAutomationExecutions(args) {
1061
- 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));
1062
- }
1063
- /** Load newest-first executions for the supplied viewer-visible automations. */
1064
- async function readAutomationRuns(args) {
1065
- if (args.automationIds.length === 0) return [];
1066
- return (await getDb().select({
1067
- ...executionColumns,
1068
- kind: juniorAutomations.kind,
1069
- automationId: juniorAutomationRuns.automationId
1070
- }).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) => ({
1071
- ...mapAutomationExecutionRecord(row),
1072
- kind: row.kind,
1073
- automationId: row.automationId
1074
- }));
1075
- }
1076
- /** Columns that describe one execution, its Conversation, and its version. */
1077
- const executionColumns = {
1078
- automationVersion: juniorAutomationRuns.automationVersion,
1079
- conversationId: juniorAutomationRuns.conversationId,
1080
- credentialMode: sql`${juniorAutomationVersions.definition}->>'credentialMode'`,
1081
- durationMs: juniorConversations.durationMs,
1082
- errorMessage: juniorAutomationRuns.errorMessage,
1083
- executedAtMs: juniorAutomationRuns.completedAtMs,
1084
- executionId: juniorAutomationRuns.id,
1085
- scheduledForMs: juniorAutomationRuns.scheduledForMs,
1086
- startedAtMs: juniorAutomationRuns.startedAtMs,
1087
- status: juniorAutomationRuns.status,
1088
- title: juniorConversations.title,
1089
- usage: juniorConversations.usage
1090
- };
1091
- function executionConversation() {
1092
- return eq(juniorConversations.conversationId, juniorAutomationRuns.conversationId);
1093
- }
1094
- function executionVersion() {
1095
- return and(eq(juniorAutomationVersions.automationId, juniorAutomationRuns.automationId), eq(juniorAutomationVersions.version, juniorAutomationRuns.automationVersion));
1096
- }
1097
- function isoTime(ms) {
1098
- return ms === null ? void 0 : new Date(ms).toISOString();
1099
- }
1100
- function mapAutomationExecutionRecord(row) {
1101
- const title = row.title?.trim();
1102
- const costUsd = agentTurnCostUsd(row.usage ?? void 0);
1103
- const totalTokens = agentTurnTotalTokens(row.usage ?? void 0);
1104
- const durationMs = positiveDuration(row.durationMs);
1105
- const error = row.errorMessage?.trim();
1106
- const scheduledFor = isoTime(row.scheduledForMs);
1107
- const startedAt = isoTime(row.startedAtMs);
1108
- return {
1109
- ...row.automationVersion !== null ? { automationVersion: row.automationVersion } : void 0,
1110
- ...row.conversationId ? { conversationId: row.conversationId } : void 0,
1111
- ...costUsd !== void 0 ? { costUsd } : void 0,
1112
- ...row.credentialMode === "creator" || row.credentialMode === "system" ? { credentialMode: row.credentialMode } : void 0,
1113
- ...durationMs !== void 0 ? { durationMs } : void 0,
1114
- ...error ? { error } : void 0,
1115
- executedAt: new Date(row.executedAtMs).toISOString(),
1116
- executionId: row.executionId,
1117
- ...scheduledFor ? { scheduledFor } : void 0,
1118
- ...startedAt ? { startedAt } : void 0,
1119
- status: row.status,
1120
- ...title ? { title } : void 0,
1121
- ...totalTokens !== void 0 ? { totalTokens } : void 0
1122
- };
1123
- }
1124
- /** Load a fixed trailing window of terminal executions for one automation by status. */
1125
- async function readAutomationExecutionStatusDays(args) {
1126
- const dayCount = args.dayCount ?? 90;
1127
- const end = utcDate(args.nowMs ?? Date.now());
1128
- const endMs = Date.parse(`${end}T23:59:59.999Z`);
1129
- const startMs = Date.parse(`${end}T00:00:00.000Z`) - (dayCount - 1) * 864e5;
1130
- const executionDate = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD')`;
1131
- const rows = await readExecutionStatusBuckets({
1132
- automationId: args.automationId,
1133
- bucket: executionDate,
1134
- endMs,
1135
- startMs
1136
- });
1137
- const byDate = /* @__PURE__ */ new Map();
1138
- for (let offset = 0; offset < dayCount; offset += 1) {
1139
- const date = utcDate(startMs + offset * 864e5);
1140
- byDate.set(date, emptyStatusDay(date));
1141
- }
1142
- for (const row of rows) {
1143
- const day = byDate.get(row.date);
1144
- if (!day) continue;
1145
- if (row.status === "completed") day.completed = row.count;
1146
- else if (row.status === "failed") day.failed = row.count;
1147
- else if (row.status === "blocked") day.blocked = row.count;
1148
- if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
1149
- }
1150
- return [...byDate.values()];
1151
- }
1152
- /** Load a fixed trailing window of terminal executions for one automation by hour. */
1153
- async function readAutomationExecutionStatusHours(args) {
1154
- const hourCount = args.hourCount ?? 168;
1155
- const nowMs = args.nowMs ?? Date.now();
1156
- const end = new Date(nowMs);
1157
- end.setUTCMinutes(0, 0, 0);
1158
- const endMs = end.getTime() + 3599999;
1159
- const startMs = end.getTime() - (hourCount - 1) * 36e5;
1160
- const executionHour = sql`to_char(to_timestamp(${juniorAutomationRuns.completedAtMs} / 1000.0) at time zone 'UTC', 'YYYY-MM-DD"T"HH24')`;
1161
- const rows = await readExecutionStatusBuckets({
1162
- automationId: args.automationId,
1163
- bucket: executionHour,
1164
- endMs,
1165
- startMs
1166
- });
1167
- const byHour = /* @__PURE__ */ new Map();
1168
- for (let offset = 0; offset < hourCount; offset += 1) {
1169
- const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
1170
- byHour.set(date, emptyStatusDay(date));
1171
- }
1172
- for (const row of rows) {
1173
- const hour = byHour.get(row.date);
1174
- if (!hour) continue;
1175
- if (row.status === "completed") hour.completed = row.count;
1176
- else if (row.status === "failed") hour.failed = row.count;
1177
- else if (row.status === "blocked") hour.blocked = row.count;
1178
- if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
1179
- }
1180
- return [...byHour.values()];
1181
- }
1182
- /** Count one automation's executions and their cost per time bucket and status. */
1183
- async function readExecutionStatusBuckets(args) {
1184
- const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
1185
- return await getDb().select({
1186
- count: count(),
1187
- costUsd: sql`SUM(${conversationCost})::double precision`,
1188
- date: args.bucket,
1189
- status: juniorAutomationRuns.status
1190
- }).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));
1191
- }
1192
- // src/chat/automations/blocked-notice.ts
1193
- function buildBlockedNoticeText(automationId, title, reason) {
1194
- const url = getDashboardTaskLink(automationId);
1195
- return [
1196
- `Your automation *${escapeSlackMrkdwnText(title)}* is blocked. It won't run again until you resume it.`,
1197
- `> ${escapeSlackMrkdwnText(reason.replace(/\s+/g, " ").trim())}`,
1198
- url ? `Fix the problem, then ${formatSlackLink(url, "resume it")}.` : "Fix the problem, then ask me to resume it."
1199
- ].join("\n");
1200
- }
1201
- /**
1202
- * Tell an Automation's creator in a direct message that a run blocked it,
1203
- * and why. Call this once, after the Automation itself is stored as blocked,
1204
- * so the dashboard matches the notice. The notice is best-effort: the reason
1205
- * also shows on the dashboard and in the Automation tools.
1206
- */
1207
- async function notifyAutomationBlocked(ref) {
1208
- await runBestEffort(async () => {
1209
- const task = ref.kind === "scheduled" ? await readScheduledAutomation(getDb(), ref.automationId) : await getEventAutomation(getDb(), ref.automationId);
1210
- if (!task) return;
1211
- const title = task.title ?? fallbackShortTitle(automationTaskDescription(task.task), ref.kind === "scheduled" ? "Scheduled automation" : "Event automation");
1212
- await postSlackMessage({
1213
- channelId: await openSlackDirectMessage(task.createdBy.slackUserId),
1214
- text: buildBlockedNoticeText(ref.automationId, title, ref.reason)
1215
- });
1216
- }, "automation.blocked_notice.failed", {
1217
- "app.task.type": ref.kind,
1218
- ...ref.dispatchId ? { "app.dispatch.id": ref.dispatchId } : void 0
1219
- });
1220
- }
1221
- // src/chat/agent-dispatch/store.ts
1222
- const DISPATCH_PREFIX = "junior:agent_dispatch";
1223
- const DISPATCH_LOCK_TTL_MS = 6e5;
1224
- const DISPATCH_MAILBOX_APPEND_INDEX_LOCK_TTL_MS = 1e4;
1225
- const nonEmptyExactStringSchema = z.string().min(1).refine((value) => value === value.trim() && value.toLowerCase() !== "unknown");
1226
- const pendingDispatchMailboxAppendIndexSchema = z.array(nonEmptyExactStringSchema);
1227
- const dispatchStatusSchema = z.enum([
1228
- "pending",
1229
- "running",
1230
- "awaiting_resume",
1231
- "completed",
1232
- "failed",
1233
- "blocked"
1234
- ]);
1235
- const dispatchActorSchema = z.object({
1236
- platform: z.literal("system"),
1237
- name: nonEmptyExactStringSchema
1238
- }).strict();
1239
- const dispatchRecordSchema = z.object({
1240
- actor: dispatchActorSchema,
1241
- createdAtMs: z.number().finite(),
1242
- credentialSubject: credentialSubjectSchema.optional(),
1243
- destination: destinationSchema,
1244
- destinationVisibility: destinationVisibilitySchema,
1245
- errorMessage: z.string().optional(),
1246
- id: nonEmptyExactStringSchema,
1247
- idempotencyKey: z.string().min(1),
1248
- input: z.string().min(1),
1249
- metadata: z.record(z.string(), z.string()).optional(),
1250
- plugin: nonEmptyExactStringSchema,
1251
- replyAttribution: replyAttributionSchema.optional(),
1252
- resultMessageTs: z.string().optional(),
1253
- source: sourceSchema,
1254
- outcomes: z.array(taskOutcomeSchema).max(5).optional(),
1255
- skill: automationSkillNameSchema.optional(),
1256
- status: dispatchStatusSchema,
1257
- title: z.string().min(1).optional(),
1258
- updatedAtMs: z.number().finite()
1259
- }).strict().superRefine((record, ctx) => {
1260
- if (!isSlackDestination(record.destination)) {
1261
- ctx.addIssue({
1262
- code: z.ZodIssueCode.custom,
1263
- message: "Dispatch destination platform must be slack",
1264
- path: ["destination"]
1265
- });
1266
- return;
1267
- }
1268
- const subject = record.credentialSubject;
1269
- if (!subject) return;
1270
- if (subject.allowedWhen === "private-direct-conversation") {
1271
- if (!record.destination.channelId.startsWith("D")) {
1272
- ctx.addIssue({
1273
- code: z.ZodIssueCode.custom,
1274
- message: "Dispatch credentialSubject requires a private direct Slack destination",
1275
- path: ["credentialSubject"]
1276
- });
1277
- return;
1278
- }
1279
- if (subject.binding.type !== "slack-direct-conversation" || subject.binding.teamId !== record.destination.teamId || subject.binding.channelId !== record.destination.channelId) ctx.addIssue({
1280
- code: z.ZodIssueCode.custom,
1281
- message: "Dispatch credentialSubject binding must match destination",
1282
- path: ["credentialSubject", "binding"]
1283
- });
1284
- return;
1285
- }
1286
- if (subject.allowedWhen === "timer-watch") {
1287
- ctx.addIssue({
1288
- code: z.ZodIssueCode.custom,
1289
- message: "Dispatch credentialSubject cannot use a timer Watch binding",
1290
- path: ["credentialSubject", "allowedWhen"]
1291
- });
1292
- return;
1293
- }
1294
- if (subject.binding.type !== subject.allowedWhen || subject.binding.plugin !== record.plugin || subject.binding.taskId !== subject.taskId) ctx.addIssue({
1295
- code: z.ZodIssueCode.custom,
1296
- message: "Dispatch credentialSubject binding must match task",
1297
- path: ["credentialSubject", "binding"]
1298
- });
1299
- });
1300
- /** Return the durable key for one plugin-facing dispatch projection. */
1301
- function getDispatchStorageKey(id) {
1302
- return `${DISPATCH_PREFIX}:record:${id}`;
1303
- }
1304
- function dispatchLockKey(id) {
1305
- return `${DISPATCH_PREFIX}:lock:${id}`;
1306
- }
1307
- function pendingDispatchMailboxAppendIndexKey() {
1308
- return `${DISPATCH_PREFIX}:incomplete`;
1309
- }
1310
- function pendingDispatchMailboxAppendIndexLockKey() {
1311
- return `${DISPATCH_PREFIX}:incomplete:lock`;
1312
- }
1313
- function normalizeMetadata(metadata) {
1314
- if (!metadata) return;
1315
- const entries = Object.entries(metadata).filter((entry) => typeof entry[0] === "string" && typeof entry[1] === "string");
1316
- return entries.length > 0 ? Object.fromEntries(entries) : void 0;
1317
- }
1318
- const DISPATCH_ID_PREFIX = "agent-dispatch:";
1319
- /** Return the stable dispatch id for one plugin idempotency key. */
1320
- function buildDispatchId(plugin, idempotencyKey) {
1321
- return `dispatch_${createHash("sha256").update(plugin).update("\0").update(idempotencyKey).digest("hex").slice(0, 32)}`;
1322
- }
1323
- /** Parse one durable dispatch projection record. */
1324
- function parseDispatchRecord(value) {
1325
- const parsed = dispatchRecordSchema.safeParse(value);
1326
- return parsed.success ? parsed.data : void 0;
1327
- }
1328
- /** Return the isolated durable conversation id for one dispatch. */
1329
- function getDispatchConversationId(dispatch) {
1330
- return `${DISPATCH_ID_PREFIX}${dispatch.id}`;
1331
- }
1332
- /** Return the stable synthetic input message id for one dispatch turn. */
1333
- function getDispatchInputMessageId(dispatchId) {
1334
- return `${DISPATCH_ID_PREFIX}${dispatchId}`;
1335
- }
1336
- /**
1337
- * Return the dispatch id of a dispatch Conversation, such as an Automation
1338
- * run. Other Conversations have no dispatch.
1339
- */
1340
- function getDispatchIdForConversation(conversationId) {
1341
- if (!conversationId.startsWith(DISPATCH_ID_PREFIX)) return void 0;
1342
- return conversationId.slice(15) || void 0;
1343
- }
1344
- /** Return the stable turn id used by every run of one dispatch. */
1345
- function getDispatchTurnId(dispatchId) {
1346
- return `dispatch:${dispatchId}`;
1347
- }
1348
- function toDispatchProjection(record) {
1349
- return {
1350
- id: record.id,
1351
- status: record.status,
1352
- ...record.resultMessageTs ? { resultMessageTs: record.resultMessageTs } : void 0,
1353
- ...record.errorMessage ? { errorMessage: record.errorMessage } : void 0
1354
- };
1355
- }
1356
- /** Gate recovery to dispatches that can still make progress. */
1357
- function isTerminalDispatchStatus(status) {
1358
- return status === "completed" || status === "failed" || status === "blocked";
1359
- }
1360
- /** Serialize dispatch projection mutations. */
1361
- async function withDispatchLock(dispatchId, task) {
1362
- const state = getStateAdapter();
1363
- await state.connect();
1364
- const lock = await state.acquireLock(dispatchLockKey(dispatchId), DISPATCH_LOCK_TTL_MS);
1365
- if (!lock) throw new Error(`Could not acquire dispatch lock for ${dispatchId}`);
1366
- try {
1367
- return await task(state);
1368
- } finally {
1369
- await state.releaseLock(lock);
1370
- }
1371
- }
1372
- async function putRecord(state, record) {
1373
- const parsed = dispatchRecordSchema.safeParse(record);
1374
- if (!parsed.success) throw new Error(`Dispatch record is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join("; ")}`);
1375
- const next = parsed.data;
1376
- await state.set(getDispatchStorageKey(next.id), next, JUNIOR_THREAD_STATE_TTL_MS);
1377
- }
1378
- async function updatePendingDispatchMailboxAppendIndex(state, update) {
1379
- const lock = await state.acquireLock(pendingDispatchMailboxAppendIndexLockKey(), DISPATCH_MAILBOX_APPEND_INDEX_LOCK_TTL_MS);
1380
- if (!lock) throw new Error("Could not acquire dispatch mailbox append index lock");
1381
- try {
1382
- const stored = await state.get(pendingDispatchMailboxAppendIndexKey());
1383
- const ids = stored === void 0 || stored === null ? [] : pendingDispatchMailboxAppendIndexSchema.parse(stored);
1384
- const next = [...new Set(update([...new Set(ids)]))].slice(-1e4);
1385
- if (next.length === ids.length && next.every((id, index) => id === ids[index])) return;
1386
- await state.set(pendingDispatchMailboxAppendIndexKey(), next, JUNIOR_THREAD_STATE_TTL_MS);
1387
- } finally {
1388
- await state.releaseLock(lock);
1389
- }
1390
- }
1391
- /** Load dispatch state for conversation work and plugin projections. */
1392
- async function getDispatchRecord(id) {
1393
- const state = getStateAdapter();
1394
- await state.connect();
1395
- return parseDispatchRecord(await state.get(getDispatchStorageKey(id)));
1396
- }
1397
- /** Create a dispatch idempotently within its owner namespace. */
1398
- async function createOrGetDispatch(args) {
1399
- const id = buildDispatchId(args.plugin, args.options.idempotencyKey);
1400
- return await withDispatchLock(id, async (state) => {
1401
- const existing = parseDispatchRecord(await state.get(getDispatchStorageKey(id)));
1402
- if (existing) return {
1403
- record: existing,
1404
- status: "already_exists"
1405
- };
1406
- const metadata = normalizeMetadata(args.options.metadata);
1407
- const record = {
1408
- actor: {
1409
- platform: "system",
1410
- name: args.plugin
1411
- },
1412
- createdAtMs: args.nowMs,
1413
- ...args.options.credentialSubject ? { credentialSubject: args.options.credentialSubject } : void 0,
1414
- destination: args.options.destination,
1415
- destinationVisibility: args.options.destinationVisibility,
1416
- id,
1417
- idempotencyKey: args.options.idempotencyKey,
1418
- input: args.options.input,
1419
- ...metadata ? { metadata } : void 0,
1420
- plugin: args.plugin,
1421
- ...args.options.replyAttribution ? { replyAttribution: args.options.replyAttribution } : void 0,
1422
- ...args.options.outcomes ? { outcomes: args.options.outcomes } : void 0,
1423
- ...args.options.skill ? { skill: args.options.skill } : void 0,
1424
- status: "pending",
1425
- source: args.options.source,
1426
- ...args.options.title?.trim() ? { title: args.options.title.trim() } : void 0,
1427
- updatedAtMs: args.nowMs
1428
- };
1429
- await updatePendingDispatchMailboxAppendIndex(state, (ids) => ids.includes(id) ? ids : [...ids, id]);
1430
- await putRecord(state, record);
1431
- return {
1432
- record,
1433
- status: "created"
1434
- };
1435
- });
1436
- }
1437
- async function transitionDispatch(id, transition) {
1438
- return await withDispatchLock(id, async (state) => {
1439
- const current = parseDispatchRecord(await state.get(getDispatchStorageKey(id)));
1440
- if (!current) return;
1441
- const transitioned = transition(current);
1442
- if (transitioned === current) return current;
1443
- const next = {
1444
- ...transitioned,
1445
- updatedAtMs: Date.now()
1446
- };
1447
- await putRecord(state, next);
1448
- return next;
1449
- });
1450
- }
1451
- /** Mark a dispatch projection as actively running. */
1452
- async function markDispatchRunning(id) {
1453
- return await transitionDispatch(id, (record) => isTerminalDispatchStatus(record.status) ? record : {
1454
- ...record,
1455
- status: "running",
1456
- errorMessage: void 0
1457
- });
1458
- }
1459
- /** Project a durable awaiting-resume turn state to the plugin API. */
1460
- async function markDispatchAwaitingResume(id) {
1461
- return await transitionDispatch(id, (record) => isTerminalDispatchStatus(record.status) ? record : {
1462
- ...record,
1463
- status: "awaiting_resume"
1464
- });
1465
- }
1466
- async function recordEventAutomationExecution(previous, next, status) {
1467
- if (!next || next.status !== status || previous?.status === status) return;
1468
- if (next.plugin !== "junior") return;
1469
- const eventAutomationId = next.metadata?.["eventAutomationId"];
1470
- if (!eventAutomationId) return;
1471
- await recordAutomationExecution(eventAutomationId, {
1472
- conversationId: getDispatchConversationId(next),
1473
- errorMessage: next.errorMessage,
1474
- executionId: next.id,
1475
- nowMs: next.updatedAtMs,
1476
- status
1477
- });
1478
- }
1479
- /**
1480
- * Project a blocked turn to the plugin API. An Event automation is blocked
1481
- * first, so a retry after a failed write still blocks it. Its creator is told
1482
- * when the block is first stored. The heartbeat blocks a Scheduled automation
1483
- * and tells its creator.
1484
- */
1485
- async function markDispatchBlocked(id, errorMessage, resultMessageTs) {
1486
- const previous = await getDispatchRecord(id);
1487
- const eventAutomationId = previous?.metadata?.["eventAutomationId"];
1488
- if (previous?.plugin === "junior" && eventAutomationId && !isTerminalDispatchStatus(previous.status) && await blockEventAutomation(getDb(), eventAutomationId, errorMessage)) await notifyAutomationBlocked({
1489
- automationId: eventAutomationId,
1490
- dispatchId: id,
1491
- kind: "event",
1492
- reason: errorMessage
1493
- });
1494
- const next = await transitionDispatch(id, (record) => isTerminalDispatchStatus(record.status) ? record : {
1495
- ...record,
1496
- errorMessage,
1497
- ...resultMessageTs ? { resultMessageTs } : void 0,
1498
- status: "blocked"
1499
- });
1500
- await recordEventAutomationExecution(previous, next, "blocked");
1501
- return next;
1502
- }
1503
- /** Project a completed turn and its accepted Slack message to the plugin API. */
1504
- async function markDispatchCompleted(id, resultMessageTs) {
1505
- const previous = await getDispatchRecord(id);
1506
- const next = await transitionDispatch(id, (record) => isTerminalDispatchStatus(record.status) ? record : {
1507
- ...record,
1508
- errorMessage: void 0,
1509
- ...resultMessageTs ? { resultMessageTs } : void 0,
1510
- status: "completed"
1511
- });
1512
- await recordEventAutomationExecution(previous, next, "completed");
1513
- return next;
1514
- }
1515
- /** Project a terminal conversation turn failure to the plugin API. */
1516
- async function markDispatchFailed(id, errorMessage, resultMessageTs) {
1517
- const previous = await getDispatchRecord(id);
1518
- const next = await transitionDispatch(id, (record) => isTerminalDispatchStatus(record.status) ? record : {
1519
- ...record,
1520
- errorMessage,
1521
- ...resultMessageTs ? { resultMessageTs } : void 0,
1522
- status: "failed"
1523
- });
1524
- await recordEventAutomationExecution(previous, next, "failed");
1525
- return next;
1526
- }
1527
- /** Remove a dispatch after its durable mailbox append has succeeded. */
1528
- async function confirmDispatchMailboxAppend(id) {
1529
- const state = getStateAdapter();
1530
- await state.connect();
1531
- await updatePendingDispatchMailboxAppendIndex(state, (ids) => ids.filter((candidate) => candidate !== id));
1532
- }
1533
- /** List dispatches whose durable mailbox append may not have completed. */
1534
- async function listPendingDispatchMailboxAppends() {
1535
- const state = getStateAdapter();
1536
- await state.connect();
1537
- const stored = await state.get(pendingDispatchMailboxAppendIndexKey());
1538
- return stored === void 0 || stored === null ? [] : [...new Set(pendingDispatchMailboxAppendIndexSchema.parse(stored))];
1539
- }
1540
- /** Load the dispatch under lock before its mailbox append becomes visible. */
1541
- async function claimDispatchMailboxAppend(id) {
1542
- return await withDispatchLock(id, async (state) => {
1543
- return parseDispatchRecord(await state.get(getDispatchStorageKey(id)));
1544
- });
1545
- }
1546
- /** Return a plugin-scoped dispatch projection without exposing raw runtime state. */
1547
- async function getPluginDispatchProjection(args) {
1548
- const record = await getDispatchRecord(args.id);
1549
- if (!record || record.plugin !== args.plugin) return;
1550
- return toDispatchProjection(record);
1551
- }
1552
- // src/chat/state/conversation.ts
1553
- function defaultConversationState() {
1554
- return {
1555
- schemaVersion: 1,
1556
- messages: [],
1557
- processing: {},
1558
- vision: { byFileId: {} }
1559
- };
1560
- }
1561
- function coercePendingAuthState(value) {
1562
- if (!isRecord(value)) return;
1563
- const kind = value["kind"];
1564
- const provider = toOptionalString(value["provider"]);
1565
- const actorId = toOptionalString(value["actorId"]);
1566
- const authSessionId = toOptionalString(value["authSessionId"]);
1567
- const scope = toOptionalString(value["scope"]);
1568
- const sessionId = toOptionalString(value["sessionId"]);
1569
- const linkSentAtMs = toOptionalNumber(value["linkSentAtMs"]);
1570
- if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
1571
- const base = {
1572
- provider,
1573
- actorId,
1574
- ...scope ? { scope } : void 0,
1575
- sessionId,
1576
- linkSentAtMs
1577
- };
1578
- return kind === "mcp" ? {
1579
- ...base,
1580
- authSessionId,
1581
- kind
1582
- } : {
1583
- ...base,
1584
- kind
1585
- };
1586
- }
1587
- /** Safely coerce an unknown persisted value into a ThreadConversationState. */
1588
- function coerceThreadConversationState(value) {
1589
- if (!isRecord(value)) return defaultConversationState();
1590
- const root = value;
1591
- const rawConversation = isRecord(root.conversation) ? root.conversation : {};
1592
- const messages = [];
1593
- const rawProcessing = isRecord(rawConversation["processing"]) ? rawConversation["processing"] : {};
1594
- const processing = {
1595
- activeTurnId: toOptionalString(rawProcessing["activeTurnId"]),
1596
- lastCompletedAtMs: toOptionalNumber(rawProcessing["lastCompletedAtMs"]),
1597
- pendingAuth: coercePendingAuthState(rawProcessing["pendingAuth"])
1598
- };
1599
- const rawVision = isRecord(rawConversation["vision"]) ? rawConversation["vision"] : {};
1600
- const rawVisionByFileId = isRecord(rawVision["byFileId"]) ? rawVision["byFileId"] : {};
1601
- const byFileId = {};
1602
- for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
1603
- if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
1604
- if (!isRecord(value)) continue;
1605
- const summary = toOptionalString(value["summary"]);
1606
- const analyzedAtMs = toOptionalNumber(value["analyzedAtMs"]);
1607
- if (!summary || !analyzedAtMs) continue;
1608
- byFileId[fileId] = {
1609
- summary,
1610
- analyzedAtMs
1611
- };
1612
- }
1613
- return {
1614
- schemaVersion: 1,
1615
- messages,
1616
- processing,
1617
- vision: {
1618
- backfillCompletedAtMs: toOptionalNumber(rawVision["backfillCompletedAtMs"]),
1619
- byFileId
1620
- }
1621
- };
1622
- }
1623
- /**
1624
- * Wrap active conversation control into the thread scratch envelope.
1625
- *
1626
- * Visible history lives in SQL. Image summaries use a separate disposable
1627
- * cache, so thread scratch does not retain them.
1628
- */
1629
- function buildConversationStatePatch(conversation) {
1630
- return { conversation: {
1631
- schemaVersion: 1,
1632
- processing: { ...conversation.processing }
1633
- } };
1634
- }
1635
- // src/chat/runtime/thread-state.ts
1636
- function threadStateKey(threadId) {
1637
- return `thread-state:${threadId}`;
1638
- }
1639
- function channelStateKey(channelId) {
1640
- return `channel-state:${channelId}`;
1641
- }
1642
- function buildThreadStatePayload(patch) {
1643
- const payload = {};
1644
- if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
1645
- if (patch.sandboxRef !== void 0) {
1646
- payload["app_sandbox_id"] = patch.sandboxRef?.id ?? "";
1647
- payload["app_sandbox_dependency_profile_hash"] = patch.sandboxRef?.profileHash ?? "";
1648
- payload["app_sandbox_workspace_id"] = patch.sandboxRef?.workspaceId ?? "";
1649
- }
1650
- return payload;
1651
- }
1652
- /**
1653
- * Merge a payload into thread scratch with Junior's TTL.
1654
- *
1655
- * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
1656
- * shorter retention policy for the same scratch keys.
1657
- */
1658
- async function mergePersistedState(key, payload) {
1659
- if (Object.keys(payload).length === 0) return;
1660
- const stateAdapter = getStateAdapter();
1661
- await stateAdapter.connect();
1662
- const existing = await stateAdapter.get(key) ?? {};
1663
- await stateAdapter.set(key, {
1664
- ...existing,
1665
- ...payload
1666
- }, JUNIOR_THREAD_STATE_TTL_MS);
1667
- }
1668
- /** Extract persisted sandbox metadata from thread state payload. */
1669
- function getPersistedSandboxState(state) {
1670
- const id = toOptionalString(state["app_sandbox_id"]);
1671
- if (!id) return;
1672
- const profileHash = toOptionalString(state["app_sandbox_dependency_profile_hash"]);
1673
- const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
1674
- return {
1675
- id,
1676
- ...profileHash ? { profileHash } : void 0,
1677
- ...workspaceId ? { workspaceId } : void 0
1678
- };
1679
- }
1680
- /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
1681
- async function persistThreadRuntimeState(conversationId, patch) {
1682
- await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
1683
- }
1684
- /** Load the persisted state payload for a thread without requiring a Chat singleton. */
1685
- async function getPersistedThreadState(threadId) {
1686
- const stateAdapter = getStateAdapter();
1687
- await stateAdapter.connect();
1688
- return await stateAdapter.get(threadStateKey(threadId)) ?? {};
1689
- }
1690
- /** Persist a thread-state patch by thread id without constructing a Chat thread. */
1691
- async function persistThreadStateById(threadId, patch) {
1692
- if (patch.conversation) await persistConversationMessages({
1693
- conversation: patch.conversation,
1694
- conversationId: threadId
1695
- });
1696
- await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
1697
- }
1698
- /** Load legacy Redis-backed channel state during the SQL cutover. */
1699
- async function getLegacyChannelState(channelId) {
1700
- const stateAdapter = getStateAdapter();
1701
- await stateAdapter.connect();
1702
- return await stateAdapter.get(channelStateKey(channelId)) ?? {};
1703
- }
1704
- /**
1705
- * Resolve durable location configuration.
1706
- *
1707
- * Slack still reads the old channel-id Redis bag once during cutover.
1708
- */
1709
- function getLocationConfigurationService(destination) {
1710
- if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
1711
- return createDurableLocationConfigurationService({
1712
- destination,
1713
- db: getDb(),
1714
- loadLegacy: async () => await getLegacyChannelState(destination.channelId)
1715
- });
1716
- }
1717
- // src/chat/services/turn-session-routing.ts
1718
- async function loadConversationChain(conversationId, conversationStore) {
1719
- const chain = [];
1720
- const seen = /* @__PURE__ */ new Set();
1721
- let cursor = conversationId;
1722
- while (cursor && !seen.has(cursor)) {
1723
- seen.add(cursor);
1724
- const conversation = await conversationStore.get({ conversationId: cursor });
1725
- if (!conversation) break;
1726
- chain.push(conversation);
1727
- cursor = conversation.parentConversationId;
1728
- }
1729
- return chain;
1730
- }
1731
- /**
1732
- * Normalize a stored Slack session source against the conversation destination.
1733
- *
1734
- * Does not create channel or thread values from the conversation id.
1735
- */
1736
- function slackSourceForDestination(args) {
1737
- if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
1738
- const threadTs = args.source.threadTs?.trim();
1739
- return {
1740
- kind: "slack",
1741
- visibility: args.source.visibility ?? "public",
1742
- teamId: args.source.teamId?.trim() || args.destination.teamId,
1743
- channelId: args.source.channelId,
1744
- ...threadTs ? { threadTs } : void 0
1745
- };
1746
- }
1747
- /**
1748
- * Resolve the Conversation Location, Destination, and session Source.
1749
- *
1750
- * Reads parent Conversations when this Conversation has no Destination.
1751
- */
1752
- async function resolveConversationRouting(args) {
1753
- const conversationStore = args.conversationStore ?? (await import("./db-DU84dCVu.js").then((n) => n.n)).getConversationStore();
1754
- const chain = await loadConversationChain(args.conversationId, conversationStore);
1755
- let destination;
1756
- let source;
1757
- let location;
1758
- for (const conversation of chain) {
1759
- destination ??= conversation.destination;
1760
- source ??= conversation.sessionSource;
1761
- location ??= conversation.location;
1762
- if (destination && source) break;
1763
- }
1764
- if (!destination) return;
1765
- if (destination.platform === "slack") {
1766
- const slackSource = slackSourceForDestination({
1767
- destination,
1768
- source
1769
- });
1770
- return {
1771
- destination,
1772
- ...location ? { location } : void 0,
1773
- ...slackSource ? { source: slackSource } : void 0
1774
- };
1775
- }
1776
- return {
1777
- destination,
1778
- ...location ? { location } : void 0,
1779
- ...source ? { source } : void 0
1780
- };
1781
- }
1782
- /** Require the Conversation Destination and Source from SQL. */
1783
- async function resolveTurnSessionRouting(args) {
1784
- const routing = await resolveConversationRouting(args);
1785
- if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
1786
- return {
1787
- destination: routing.destination,
1788
- ...routing.location ? { location: routing.location } : void 0,
1789
- source: routing.source
1790
- };
1791
- }
1792
- export { deleteEventAutomation as $, readAutomationExecutionStatusDays as A, blockScheduledAutomation as B, markDispatchCompleted as C, hasEventCatalogEntries as Ct, emptyAutomationRunWindows as D, registeredResourceTypeSchema as Dt, notifyAutomationBlocked as E, registeredEventTypeSchema as Et, readAutomationTitlesByConversationId as F, readScheduledAutomation as G, deleteScheduledAutomation as H, recordAutomationExecution as I, scheduledRunId as J, saveScheduledAutomation as K, conversationAggregateColumns as L, readAutomationExecutionSummaries as M, readAutomationExecutions as N, existingConversationId as O, requireEventIdentifier as Ot, readAutomationRuns as P, createEventAutomation as Q, conversationRangeColumns as R, markDispatchBlocked as S, eventWatchUnavailable as St, markDispatchRunning as T, registeredEventTriggerProblems as Tt, listScheduledAutomationsForTeam as U, createScheduledAutomation as V, parseScheduledAutomationRow as W, blockEventAutomation as X, withScheduledAutomationLock as Y, collectEventAutomationMatchKeys as Z, getDispatchTurnId as _, automationEventCatalog as _t, getPersistedThreadState as a, setEventAutomationStatus as at, listPendingDispatchMailboxAppends as b, eventGuidance as bt, coerceThreadConversationState as c, automationDefinition as ct, confirmDispatchMailboxAppend as d, readAutomationVersion as dt, findMatchingEventAutomations as et, createOrGetDispatch as f, sameDefinitionValue as ft, getDispatchRecord as g, CORE_EVENT_NAMESPACE as gt, getDispatchInputMessageId as h, requireAutomationRevision as ht, getPersistedSandboxState as i, saveEventAutomation as it, readAutomationExecutionStatusHours as j, readAutomationExecutionByConversationId as k, requireValidEventTrigger as kt, buildDispatchId as l, automationVersionOf as lt, getDispatchIdForConversation as m, automationRevision as mt, resolveTurnSessionRouting as n, listDeletedEventAutomationsCreatedBy as nt, persistThreadRuntimeState as o, admitEventAutomationRun as ot, getDispatchConversationId as p, AutomationConflictError as pt, saveScheduledAutomationInLock as q, getLocationConfigurationService as r, parseEventAutomationRow as rt, persistThreadStateById as s, eventAutomationRunLimitReason as st, resolveConversationRouting as t, getEventAutomation as tt, claimDispatchMailboxAppend as u, listAutomationVersions as ut, getPluginDispatchProjection as v, describeRegisteredEventTrigger as vt, markDispatchFailed as w, registeredEventMatchSchema as wt, markDispatchAwaitingResume as x, eventNamespaceSchema as xt, isTerminalDispatchStatus as y, eventCatalogEntry as yt, conversationUsageCostExpr as z };