@sentry/junior 0.224.0 → 0.226.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 (63) hide show
  1. package/dist/{agent-hooks-DNLBwmsh.js → agent-hooks-FUetyyLe.js} +23 -16
  2. package/dist/{agent-runner-9g6TQk9y.js → agent-runner-DEF7auSj.js} +3114 -318
  3. package/dist/api/schema.d.ts +353 -10
  4. package/dist/api/schema.js +4 -4
  5. package/dist/api.js +22 -18
  6. package/dist/{app-BbSD6EtD.d.ts → app-TVL42pGL.d.ts} +1 -1
  7. package/dist/app.d.ts +1 -1
  8. package/dist/app.js +893 -7660
  9. package/dist/{briefs-CjXnGKzZ.js → briefs-Cb4T2BUI.js} +5 -5
  10. package/dist/{catalog-runtime-CVZ9TEuK.js → catalog-runtime-BYGR3Dr4.js} +1 -1
  11. package/dist/{checkpoint-Ceck_fLO.js → checkpoint-CJe-dZFF.js} +76 -10
  12. package/dist/cli/chat.js +13 -13
  13. package/dist/cli/check.js +3 -3
  14. package/dist/cli/main.js +1 -1
  15. package/dist/cli/plugins.js +3 -3
  16. package/dist/cli/snapshot-create.js +3 -3
  17. package/dist/cli/upgrade.js +3 -3
  18. package/dist/{client-B27ufhzl.js → client-C2WBBx7m.js} +2 -2
  19. package/dist/{config-BAhl7-RC.js → config-Bws6Rpsh.js} +11 -13
  20. package/dist/{conversation-1HUoZr2l.js → conversation-DPbmIwjy.js} +67 -6
  21. package/dist/{conversation-privacy-C-4JQzKD.js → conversation-privacy-pCcW0a5Y.js} +1 -1
  22. package/dist/{credential-sync-BXHIxbtS.js → credential-sync-ibuNsMyl.js} +14 -134
  23. package/dist/{executor-BG2Armby.js → executor-D36FWjcf.js} +1 -1
  24. package/dist/{history-yaSjGMD_.d.ts → history-DI9KJT3J.d.ts} +38 -1
  25. package/dist/instrumentation.js +2 -2
  26. package/dist/{vercel-queue-DIkVcfK4.js → job-queue-2mFFDMHB.js} +61 -2
  27. package/dist/{logging-iY0ssa2q.js → logging-CvjMHRvg.js} +2 -2
  28. package/dist/{model-profile-CZmVoGdX.js → model-profile-BwU8mqwD.js} +14 -1
  29. package/dist/nitro.d.ts +1 -1
  30. package/dist/nitro.js +3 -4
  31. package/dist/{oauth-authorization-BIijVS2N.js → oauth-authorization-l4O1rXsL.js} +1 -1
  32. package/dist/{oauth-callback-server-DPkK3kzi.js → oauth-callback-server-Ds8M5FFX.js} +2 -2
  33. package/dist/pending-auth-DLNJbD8H.js +59 -0
  34. package/dist/{profile-6KWhg_-U.js → profile-dvV7PB7u.js} +4 -4
  35. package/dist/{prompt-90miy8VV.js → prompt-DehgjkO5.js} +1 -1
  36. package/dist/{registry-Ctgdjt-W.js → registry-C6FHctIu.js} +3 -3
  37. package/dist/{resolve-CB45ZukQ.js → resolve-DqwGI9wq.js} +2 -2
  38. package/dist/{runner-BwKCqoF3.js → runner-CzYEcB73.js} +9 -9
  39. package/dist/{sandbox-egress-signals-Cmy8ODat.js → sandbox-egress-signals-BZOv0fns.js} +1 -1
  40. package/dist/{schema-RpbW5Od2.js → schema-BZg-xzfG.js} +2 -2
  41. package/dist/{skills-c2bMDVRS.js → skills-EhiVbjF4.js} +2 -2
  42. package/dist/{spawn-Cg6lyjE7.js → spawn-Ck3L0rEr.js} +2 -2
  43. package/dist/{task-queue-SL4uLfBB.js → task-queue-TXhAWQwj.js} +3 -4
  44. package/dist/{task-runner-fntmnqzx.js → task-runner-axUJS1No.js} +380 -11
  45. package/dist/{thread-state-Wfr0GdKS.js → thread-state-CTuWhjru.js} +5 -5
  46. package/dist/{turn-failure-response-DLjSEm-R.js → turn-failure-response-csVoLOzx.js} +8 -9
  47. package/dist/{turn-lifecycle-5_jvLqRz.js → turn-lifecycle-C1S6vELh.js} +1 -1
  48. package/dist/{turn-session-routing-CQaysLoe.js → turn-session-routing-5RejBvit.js} +1 -1
  49. package/dist/{validation-CnZkCN7o.js → validation-q2PFxkTQ.js} +1 -1
  50. package/dist/{version-C6lA-h_o.js → version-ByLtIYyy.js} +1 -1
  51. package/dist/version.js +1 -1
  52. package/dist/web-authorization-Biy8nsS7.js +162 -0
  53. package/dist/web-input-DM9LaEdn.js +7774 -0
  54. package/dist/{reporting-window-DbUqng0P.js → web-message-id-xPI_EFSC.js} +11 -1
  55. package/dist/{work-4Nhz9mVv.js → work-QrbHdXTc.js} +7 -8
  56. package/dist/{worker-CdWPsNL2.js → worker-r17aopXW.js} +5 -6
  57. package/package.json +4 -4
  58. package/dist/execution-stats-DikPOxJ1.js +0 -373
  59. package/dist/job-queue-D4oAVrL9.js +0 -63
  60. package/dist/short-title-xEkZwkcV.js +0 -65
  61. package/dist/stats-DP9zl3Jg.js +0 -2758
  62. package/dist/web-authorization-Bbx999_q.js +0 -38
  63. package/dist/web-input-BoE1xE-K.js +0 -899
@@ -1,2758 +0,0 @@
1
- import { F as isRecord$1, I as toOptionalNumber, L as toOptionalString } from "./logging-iY0ssa2q.js";
2
- import { a as getChatConfig } from "./config-BAhl7-RC.js";
3
- import { _ as parseSlackMessageTs, d as parseStoredSlackActor, h as parseSlackTeamId, p as parseSlackChannelId } from "./context-Bplcgypl.js";
4
- import { Ft as saveObjectAnnotations, J as withSlackRetries, Kt as getConversationStore, U as getSlackClient, fn as parseDestination, ht as getDashboardTaskLink, mn as sameDestination, pt as JUNIOR_THREAD_STATE_TTL_MS, qt as getDb, u as getPlugins } from "./agent-hooks-DNLBwmsh.js";
5
- import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
6
- import { E as juniorConversations, a as juniorSchedulerRuns, c as juniorStats, l as juniorEventAutomations, o as juniorSchedulerTasks, w as juniorAttachments } from "./executor-BG2Armby.js";
7
- import { t as fallbackShortTitle } from "./short-title-xEkZwkcV.js";
8
- import { C as getDefaultRedisStateAdapterFor, w as getStateAdapter } from "./profile-6KWhg_-U.js";
9
- import "./vercel-queue-DIkVcfK4.js";
10
- import { z } from "zod";
11
- import { createHash, randomUUID } from "node:crypto";
12
- import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, notInArray, or, sql } from "drizzle-orm";
13
- import { actorUserIdSchema, destinationSchema, destinationVisibilitySchema, eventMatchSchema, eventMatches, eventTypeSchema, normalizeEventIdentifier, ownedObjectAnnotationSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
14
- //#region src/chat/tools/execution/tool-input-error.ts
15
- /** Thrown when a tool fails due to invalid model/user input, not a system error. */
16
- var ToolInputError = class extends Error {
17
- constructor(message, options) {
18
- super(message, options);
19
- this.name = "ToolInputError";
20
- }
21
- };
22
- //#endregion
23
- //#region src/chat/state/turn-id.ts
24
- /** Build a stable turn identifier from a message ID. */
25
- function buildDeterministicTurnId(messageId) {
26
- return `turn_${messageId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
27
- }
28
- /** Build the stable visible assistant-message identity for one logical turn. */
29
- function buildDeterministicAssistantMessageId(turnId) {
30
- return `${turnId}:assistant:1`;
31
- }
32
- //#endregion
33
- //#region src/chat/tool-support/structured-result.ts
34
- const juniorToolContinuationSchema = z.object({
35
- arguments: z.record(z.string(), z.unknown()),
36
- reason: z.string().min(1).optional()
37
- }).strict();
38
- const juniorToolBoundContinuationSchema = juniorToolContinuationSchema.extend({ tool_name: z.string().min(1) });
39
- /** Shared optional fields for canonical Junior tool outputs. */
40
- const juniorToolOutputSchema = z.object({
41
- target: z.string().min(1).optional(),
42
- truncated: z.boolean().optional(),
43
- /** True when this attempt did not finish before its time budget. */
44
- timed_out: z.boolean().optional(),
45
- continuation: juniorToolContinuationSchema.optional()
46
- }).passthrough();
47
- function sortJsonValue(value) {
48
- if (Array.isArray(value)) return value.map(sortJsonValue);
49
- if (!value || typeof value !== "object") return value;
50
- return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortJsonValue(item)]));
51
- }
52
- function isRecord(value) {
53
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
54
- }
55
- /** Bind continuation metadata to the exposed runtime tool name. */
56
- function injectContinuationToolName(details, toolName) {
57
- if (!isRecord(details) || !isRecord(details.continuation)) return details;
58
- return {
59
- ...details,
60
- continuation: juniorToolBoundContinuationSchema.parse({
61
- ...details.continuation,
62
- tool_name: toolName
63
- })
64
- };
65
- }
66
- function makeStructuredToolOutput(details, options = {}) {
67
- return {
68
- content: [{
69
- type: "text",
70
- text: JSON.stringify(sortJsonValue(details))
71
- }, ...options.content ?? []],
72
- details
73
- };
74
- }
75
- //#endregion
76
- //#region src/chat/task-execution/state.ts
77
- /**
78
- * Expiring conversation mailbox and execution index store.
79
- *
80
- * The conversation record owns pending inbound work, execution status, and the
81
- * lease. `conversation:active` feeds heartbeat recovery and contains every
82
- * non-idle conversation until the lease/status path makes it idle.
83
- * `conversation:by-activity` supports legacy SQL import only; SQL owns durable
84
- * conversation metadata in configured runtime.
85
- */
86
- const CONVERSATION_PREFIX = "junior:conversation:v2";
87
- const CONVERSATION_SCHEMA_VERSION = 2;
88
- const CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH = 1e4;
89
- const CONVERSATION_INDEX_LOCK_TTL_MS = 1e4;
90
- const CONVERSATION_INDEX_LOCK_WAIT_MS = 2e3;
91
- const CONVERSATION_INDEX_LOCK_RETRY_MS = 25;
92
- const CONVERSATION_MUTATION_LOCK_TTL_MS = 1e4;
93
- const CONVERSATION_MUTATION_WAIT_MS = 1e4;
94
- const CONVERSATION_MUTATION_RETRY_MS = 25;
95
- var InvalidConversationRecordError = class extends Error {
96
- constructor(conversationId) {
97
- super(`Conversation record is invalid for ${conversationId}`);
98
- this.name = "InvalidConversationRecordError";
99
- }
100
- };
101
- /** Return whether an error means a stored conversation record failed validation. */
102
- function isInvalidConversationRecordError(error) {
103
- return error instanceof InvalidConversationRecordError;
104
- }
105
- var ConversationMutationFencedError = class extends Error {
106
- constructor(conversationId) {
107
- super(`Conversation mutation lock was lost before write for ${conversationId}`);
108
- this.name = "ConversationMutationFencedError";
109
- }
110
- };
111
- const CONVERSATION_BY_ACTIVITY_INDEX_KEY = `${CONVERSATION_PREFIX}:by-activity`;
112
- const CONVERSATION_ACTIVE_INDEX_KEY = `${CONVERSATION_PREFIX}:active`;
113
- const CONVERSATION_WORK_LEASE_TTL_MS = 9e4;
114
- const CONVERSATION_WORK_CHECK_IN_INTERVAL_MS = 15e3;
115
- const CONVERSATION_WORK_STALE_ENQUEUE_MS = 6e4;
116
- const inboundMessageSourceSchema = z.enum([
117
- "api",
118
- "internal",
119
- "local",
120
- "plugin",
121
- "event",
122
- "scheduler",
123
- "slack",
124
- "web"
125
- ]);
126
- const agentInputSchema = z.object({
127
- attachments: z.array(z.unknown()).optional(),
128
- authorId: z.string().min(1).optional(),
129
- metadata: z.record(z.string(), z.unknown()).optional(),
130
- text: z.string()
131
- }).strict().refine((input) => input.text.trim() || input.attachments?.length, { message: "agent input requires text or attachments" });
132
- /** Durable delivery modes for pending inbound mailbox work. */
133
- const inboundMessageDeliverySchema = z.enum(["defer", "interrupt"]);
134
- /** Redis mailbox shape kept for deployed workers that still require this field. */
135
- const storedInboundMessageSchema = z.object({
136
- attemptCount: z.number().finite().optional(),
137
- conversationId: z.string().refine((value) => value.trim().length > 0),
138
- createdAtMs: z.number().finite(),
139
- delivery: inboundMessageDeliverySchema,
140
- destination: destinationSchema.optional(),
141
- inboundMessageId: z.string().refine((value) => value.trim().length > 0),
142
- injectedAtMs: z.number().finite().optional(),
143
- input: agentInputSchema,
144
- receivedAtMs: z.number().finite(),
145
- source: inboundMessageSourceSchema
146
- }).strict().extend({ publishExternally: z.boolean() });
147
- function conversationKey(conversationId) {
148
- return `${CONVERSATION_PREFIX}:${conversationId}`;
149
- }
150
- function conversationStopKey(conversationId) {
151
- return `${CONVERSATION_PREFIX}:stop:${conversationId}`;
152
- }
153
- function indexLockKey(indexKey) {
154
- return `${indexKey}:lock`;
155
- }
156
- function mutationLockKey(conversationId) {
157
- return `${CONVERSATION_PREFIX}:mutation:${conversationId}`;
158
- }
159
- function now$1() {
160
- return Date.now();
161
- }
162
- function compareMessages(left, right) {
163
- return left.createdAtMs - right.createdAtMs || left.receivedAtMs - right.receivedAtMs || left.inboundMessageId.localeCompare(right.inboundMessageId);
164
- }
165
- function inputHasAttachments(input) {
166
- return Array.isArray(input.attachments) && input.attachments.length > 0;
167
- }
168
- /**
169
- * Upgrade a still-pending payload when a duplicate source event carries file
170
- * attachments the stored copy lacks (Slack `app_mention`/`message` twins),
171
- * keeping the stored ordering timestamps and delivery attempts.
172
- */
173
- function upgradedPendingMessage(stored, duplicate) {
174
- const promotesInterrupt = stored.delivery === "defer" && duplicate.delivery === "interrupt";
175
- const delivery = promotesInterrupt ? "interrupt" : stored.delivery;
176
- const input = promotesInterrupt ? {
177
- ...duplicate.input,
178
- ...inputHasAttachments(duplicate.input) || !inputHasAttachments(stored.input) ? void 0 : { attachments: stored.input.attachments }
179
- } : inputHasAttachments(duplicate.input) && !inputHasAttachments(stored.input) ? duplicate.input : stored.input;
180
- if (input === stored.input && delivery === stored.delivery) return stored;
181
- return {
182
- ...stored,
183
- delivery,
184
- input
185
- };
186
- }
187
- function compareIndexDescending(left, right) {
188
- return right.score - left.score || right.conversationId.localeCompare(left.conversationId);
189
- }
190
- function compareIndexAscending(left, right) {
191
- return left.score - right.score || left.conversationId.localeCompare(right.conversationId);
192
- }
193
- function uniqueStrings(values) {
194
- return [...new Set(values)];
195
- }
196
- function normalizeSource(value) {
197
- const parsed = inboundMessageSourceSchema.safeParse(value);
198
- return parsed.success ? parsed.data : void 0;
199
- }
200
- function normalizeExecutionStatus(value) {
201
- if (value === "paused") return value;
202
- if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
203
- }
204
- function normalizeMessage(value) {
205
- const parsed = storedInboundMessageSchema.safeParse(value);
206
- if (!parsed.success) return;
207
- const { publishExternally: _publishExternally, ...message } = parsed.data;
208
- return message;
209
- }
210
- function storeMessage(message, publishExternally) {
211
- return {
212
- ...message,
213
- publishExternally
214
- };
215
- }
216
- /** Whether this is the final attempt before an unacked message is dead-lettered. */
217
- function isFinalAttempt(message) {
218
- return (message.attemptCount ?? 0) >= 4;
219
- }
220
- function normalizeActor(value) {
221
- return parseStoredSlackActor(value);
222
- }
223
- function normalizeLease(value) {
224
- if (!isRecord$1(value)) return;
225
- const token = toOptionalString(value.token);
226
- const acquiredAtMs = toOptionalNumber(value.acquiredAtMs);
227
- const lastCheckInAtMs = toOptionalNumber(value.lastCheckInAtMs);
228
- const expiresAtMs = toOptionalNumber(value.expiresAtMs);
229
- if (!token || typeof acquiredAtMs !== "number" || typeof lastCheckInAtMs !== "number" || typeof expiresAtMs !== "number") return;
230
- return {
231
- token,
232
- acquiredAtMs,
233
- lastCheckInAtMs,
234
- expiresAtMs
235
- };
236
- }
237
- function normalizeStop(value) {
238
- if (!isRecord$1(value)) return;
239
- const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.filter((id) => typeof id === "string")) : [];
240
- const runId = toOptionalString(value.runId);
241
- return runId ? {
242
- inboundMessageIds,
243
- runId
244
- } : void 0;
245
- }
246
- /** Decode execution state and repair idle records that still own work. */
247
- function normalizeExecution(conversationId, value) {
248
- if (!isRecord$1(value)) return;
249
- const status = normalizeExecutionStatus(value.status);
250
- if (!status) return;
251
- const pendingMessages = [];
252
- if (Array.isArray(value.pendingMessages)) {
253
- for (const rawMessage of value.pendingMessages) {
254
- const message = normalizeMessage(rawMessage);
255
- if (!message || message.conversationId !== conversationId) return;
256
- if (message.injectedAtMs !== void 0) continue;
257
- pendingMessages.push(message);
258
- }
259
- pendingMessages.sort(compareMessages);
260
- }
261
- const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))) : [];
262
- const lease = normalizeLease(value.lease);
263
- const runId = toOptionalString(value.runId);
264
- return {
265
- status: status === "idle" && lease ? "running" : status === "idle" && pendingMessages.length > 0 ? "pending" : status,
266
- inboundMessageIds: uniqueStrings([...inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
267
- pendingCount: pendingMessages.length,
268
- pendingMessages,
269
- lease,
270
- lastCheckpointAtMs: toOptionalNumber(value.lastCheckpointAtMs),
271
- lastEnqueuedAtMs: toOptionalNumber(value.lastEnqueuedAtMs),
272
- lastProgressAtMs: toOptionalNumber(value.lastProgressAtMs),
273
- retryCount: toOptionalNumber(value.retryCount),
274
- runId,
275
- updatedAtMs: toOptionalNumber(value.updatedAtMs)
276
- };
277
- }
278
- /** Decode current conversation records. */
279
- function normalizeConversation(conversationId, value) {
280
- if (!isRecord$1(value) || value.schemaVersion !== CONVERSATION_SCHEMA_VERSION) return;
281
- const storedConversationId = toOptionalString(value.conversationId);
282
- const createdAtMs = toOptionalNumber(value.createdAtMs);
283
- const lastActivityAtMs = toOptionalNumber(value.lastActivityAtMs);
284
- const updatedAtMs = toOptionalNumber(value.updatedAtMs);
285
- const execution = normalizeExecution(conversationId, value.execution);
286
- const destination = value.destination === void 0 ? void 0 : parseDestination(value.destination);
287
- if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value.destination !== void 0 && !destination) return;
288
- if (execution.pendingMessages.length > 0 && execution.pendingMessages.some((message) => {
289
- if (!message.destination) return false;
290
- return !destination || !sameDestination(message.destination, destination);
291
- })) return;
292
- return {
293
- schemaVersion: CONVERSATION_SCHEMA_VERSION,
294
- conversationId,
295
- createdAtMs,
296
- lastActivityAtMs,
297
- updatedAtMs,
298
- execution,
299
- ...destination ? { destination } : void 0,
300
- ...toOptionalString(value.title) ? { title: toOptionalString(value.title) } : void 0,
301
- ...toOptionalString(value.channelName) ? { channelName: toOptionalString(value.channelName) } : void 0,
302
- ...normalizeActor(value.actor) ? { actor: normalizeActor(value.actor) } : void 0,
303
- ...normalizeSource(value.source) ? { source: normalizeSource(value.source) } : void 0
304
- };
305
- }
306
- function emptyConversation(args) {
307
- return {
308
- schemaVersion: CONVERSATION_SCHEMA_VERSION,
309
- conversationId: args.conversationId,
310
- createdAtMs: args.nowMs,
311
- lastActivityAtMs: args.nowMs,
312
- updatedAtMs: args.nowMs,
313
- ...args.destination ? { destination: args.destination } : void 0,
314
- ...args.source ? { source: args.source } : void 0,
315
- execution: {
316
- status: "idle",
317
- inboundMessageIds: [],
318
- pendingCount: 0,
319
- pendingMessages: [],
320
- updatedAtMs: args.nowMs
321
- }
322
- };
323
- }
324
- function isLeaseActive(lease, nowMs) {
325
- return Boolean(lease && lease.expiresAtMs > nowMs);
326
- }
327
- function pendingMessages(conversation) {
328
- return [...conversation.execution.pendingMessages].sort(compareMessages);
329
- }
330
- function isRunnableStatus(status) {
331
- return status !== "failed" && status !== "idle";
332
- }
333
- function hasRunnableWork(conversation) {
334
- return isRunnableStatus(conversation.execution.status) || pendingMessages(conversation).length > 0;
335
- }
336
- function executionWithPendingMessages(execution, pending) {
337
- const pendingMessages = [...pending].sort(compareMessages);
338
- const status = execution.status === "idle" && execution.lease ? "running" : execution.status === "idle" && pendingMessages.length > 0 ? "pending" : execution.status;
339
- return {
340
- ...execution,
341
- status,
342
- inboundMessageIds: uniqueStrings([...execution.inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
343
- pendingMessages,
344
- pendingCount: pendingMessages.length
345
- };
346
- }
347
- function withExecutionUpdate(conversation, execution, nowMs) {
348
- return {
349
- ...conversation,
350
- updatedAtMs: nowMs,
351
- execution: {
352
- ...executionWithPendingMessages(execution, execution.pendingMessages),
353
- updatedAtMs: nowMs
354
- }
355
- };
356
- }
357
- async function getConnectedState(stateAdapter) {
358
- const state = stateAdapter ?? getStateAdapter();
359
- await state.connect();
360
- return state;
361
- }
362
- async function sleep(ms) {
363
- await new Promise((resolve) => {
364
- setTimeout(resolve, ms).unref?.();
365
- });
366
- }
367
- async function withIndexLock(state, indexKey, callback) {
368
- const startedAtMs = now$1();
369
- let lock;
370
- while (true) {
371
- lock = await state.acquireLock(indexLockKey(indexKey), CONVERSATION_INDEX_LOCK_TTL_MS);
372
- if (lock) break;
373
- if (now$1() - startedAtMs >= CONVERSATION_INDEX_LOCK_WAIT_MS) throw new Error(`Could not acquire conversation index lock for ${indexKey}`);
374
- await sleep(CONVERSATION_INDEX_LOCK_RETRY_MS);
375
- }
376
- try {
377
- return await callback();
378
- } finally {
379
- await state.releaseLock(lock);
380
- }
381
- }
382
- function normalizeIndexEntry(value) {
383
- if (!isRecord$1(value)) return;
384
- const conversationId = toOptionalString(value.conversationId);
385
- const score = toOptionalNumber(value.score);
386
- if (!conversationId || typeof score !== "number") return;
387
- return {
388
- conversationId,
389
- score
390
- };
391
- }
392
- function uniqueIndexEntries(value) {
393
- if (!Array.isArray(value)) return [];
394
- const entries = /* @__PURE__ */ new Map();
395
- for (const item of value) {
396
- const entry = normalizeIndexEntry(item);
397
- if (!entry) continue;
398
- const existing = entries.get(entry.conversationId);
399
- if (!existing || entry.score > existing.score) entries.set(entry.conversationId, entry);
400
- }
401
- return [...entries.values()];
402
- }
403
- function retainedIndexEntries(indexKey, entries) {
404
- if (indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) return entries.sort(compareIndexDescending).slice(0, CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH);
405
- if (indexKey === CONVERSATION_ACTIVE_INDEX_KEY) return entries.sort(compareIndexAscending);
406
- throw new Error(`Unknown conversation index ${indexKey}`);
407
- }
408
- function redisIndexKey(indexKey) {
409
- const prefix = getChatConfig().state.keyPrefix;
410
- return [...prefix ? [prefix] : [], indexKey].join(":");
411
- }
412
- function parseRedisIndexEntries(values) {
413
- if (!Array.isArray(values)) return [];
414
- const entries = [];
415
- for (let index = 0; index < values.length; index += 2) {
416
- const conversationId = toOptionalString(values[index]);
417
- const score = typeof values[index + 1] === "number" ? values[index + 1] : Number(values[index + 1]);
418
- if (!conversationId || !Number.isFinite(score)) continue;
419
- entries.push({
420
- conversationId,
421
- score
422
- });
423
- }
424
- return entries;
425
- }
426
- function redisConversationIndexStore(client) {
427
- const upsertBoundedActivityScript = `
428
- redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
429
- redis.call("PEXPIRE", KEYS[1], ARGV[3])
430
- local extra = redis.call("ZCARD", KEYS[1]) - tonumber(ARGV[4])
431
- if extra > 0 then
432
- redis.call("ZREMRANGEBYRANK", KEYS[1], 0, extra - 1)
433
- end
434
- return 1
435
- `;
436
- return {
437
- async list(args) {
438
- const key = redisIndexKey(args.indexKey);
439
- const limit = args.limit;
440
- const offset = Math.max(0, args.offset ?? 0);
441
- if (limit === 0) return [];
442
- return parseRedisIndexEntries(args.scoreMax !== void 0 ? await client.sendCommand([
443
- "ZRANGEBYSCORE",
444
- key,
445
- "-inf",
446
- String(args.scoreMax),
447
- "WITHSCORES",
448
- ...limit !== void 0 || offset > 0 ? [
449
- "LIMIT",
450
- String(offset),
451
- String(limit ?? 1e9)
452
- ] : []
453
- ]) : await client.sendCommand([
454
- args.order === "asc" ? "ZRANGE" : "ZREVRANGE",
455
- key,
456
- String(offset),
457
- String(limit === void 0 ? -1 : offset + Math.max(0, limit - 1)),
458
- "WITHSCORES"
459
- ]));
460
- },
461
- async remove(args) {
462
- await client.sendCommand([
463
- "ZREM",
464
- redisIndexKey(args.indexKey),
465
- args.conversationId
466
- ]);
467
- },
468
- async upsert(args) {
469
- const key = redisIndexKey(args.indexKey);
470
- if (args.indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
471
- await client.sendCommand([
472
- "EVAL",
473
- upsertBoundedActivityScript,
474
- "1",
475
- key,
476
- String(args.score),
477
- args.conversationId,
478
- String(JUNIOR_THREAD_STATE_TTL_MS),
479
- String(CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH)
480
- ]);
481
- return;
482
- }
483
- if (args.indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
484
- await client.sendCommand([
485
- "ZADD",
486
- key,
487
- String(args.score),
488
- args.conversationId
489
- ]);
490
- await client.sendCommand([
491
- "PEXPIRE",
492
- key,
493
- String(JUNIOR_THREAD_STATE_TTL_MS)
494
- ]);
495
- return;
496
- }
497
- throw new Error(`Unknown conversation index ${args.indexKey}`);
498
- }
499
- };
500
- }
501
- function emulatedConversationIndexStore(state) {
502
- const readIndex = async (indexKey) => uniqueIndexEntries(await state.get(indexKey));
503
- const writeIndex = async (indexKey, entries) => {
504
- await state.set(indexKey, entries, JUNIOR_THREAD_STATE_TTL_MS);
505
- };
506
- return {
507
- async list(args) {
508
- const entries = (await readIndex(args.indexKey)).filter((entry) => args.scoreMax === void 0 ? true : entry.score <= args.scoreMax).sort(args.order === "asc" ? compareIndexAscending : compareIndexDescending);
509
- const offset = Math.max(0, args.offset ?? 0);
510
- return entries.slice(offset, args.limit === void 0 ? entries.length : offset + args.limit);
511
- },
512
- async remove(args) {
513
- await withIndexLock(state, args.indexKey, async () => {
514
- const entries = await readIndex(args.indexKey);
515
- const next = entries.filter((entry) => entry.conversationId !== args.conversationId);
516
- if (next.length === entries.length) return;
517
- await writeIndex(args.indexKey, next);
518
- });
519
- },
520
- async upsert(args) {
521
- await withIndexLock(state, args.indexKey, async () => {
522
- const withoutCurrent = (await readIndex(args.indexKey)).filter((entry) => entry.conversationId !== args.conversationId);
523
- const next = retainedIndexEntries(args.indexKey, [...withoutCurrent, {
524
- conversationId: args.conversationId,
525
- score: args.score
526
- }]);
527
- await writeIndex(args.indexKey, next);
528
- });
529
- }
530
- };
531
- }
532
- async function getConversationIndexStore(state) {
533
- const redisStateAdapter = await getDefaultRedisStateAdapterFor(state);
534
- if (redisStateAdapter) return redisConversationIndexStore(redisStateAdapter.getClient());
535
- return emulatedConversationIndexStore(state);
536
- }
537
- async function upsertIndexEntry(args) {
538
- await (await getConversationIndexStore(args.state)).upsert({
539
- conversationId: args.conversationId,
540
- indexKey: args.indexKey,
541
- score: args.score
542
- });
543
- }
544
- async function removeIndexEntry(args) {
545
- await (await getConversationIndexStore(args.state)).remove({
546
- conversationId: args.conversationId,
547
- indexKey: args.indexKey
548
- });
549
- }
550
- async function acquireMutationLock(state, conversationId) {
551
- const startedAtMs = now$1();
552
- while (true) {
553
- const lock = await state.acquireLock(mutationLockKey(conversationId), CONVERSATION_MUTATION_LOCK_TTL_MS);
554
- if (lock) return lock;
555
- if (now$1() - startedAtMs >= CONVERSATION_MUTATION_WAIT_MS) throw new Error(`Could not acquire conversation mutation lock for ${conversationId}`);
556
- await sleep(CONVERSATION_MUTATION_RETRY_MS);
557
- }
558
- }
559
- async function withConversationMutation(args, callback) {
560
- const state = await getConnectedState(args.state);
561
- const lock = await acquireMutationLock(state, args.conversationId);
562
- try {
563
- return await callback(state, lock);
564
- } finally {
565
- await state.releaseLock(lock);
566
- }
567
- }
568
- async function readConversation(state, conversationId) {
569
- const raw = await state.get(conversationKey(conversationId));
570
- if (raw == null) return;
571
- const conversation = normalizeConversation(conversationId, raw);
572
- if (!conversation) throw new InvalidConversationRecordError(conversationId);
573
- return conversation;
574
- }
575
- /**
576
- * Persist a conversation and refresh its reporting and active-recovery indexes.
577
- *
578
- * Conversation writes are lock-serialized blind whole-record writes, so the
579
- * mutation lock is re-validated (and extended) immediately before the write:
580
- * a stalled mutator that lost its lock must fail loudly instead of clobbering
581
- * a newer record with a stale copy.
582
- */
583
- async function writeConversation(state, lock, conversation) {
584
- const execution = executionWithPendingMessages(conversation.execution, conversation.execution.pendingMessages);
585
- const next = {
586
- ...conversation,
587
- execution
588
- };
589
- await fenceConversationMutation(state, lock, next.conversationId);
590
- const hasSlackDestination = next.destination?.platform === "slack";
591
- const stored = {
592
- ...next,
593
- execution: {
594
- ...next.execution,
595
- pendingMessages: next.execution.pendingMessages.map((message) => storeMessage(message, hasSlackDestination && (message.source === "slack" || message.source === "event" || message.source === "plugin" || message.source === "scheduler")))
596
- }
597
- };
598
- await state.set(conversationKey(next.conversationId), stored, JUNIOR_THREAD_STATE_TTL_MS);
599
- await upsertIndexEntry({
600
- state,
601
- indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
602
- conversationId: next.conversationId,
603
- score: next.lastActivityAtMs
604
- });
605
- if (!hasRunnableWork(next)) {
606
- await removeIndexEntry({
607
- state,
608
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
609
- conversationId: next.conversationId
610
- });
611
- return;
612
- }
613
- await upsertIndexEntry({
614
- state,
615
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
616
- conversationId: next.conversationId,
617
- score: next.execution.updatedAtMs ?? next.updatedAtMs
618
- });
619
- }
620
- function assertSameOptionalConversationDestination(args) {
621
- if (!args.next || !args.current) return;
622
- if (sameDestination(args.current, args.next)) return;
623
- throw new Error(`Conversation destination changed for ${args.conversationId}`);
624
- }
625
- function conversationWorkState(conversation) {
626
- const lease = conversation.execution.lease;
627
- return {
628
- ...conversation,
629
- lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
630
- ...lease ? { lease: {
631
- acquiredAtMs: lease.acquiredAtMs,
632
- lastCheckInAtMs: lease.lastCheckInAtMs,
633
- leaseExpiresAtMs: lease.expiresAtMs,
634
- leaseToken: lease.token
635
- } } : void 0,
636
- messages: pendingMessages(conversation),
637
- needsRun: hasRunnableWork(conversation)
638
- };
639
- }
640
- /** Return a persisted conversation record, if one exists. */
641
- async function getConversation$1(args) {
642
- return await readConversation(await getConnectedState(args.state), args.conversationId);
643
- }
644
- /** Return a persisted conversation work record, if one exists. */
645
- async function getConversationWorkState$1(args) {
646
- const conversation = await getConversation$1(args);
647
- return conversation ? conversationWorkState(conversation) : void 0;
648
- }
649
- /** Return whether a conversation has pending or resumable execution work. */
650
- function hasRunnableConversationWork$1(conversation) {
651
- return hasRunnableWork(conversation);
652
- }
653
- async function appendInboundMessageWithAdmission(args) {
654
- const nowMs = args.nowMs ?? now$1();
655
- return await withConversationMutation({
656
- conversationId: args.message.conversationId,
657
- state: args.state
658
- }, async (state, lock) => {
659
- const existing = await readConversation(state, args.message.conversationId);
660
- const current = existing ?? emptyConversation({
661
- conversationId: args.message.conversationId,
662
- destination: args.message.destination,
663
- nowMs,
664
- source: args.message.source
665
- });
666
- if (existing) assertSameOptionalConversationDestination({
667
- conversationId: args.message.conversationId,
668
- current: current.destination,
669
- next: args.message.destination
670
- });
671
- const existingPending = current.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId);
672
- if (current.execution.inboundMessageIds.includes(args.message.inboundMessageId)) {
673
- if (!existingPending) return { status: "duplicate" };
674
- const nextStatus = current.execution.status === "idle" ? "pending" : current.execution.status;
675
- await writeConversation(state, lock, withExecutionUpdate(current, {
676
- ...current.execution,
677
- status: nextStatus,
678
- pendingMessages: current.execution.pendingMessages.map((message) => message.inboundMessageId === args.message.inboundMessageId ? upgradedPendingMessage(message, args.message) : message)
679
- }, nowMs));
680
- return { status: "duplicate" };
681
- }
682
- if (args.exclusive && hasRunnableWork(current)) return { status: "active" };
683
- let status;
684
- if (current.execution.lease) status = current.execution.status === "running" ? "running" : "paused";
685
- else if (current.execution.status === "paused" && args.message.delivery === "defer") status = "paused";
686
- else status = "pending";
687
- await writeConversation(state, lock, withExecutionUpdate({
688
- ...current,
689
- destination: current.destination ?? args.message.destination,
690
- source: current.source ?? args.message.source,
691
- lastActivityAtMs: nowMs
692
- }, {
693
- ...current.execution,
694
- status,
695
- inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId],
696
- pendingMessages: [...current.execution.pendingMessages, args.message].sort(compareMessages)
697
- }, nowMs));
698
- return { status: "appended" };
699
- });
700
- }
701
- /** Persist one inbound message idempotently in its conversation mailbox. */
702
- async function appendInboundMessage(args) {
703
- const result = await appendInboundMessageWithAdmission({
704
- ...args,
705
- exclusive: false
706
- });
707
- if (result.status === "active") throw new Error("Non-exclusive mailbox append returned active");
708
- return result;
709
- }
710
- /** Append only when the Conversation has no other runnable work. */
711
- async function appendExclusiveInboundMessage(args) {
712
- return await appendInboundMessageWithAdmission({
713
- ...args,
714
- exclusive: true
715
- });
716
- }
717
- /** Mark a conversation runnable when there is no new mailbox message. */
718
- async function requestConversationWork$1(args) {
719
- const nowMs = args.nowMs ?? now$1();
720
- return await withConversationMutation(args, async (state, lock) => {
721
- const existing = await readConversation(state, args.conversationId);
722
- if (existing) assertSameOptionalConversationDestination({
723
- conversationId: args.conversationId,
724
- current: existing.destination,
725
- next: args.destination
726
- });
727
- const current = existing ?? emptyConversation({
728
- conversationId: args.conversationId,
729
- destination: args.destination,
730
- nowMs
731
- });
732
- const status = current.execution.lease ? "paused" : "pending";
733
- await writeConversation(state, lock, withExecutionUpdate({
734
- ...current,
735
- destination: current.destination ?? args.destination
736
- }, {
737
- ...current.execution,
738
- status
739
- }, nowMs));
740
- return { status: existing === void 0 ? "created" : "updated" };
741
- });
742
- }
743
- /** Record that a wake-up nudge was accepted for the conversation. */
744
- async function markConversationWorkEnqueued$1(args) {
745
- const nowMs = args.nowMs ?? now$1();
746
- await withConversationMutation(args, async (state, lock) => {
747
- const current = await readConversation(state, args.conversationId);
748
- if (!current) return;
749
- await writeConversation(state, lock, withExecutionUpdate(current, {
750
- ...current.execution,
751
- lastEnqueuedAtMs: nowMs
752
- }, nowMs));
753
- });
754
- }
755
- /** Clear a wake marker after its queue delivery finds no runnable work. */
756
- async function clearConsumedConversationWake$1(args) {
757
- const nowMs = args.nowMs ?? now$1();
758
- return await withConversationMutation(args, async (state, lock) => {
759
- const current = await readConversation(state, args.conversationId);
760
- if (!current || hasRunnableWork(current) || current.execution.lastEnqueuedAtMs === void 0) return false;
761
- await writeConversation(state, lock, withExecutionUpdate(current, {
762
- ...current.execution,
763
- lastEnqueuedAtMs: void 0
764
- }, nowMs));
765
- return true;
766
- });
767
- }
768
- /** Try to acquire the durable execution lease for one conversation. */
769
- async function startConversationWork$1(args) {
770
- const nowMs = args.nowMs ?? now$1();
771
- return await withConversationMutation(args, async (state, lock) => {
772
- const current = await readConversation(state, args.conversationId);
773
- if (!current) return { status: "no_work" };
774
- if (isLeaseActive(current.execution.lease, nowMs)) return {
775
- status: "active",
776
- leaseExpiresAtMs: current.execution.lease.expiresAtMs
777
- };
778
- if (!hasRunnableWork(current)) return { status: "no_work" };
779
- const lease = {
780
- token: randomUUID(),
781
- acquiredAtMs: nowMs,
782
- lastCheckInAtMs: nowMs,
783
- expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
784
- };
785
- const startsNewRun = current.execution.runId === void 0;
786
- await writeConversation(state, lock, withExecutionUpdate(current, {
787
- ...current.execution,
788
- lease,
789
- status: current.execution.status === "paused" ? "paused" : "running",
790
- runId: current.execution.runId ?? randomUUID(),
791
- lastEnqueuedAtMs: void 0,
792
- retryCount: startsNewRun ? 0 : current.execution.retryCount
793
- }, nowMs));
794
- return {
795
- status: "acquired",
796
- leaseToken: lease.token,
797
- leaseExpiresAtMs: lease.expiresAtMs
798
- };
799
- });
800
- }
801
- /** Extend the durable execution lease when the worker checks in. */
802
- async function checkInConversationWork$1(args) {
803
- const nowMs = args.nowMs ?? now$1();
804
- return await withConversationMutation(args, async (state, lock) => {
805
- const current = await readConversation(state, args.conversationId);
806
- if (!current || current.execution.lease?.token !== args.leaseToken) return false;
807
- await writeConversation(state, lock, withExecutionUpdate(current, {
808
- ...current.execution,
809
- lease: {
810
- ...current.execution.lease,
811
- lastCheckInAtMs: nowMs,
812
- expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
813
- }
814
- }, nowMs));
815
- return true;
816
- });
817
- }
818
- /**
819
- * Resolve pending mailbox entries after the caller accepts responsibility.
820
- *
821
- * Returning ids acknowledges only that subset; returning nothing acknowledges
822
- * every pending entry passed to the handler.
823
- */
824
- async function drainConversationMailbox$1(args) {
825
- const nowMs = args.nowMs ?? now$1();
826
- const pending = await withConversationMutation(args, async (state) => {
827
- const current = await readConversation(state, args.conversationId);
828
- if (!current || current.execution.lease?.token !== args.leaseToken) throw new Error(`Conversation lease is not held for ${args.conversationId}`);
829
- return pendingMessages(current);
830
- });
831
- if (pending.length === 0) return {
832
- changed: false,
833
- messages: []
834
- };
835
- const result = await args.handle(pending);
836
- const pendingIds = new Set(pending.map((message) => message.inboundMessageId));
837
- const acknowledgedIds = new Set(result ?? pending.map((message) => message.inboundMessageId));
838
- for (const inboundMessageId of acknowledgedIds) if (!pendingIds.has(inboundMessageId)) throw new Error(`Conversation mailbox drain result is not pending for ${args.conversationId}`);
839
- if (acknowledgedIds.size === 0) return {
840
- changed: false,
841
- messages: []
842
- };
843
- await withConversationMutation(args, async (state, lock) => {
844
- const current = await readConversation(state, args.conversationId);
845
- if (!current || current.execution.lease?.token !== args.leaseToken) throw new Error(`Conversation lease is not held for ${args.conversationId}`);
846
- const pendingMessages = current.execution.pendingMessages.filter((message) => !acknowledgedIds.has(message.inboundMessageId));
847
- await writeConversation(state, lock, withExecutionUpdate(current, {
848
- ...current.execution,
849
- status: current.execution.status === "pending" && pendingMessages.length === 0 ? "running" : current.execution.status,
850
- lastProgressAtMs: nowMs,
851
- retryCount: 0,
852
- pendingMessages
853
- }, nowMs));
854
- });
855
- return {
856
- changed: true,
857
- messages: pending.filter((message) => acknowledgedIds.has(message.inboundMessageId))
858
- };
859
- }
860
- /** Acknowledge leased mailbox entries after the handler accepts responsibility. */
861
- async function ackMessages$1(args) {
862
- const nowMs = args.nowMs ?? now$1();
863
- const inboundMessageIds = new Set(args.inboundMessageIds);
864
- return await withConversationMutation(args, async (state, lock) => {
865
- const current = await readConversation(state, args.conversationId);
866
- if (!current || current.execution.lease?.token !== args.leaseToken) return false;
867
- if (inboundMessageIds.size === 0) return true;
868
- const pendingMessages = current.execution.pendingMessages.filter((message) => !inboundMessageIds.has(message.inboundMessageId));
869
- if (pendingMessages.length === current.execution.pendingMessages.length) return true;
870
- await writeConversation(state, lock, withExecutionUpdate(current, {
871
- ...current.execution,
872
- lastProgressAtMs: nowMs,
873
- retryCount: 0,
874
- pendingMessages
875
- }, nowMs));
876
- return true;
877
- });
878
- }
879
- function isHumanFacingMessage(message) {
880
- return message.source === "web" || message.source === "slack";
881
- }
882
- async function readConversationStop(state, conversationId) {
883
- return normalizeStop(await state.get(conversationStopKey(conversationId)));
884
- }
885
- async function fenceConversationMutation(state, lock, conversationId) {
886
- if (!await state.extendLock(lock, CONVERSATION_MUTATION_LOCK_TTL_MS)) throw new ConversationMutationFencedError(conversationId);
887
- }
888
- /** Return whether one Conversation run has a durable stop request. */
889
- async function hasConversationStop(args) {
890
- return (await readConversationStop(await getConnectedState(args.state), args.conversationId))?.runId === args.runId;
891
- }
892
- /** Persist a stop request for the current run without process affinity. */
893
- async function stopConversationWork$1(args) {
894
- const nowMs = args.nowMs ?? now$1();
895
- return await withConversationMutation(args, async (state, lock) => {
896
- const current = await readConversation(state, args.conversationId);
897
- if (!current || !hasRunnableWork(current)) return { status: "no_work" };
898
- const runId = current.execution.runId ?? randomUUID();
899
- const inboundMessageIds = current.execution.pendingMessages.filter(isHumanFacingMessage).map((message) => message.inboundMessageId);
900
- if (current.execution.runId === void 0) await writeConversation(state, lock, withExecutionUpdate(current, {
901
- ...current.execution,
902
- runId
903
- }, nowMs));
904
- await fenceConversationMutation(state, lock, args.conversationId);
905
- await state.set(conversationStopKey(args.conversationId), {
906
- inboundMessageIds,
907
- runId
908
- }, JUNIOR_THREAD_STATE_TTL_MS);
909
- return {
910
- runId,
911
- status: "requested"
912
- };
913
- });
914
- }
915
- /** Clear one observed stop request and discard older human-facing mailbox work. */
916
- async function completeConversationStop$1(args) {
917
- const nowMs = args.nowMs ?? now$1();
918
- return await withConversationMutation(args, async (state, lock) => {
919
- const current = await readConversation(state, args.conversationId);
920
- if (!current || current.execution.lease?.token !== args.leaseToken) return {
921
- status: "lost_lease",
922
- removedInboundMessageIds: []
923
- };
924
- const stop = await readConversationStop(state, args.conversationId);
925
- if (!stop || stop.runId !== args.runId) return {
926
- status: "none",
927
- removedInboundMessageIds: []
928
- };
929
- const stoppedInboundMessageIds = new Set(stop.inboundMessageIds);
930
- const removedInboundMessageIds = [];
931
- const pendingMessages = current.execution.pendingMessages.filter((message) => {
932
- const shouldStop = stoppedInboundMessageIds.has(message.inboundMessageId);
933
- if (shouldStop) removedInboundMessageIds.push(message.inboundMessageId);
934
- return !shouldStop;
935
- });
936
- await writeConversation(state, lock, withExecutionUpdate(current, {
937
- ...current.execution,
938
- lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
939
- pendingMessages
940
- }, nowMs));
941
- await fenceConversationMutation(state, lock, args.conversationId);
942
- await state.delete(conversationStopKey(args.conversationId));
943
- return {
944
- status: "cleared",
945
- removedInboundMessageIds
946
- };
947
- });
948
- }
949
- /** Cancel human-facing pending mailbox rows without requiring a worker lease. */
950
- async function cancelHumanFacingPendingMessages$1(args) {
951
- const nowMs = args.nowMs ?? now$1();
952
- const requestedIds = args.inboundMessageIds === void 0 ? void 0 : new Set(args.inboundMessageIds);
953
- return await withConversationMutation(args, async (state, lock) => {
954
- const current = await readConversation(state, args.conversationId);
955
- if (!current) return { cancelledInboundMessageIds: [] };
956
- const cancelledInboundMessageIds = [];
957
- const pendingMessages = [];
958
- for (const message of current.execution.pendingMessages) {
959
- const isRequested = requestedIds === void 0 || requestedIds.has(message.inboundMessageId);
960
- const isInSnapshot = args.receivedBeforeMs === void 0 || message.receivedAtMs <= args.receivedBeforeMs;
961
- if (isHumanFacingMessage(message) && isRequested && isInSnapshot) {
962
- cancelledInboundMessageIds.push(message.inboundMessageId);
963
- continue;
964
- }
965
- pendingMessages.push(message);
966
- }
967
- if (cancelledInboundMessageIds.length === 0) return { cancelledInboundMessageIds };
968
- const becomesIdle = current.execution.status === "pending" && pendingMessages.length === 0;
969
- await writeConversation(state, lock, withExecutionUpdate(current, {
970
- ...current.execution,
971
- lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
972
- pendingMessages,
973
- retryCount: becomesIdle ? 0 : current.execution.retryCount,
974
- runId: becomesIdle ? void 0 : current.execution.runId,
975
- status: becomesIdle ? "idle" : current.execution.status
976
- }, nowMs));
977
- return { cancelledInboundMessageIds };
978
- });
979
- }
980
- /** Mark the leased conversation as needing another queue-delivered slice. */
981
- async function requestAnotherSlice$1(args) {
982
- const nowMs = args.nowMs ?? now$1();
983
- return await withConversationMutation(args, async (state, lock) => {
984
- const current = await readConversation(state, args.conversationId);
985
- if (!current || current.execution.lease?.token !== args.leaseToken) return false;
986
- assertSameOptionalConversationDestination({
987
- conversationId: args.conversationId,
988
- current: current.destination,
989
- next: args.destination
990
- });
991
- await writeConversation(state, lock, withExecutionUpdate(current, {
992
- ...current.execution,
993
- status: "paused"
994
- }, nowMs));
995
- return true;
996
- });
997
- }
998
- /** Begin a requested turn resume under the worker's existing lease. */
999
- async function beginConversationResume$1(args) {
1000
- const nowMs = args.nowMs ?? now$1();
1001
- return await withConversationMutation(args, async (state, lock) => {
1002
- const current = await readConversation(state, args.conversationId);
1003
- if (!current || current.execution.lease?.token !== args.leaseToken || current.execution.status !== "paused") return false;
1004
- await writeConversation(state, lock, withExecutionUpdate(current, {
1005
- ...current.execution,
1006
- status: "running"
1007
- }, nowMs));
1008
- return true;
1009
- });
1010
- }
1011
- /** Release the durable execution lease without changing completion state. */
1012
- async function releaseConversationWork$1(args) {
1013
- const nowMs = args.nowMs ?? now$1();
1014
- return await withConversationMutation(args, async (state, lock) => {
1015
- const current = await readConversation(state, args.conversationId);
1016
- if (!current || current.execution.lease?.token !== args.leaseToken) return false;
1017
- await writeConversation(state, lock, withExecutionUpdate(current, {
1018
- ...current.execution,
1019
- lease: void 0,
1020
- status: current.execution.status === "running" ? "pending" : current.execution.status
1021
- }, nowMs));
1022
- return true;
1023
- });
1024
- }
1025
- /** Count one failed execution attempt and stop the conversation when retries are exhausted. */
1026
- async function recordConversationRetry$1(args) {
1027
- const nowMs = args.nowMs ?? now$1();
1028
- return await withConversationMutation(args, async (state, lock) => {
1029
- const current = await readConversation(state, args.conversationId);
1030
- if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
1031
- const count = (current.execution.retryCount ?? 0) + 1;
1032
- const stopped = count >= 5;
1033
- await writeConversation(state, lock, withExecutionUpdate(current, {
1034
- ...current.execution,
1035
- lastEnqueuedAtMs: void 0,
1036
- lease: stopped ? void 0 : current.execution.lease,
1037
- retryCount: count,
1038
- pendingMessages: stopped ? [] : current.execution.pendingMessages,
1039
- runId: stopped ? void 0 : current.execution.runId,
1040
- status: stopped ? "failed" : "paused"
1041
- }, nowMs));
1042
- return stopped ? "stopped" : "recorded";
1043
- });
1044
- }
1045
- /** Finish a leased conversation and report whether runnable work remains. */
1046
- async function completeConversationWork$1(args) {
1047
- const nowMs = args.nowMs ?? now$1();
1048
- return await withConversationMutation(args, async (state, lock) => {
1049
- const current = await readConversation(state, args.conversationId);
1050
- if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
1051
- const hasPending = pendingMessages(current).length > 0;
1052
- const stopped = args.resumeIfStopped === true && (await readConversationStop(state, args.conversationId))?.runId === current.execution.runId;
1053
- const needsRun = current.execution.status === "paused" || stopped;
1054
- const runnable = needsRun || hasPending;
1055
- await writeConversation(state, lock, withExecutionUpdate(current, {
1056
- ...current.execution,
1057
- lease: void 0,
1058
- status: needsRun ? "paused" : hasPending ? "pending" : "idle",
1059
- lastProgressAtMs: args.madeProgress === false ? current.execution.lastProgressAtMs : nowMs,
1060
- retryCount: runnable || args.madeProgress === false ? current.execution.retryCount : 0,
1061
- runId: runnable ? current.execution.runId : void 0
1062
- }, nowMs));
1063
- return runnable ? "pending" : "completed";
1064
- });
1065
- }
1066
- /**
1067
- * Record one failed execution attempt for pending messages, dead-lettering
1068
- * the conversation when its retry budget or the legacy message delivery limit
1069
- * is exhausted.
1070
- *
1071
- * Retries are counted only when the run made no durable progress: if any
1072
- * attempted message left the mailbox, the remaining pending entries may be
1073
- * deliberate deferrals and are left untouched. Consumed message ids stay in
1074
- * `inboundMessageIds` so source retries remain duplicates.
1075
- */
1076
- async function recordAttemptFailure$1(args) {
1077
- const nowMs = args.nowMs ?? now$1();
1078
- return await withConversationMutation(args, async (state, lock) => {
1079
- const current = await readConversation(state, args.conversationId);
1080
- if (!current || current.execution.lease?.token !== args.leaseToken) return {
1081
- status: "lost_lease",
1082
- pendingCount: 0,
1083
- deadLetteredMessages: [],
1084
- retryCount: 0
1085
- };
1086
- const pendingIds = new Set(current.execution.pendingMessages.map((message) => message.inboundMessageId));
1087
- if (args.inboundMessageIds.length === 0 || args.inboundMessageIds.some((id) => !pendingIds.has(id))) return {
1088
- status: "skipped",
1089
- pendingCount: current.execution.pendingMessages.length,
1090
- deadLetteredMessages: [],
1091
- retryCount: current.execution.retryCount ?? 0
1092
- };
1093
- const retryCount = (current.execution.retryCount ?? 0) + 1;
1094
- const retriesExhausted = retryCount >= 5;
1095
- const attemptedIds = new Set(args.inboundMessageIds);
1096
- const deadLetteredMessages = [];
1097
- const pendingMessages = [];
1098
- for (const message of current.execution.pendingMessages) {
1099
- if (!attemptedIds.has(message.inboundMessageId)) {
1100
- if (retriesExhausted) deadLetteredMessages.push(message);
1101
- else pendingMessages.push(message);
1102
- continue;
1103
- }
1104
- const attempted = {
1105
- ...message,
1106
- attemptCount: (message.attemptCount ?? 0) + 1
1107
- };
1108
- if (retriesExhausted || attempted.attemptCount >= 5) {
1109
- deadLetteredMessages.push(attempted);
1110
- continue;
1111
- }
1112
- pendingMessages.push(attempted);
1113
- }
1114
- await writeConversation(state, lock, withExecutionUpdate(current, {
1115
- ...current.execution,
1116
- retryCount,
1117
- pendingMessages
1118
- }, nowMs));
1119
- return {
1120
- status: "recorded",
1121
- pendingCount: pendingMessages.length,
1122
- deadLetteredMessages,
1123
- retryCount
1124
- };
1125
- });
1126
- }
1127
- /** Record a terminal failure completion for a leased conversation. */
1128
- async function deadLetterAttempt$1(args) {
1129
- const nowMs = args.nowMs ?? now$1();
1130
- return await withConversationMutation(args, async (state, lock) => {
1131
- const current = await readConversation(state, args.conversationId);
1132
- if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
1133
- const runnable = pendingMessages(current).length > 0;
1134
- await writeConversation(state, lock, withExecutionUpdate(current, {
1135
- ...current.execution,
1136
- lease: void 0,
1137
- status: runnable ? "pending" : "failed",
1138
- runId: runnable ? current.execution.runId : void 0
1139
- }, nowMs));
1140
- return runnable ? "pending" : "failed";
1141
- });
1142
- }
1143
- /** Recover an expired lease, consuming the retry budget under the mutation lock. */
1144
- async function clearExpiredConversationLease$1(args) {
1145
- const nowMs = args.nowMs ?? now$1();
1146
- return await withConversationMutation(args, async (state, lock) => {
1147
- const current = await readConversation(state, args.conversationId);
1148
- if (!current?.execution.lease || current.execution.lease.expiresAtMs > nowMs) return "not_expired";
1149
- const retryCount = (current.execution.retryCount ?? 0) + 1;
1150
- const stopped = retryCount >= 5;
1151
- await writeConversation(state, lock, withExecutionUpdate(current, {
1152
- ...current.execution,
1153
- lastEnqueuedAtMs: void 0,
1154
- lease: void 0,
1155
- retryCount,
1156
- pendingMessages: stopped ? [] : current.execution.pendingMessages,
1157
- runId: stopped ? void 0 : current.execution.runId,
1158
- status: stopped ? "failed" : "paused"
1159
- }, nowMs));
1160
- return stopped ? "stopped" : "requeued";
1161
- });
1162
- }
1163
- /** Remove one conversation from the active index after it is missing or idle. */
1164
- async function removeActiveConversation$1(args) {
1165
- await removeIndexEntry({
1166
- state: await getConnectedState(args.state),
1167
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
1168
- conversationId: args.conversationId
1169
- });
1170
- }
1171
- /** List active conversation ids by oldest execution update first. */
1172
- async function listActiveConversationIds$1(args = {}) {
1173
- return (await (await getConversationIndexStore(await getConnectedState(args.state))).list({
1174
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
1175
- limit: args.limit,
1176
- order: "asc",
1177
- scoreMax: args.staleBeforeMs
1178
- })).map((entry) => entry.conversationId);
1179
- }
1180
- //#endregion
1181
- //#region src/chat/task-execution/store.ts
1182
- function metadataStore(options) {
1183
- return options.conversationStore ?? getConversationStore();
1184
- }
1185
- function duplicateInboundNudgeIdempotencyKey(message, nowMs) {
1186
- return `duplicate:${message.conversationId}:${message.inboundMessageId}:${nowMs}`;
1187
- }
1188
- function hasRecentEnqueueMarker(conversation, nowMs) {
1189
- const lastEnqueuedAtMs = conversation.execution.lastEnqueuedAtMs;
1190
- return typeof lastEnqueuedAtMs === "number" && lastEnqueuedAtMs + 6e4 > nowMs;
1191
- }
1192
- function now() {
1193
- return Date.now();
1194
- }
1195
- async function recordExecutionMetadata(args) {
1196
- const conversation = await getConversation$1({
1197
- conversationId: args.conversationId,
1198
- state: args.state
1199
- });
1200
- if (!conversation) return;
1201
- await metadataStore(args).recordExecution({
1202
- channelName: conversation.channelName,
1203
- conversationId: conversation.conversationId,
1204
- createdAtMs: conversation.createdAtMs,
1205
- destination: conversation.destination,
1206
- execution: {
1207
- lastCheckpointAtMs: conversation.execution.lastCheckpointAtMs,
1208
- lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
1209
- runId: conversation.execution.runId,
1210
- status: conversation.execution.status,
1211
- updatedAtMs: conversation.execution.updatedAtMs
1212
- },
1213
- lastActivityAtMs: conversation.lastActivityAtMs,
1214
- metrics: null,
1215
- actor: conversation.actor,
1216
- source: conversation.source,
1217
- title: conversation.title,
1218
- updatedAtMs: conversation.updatedAtMs
1219
- });
1220
- }
1221
- /** Return a persisted conversation record, if one exists. */
1222
- async function getConversation(args) {
1223
- return await getConversation$1(args);
1224
- }
1225
- /** Return a persisted conversation work record, if one exists. */
1226
- async function getConversationWorkState(args) {
1227
- return await getConversationWorkState$1(args);
1228
- }
1229
- /** Count one failed conversation execution and persist its terminal retry state. */
1230
- async function recordConversationRetry(args) {
1231
- const result = await recordConversationRetry$1(args);
1232
- await recordExecutionMetadata(args);
1233
- return result;
1234
- }
1235
- /** Count mailbox messages that have not yet reached the conversation event log. */
1236
- function countPendingConversationMessages(conversation) {
1237
- return conversation.execution.pendingMessages.length;
1238
- }
1239
- /** Return whether a conversation has pending or resumable execution work. */
1240
- function hasRunnableConversationWork(conversation) {
1241
- return conversation.execution.status !== "idle" || countPendingConversationMessages(conversation) > 0;
1242
- }
1243
- /**
1244
- * Ensure runnable conversation work has one accepted queue wake-up nudge.
1245
- *
1246
- * Ordinary wakes coalesce on a recent accepted marker. A caller can ignore the
1247
- * marker without replacing an active lease. Replacement is only for consumed
1248
- * or known-stale deliveries where another queue nudge must exist.
1249
- */
1250
- async function ensureConversationWake(args) {
1251
- const nowMs = args.nowMs ?? now();
1252
- const conversation = await getConversation$1({
1253
- conversationId: args.conversationId,
1254
- state: args.state
1255
- });
1256
- if (!conversation || !hasRunnableConversationWork(conversation)) return { status: "no_work" };
1257
- if (args.replaceExistingWake !== true && conversation.execution.lease && conversation.execution.lease.expiresAtMs > nowMs) return { status: "lease_active" };
1258
- if (args.ignoreEnqueueMarker !== true && args.replaceExistingWake !== true && hasRecentEnqueueMarker(conversation, nowMs)) return { status: "already_enqueued" };
1259
- const queueResult = await args.queue.send({
1260
- schemaVersion: 2,
1261
- conversationId: args.conversationId
1262
- }, {
1263
- delayMs: args.delayMs,
1264
- idempotencyKey: args.idempotencyKey
1265
- });
1266
- await markConversationWorkEnqueued({
1267
- conversationId: args.conversationId,
1268
- conversationStore: args.conversationStore,
1269
- nowMs,
1270
- state: args.state
1271
- });
1272
- return {
1273
- status: "enqueued",
1274
- queueMessageId: queueResult?.messageId
1275
- };
1276
- }
1277
- async function enqueueAfterAppend(args) {
1278
- const nowMs = args.nowMs ?? now();
1279
- const appendResult = args.appendResult;
1280
- if (appendResult.status === "active") return appendResult;
1281
- let idempotencyKey = args.message.inboundMessageId;
1282
- if (appendResult.status === "duplicate") {
1283
- const conversation = await getConversation$1({
1284
- conversationId: args.message.conversationId,
1285
- state: args.state
1286
- });
1287
- if (!conversation) return appendResult;
1288
- if (hasRecentEnqueueMarker(conversation, nowMs)) {
1289
- await recordExecutionMetadata({
1290
- conversationId: args.message.conversationId,
1291
- conversationStore: args.conversationStore,
1292
- state: args.state
1293
- });
1294
- return appendResult;
1295
- }
1296
- if (!conversation.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId)) {
1297
- await recordExecutionMetadata({
1298
- conversationId: args.message.conversationId,
1299
- conversationStore: args.conversationStore,
1300
- state: args.state
1301
- });
1302
- return appendResult;
1303
- }
1304
- idempotencyKey = duplicateInboundNudgeIdempotencyKey(args.message, nowMs);
1305
- }
1306
- const wake = await ensureConversationWake({
1307
- conversationId: args.message.conversationId,
1308
- conversationStore: args.conversationStore,
1309
- delayMs: args.queueDelayMs,
1310
- idempotencyKey,
1311
- ignoreEnqueueMarker: args.message.source === "event" ? void 0 : true,
1312
- nowMs,
1313
- queue: args.queue,
1314
- replaceExistingWake: args.replaceExistingWake,
1315
- state: args.state
1316
- });
1317
- if (wake.status !== "enqueued") await recordExecutionMetadata({
1318
- conversationId: args.message.conversationId,
1319
- conversationStore: args.conversationStore,
1320
- state: args.state
1321
- });
1322
- return {
1323
- ...appendResult,
1324
- ...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : void 0
1325
- };
1326
- }
1327
- /** Persist inbound work and ensure a worker wake-up. */
1328
- async function appendAndEnqueueInboundMessage(args) {
1329
- const nowMs = args.nowMs ?? now();
1330
- const result = await enqueueAfterAppend({
1331
- ...args,
1332
- appendResult: await appendInboundMessage({
1333
- message: args.message,
1334
- nowMs,
1335
- state: args.state
1336
- }),
1337
- nowMs
1338
- });
1339
- if (result.status === "active") throw new Error("Non-exclusive mailbox enqueue returned active");
1340
- return result;
1341
- }
1342
- /** Persist exclusive inbound work and wake its worker when admitted. */
1343
- async function appendAndEnqueueExclusiveInboundMessage(args) {
1344
- const nowMs = args.nowMs ?? now();
1345
- return await enqueueAfterAppend({
1346
- ...args,
1347
- appendResult: await appendExclusiveInboundMessage({
1348
- message: args.message,
1349
- nowMs,
1350
- state: args.state
1351
- }),
1352
- nowMs
1353
- });
1354
- }
1355
- /** Persist a stop request for the current Conversation run. */
1356
- async function stopConversationWork(args) {
1357
- const result = await stopConversationWork$1(args);
1358
- if (result.status === "requested") await recordExecutionMetadata(args);
1359
- return result;
1360
- }
1361
- /** Finish an observed stop request under the current worker lease. */
1362
- async function completeConversationStop(args) {
1363
- const result = await completeConversationStop$1(args);
1364
- if (result.status === "cleared") await recordExecutionMetadata(args);
1365
- return result;
1366
- }
1367
- /** Clear an accepted wake marker after its delivery finds no runnable work. */
1368
- async function clearConsumedConversationWake(args) {
1369
- const result = await clearConsumedConversationWake$1(args);
1370
- if (result) await recordExecutionMetadata(args);
1371
- return result;
1372
- }
1373
- /** Mark a conversation runnable when there is no new mailbox message. */
1374
- async function requestConversationWork(args) {
1375
- const result = await requestConversationWork$1(args);
1376
- await recordExecutionMetadata({
1377
- conversationId: args.conversationId,
1378
- conversationStore: args.conversationStore,
1379
- state: args.state
1380
- });
1381
- return result;
1382
- }
1383
- /** Record that a wake-up nudge was accepted for the conversation. */
1384
- async function markConversationWorkEnqueued(args) {
1385
- await markConversationWorkEnqueued$1(args);
1386
- await recordExecutionMetadata(args);
1387
- }
1388
- /** Try to acquire the durable execution lease for one conversation. */
1389
- async function startConversationWork(args) {
1390
- const result = await startConversationWork$1(args);
1391
- await recordExecutionMetadata(args);
1392
- return result;
1393
- }
1394
- /** Extend the durable execution lease when the worker checks in. */
1395
- async function checkInConversationWork(args) {
1396
- const result = await checkInConversationWork$1(args);
1397
- if (result) await recordExecutionMetadata(args);
1398
- return result;
1399
- }
1400
- /** Drain pending mailbox entries after the caller accepts responsibility. */
1401
- async function drainConversationMailbox(args) {
1402
- const result = await drainConversationMailbox$1(args);
1403
- if (result.changed) await recordExecutionMetadata(args);
1404
- return result.messages;
1405
- }
1406
- /** Acknowledge leased mailbox entries after the handler accepts responsibility. */
1407
- async function ackMessages(args) {
1408
- const result = await ackMessages$1(args);
1409
- await recordExecutionMetadata(args);
1410
- return result;
1411
- }
1412
- /** Cancel human-facing pending mailbox rows without requiring a worker lease. */
1413
- async function cancelHumanFacingPendingMessages(args) {
1414
- const result = await cancelHumanFacingPendingMessages$1(args);
1415
- if (result.cancelledInboundMessageIds.length > 0) await recordExecutionMetadata(args);
1416
- return result;
1417
- }
1418
- /** Mark the leased conversation as needing another queue-delivered slice. */
1419
- async function requestAnotherSlice(args) {
1420
- const result = await requestAnotherSlice$1(args);
1421
- await recordExecutionMetadata(args);
1422
- return result;
1423
- }
1424
- /** Begin a requested turn resume without releasing the current lease. */
1425
- async function beginConversationResume(args) {
1426
- const result = await beginConversationResume$1(args);
1427
- if (result) await recordExecutionMetadata(args);
1428
- return result;
1429
- }
1430
- /** Release the durable execution lease without changing completion state. */
1431
- async function releaseConversationWork(args) {
1432
- const result = await releaseConversationWork$1(args);
1433
- await recordExecutionMetadata(args);
1434
- return result;
1435
- }
1436
- /** Finish a leased conversation and report whether runnable work remains. */
1437
- async function completeConversationWork(args) {
1438
- const result = await completeConversationWork$1(args);
1439
- await recordExecutionMetadata(args);
1440
- return result;
1441
- }
1442
- /** Record one failed delivery attempt and dead-letter messages at their limit. */
1443
- async function recordAttemptFailure(args) {
1444
- const result = await recordAttemptFailure$1(args);
1445
- if (result.status === "recorded") await recordExecutionMetadata(args);
1446
- return result;
1447
- }
1448
- /** Record a terminal failure completion for a leased conversation. */
1449
- async function deadLetterAttempt(args) {
1450
- const result = await deadLetterAttempt$1(args);
1451
- await recordExecutionMetadata(args);
1452
- return result;
1453
- }
1454
- /** Recover an expired lease and persist the resulting retry state. */
1455
- async function clearExpiredConversationLease(args) {
1456
- const result = await clearExpiredConversationLease$1(args);
1457
- await recordExecutionMetadata(args);
1458
- return result;
1459
- }
1460
- /** Remove one conversation from the active index after it is missing or idle. */
1461
- async function removeActiveConversation(args) {
1462
- return await removeActiveConversation$1(args);
1463
- }
1464
- /** List active conversation ids by oldest execution update first. */
1465
- async function listActiveConversationIds(args = {}) {
1466
- return await listActiveConversationIds$1(args);
1467
- }
1468
- //#endregion
1469
- //#region src/chat/events/catalog.ts
1470
- /** Core-owned event namespace. Not a plugin publisher. */
1471
- const CORE_EVENT_NAMESPACE = "junior";
1472
- /** True when the catalog has any enabled registration. */
1473
- function hasEventCatalogEntries(catalog) {
1474
- return Object.keys(catalog).length > 0;
1475
- }
1476
- /**
1477
- * True when at least one plugin namespace is enabled.
1478
- *
1479
- * Core Workspace snapshot events stay in the catalog for search and temporary
1480
- * watches. Durable event automations still require a plugin publisher.
1481
- */
1482
- function hasPluginEventCatalogEntries(catalog) {
1483
- return Object.keys(pluginEventCatalog(catalog)).length > 0;
1484
- }
1485
- /**
1486
- * Catalog entries that durable event automations may select.
1487
- *
1488
- * Core Workspace snapshot events only wake temporary watches. Snapshot finish
1489
- * does not run event-automation ingest, so those namespaces stay out of create/update
1490
- * schemas and trigger availability.
1491
- */
1492
- function pluginEventCatalog(catalog) {
1493
- return Object.fromEntries(Object.entries(catalog).filter(([namespace]) => namespace !== CORE_EVENT_NAMESPACE));
1494
- }
1495
- function enumSchema(values, unavailableMessage) {
1496
- if (values.length === 0) return z.string().refine(() => false, unavailableMessage);
1497
- return z.enum(values);
1498
- }
1499
- /** Build the model-facing namespace enum from enabled event plugins. */
1500
- function eventNamespaceSchema(catalog) {
1501
- return enumSchema(Object.keys(catalog).sort(), "No event namespaces are enabled.");
1502
- }
1503
- /** Build the model-facing event enum from enabled plugin registrations. */
1504
- function registeredEventTypeSchema(catalog) {
1505
- return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.flatMap((resourceType) => resourceType.supportedEvents)))].sort(), "No event types are enabled.");
1506
- }
1507
- /** Build the model-facing resource type enum from enabled plugin registrations. */
1508
- function registeredResourceTypeSchema(catalog) {
1509
- return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.map((resourceType) => resourceType.type)))].sort(), "No resource types are enabled.");
1510
- }
1511
- /** Return whether one enabled plugin declared an event type. */
1512
- function pluginSupportsEvent(catalog, namespace, resourceType, eventType) {
1513
- return catalog[namespace]?.resourceTypes.find((candidate) => candidate.type === resourceType)?.supportedEvents.includes(eventType) ?? false;
1514
- }
1515
- /** Return app guidance for one registered resource type and event type. */
1516
- function eventGuidance(catalog, namespace, resourceType, eventType) {
1517
- return catalog[namespace]?.resourceTypes.find((candidate) => candidate.type === resourceType)?.guidance?.[eventType];
1518
- }
1519
- /** Return declared match keys for one registered resource type. */
1520
- function eventMatchFields(catalog, namespace, resourceType) {
1521
- return catalog[namespace]?.resourceTypes.find((candidate) => candidate.type === resourceType)?.matchFields;
1522
- }
1523
- /** Build the match object the tools accept for one resource type. */
1524
- function registeredEventMatchSchema() {
1525
- return eventMatchSchema.optional().describe("Optional exact values from the resource type matchFields. A single value must equal the event data. A list means the event value may be any one entry. Omit a key to ignore it. Unmatched events are dropped with no agent turn.");
1526
- }
1527
- /** Reject match keys the resource type does not list. */
1528
- function requireSupportedEventMatch(catalog, input) {
1529
- const match = input.match;
1530
- if (!match || Object.keys(match).length === 0) return void 0;
1531
- const fields = eventMatchFields(catalog, input.namespace, input.resourceType);
1532
- if (!fields || Object.keys(fields).length === 0) throw new ToolInputError(`Resource type "${input.namespace}:${input.resourceType}" does not support match.`);
1533
- const normalized = {};
1534
- for (const [key, value] of Object.entries(match)) {
1535
- const field = fields[key];
1536
- if (!field) throw new ToolInputError(`Resource type "${input.namespace}:${input.resourceType}" does not support match key "${key}".`);
1537
- if (Array.isArray(value)) {
1538
- if (field.kind === "boolean") throw new ToolInputError(`Match key "${key}" is boolean and cannot use a list.`);
1539
- for (const entry of value) {
1540
- if (typeof entry !== field.kind) throw new ToolInputError(`Match key "${key}" expects ${field.kind} values.`);
1541
- if (field.enum && typeof entry === "string" && !field.enum.includes(entry)) throw new ToolInputError(`Match key "${key}" does not allow value "${entry}".`);
1542
- }
1543
- normalized[key] = [...new Set(value)];
1544
- continue;
1545
- }
1546
- if (typeof value !== field.kind) throw new ToolInputError(`Match key "${key}" expects a ${field.kind} value.`);
1547
- if (field.enum && typeof value === "string" && !field.enum.includes(value)) throw new ToolInputError(`Match key "${key}" does not allow value "${value}".`);
1548
- normalized[key] = value;
1549
- }
1550
- return Object.keys(normalized).length > 0 ? normalized : void 0;
1551
- }
1552
- /** Normalize one selector with the convention declared by its plugin. */
1553
- function normalizeCatalogEventIdentifier(catalog, namespace, identifier) {
1554
- return normalizeEventIdentifier(catalog[namespace], identifier);
1555
- }
1556
- //#endregion
1557
- //#region src/chat/sandbox/snapshot/events.ts
1558
- const WORKSPACE_SNAPSHOT_NAMESPACE = CORE_EVENT_NAMESPACE;
1559
- const WORKSPACE_SNAPSHOT_RESOURCE_TYPE = "workspace_snapshot";
1560
- const WORKSPACE_SNAPSHOT_READY_EVENT = "workspace_snapshot.ready";
1561
- const WORKSPACE_SNAPSHOT_FAILED_EVENT = "workspace_snapshot.failed";
1562
- /**
1563
- * Core catalog entry for Workspace snapshot ready and failed events.
1564
- *
1565
- * Uses the same registration shape as plugins so search, guidance, and tool
1566
- * schemas treat these events like any other resource type.
1567
- */
1568
- function workspaceSnapshotEvents() {
1569
- return { resourceTypes: [{
1570
- type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE,
1571
- supportedEvents: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
1572
- suggestedEvents: [],
1573
- guidance: {
1574
- [WORKSPACE_SNAPSHOT_READY_EVENT]: "Call switchWorkspace again with the same Workspace name. Do not create another watch when switchWorkspace already returned a subscription.",
1575
- [WORKSPACE_SNAPSHOT_FAILED_EVENT]: "Report the snapshot failure. Do not keep waiting for this Workspace unless the user asks to retry."
1576
- }
1577
- }] };
1578
- }
1579
- /** Describe the events that report when a snapshot build ends. */
1580
- function workspaceSnapshotWatch(input) {
1581
- return {
1582
- identifier: input.workspaceId,
1583
- label: `Workspace ${input.workspaceName} snapshot`,
1584
- namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
1585
- supportedEvents: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
1586
- suggestedEvents: [],
1587
- type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE
1588
- };
1589
- }
1590
- /** Report that a Workspace snapshot build is ready or failed. */
1591
- function workspaceSnapshotFinishedEvent(input) {
1592
- const occurredAtMs = input.occurredAtMs ?? Date.now();
1593
- const eventType = input.status === "ready" ? WORKSPACE_SNAPSHOT_READY_EVENT : WORKSPACE_SNAPSHOT_FAILED_EVENT;
1594
- const trustedSummary = input.status === "ready" ? "Workspace snapshot is ready." : "Workspace snapshot build failed.";
1595
- const event = {
1596
- eventKey: `${WORKSPACE_SNAPSHOT_NAMESPACE}:${input.workspaceId}:${input.resultId}:${input.status}`,
1597
- eventType,
1598
- identifier: input.workspaceId,
1599
- namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
1600
- occurredAtMs,
1601
- terminal: true,
1602
- trustedSummary,
1603
- data: {
1604
- workspaceId: input.workspaceId,
1605
- status: input.status
1606
- }
1607
- };
1608
- if (input.status === "failed" && input.error) event.untrustedText = input.error;
1609
- return event;
1610
- }
1611
- //#endregion
1612
- //#region src/chat/events/runtime-catalog.ts
1613
- /**
1614
- * Enabled event registrations for search, guidance, and tool schemas.
1615
- *
1616
- * Includes core Workspace snapshot events under the `junior` namespace, plus
1617
- * every enabled plugin registration. Plugins may not use the `junior` namespace.
1618
- */
1619
- function getEventCatalog() {
1620
- const catalog = { [CORE_EVENT_NAMESPACE]: workspaceSnapshotEvents() };
1621
- for (const plugin of getPlugins()) {
1622
- const registration = plugin.events;
1623
- if (!registration || registration.isEnabled?.() === false) continue;
1624
- if (plugin.manifest.name === "junior") throw new Error(`Plugin "${CORE_EVENT_NAMESPACE}" cannot register events; that namespace is reserved for core Workspace snapshots`);
1625
- catalog[plugin.manifest.name] = registration;
1626
- }
1627
- return catalog;
1628
- }
1629
- /** Validate the persisted Slack creator identity for an event automation. */
1630
- const eventAutomationPrincipalSchema = z.object({
1631
- slackUserId: actorUserIdSchema,
1632
- fullName: z.string().optional(),
1633
- userName: z.string().optional()
1634
- }).strict();
1635
- /** Validate one persisted event-automation selector and its presentation metadata. */
1636
- const eventAutomationTriggerSchema = z.object({
1637
- events: z.array(eventTypeSchema).min(1),
1638
- label: z.string().min(1),
1639
- match: eventMatchSchema.optional(),
1640
- namespace: z.string().min(1),
1641
- identifier: z.string().min(1).max(300),
1642
- resourceType: z.string().min(1)
1643
- }).strict();
1644
- /** Event automations target a Slack channel or DM, never a message thread. */
1645
- const eventAutomationDestinationSchema = slackDestinationSchema.omit({ threadTs: true });
1646
- const eventAutomationOutcomeSchema = taskOutcomeSchema.extend({ destination: eventAutomationDestinationSchema });
1647
- /** Validate one persisted event automation. */
1648
- const eventAutomationSchema = z.object({
1649
- id: z.string().min(1),
1650
- createdAtMs: z.number().finite(),
1651
- createdBy: eventAutomationPrincipalSchema,
1652
- credentialMode: z.enum(["system", "creator"]),
1653
- destination: eventAutomationDestinationSchema,
1654
- destinationVisibility: destinationVisibilitySchema,
1655
- /** Explicit visible effects after successful work. An empty list is silent. */
1656
- outcomes: z.array(eventAutomationOutcomeSchema).max(5),
1657
- task: z.object({ text: z.string().min(1) }).strict(),
1658
- trigger: eventAutomationTriggerSchema
1659
- }).strict();
1660
- //#endregion
1661
- //#region src/chat/event-automations/store.ts
1662
- const retainedEventAutomationSchema = eventAutomationSchema.extend({
1663
- destination: slackDestinationSchema,
1664
- outcomes: z.array(taskOutcomeSchema).max(5)
1665
- });
1666
- /** JSON task payload must not carry SQL-backed columns. */
1667
- function eventAutomationJsonPayload(task) {
1668
- const { status: _status, title: _title, ...payload } = task;
1669
- return payload;
1670
- }
1671
- function parseTask(row) {
1672
- const raw = row.task && typeof row.task === "object" ? { ...row.task } : row.task;
1673
- if (raw && typeof raw === "object" && "title" in raw) delete raw.title;
1674
- if (raw && typeof raw === "object" && !("outcomes" in raw) && "destination" in raw) raw.outcomes = [{
1675
- action: "send_message",
1676
- destination: raw.destination
1677
- }];
1678
- const retained = retainedEventAutomationSchema.parse(raw);
1679
- const { threadTs: _threadTs, ...destination } = retained.destination;
1680
- const title = row.title?.trim();
1681
- return {
1682
- ...retained,
1683
- destination,
1684
- outcomes: retained.outcomes.map((outcome) => {
1685
- const { threadTs: _threadTs, ...destination } = outcome.destination;
1686
- return {
1687
- ...outcome,
1688
- destination
1689
- };
1690
- }),
1691
- status: row.status === "deleted" ? "deleted" : "active",
1692
- ...title ? { title } : void 0
1693
- };
1694
- }
1695
- function activeEventAutomationWhere() {
1696
- return ne(juniorEventAutomations.status, "deleted");
1697
- }
1698
- /** Read one event automation by id, including deleted rows when present. */
1699
- async function getEventAutomation(db, id) {
1700
- const rows = await db.select({
1701
- status: juniorEventAutomations.status,
1702
- task: juniorEventAutomations.task,
1703
- title: juniorEventAutomations.title
1704
- }).from(juniorEventAutomations).where(eq(juniorEventAutomations.id, id)).limit(1);
1705
- return rows[0] ? parseTask(rows[0]) : void 0;
1706
- }
1707
- /** Create one retry-stable event automation, or revive a deleted row with the new payload. */
1708
- async function createEventAutomation(db, task) {
1709
- const parsed = eventAutomationSchema.parse(eventAutomationJsonPayload(task));
1710
- const title = task.title?.trim() || null;
1711
- await db.insert(juniorEventAutomations).values({
1712
- id: parsed.id,
1713
- teamId: parsed.destination.teamId,
1714
- namespace: parsed.trigger.namespace,
1715
- identifier: parsed.trigger.identifier,
1716
- createdAtMs: parsed.createdAtMs,
1717
- status: "active",
1718
- title,
1719
- task: parsed
1720
- }).onConflictDoNothing();
1721
- const existing = await getEventAutomation(db, parsed.id);
1722
- if (!existing) return {
1723
- ...parsed,
1724
- status: "active",
1725
- ...title ? { title } : void 0
1726
- };
1727
- if (existing.status !== "deleted") return existing;
1728
- const rows = await db.update(juniorEventAutomations).set({
1729
- teamId: parsed.destination.teamId,
1730
- namespace: parsed.trigger.namespace,
1731
- identifier: parsed.trigger.identifier,
1732
- status: "active",
1733
- title,
1734
- task: parsed
1735
- }).where(and(eq(juniorEventAutomations.id, parsed.id), eq(juniorEventAutomations.status, "deleted"))).returning({
1736
- status: juniorEventAutomations.status,
1737
- task: juniorEventAutomations.task,
1738
- title: juniorEventAutomations.title
1739
- });
1740
- return rows[0] ? parseTask(rows[0]) : await getEventAutomation(db, parsed.id) ?? {
1741
- ...parsed,
1742
- status: "active",
1743
- ...title ? { title } : void 0
1744
- };
1745
- }
1746
- /** Replace an existing non-deleted event automation. */
1747
- async function saveEventAutomation(db, task) {
1748
- const parsed = eventAutomationSchema.parse(eventAutomationJsonPayload(task));
1749
- const title = task.title?.trim() || null;
1750
- const rows = await db.update(juniorEventAutomations).set({
1751
- namespace: parsed.trigger.namespace,
1752
- identifier: parsed.trigger.identifier,
1753
- title,
1754
- task: parsed
1755
- }).where(and(eq(juniorEventAutomations.id, parsed.id), activeEventAutomationWhere())).returning({
1756
- status: juniorEventAutomations.status,
1757
- task: juniorEventAutomations.task,
1758
- title: juniorEventAutomations.title
1759
- });
1760
- return rows[0] ? parseTask(rows[0]) : void 0;
1761
- }
1762
- /** Mark one existing event automation deleted while retaining the row for history. */
1763
- async function deleteEventAutomation(db, id) {
1764
- const rows = await db.update(juniorEventAutomations).set({ status: "deleted" }).where(and(eq(juniorEventAutomations.id, id), activeEventAutomationWhere())).returning({
1765
- status: juniorEventAutomations.status,
1766
- task: juniorEventAutomations.task,
1767
- title: juniorEventAutomations.title
1768
- });
1769
- return rows[0] ? parseTask(rows[0]) : void 0;
1770
- }
1771
- /** List live event automations in one Slack workspace. */
1772
- async function listEventAutomationsForTeam(db, teamId) {
1773
- return (await db.select({
1774
- status: juniorEventAutomations.status,
1775
- task: juniorEventAutomations.task,
1776
- title: juniorEventAutomations.title
1777
- }).from(juniorEventAutomations).where(and(eq(juniorEventAutomations.teamId, teamId), activeEventAutomationWhere())).orderBy(asc(juniorEventAutomations.createdAtMs), asc(juniorEventAutomations.id))).map(parseTask);
1778
- }
1779
- function viewerSlackIdentities(user) {
1780
- return user.identities.filter((identity) => identity.provider === "slack" && Boolean(identity.providerTenantId) && Boolean(identity.providerSubjectId));
1781
- }
1782
- /** Return whether one event automation was created by a viewer-linked Slack identity. */
1783
- function eventAutomationBelongsToUser(task, user) {
1784
- return viewerSlackIdentities(user).some((identity) => identity.providerTenantId === task.destination.teamId && identity.providerSubjectId === task.createdBy.slackUserId);
1785
- }
1786
- /** List a bounded newest-first page of live event automations created by one user. */
1787
- async function listEventAutomationsCreatedBy(db, user, limit, query) {
1788
- const identities = viewerSlackIdentities(user);
1789
- const ownership = or(...identities.map((identity) => and(eq(juniorEventAutomations.teamId, identity.providerTenantId), sql`${juniorEventAutomations.task}->'createdBy'->>'slackUserId' = ${identity.providerSubjectId}`)));
1790
- if (!ownership) return [];
1791
- return (await db.select({
1792
- status: juniorEventAutomations.status,
1793
- task: juniorEventAutomations.task,
1794
- title: juniorEventAutomations.title
1795
- }).from(juniorEventAutomations).where(and(ownership, activeEventAutomationWhere(), query ? sql`strpos(lower(coalesce(${juniorEventAutomations.title}, ${juniorEventAutomations.task}->'task'->>'text')), ${query}) > 0` : void 0)).orderBy(desc(juniorEventAutomations.createdAtMs), desc(juniorEventAutomations.id)).limit(limit)).map(parseTask);
1796
- }
1797
- /**
1798
- * List deleted event automations created by one user, newest first.
1799
- * Used only to keep historical runs after the live automation list drops the row.
1800
- */
1801
- async function listDeletedEventAutomationsCreatedBy(db, user, limit) {
1802
- const identities = viewerSlackIdentities(user);
1803
- const ownership = or(...identities.map((identity) => and(eq(juniorEventAutomations.teamId, identity.providerTenantId), sql`${juniorEventAutomations.task}->'createdBy'->>'slackUserId' = ${identity.providerSubjectId}`)));
1804
- if (!ownership) return [];
1805
- return (await db.select({
1806
- status: juniorEventAutomations.status,
1807
- task: juniorEventAutomations.task,
1808
- title: juniorEventAutomations.title
1809
- }).from(juniorEventAutomations).where(and(ownership, eq(juniorEventAutomations.status, "deleted"))).orderBy(desc(juniorEventAutomations.createdAtMs), desc(juniorEventAutomations.id)).limit(limit)).map(parseTask);
1810
- }
1811
- /** List live event automations whose current Slack destination is public. */
1812
- async function listPublicEventAutomationsForTeams(db, teamIds, limit, query) {
1813
- if (teamIds.length === 0) return [];
1814
- return (await db.select({
1815
- status: juniorEventAutomations.status,
1816
- task: juniorEventAutomations.task,
1817
- title: juniorEventAutomations.title
1818
- }).from(juniorEventAutomations).innerJoin(juniorDestinations, and(eq(juniorDestinations.provider, "slack"), eq(juniorDestinations.providerTenantId, juniorEventAutomations.teamId), sql`${juniorDestinations.providerDestinationId} = ${juniorEventAutomations.task}->'destination'->>'channelId'`)).where(and(inArray(juniorEventAutomations.teamId, teamIds), activeEventAutomationWhere(), query ? sql`strpos(lower(coalesce(${juniorEventAutomations.title}, ${juniorEventAutomations.task}->'task'->>'text')), ${query}) > 0` : void 0, eq(juniorDestinations.visibility, "public"))).orderBy(desc(juniorEventAutomations.createdAtMs), desc(juniorEventAutomations.id)).limit(limit)).map(parseTask);
1819
- }
1820
- /**
1821
- * Collect match keys from live event automations for these identifiers and event types.
1822
- * Does not evaluate match values — only reports keys that filters use.
1823
- */
1824
- async function collectEventAutomationMatchKeys(db, input) {
1825
- const eventTypes = new Set(input.eventTypes.map((eventType) => eventType.trim()).filter(Boolean));
1826
- const identifiers = [...new Set(input.identifiers.map((value) => value.trim()).filter(Boolean))];
1827
- if (eventTypes.size === 0 || identifiers.length === 0) return [];
1828
- const rows = await db.select({
1829
- status: juniorEventAutomations.status,
1830
- task: juniorEventAutomations.task,
1831
- title: juniorEventAutomations.title
1832
- }).from(juniorEventAutomations).where(and(eq(juniorEventAutomations.teamId, input.teamId), eq(juniorEventAutomations.namespace, input.namespace), inArray(juniorEventAutomations.identifier, identifiers), activeEventAutomationWhere())).orderBy(asc(juniorEventAutomations.createdAtMs), asc(juniorEventAutomations.id));
1833
- const keys = /* @__PURE__ */ new Set();
1834
- for (const row of rows) {
1835
- const task = parseTask(row);
1836
- if (!task.trigger.events.some((eventType) => eventTypes.has(eventType))) continue;
1837
- for (const key of Object.keys(task.trigger.match ?? {})) keys.add(key);
1838
- }
1839
- return [...keys].sort();
1840
- }
1841
- /** Find every live task matching one normalized event. */
1842
- async function findMatchingEventAutomations(db, event, teamId) {
1843
- return (await db.select({
1844
- status: juniorEventAutomations.status,
1845
- task: juniorEventAutomations.task,
1846
- title: juniorEventAutomations.title
1847
- }).from(juniorEventAutomations).where(and(eq(juniorEventAutomations.teamId, teamId), eq(juniorEventAutomations.namespace, event.namespace), eq(juniorEventAutomations.identifier, event.identifier), activeEventAutomationWhere())).orderBy(asc(juniorEventAutomations.createdAtMs), asc(juniorEventAutomations.id))).map(parseTask).filter((task) => task.trigger.events.includes(event.eventType) && eventMatches(task.trigger.match, event.data));
1848
- }
1849
- //#endregion
1850
- //#region src/chat/task-outcomes.ts
1851
- const taskMessageDestinationInputSchema = z.enum(["current_conversation", "task_creator"]).describe("Where to send the message. Use current_conversation for posts, digests, summaries, and channel reminders. Use task_creator only when the user asks for a direct reminder or notification.");
1852
- /** Input accepted by task authoring tools before a user becomes a DM Destination. */
1853
- const taskOutcomeInputSchema = z.object({
1854
- action: z.literal("send_message"),
1855
- destination: taskMessageDestinationInputSchema
1856
- }).strict();
1857
- /** Resolve explicit message outcomes to the Slack Destinations stored on an Automation. */
1858
- async function resolveTaskOutcomes(outcomes, currentDestination, creatorSlackUserId) {
1859
- if (outcomes === void 0) return [];
1860
- const resolved = [];
1861
- for (const outcome of outcomes) {
1862
- if (outcome.destination === "current_conversation") {
1863
- resolved.push({
1864
- action: "send_message",
1865
- destination: currentDestination
1866
- });
1867
- continue;
1868
- }
1869
- const userId = creatorSlackUserId;
1870
- const channelId = (await withSlackRetries(() => getSlackClient().conversations.open({ users: userId }), 3, { action: "conversations.open" })).channel?.id;
1871
- if (!channelId) throw new Error("Slack did not return a direct message destination.");
1872
- resolved.push({
1873
- action: "send_message",
1874
- destination: {
1875
- platform: "slack",
1876
- teamId: currentDestination.teamId,
1877
- channelId
1878
- }
1879
- });
1880
- }
1881
- return resolved;
1882
- }
1883
- function outcomeTargetsDestination(outcome, destination) {
1884
- return outcome.destination.teamId === destination.teamId && outcome.destination.channelId === destination.channelId && (!outcome.destination.threadTs || outcome.destination.threadTs === destination.threadTs);
1885
- }
1886
- /** Bind same-channel message outcomes to the Automation Destination. */
1887
- function effectiveTaskOutcomes(outcomes, destination) {
1888
- return outcomes.map((outcome) => destination.threadTs && outcomeTargetsDestination(outcome, destination) ? {
1889
- ...outcome,
1890
- destination
1891
- } : outcome);
1892
- }
1893
- /** Move outcomes that target the task Destination and keep other outcomes unchanged. */
1894
- function moveTaskOutcomes(outcomes, currentDestination, nextDestination) {
1895
- return effectiveTaskOutcomes(outcomes, currentDestination).map((outcome) => outcomeTargetsDestination(outcome, currentDestination) ? {
1896
- ...outcome,
1897
- destination: nextDestination
1898
- } : outcome);
1899
- }
1900
- //#endregion
1901
- //#region src/chat/event-automations/tool-support.ts
1902
- const compactEventAutomationResultSchema = z.object({
1903
- id: z.string().min(1),
1904
- title: z.string().min(1).nullable(),
1905
- dashboardUrl: z.string().url().nullable(),
1906
- instruction: z.string().min(1),
1907
- trigger: z.object({
1908
- namespace: z.string().min(1),
1909
- identifier: z.string().min(1),
1910
- resourceType: z.string().min(1),
1911
- label: z.string().min(1),
1912
- events: z.array(z.string().min(1)).min(1),
1913
- match: z.record(z.string(), z.unknown()).optional(),
1914
- available: z.boolean()
1915
- }).strict(),
1916
- credentialMode: z.enum(["system", "creator"]),
1917
- isCreator: z.boolean(),
1918
- outcomes: z.array(z.object({
1919
- action: z.literal("send_message"),
1920
- destination: z.object({
1921
- channel: z.string().min(1),
1922
- thread: z.string().min(1).nullable()
1923
- }).strict()
1924
- }).strict()).max(5),
1925
- createdBy: z.object({
1926
- name: z.string().min(1).nullable(),
1927
- username: z.string().min(1).nullable()
1928
- }).strict()
1929
- }).strict();
1930
- /** Validate one successful event-automation mutation result. */
1931
- const eventAutomationToolResultSchema = juniorToolOutputSchema.extend({
1932
- automation: compactEventAutomationResultSchema,
1933
- objectCards: z.array(ownedObjectAnnotationSchema)
1934
- }).strict();
1935
- /** Validate one successful event-automation list result. */
1936
- const eventAutomationListToolResultSchema = juniorToolOutputSchema.extend({
1937
- automations: z.array(compactEventAutomationResultSchema),
1938
- truncated: z.boolean()
1939
- }).strict();
1940
- /** Build the validated event trigger accepted by event-automation tools. */
1941
- function registeredEventAutomationTriggerSchema(catalog) {
1942
- const plugins = pluginEventCatalog(catalog);
1943
- return z.object({
1944
- namespace: eventNamespaceSchema(plugins),
1945
- identifier: z.string().trim().min(1).max(300),
1946
- resourceType: registeredResourceTypeSchema(plugins),
1947
- label: z.string().trim().min(1).max(500),
1948
- events: z.array(registeredEventTypeSchema(plugins)).min(1),
1949
- match: registeredEventMatchSchema()
1950
- }).strict();
1951
- }
1952
- /** Reject an event-automation trigger that is no longer supported by the catalog. */
1953
- function requireSupportedEventAutomationTrigger(catalog, trigger) {
1954
- const plugins = pluginEventCatalog(catalog);
1955
- for (const eventType of trigger.events) if (!pluginSupportsEvent(plugins, trigger.namespace, trigger.resourceType, eventType)) throw new ToolInputError(`Resource type "${trigger.namespace}:${trigger.resourceType}" does not support event "${eventType}".`);
1956
- return requireSupportedEventMatch(plugins, {
1957
- match: trigger.match,
1958
- namespace: trigger.namespace,
1959
- resourceType: trigger.resourceType
1960
- });
1961
- }
1962
- /** Require the active Slack authority used for event-automation management. */
1963
- function requireEventAutomationSlackContext(context) {
1964
- if (context.source.kind !== "slack" || context.destination.platform !== "slack" || context.actor?.platform !== "slack" || context.actor.teamId !== context.source.teamId) throw new ToolInputError("Event automations require an active Slack channel or DM and actor.");
1965
- return {
1966
- actor: context.actor,
1967
- destination: {
1968
- platform: "slack",
1969
- teamId: context.source.teamId,
1970
- channelId: context.source.channelId
1971
- },
1972
- source: context.source
1973
- };
1974
- }
1975
- /** Return whether an event automation belongs to the active Slack destination. */
1976
- function eventAutomationMatchesDestination(task, destination) {
1977
- return task.destination.teamId === destination.teamId && task.destination.channelId === destination.channelId;
1978
- }
1979
- /**
1980
- * Return whether the active destination may update or delete this automation.
1981
- * Same-destination automations stay local. Public automations may be managed by id from
1982
- * another destination in the same workspace.
1983
- */
1984
- function eventAutomationIsWritableFrom(task, destination) {
1985
- if (task.destination.teamId !== destination.teamId) return false;
1986
- return task.destination.channelId === destination.channelId || task.destinationVisibility === "public";
1987
- }
1988
- /** Load one automation the active destination may update or delete. */
1989
- async function writableEventAutomation(context, id) {
1990
- const { destination } = requireEventAutomationSlackContext(context);
1991
- const task = await getEventAutomation(getDb(), id);
1992
- if (!task || task.status === "deleted" || !eventAutomationIsWritableFrom(task, destination)) throw new ToolInputError("Event automation was not found.");
1993
- return task;
1994
- }
1995
- function eventAutomationTriggerAvailable(task, catalog) {
1996
- const registration = pluginEventCatalog(catalog)[task.trigger.namespace];
1997
- return Boolean(registration && task.trigger.events.every((eventType) => registration.resourceTypes.some((resourceType) => resourceType.supportedEvents.includes(eventType))));
1998
- }
1999
- /** Project an event automation into the bounded tool-result shape. */
2000
- function compactEventAutomation(task, catalog, requesterSlackUserId) {
2001
- return compactEventAutomationResultSchema.parse({
2002
- id: task.id,
2003
- title: task.title?.trim() || null,
2004
- dashboardUrl: getDashboardTaskLink(task.id) ?? null,
2005
- instruction: task.task.text,
2006
- trigger: {
2007
- namespace: task.trigger.namespace,
2008
- identifier: task.trigger.identifier,
2009
- resourceType: task.trigger.resourceType,
2010
- label: task.trigger.label,
2011
- events: task.trigger.events,
2012
- ...task.trigger.match ? { match: task.trigger.match } : void 0,
2013
- available: eventAutomationTriggerAvailable(task, catalog)
2014
- },
2015
- credentialMode: task.credentialMode,
2016
- isCreator: task.createdBy.slackUserId === requesterSlackUserId,
2017
- outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
2018
- action: outcome.action,
2019
- destination: {
2020
- channel: outcome.destination.channelId,
2021
- thread: outcome.destination.threadTs ?? null
2022
- }
2023
- })),
2024
- createdBy: {
2025
- name: task.createdBy.fullName ?? null,
2026
- username: task.createdBy.userName ?? null
2027
- }
2028
- });
2029
- }
2030
- /** Return the standard successful event-automation tool result. */
2031
- async function eventAutomationToolResult(conversationId, task, catalog, requesterSlackUserId) {
2032
- const automation = compactEventAutomation(task, catalog, requesterSlackUserId);
2033
- const filters = Object.entries(task.trigger.match ?? {}).map(([key, value]) => `${key} = ${JSON.stringify(value)}`);
2034
- const title = automation.title ?? fallbackShortTitle(task.task.text, "Event automation");
2035
- return {
2036
- automation,
2037
- objectCards: await saveObjectAnnotations(conversationId, "junior", [{
2038
- kind: "object",
2039
- objectType: "automation",
2040
- label: title,
2041
- key: task.id,
2042
- title,
2043
- url: automation.dashboardUrl,
2044
- description: task.task.text,
2045
- trigger: [
2046
- task.trigger.label,
2047
- task.trigger.events.join(", "),
2048
- ...filters
2049
- ].join(" · "),
2050
- warning: !automation.trigger.available ? "Trigger unavailable. This automation cannot receive events." : void 0
2051
- }])
2052
- };
2053
- }
2054
- //#endregion
2055
- //#region src/chat/scheduled-automations/types.ts
2056
- /** Durable scheduled-automation domain types owned by Junior core. */
2057
- const scheduledAutomationStatusSchema = z.enum([
2058
- "active",
2059
- "blocked",
2060
- "completed",
2061
- "deleted"
2062
- ]);
2063
- const scheduledAutomationCredentialModeSchema = z.enum(["system", "creator"]);
2064
- const scheduledRunStatusSchema = z.enum([
2065
- "pending",
2066
- "running",
2067
- "completed",
2068
- "failed",
2069
- "blocked",
2070
- "skipped"
2071
- ]);
2072
- const scheduledAutomationPrincipalSchema = z.object({
2073
- slackUserId: actorUserIdSchema,
2074
- fullName: z.string().optional(),
2075
- userName: z.string().optional()
2076
- }).strict();
2077
- const scheduledAutomationRecurrenceSchema = z.object({
2078
- dayOfMonth: z.number().optional(),
2079
- frequency: z.enum([
2080
- "daily",
2081
- "weekly",
2082
- "monthly",
2083
- "yearly"
2084
- ]),
2085
- interval: z.number(),
2086
- month: z.number().optional(),
2087
- startDate: z.string(),
2088
- time: z.object({
2089
- hour: z.number(),
2090
- minute: z.number()
2091
- }).strict(),
2092
- weekdays: z.array(z.number()).optional()
2093
- }).strict();
2094
- const scheduledAutomationScheduleSchema = z.object({
2095
- description: z.string(),
2096
- kind: z.enum(["one_off", "recurring"]),
2097
- recurrence: scheduledAutomationRecurrenceSchema.optional(),
2098
- timezone: z.string()
2099
- }).strict();
2100
- const scheduledAutomationExecutionActorSchema = z.object({
2101
- platform: z.literal("system"),
2102
- name: z.string()
2103
- }).strict();
2104
- /** Scheduled automations target a Slack conversation, never one message thread. */
2105
- const scheduledAutomationDestinationSchema = slackDestinationSchema.omit({ threadTs: true });
2106
- const scheduledAutomationOutcomeSchema = z.object({
2107
- action: z.literal("send_message"),
2108
- destination: scheduledAutomationDestinationSchema
2109
- }).strict();
2110
- /** Validate the current scheduled-automation domain shape. */
2111
- const scheduledAutomationSchema = z.object({
2112
- id: z.string(),
2113
- conversationAccess: z.object({
2114
- audience: z.enum([
2115
- "direct",
2116
- "group",
2117
- "channel"
2118
- ]),
2119
- visibility: z.enum(["private", "public"])
2120
- }).strict(),
2121
- createdAtMs: z.number(),
2122
- createdBy: scheduledAutomationPrincipalSchema,
2123
- /** Authoritative provider identity that created the task. */
2124
- creatorIdentityId: z.string(),
2125
- /** Selects system credentials or task-bound creator credential delegation. */
2126
- credentialMode: scheduledAutomationCredentialModeSchema,
2127
- destination: scheduledAutomationDestinationSchema,
2128
- executionActor: scheduledAutomationExecutionActorSchema.optional(),
2129
- lastRunAtMs: z.number().optional(),
2130
- nextRunAtMs: z.number().optional(),
2131
- originalRequest: z.string().optional(),
2132
- runNowAtMs: z.number().optional(),
2133
- schedule: scheduledAutomationScheduleSchema,
2134
- status: scheduledAutomationStatusSchema,
2135
- statusReason: z.string().optional(),
2136
- /** Explicit visible effects after successful work. An empty list is silent. */
2137
- outcomes: z.array(scheduledAutomationOutcomeSchema).max(5),
2138
- task: z.object({ text: z.string() }).strict(),
2139
- /** SQL-backed short display title generated from the task instruction. */
2140
- title: z.string().optional(),
2141
- updatedAtMs: z.number()
2142
- }).strict();
2143
- /** Validate the current scheduled-run domain shape. */
2144
- const scheduledRunSchema = z.object({
2145
- id: z.string(),
2146
- attempt: z.number(),
2147
- claimedAtMs: z.number(),
2148
- completedAtMs: z.number().optional(),
2149
- dispatchId: z.string().optional(),
2150
- errorMessage: z.string().optional(),
2151
- resultMessageTs: z.string().optional(),
2152
- scheduledForMs: z.number(),
2153
- startedAtMs: z.number().optional(),
2154
- status: scheduledRunStatusSchema,
2155
- taskId: z.string()
2156
- }).strict();
2157
- const SCHEDULED_AUTOMATION_SYSTEM_ACTOR = Object.freeze({
2158
- platform: "system",
2159
- name: "scheduled-automation"
2160
- });
2161
- //#endregion
2162
- //#region src/chat/scheduled-automations/tasks.ts
2163
- const SCHEDULER_KEY_PREFIX = "junior:scheduler";
2164
- const retainedScheduledAutomationSchema = scheduledAutomationSchema.omit({
2165
- creatorIdentityId: true,
2166
- title: true
2167
- }).extend({
2168
- destination: slackDestinationSchema,
2169
- outcomes: z.array(taskOutcomeSchema).max(5),
2170
- status: z.enum([
2171
- "active",
2172
- "blocked",
2173
- "completed",
2174
- "deleted",
2175
- "paused"
2176
- ]),
2177
- version: z.number().optional()
2178
- }).strict();
2179
- /** Decode a retained scheduler task row and reject invalid routing context. */
2180
- function parseScheduledAutomationRow(row) {
2181
- const record = z.record(z.string(), z.unknown()).safeParse(row.record);
2182
- if (!record.success) return void 0;
2183
- const { creatorIdentityId: legacyCreatorIdentityId, title: legacyTitle, ...retained } = record.data;
2184
- const current = retained.outcomes === void 0 && retained.destination !== void 0 ? {
2185
- ...retained,
2186
- outcomes: [{
2187
- action: "send_message",
2188
- destination: retained.destination
2189
- }]
2190
- } : retained;
2191
- const parsed = retainedScheduledAutomationSchema.safeParse(current);
2192
- if (!parsed.success) return void 0;
2193
- const { status, version: _version, ...retainedTask } = parsed.data;
2194
- const destination = {
2195
- platform: "slack",
2196
- teamId: retainedTask.destination.teamId,
2197
- channelId: retainedTask.destination.channelId
2198
- };
2199
- const task = {
2200
- ...retainedTask,
2201
- destination,
2202
- outcomes: retainedTask.outcomes.map((outcome) => ({
2203
- ...outcome,
2204
- destination: {
2205
- platform: "slack",
2206
- teamId: outcome.destination.teamId,
2207
- channelId: outcome.destination.channelId
2208
- }
2209
- }))
2210
- };
2211
- const fallbackIdentity = row.creatorIdentityId === null ? z.string().safeParse(legacyCreatorIdentityId) : void 0;
2212
- const creatorIdentityId = row.creatorIdentityId ?? (fallbackIdentity?.success ? fallbackIdentity.data : void 0);
2213
- if (creatorIdentityId === void 0) return void 0;
2214
- const fallbackTitle = row.title === null ? z.string().safeParse(legacyTitle) : void 0;
2215
- const title = (row.title !== null ? row.title : fallbackTitle?.success ? fallbackTitle.data : void 0)?.trim() || void 0;
2216
- if (status === "paused") {
2217
- const { nextRunAtMs: _nextRunAtMs, runNowAtMs: _runNowAtMs, ...retained } = task;
2218
- return {
2219
- ...retained,
2220
- creatorIdentityId,
2221
- status: "deleted",
2222
- ...title ? { title } : void 0
2223
- };
2224
- }
2225
- return {
2226
- ...task,
2227
- creatorIdentityId,
2228
- status,
2229
- ...title ? { title } : void 0
2230
- };
2231
- }
2232
- /** Keep scan paths from returning current or legacy tombstones. */
2233
- function isListedScheduledAutomation(task) {
2234
- return task !== void 0 && task.status !== "deleted";
2235
- }
2236
- /** Build the stable run id for one task occurrence. */
2237
- function scheduledRunId(taskId, scheduledForMs) {
2238
- return `${taskId}:${scheduledForMs}`;
2239
- }
2240
- /** Acquire the deployed advisory lock for one scheduled automation. */
2241
- function withScheduledAutomationLock(db, taskId, callback) {
2242
- return db.transaction(async (tx) => {
2243
- await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${SCHEDULER_KEY_PREFIX}:task:${taskId}:lock`}))`);
2244
- return await callback(tx);
2245
- });
2246
- }
2247
- function requireStoredTask(task) {
2248
- const parsed = scheduledAutomationSchema.safeParse(task);
2249
- if (!parsed.success) throw new Error("Scheduled automation routing context is invalid.");
2250
- const { title, ...current } = parsed.data;
2251
- const normalizedTitle = title?.trim() || void 0;
2252
- return {
2253
- ...current,
2254
- ...normalizedTitle ? { title: normalizedTitle } : void 0
2255
- };
2256
- }
2257
- function scheduledAutomationJsonRecord(task) {
2258
- const { title: _title, ...record } = task;
2259
- return record;
2260
- }
2261
- async function upsertScheduledAutomation(db, task) {
2262
- const title = task.title?.trim() || null;
2263
- await db.insert(juniorSchedulerTasks).values({
2264
- createdAtMs: task.createdAtMs,
2265
- creatorIdentityId: task.creatorIdentityId,
2266
- creatorSlackUserId: task.createdBy.slackUserId,
2267
- id: task.id,
2268
- nextRunAtMs: task.nextRunAtMs,
2269
- record: scheduledAutomationJsonRecord(task),
2270
- runNowAtMs: task.runNowAtMs,
2271
- status: task.status,
2272
- teamId: task.destination.teamId,
2273
- title
2274
- }).onConflictDoUpdate({
2275
- target: juniorSchedulerTasks.id,
2276
- set: {
2277
- createdAtMs: sql`excluded.created_at_ms`,
2278
- creatorIdentityId: sql`excluded.creator_identity_id`,
2279
- creatorSlackUserId: sql`excluded.creator_slack_user_id`,
2280
- nextRunAtMs: sql`excluded.next_run_at_ms`,
2281
- record: sql`excluded.record`,
2282
- runNowAtMs: sql`excluded.run_now_at_ms`,
2283
- status: sql`excluded.status`,
2284
- teamId: sql`excluded.team_id`,
2285
- title: sql`excluded.title`
2286
- }
2287
- });
2288
- }
2289
- /** Read and decode one scheduled automation. */
2290
- async function readScheduledAutomation(db, taskId) {
2291
- const rows = await db.select({
2292
- creatorIdentityId: juniorSchedulerTasks.creatorIdentityId,
2293
- record: juniorSchedulerTasks.record,
2294
- title: juniorSchedulerTasks.title
2295
- }).from(juniorSchedulerTasks).where(eq(juniorSchedulerTasks.id, taskId)).limit(1);
2296
- return rows[0] ? parseScheduledAutomationRow(rows[0]) : void 0;
2297
- }
2298
- async function readListedScheduledAutomations(db, teamId) {
2299
- return (await db.select({
2300
- creatorIdentityId: juniorSchedulerTasks.creatorIdentityId,
2301
- record: juniorSchedulerTasks.record,
2302
- title: juniorSchedulerTasks.title
2303
- }).from(juniorSchedulerTasks).where(and(notInArray(juniorSchedulerTasks.status, ["deleted", "paused"]), teamId === void 0 ? void 0 : eq(juniorSchedulerTasks.teamId, teamId))).orderBy(asc(juniorSchedulerTasks.createdAtMs), asc(juniorSchedulerTasks.id))).map(parseScheduledAutomationRow).filter(isListedScheduledAutomation);
2304
- }
2305
- /** List decoded scheduled automations in stable creation order. */
2306
- async function listScheduledAutomations(db) {
2307
- return await readListedScheduledAutomations(db);
2308
- }
2309
- /** List decoded scheduled automations for one team in stable creation order. */
2310
- async function listScheduledAutomationsForTeam(db, teamId) {
2311
- return await readListedScheduledAutomations(db, teamId);
2312
- }
2313
- async function writeScheduledAutomation(db, task, current) {
2314
- if (current?.status === "blocked" && task.status === "active" && typeof task.nextRunAtMs === "number" && Number.isFinite(task.nextRunAtMs)) await db.delete(juniorSchedulerRuns).where(and(eq(juniorSchedulerRuns.id, scheduledRunId(task.id, task.nextRunAtMs)), eq(juniorSchedulerRuns.status, "blocked")));
2315
- if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
2316
- await upsertScheduledAutomation(db, task);
2317
- }
2318
- async function skipPendingRunsForDeletedTask(db, task) {
2319
- const errorMessage = `Scheduled automation ${task.id} was deleted before the run started.`;
2320
- const rows = await db.select({ record: juniorSchedulerRuns.record }).from(juniorSchedulerRuns).where(and(eq(juniorSchedulerRuns.taskId, task.id), eq(juniorSchedulerRuns.status, "pending")));
2321
- for (const row of rows) {
2322
- const parsed = scheduledRunSchema.safeParse(row.record);
2323
- if (!parsed.success || parsed.data.status !== "pending") continue;
2324
- const next = scheduledRunSchema.parse({
2325
- ...parsed.data,
2326
- completedAtMs: task.updatedAtMs,
2327
- errorMessage,
2328
- status: "skipped"
2329
- });
2330
- await db.update(juniorSchedulerRuns).set({
2331
- record: next,
2332
- status: next.status
2333
- }).where(and(eq(juniorSchedulerRuns.id, next.id), eq(juniorSchedulerRuns.status, "pending")));
2334
- }
2335
- }
2336
- /** Create a scheduled automation once under its retry-stable task lock. */
2337
- async function createScheduledAutomation(db, task) {
2338
- const next = requireStoredTask(task);
2339
- return await withScheduledAutomationLock(db, task.id, async (tx) => {
2340
- const current = await readScheduledAutomation(tx, task.id);
2341
- if (current) return current;
2342
- await writeScheduledAutomation(tx, next, void 0);
2343
- return next;
2344
- });
2345
- }
2346
- /** Save a scheduled automation and clear its blocked occurrence on reactivation. */
2347
- async function saveScheduledAutomation(db, task) {
2348
- const next = requireStoredTask(task);
2349
- await withScheduledAutomationLock(db, task.id, async (tx) => {
2350
- const current = await readScheduledAutomation(tx, task.id);
2351
- await writeScheduledAutomation(tx, next, current);
2352
- });
2353
- return next;
2354
- }
2355
- /** Save a scheduled automation inside a task lock already held by the caller. */
2356
- async function saveScheduledAutomationInLock(db, task, current) {
2357
- await writeScheduledAutomation(db, requireStoredTask(task), current);
2358
- }
2359
- /** List scheduled automations whose current Slack destination is public. */
2360
- async function listPublicScheduledAutomationsForTeams(db, teamIds, input) {
2361
- if (teamIds.length === 0) return [];
2362
- return (await db.select({
2363
- creatorIdentityId: juniorSchedulerTasks.creatorIdentityId,
2364
- record: juniorSchedulerTasks.record,
2365
- title: juniorSchedulerTasks.title
2366
- }).from(juniorSchedulerTasks).innerJoin(juniorDestinations, and(eq(juniorDestinations.provider, "slack"), eq(juniorDestinations.providerTenantId, juniorSchedulerTasks.teamId), sql`${juniorDestinations.providerDestinationId} = ${juniorSchedulerTasks.record}->'destination'->>'channelId'`)).where(and(inArray(juniorSchedulerTasks.teamId, teamIds), notInArray(juniorSchedulerTasks.status, [
2367
- "completed",
2368
- "deleted",
2369
- "paused"
2370
- ]), input.query ? sql`strpos(lower(coalesce(${juniorSchedulerTasks.title}, ${juniorSchedulerTasks.record}->'task'->>'text')), ${input.query}) > 0` : void 0, eq(juniorDestinations.visibility, "public"))).orderBy(desc(juniorSchedulerTasks.createdAtMs), desc(juniorSchedulerTasks.id)).limit(input.limit)).map(parseScheduledAutomationRow).filter(isListedScheduledAutomation);
2371
- }
2372
- //#endregion
2373
- //#region src/chat/slack/context.ts
2374
- function toTrimmedSlackString(value) {
2375
- return toOptionalString(value)?.trim() || void 0;
2376
- }
2377
- const slackMessageEnvelopeSchema = z.object({ raw: z.unknown().optional() });
2378
- const rawSlackMessageSchema = z.object({
2379
- channel: z.unknown().optional(),
2380
- message: z.unknown().optional(),
2381
- team: z.unknown().optional(),
2382
- team_id: z.unknown().optional(),
2383
- thread_ts: z.unknown().optional(),
2384
- ts: z.unknown().optional(),
2385
- user_team: z.unknown().optional()
2386
- });
2387
- const nestedRawSlackMessageSchema = z.object({ ts: z.unknown().optional() });
2388
- /** Project only the Slack raw fields consumed by runtime thread context. */
2389
- function readSlackRawMessageContext(message) {
2390
- const envelope = slackMessageEnvelopeSchema.safeParse(message);
2391
- if (!envelope.success) return;
2392
- const raw = rawSlackMessageSchema.safeParse(envelope.data.raw);
2393
- if (!raw.success) return;
2394
- const nestedMessage = nestedRawSlackMessageSchema.safeParse(raw.data.message);
2395
- const channelId = parseSlackChannelId(raw.data.channel);
2396
- const threadTs = parseSlackMessageTs(raw.data.thread_ts);
2397
- const messageTs = parseSlackMessageTs(raw.data.ts);
2398
- const nestedMessageTs = nestedMessage.success && parseSlackMessageTs(nestedMessage.data.ts);
2399
- const teamId = parseSlackTeamId(raw.data.team_id) ?? parseSlackTeamId(raw.data.team);
2400
- const authorTeamId = parseSlackTeamId(raw.data.user_team);
2401
- return {
2402
- ...channelId ? { channelId } : void 0,
2403
- ...threadTs ? { threadTs } : void 0,
2404
- ...messageTs ? { messageTs } : void 0,
2405
- ...nestedMessageTs ? { nestedMessageTs } : void 0,
2406
- ...teamId ? { teamId } : void 0,
2407
- ...authorTeamId ? { authorTeamId } : void 0
2408
- };
2409
- }
2410
- /** Extract a channel ID and validated Slack timestamp from `slack:<channel>:<ts>`. */
2411
- function parseSlackThreadId(threadId) {
2412
- const normalizedThreadId = toTrimmedSlackString(threadId);
2413
- if (!normalizedThreadId) return;
2414
- const parts = normalizedThreadId.split(":");
2415
- if (parts.length !== 3 || parts[0] !== "slack") return;
2416
- const channelId = parseSlackChannelId(parts[1]);
2417
- const threadTs = parseSlackMessageTs(parts[2]);
2418
- if (!channelId || !threadTs) return;
2419
- return {
2420
- channelId,
2421
- threadTs
2422
- };
2423
- }
2424
- /** Resolve the Slack channel ID from a `slack:<channel>:<ts>` thread identifier. */
2425
- function resolveSlackChannelIdFromThreadId(threadId) {
2426
- return parseSlackThreadId(threadId)?.channelId;
2427
- }
2428
- /** Best-effort channel ID extraction from a raw Slack message payload. */
2429
- function resolveSlackChannelIdFromMessage(message) {
2430
- const messageChannelId = parseSlackChannelId(message.channelId);
2431
- if (messageChannelId) return messageChannelId;
2432
- const raw = message.raw;
2433
- if (raw && typeof raw === "object") {
2434
- const rawChannel = parseSlackChannelId(raw.channel);
2435
- if (rawChannel) return rawChannel;
2436
- }
2437
- return resolveSlackChannelIdFromThreadId(toTrimmedSlackString(message.threadId));
2438
- }
2439
- //#endregion
2440
- //#region src/chat/attachments/store.ts
2441
- const DAY_MS = 864e5;
2442
- const ATTACHMENT_GC_BATCH_LIMIT = 200;
2443
- /** Time that Junior keeps attachment bytes after the file is stored. */
2444
- const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
2445
- function attachmentDigest(file) {
2446
- return createHash("sha256").update(file.data).digest("hex");
2447
- }
2448
- /** Stable conversation-owned id for one file body and presentation metadata. */
2449
- function attachmentId(args) {
2450
- const identity = [
2451
- args.conversationId,
2452
- args.storageProvider,
2453
- args.sha256,
2454
- args.filename,
2455
- args.contentType
2456
- ];
2457
- if (args.source) identity.push(args.source.provider, args.source.id);
2458
- return createHash("sha256").update(identity.join("\0")).digest("hex");
2459
- }
2460
- /**
2461
- * Object key for one write attempt.
2462
- *
2463
- * Attachment ids are content-stable. Object keys are not: each put gets a fresh
2464
- * key so a failed-write cleanup or GC delete cannot remove another writer's
2465
- * durable blob.
2466
- */
2467
- function attachmentKey(args) {
2468
- return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
2469
- }
2470
- async function bestEffortDelete(storage, key) {
2471
- try {
2472
- await storage.delete([key]);
2473
- } catch {}
2474
- }
2475
- async function isConversationPurged(db, conversationId) {
2476
- const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
2477
- return row?.transcriptPurgedAt != null;
2478
- }
2479
- function purgedConversationError(conversationId) {
2480
- return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
2481
- }
2482
- async function assertConversationNotPurged(db, conversationId) {
2483
- if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
2484
- }
2485
- /** Mark a just-written row for deletion and drop its unused object. */
2486
- async function rejectPurgedAttachmentWrite(args) {
2487
- await args.db.db().update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
2488
- await bestEffortDelete(args.storage, args.storageKey);
2489
- throw purgedConversationError(args.conversationId);
2490
- }
2491
- /**
2492
- * Return another writer's live row only when the conversation is still active.
2493
- *
2494
- * The caller already wrote a unique object for this attempt. Delete that unused
2495
- * object either way. If the conversation is purged, do not report success for a
2496
- * row that purge/GC is about to remove.
2497
- */
2498
- async function reuseLiveAttachment(args) {
2499
- await bestEffortDelete(args.storage, args.storageKey);
2500
- await assertConversationNotPurged(args.db, args.conversationId);
2501
- return { id: args.id };
2502
- }
2503
- /**
2504
- * Persist one conversation-owned file.
2505
- *
2506
- * Identity is content-stable under the conversation. Object storage is written
2507
- * first under a unique key; the SQL row is created only after that write
2508
- * succeeds. A row means the attachment is durable. Retries reuse an existing
2509
- * live row. A purge-marked row is revived by writing a new object and pointing
2510
- * the row at it, unless the conversation is still purged. If the SQL write
2511
- * fails after object storage accepts the bytes, this path deletes that unique
2512
- * object. A process crash between those steps can leave an unreferenced unique
2513
- * object with no SQL row.
2514
- */
2515
- async function storeAttachment(args) {
2516
- const now = new Date(args.nowMs ?? Date.now());
2517
- const sha256 = attachmentDigest(args.file);
2518
- const id = attachmentId({
2519
- conversationId: args.conversationId,
2520
- contentType: args.file.mimeType,
2521
- filename: args.file.filename,
2522
- source: args.source,
2523
- storageProvider: args.storage.provider,
2524
- sha256
2525
- });
2526
- const [existing] = await args.db.db().select({
2527
- contentType: juniorAttachments.contentType,
2528
- conversationId: juniorAttachments.conversationId,
2529
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2530
- filename: juniorAttachments.filename,
2531
- id: juniorAttachments.id,
2532
- provider: juniorAttachments.provider,
2533
- providerId: juniorAttachments.providerId,
2534
- storageProvider: juniorAttachments.storageProvider,
2535
- sha256: juniorAttachments.sha256,
2536
- storageKey: juniorAttachments.storageKey
2537
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
2538
- if (existing) {
2539
- if (existing.contentType !== args.file.mimeType || existing.conversationId !== args.conversationId || existing.filename !== args.file.filename || existing.provider !== (args.source?.provider ?? null) || existing.providerId !== (args.source?.id ?? null) || existing.storageProvider !== args.storage.provider || existing.sha256 !== sha256) throw new Error(`Attachment write conflicts with ${existing.id}`);
2540
- if (existing.deleteRequestedAt === null) {
2541
- await assertConversationNotPurged(args.db, args.conversationId);
2542
- return { id: existing.id };
2543
- }
2544
- }
2545
- await assertConversationNotPurged(args.db, args.conversationId);
2546
- const storageKey = attachmentKey({
2547
- attachmentId: id,
2548
- conversationId: args.conversationId,
2549
- filename: args.file.filename,
2550
- writeId: randomUUID()
2551
- });
2552
- await args.storage.put({
2553
- body: args.file.data,
2554
- contentType: args.file.mimeType,
2555
- key: storageKey
2556
- });
2557
- if (existing?.deleteRequestedAt != null) {
2558
- if (await isConversationPurged(args.db, args.conversationId)) {
2559
- await bestEffortDelete(args.storage, storageKey);
2560
- throw purgedConversationError(args.conversationId);
2561
- }
2562
- const oldStorageKey = existing.storageKey;
2563
- if ((await args.db.db().update(juniorAttachments).set({
2564
- deleteRequestedAt: null,
2565
- storageKey
2566
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
2567
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
2568
- conversationId: args.conversationId,
2569
- db: args.db,
2570
- id,
2571
- now,
2572
- storage: args.storage,
2573
- storageKey
2574
- });
2575
- if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
2576
- return { id };
2577
- }
2578
- const [afterRace] = await args.db.db().select({
2579
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2580
- id: juniorAttachments.id,
2581
- storageKey: juniorAttachments.storageKey
2582
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
2583
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
2584
- conversationId: args.conversationId,
2585
- db: args.db,
2586
- id: afterRace.id,
2587
- storage: args.storage,
2588
- storageKey
2589
- });
2590
- }
2591
- let inserted = [];
2592
- try {
2593
- inserted = await args.db.db().insert(juniorAttachments).values({
2594
- id,
2595
- conversationId: args.conversationId,
2596
- storageProvider: args.storage.provider,
2597
- storageKey,
2598
- provider: args.source?.provider,
2599
- providerId: args.source?.id,
2600
- filename: args.file.filename,
2601
- contentType: args.file.mimeType,
2602
- bytes: args.file.bytes,
2603
- sha256,
2604
- createdAt: now
2605
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
2606
- } catch (error) {
2607
- await bestEffortDelete(args.storage, storageKey);
2608
- throw error;
2609
- }
2610
- if (inserted.length > 0) {
2611
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
2612
- conversationId: args.conversationId,
2613
- db: args.db,
2614
- id,
2615
- now,
2616
- storage: args.storage,
2617
- storageKey
2618
- });
2619
- return { id };
2620
- }
2621
- const [row] = await args.db.db().select({
2622
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2623
- id: juniorAttachments.id,
2624
- storageKey: juniorAttachments.storageKey
2625
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
2626
- if (!row) {
2627
- await bestEffortDelete(args.storage, storageKey);
2628
- throw new Error(`Attachment row missing after write for ${id}`);
2629
- }
2630
- if (row.deleteRequestedAt === null) return reuseLiveAttachment({
2631
- conversationId: args.conversationId,
2632
- db: args.db,
2633
- id: row.id,
2634
- storage: args.storage,
2635
- storageKey
2636
- });
2637
- if (await isConversationPurged(args.db, args.conversationId)) {
2638
- await bestEffortDelete(args.storage, storageKey);
2639
- throw purgedConversationError(args.conversationId);
2640
- }
2641
- if ((await args.db.db().update(juniorAttachments).set({
2642
- deleteRequestedAt: null,
2643
- storageKey
2644
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
2645
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
2646
- conversationId: args.conversationId,
2647
- db: args.db,
2648
- id,
2649
- now,
2650
- storage: args.storage,
2651
- storageKey
2652
- });
2653
- if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
2654
- return { id };
2655
- }
2656
- const [afterRace] = await args.db.db().select({
2657
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2658
- id: juniorAttachments.id
2659
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
2660
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
2661
- conversationId: args.conversationId,
2662
- db: args.db,
2663
- id: afterRace.id,
2664
- storage: args.storage,
2665
- storageKey
2666
- });
2667
- await bestEffortDelete(args.storage, storageKey);
2668
- throw new Error(`Attachment ${id} disappeared while reviving`);
2669
- }
2670
- /** Load one live attachment owned by a conversation. */
2671
- async function readLiveAttachment(args) {
2672
- const [row] = await args.db.db().select({
2673
- bytes: juniorAttachments.bytes,
2674
- contentType: juniorAttachments.contentType,
2675
- conversationId: juniorAttachments.conversationId,
2676
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2677
- filename: juniorAttachments.filename,
2678
- id: juniorAttachments.id,
2679
- storageProvider: juniorAttachments.storageProvider,
2680
- storageKey: juniorAttachments.storageKey
2681
- }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
2682
- if (!row) return null;
2683
- if (await isConversationPurged(args.db, args.conversationId)) return null;
2684
- return {
2685
- bytes: row.bytes,
2686
- contentType: row.contentType,
2687
- conversationId: row.conversationId,
2688
- filename: row.filename,
2689
- id: row.id,
2690
- storageKey: row.storageKey,
2691
- storageProvider: row.storageProvider
2692
- };
2693
- }
2694
- /** Persist many conversation-owned files. */
2695
- async function storeAttachments(args) {
2696
- const stored = [];
2697
- for (const file of args.files) stored.push(await storeAttachment({
2698
- conversationId: args.conversationId,
2699
- db: args.db,
2700
- file,
2701
- ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
2702
- storage: args.storage
2703
- }));
2704
- return stored;
2705
- }
2706
- /** Mark attachments unavailable when their conversation content is purged. */
2707
- async function requestAttachmentDeletion(db, conversationIds, nowMs) {
2708
- if (conversationIds.length === 0) return;
2709
- await db.db().update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
2710
- }
2711
- /**
2712
- * Delete purged attachments in one bounded batch.
2713
- *
2714
- * Eligible rows are 30 days old, explicitly purge-marked, or owned by a
2715
- * conversation whose transcript is already purged. Delete object keys first,
2716
- * then remove rows that are still eligible so a failed blob delete remains
2717
- * retryable.
2718
- */
2719
- async function collectAttachmentGarbage(args) {
2720
- const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
2721
- const rows = await args.db.db().select({
2722
- id: juniorAttachments.id,
2723
- storageKey: juniorAttachments.storageKey
2724
- }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(eq(juniorAttachments.storageProvider, args.storage.provider), or(lte(juniorAttachments.createdAt, expiresBefore), isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt)))).orderBy(asc(juniorAttachments.createdAt), asc(juniorAttachments.id)).limit(args.limit ?? ATTACHMENT_GC_BATCH_LIMIT);
2725
- if (rows.length === 0) return { deleted: 0 };
2726
- await args.storage.delete(rows.map((row) => row.storageKey));
2727
- const stillEligible = await args.db.db().select({ id: juniorAttachments.id }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(inArray(juniorAttachments.id, rows.map((row) => row.id)), or(lte(juniorAttachments.createdAt, expiresBefore), isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt))));
2728
- if (stillEligible.length === 0) return { deleted: 0 };
2729
- return { deleted: (await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({ id: juniorAttachments.id })).length };
2730
- }
2731
- //#endregion
2732
- //#region src/stats.ts
2733
- function utcDate(nowMs) {
2734
- return new Date(nowMs).toISOString().slice(0, 10);
2735
- }
2736
- /** Increment one daily named counter. */
2737
- async function incrementStat(key, options = {}) {
2738
- const date = utcDate(options.nowMs ?? Date.now());
2739
- await getDb().insert(juniorStats).values({
2740
- ...key,
2741
- date,
2742
- count: 1
2743
- }).onConflictDoUpdate({
2744
- target: [
2745
- juniorStats.date,
2746
- juniorStats.namespace,
2747
- juniorStats.metric,
2748
- juniorStats.name
2749
- ],
2750
- set: { count: sql`${juniorStats.count} + 1` }
2751
- });
2752
- }
2753
- /** Read daily counters inside an inclusive UTC date range. */
2754
- async function readStats(start, end) {
2755
- return await getDb().select().from(juniorStats).where(and(gte(juniorStats.date, start), lte(juniorStats.date, end))).orderBy(asc(juniorStats.date), asc(juniorStats.namespace), asc(juniorStats.metric), asc(juniorStats.name));
2756
- }
2757
- //#endregion
2758
- export { workspaceSnapshotFinishedEvent as $, eventAutomationTriggerAvailable as A, recordConversationRetry as At, createEventAutomation as B, hasRunnableConversationWork$1 as Bt, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as C, drainConversationMailbox as Ct, eventAutomationMatchesDestination as D, hasRunnableConversationWork as Dt, eventAutomationListToolResultSchema as E, getConversationWorkState as Et, effectiveTaskOutcomes as F, startConversationWork as Ft, listDeletedEventAutomationsCreatedBy as G, makeStructuredToolOutput as Gt, eventAutomationBelongsToUser as H, isInvalidConversationRecordError as Ht, moveTaskOutcomes as I, stopConversationWork as It, listPublicEventAutomationsForTeams as J, ToolInputError as Jt, listEventAutomationsCreatedBy as K, buildDeterministicAssistantMessageId as Kt, resolveTaskOutcomes as L, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as Lt, requireEventAutomationSlackContext as M, removeActiveConversation as Mt, requireSupportedEventAutomationTrigger as N, requestAnotherSlice as Nt, eventAutomationToolResult as O, listActiveConversationIds as Ot, writableEventAutomation as P, requestConversationWork as Pt, WORKSPACE_SNAPSHOT_READY_EVENT as Q, taskOutcomeInputSchema as R, CONVERSATION_WORK_STALE_ENQUEUE_MS as Rt, withScheduledAutomationLock as S, deadLetterAttempt as St, compactEventAutomation as T, getConversation as Tt, findMatchingEventAutomations as U, injectContinuationToolName as Ut, deleteEventAutomation as V, isFinalAttempt as Vt, getEventAutomation as W, juniorToolOutputSchema as Wt, getEventCatalog as X, saveEventAutomation as Y, WORKSPACE_SNAPSHOT_FAILED_EVENT as Z, parseScheduledAutomationRow as _, clearConsumedConversationWake as _t, requestAttachmentDeletion as a, normalizeCatalogEventIdentifier as at, saveScheduledAutomationInLock as b, completeConversationWork as bt, parseSlackThreadId as c, registeredEventTypeSchema as ct, resolveSlackChannelIdFromThreadId as d, ackMessages as dt, workspaceSnapshotWatch as et, createScheduledAutomation as f, appendAndEnqueueExclusiveInboundMessage as ft, listScheduledAutomationsForTeam as g, checkInConversationWork as gt, listScheduledAutomations as h, cancelHumanFacingPendingMessages as ht, readLiveAttachment as i, hasPluginEventCatalogEntries as it, registeredEventAutomationTriggerSchema as j, releaseConversationWork as jt, eventAutomationToolResultSchema as k, recordAttemptFailure as kt, readSlackRawMessageContext as l, registeredResourceTypeSchema as lt, listPublicScheduledAutomationsForTeams as m, beginConversationResume as mt, readStats as n, eventNamespaceSchema as nt, storeAttachment as o, pluginSupportsEvent as ot, isListedScheduledAutomation as p, appendAndEnqueueInboundMessage as pt, listEventAutomationsForTeam as q, buildDeterministicTurnId as qt, collectAttachmentGarbage as r, hasEventCatalogEntries as rt, storeAttachments as s, registeredEventMatchSchema as st, incrementStat as t, eventGuidance as tt, resolveSlackChannelIdFromMessage as u, requireSupportedEventMatch as ut, readScheduledAutomation as v, clearExpiredConversationLease as vt, scheduledRunSchema as w, ensureConversationWake as wt, scheduledRunId as x, countPendingConversationMessages as xt, saveScheduledAutomation as y, completeConversationStop as yt, collectEventAutomationMatchKeys as z, hasConversationStop as zt };