@sentry/junior 0.137.0 → 0.139.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 (103) hide show
  1. package/dist/{agent-hooks-MZOKEP3J.js → agent-hooks-MJXMD7JP.js} +11 -9
  2. package/dist/api/schema/task.d.ts +100 -1
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +9 -1
  5. package/dist/api.js +202 -55
  6. package/dist/app.d.ts +7 -0
  7. package/dist/app.js +601 -1356
  8. package/dist/{catalog-runtime-MD66YLFV.js → catalog-runtime-GCCFYPIK.js} +6 -6
  9. package/dist/chat/agent/request.d.ts +44 -4
  10. package/dist/chat/agent-dispatch/heartbeat.d.ts +5 -0
  11. package/dist/chat/agent-dispatch/types.d.ts +1 -1
  12. package/dist/chat/agent-invocations/errors.d.ts +8 -0
  13. package/dist/chat/agent-invocations/spawn.d.ts +12 -0
  14. package/dist/chat/agent-invocations/store.d.ts +44 -0
  15. package/dist/chat/agent-invocations/types.d.ts +449 -0
  16. package/dist/chat/agent-invocations/work.d.ts +31 -0
  17. package/dist/chat/config.d.ts +1 -0
  18. package/dist/chat/conversations/sql/store.d.ts +8 -0
  19. package/dist/chat/conversations/store.d.ts +7 -0
  20. package/dist/chat/credentials/context.d.ts +14 -0
  21. package/dist/chat/experimental.d.ts +16 -0
  22. package/dist/chat/resource-events/actor.d.ts +23 -0
  23. package/dist/chat/runtime/agent-runner.d.ts +2 -1
  24. package/dist/chat/services/auth-pause.d.ts +0 -1
  25. package/dist/chat/services/mcp-auth-orchestration.d.ts +3 -2
  26. package/dist/chat/services/plugin-auth-orchestration.d.ts +3 -2
  27. package/dist/chat/state/turn-session.d.ts +1 -5
  28. package/dist/chat/task-execution/state.d.ts +23 -11
  29. package/dist/chat/task-execution/store.d.ts +20 -11
  30. package/dist/chat/task-execution/worker.d.ts +2 -2
  31. package/dist/chat/tasks/execution-stats.d.ts +34 -3
  32. package/dist/chat/tasks/read.d.ts +3 -1
  33. package/dist/chat/tools/runtime/spawn-agent.d.ts +31 -0
  34. package/dist/chat/tools/types.d.ts +2 -0
  35. package/dist/{chunk-T6Z5S6PQ.js → chunk-2ECYPYKP.js} +1 -1
  36. package/dist/chunk-3T2JAGRH.js +115 -0
  37. package/dist/chunk-3Y47VMHV.js +6 -0
  38. package/dist/chunk-4V4QIYJH.js +41 -0
  39. package/dist/{chunk-SYCX4DOK.js → chunk-5GSZWRE2.js} +434 -65
  40. package/dist/chunk-5IDFPCON.js +46 -0
  41. package/dist/{chunk-36EG34YI.js → chunk-6OHTDR4F.js} +1 -1
  42. package/dist/chunk-6SU2DT27.js +441 -0
  43. package/dist/{chunk-UG6ZYPBI.js → chunk-75I3UBIL.js} +73 -60
  44. package/dist/chunk-AEQISMMU.js +711 -0
  45. package/dist/{chunk-5PNJMOY5.js → chunk-C2N6MNO4.js} +9 -2
  46. package/dist/{chunk-BZAMASJP.js → chunk-CXH25EL4.js} +2 -2
  47. package/dist/{chunk-K2NCQJKH.js → chunk-DW4PMHNW.js} +3 -3
  48. package/dist/chunk-EM225ITJ.js +56 -0
  49. package/dist/{chunk-UOXATPSI.js → chunk-G52UXKGO.js} +7 -5
  50. package/dist/chunk-GI52BW74.js +207 -0
  51. package/dist/{chunk-3Q342EJJ.js → chunk-GWQSZT4C.js} +2 -2
  52. package/dist/{chunk-EPBBYMNE.js → chunk-HUO3UTAQ.js} +1 -1
  53. package/dist/{chunk-WPPXIAFB.js → chunk-IIESAYDL.js} +17 -434
  54. package/dist/chunk-IUFM5JWV.js +24 -0
  55. package/dist/{chunk-UZQ4VY3M.js → chunk-J3S57AXY.js} +1 -1
  56. package/dist/{chunk-DQXAAVTR.js → chunk-J6EJQCHY.js} +46 -1471
  57. package/dist/{chunk-6ZK6FZIV.js → chunk-KCBZSJRU.js} +6 -27
  58. package/dist/chunk-MQ5RYATN.js +1523 -0
  59. package/dist/{chunk-5G34IEK2.js → chunk-MXTVUV3I.js} +2 -56
  60. package/dist/{chunk-YRPC6MJY.js → chunk-MXVD2BDS.js} +1 -1
  61. package/dist/{chunk-POBSY47Q.js → chunk-PJW6U46K.js} +337 -306
  62. package/dist/chunk-Q6QZTTLS.js +55 -0
  63. package/dist/{chunk-ZFS67WIR.js → chunk-QTBKPZDA.js} +57 -6
  64. package/dist/chunk-R776HKPK.js +81 -0
  65. package/dist/{chunk-77VDLF3Z.js → chunk-RUIXF3YQ.js} +10 -0
  66. package/dist/chunk-U27DSXKB.js +714 -0
  67. package/dist/{chunk-XZ7NPXAB.js → chunk-U7CMWQ7Z.js} +1 -1
  68. package/dist/{chunk-RB4NJKEX.js → chunk-UDBUS533.js} +125 -51
  69. package/dist/chunk-WQRX57EA.js +668 -0
  70. package/dist/chunk-WZH4JV7R.js +320 -0
  71. package/dist/{chunk-HCIVH3JS.js → chunk-YCTDA7BD.js} +28 -0
  72. package/dist/{chunk-YNFERGKP.js → chunk-YGZ2OLXL.js} +1 -1
  73. package/dist/{chunk-EWDSB24B.js → chunk-ZQCGQMF2.js} +16 -776
  74. package/dist/{chunk-KJ4HGRHN.js → chunk-ZYQSPQYR.js} +515 -601
  75. package/dist/cli/chat.js +68 -29
  76. package/dist/cli/check.js +7 -7
  77. package/dist/cli/plugins.js +15 -13
  78. package/dist/cli/snapshot-create.js +11 -10
  79. package/dist/cli/upgrade.js +8 -8
  80. package/dist/conversation-work-KATFHLG3.js +56 -0
  81. package/dist/db/schema/agent-invocations.d.ts +544 -0
  82. package/dist/db/schema/task-executions.d.ts +23 -2
  83. package/dist/db/schema.d.ts +563 -2
  84. package/dist/{db-66E7VDNC.js → db-UXPPGHDF.js} +7 -7
  85. package/dist/experimental-HH6OM6UH.js +13 -0
  86. package/dist/instrumentation.js +4 -4
  87. package/dist/nitro.js +4 -3
  88. package/dist/{oauth-callback-server-7QPD4Q7P.js → oauth-callback-server-4ZYMD5UA.js} +28 -19
  89. package/dist/{runner-L2BKJKOD.js → runner-MZSEONRZ.js} +32 -18
  90. package/dist/{sandbox-egress-signals-A5HWIQH4.js → sandbox-egress-signals-EKPAVWQL.js} +2 -2
  91. package/dist/{skills-HOQ2NSPW.js → skills-IMVPXSQ7.js} +7 -7
  92. package/dist/spawn-S5LSVOCE.js +38 -0
  93. package/dist/{validation-ENHI7S2C.js → validation-ZKCY2BVR.js} +7 -7
  94. package/dist/version.js +1 -1
  95. package/dist/work-GG3XDYRX.js +46 -0
  96. package/dist/worker-23AUELCJ.js +24 -0
  97. package/migrations/0021_first_warhawk.sql +35 -0
  98. package/migrations/0022_task_execution_status.sql +3 -0
  99. package/migrations/meta/0021_snapshot.json +2176 -0
  100. package/migrations/meta/0022_snapshot.json +2186 -0
  101. package/migrations/meta/_journal.json +15 -1
  102. package/package.json +4 -4
  103. package/dist/chunk-6QW2RRQT.js +0 -233
@@ -0,0 +1,1523 @@
1
+ import {
2
+ JUNIOR_THREAD_STATE_TTL_MS
3
+ } from "./chunk-3Y47VMHV.js";
4
+ import {
5
+ getConversationStore,
6
+ parseDestination,
7
+ sameDestination
8
+ } from "./chunk-QTBKPZDA.js";
9
+ import {
10
+ getDefaultRedisStateAdapterFor,
11
+ getStateAdapter
12
+ } from "./chunk-MXTVUV3I.js";
13
+ import {
14
+ getChatConfig
15
+ } from "./chunk-75I3UBIL.js";
16
+ import {
17
+ parseStoredSlackActor
18
+ } from "./chunk-HZF5P5UN.js";
19
+ import {
20
+ isRecord,
21
+ toOptionalNumber,
22
+ toOptionalString
23
+ } from "./chunk-2ECYPYKP.js";
24
+
25
+ // src/chat/task-execution/state.ts
26
+ import { randomUUID } from "crypto";
27
+ import { destinationSchema } from "@sentry/junior-plugin-api";
28
+ import { z } from "zod";
29
+ var CONVERSATION_PREFIX = "junior:conversation";
30
+ var CONVERSATION_SCHEMA_VERSION = 2;
31
+ var CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH = 1e4;
32
+ var CONVERSATION_INDEX_LOCK_TTL_MS = 1e4;
33
+ var CONVERSATION_INDEX_LOCK_WAIT_MS = 2e3;
34
+ var CONVERSATION_INDEX_LOCK_RETRY_MS = 25;
35
+ var CONVERSATION_MUTATION_LOCK_TTL_MS = 1e4;
36
+ var CONVERSATION_MUTATION_WAIT_MS = 1e4;
37
+ var CONVERSATION_MUTATION_RETRY_MS = 25;
38
+ var InvalidConversationRecordError = class extends Error {
39
+ constructor(conversationId) {
40
+ super(`Conversation record is invalid for ${conversationId}`);
41
+ this.name = "InvalidConversationRecordError";
42
+ }
43
+ };
44
+ function isInvalidConversationRecordError(error) {
45
+ return error instanceof InvalidConversationRecordError;
46
+ }
47
+ var ConversationMutationFencedError = class extends Error {
48
+ constructor(conversationId) {
49
+ super(
50
+ `Conversation mutation lock was lost before write for ${conversationId}`
51
+ );
52
+ this.name = "ConversationMutationFencedError";
53
+ }
54
+ };
55
+ var CONVERSATION_BY_ACTIVITY_INDEX_KEY = `${CONVERSATION_PREFIX}:by-activity`;
56
+ var CONVERSATION_ACTIVE_INDEX_KEY = `${CONVERSATION_PREFIX}:active`;
57
+ var CONVERSATION_WORK_LEASE_TTL_MS = 9e4;
58
+ var CONVERSATION_WORK_CHECK_IN_INTERVAL_MS = 15e3;
59
+ var CONVERSATION_WORK_STALE_ENQUEUE_MS = 6e4;
60
+ var CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS = 5;
61
+ var CONVERSATION_WORK_MAX_RETRIES = 5;
62
+ var inboundMessageSourceSchema = z.enum([
63
+ "api",
64
+ "internal",
65
+ "local",
66
+ "plugin",
67
+ "resource_event",
68
+ "scheduler",
69
+ "slack"
70
+ ]);
71
+ var agentInputSchema = z.object({
72
+ attachments: z.array(z.unknown()).optional(),
73
+ authorId: z.string().min(1).optional(),
74
+ metadata: z.record(z.string(), z.unknown()).optional(),
75
+ text: z.string()
76
+ }).strict().refine((input) => input.text.trim() || input.attachments?.length, {
77
+ message: "agent input requires text or attachments"
78
+ });
79
+ var inboundMessageDeliverySchema = z.enum(["defer", "interrupt"]);
80
+ var inboundMessageSchema = z.object({
81
+ attemptCount: z.number().finite().optional(),
82
+ conversationId: z.string().refine((value) => value.trim().length > 0),
83
+ createdAtMs: z.number().finite(),
84
+ delivery: inboundMessageDeliverySchema,
85
+ destination: destinationSchema.optional(),
86
+ inboundMessageId: z.string().refine((value) => value.trim().length > 0),
87
+ injectedAtMs: z.number().finite().optional(),
88
+ input: agentInputSchema,
89
+ receivedAtMs: z.number().finite(),
90
+ source: inboundMessageSourceSchema
91
+ }).strict();
92
+ function conversationKey(conversationId) {
93
+ return `${CONVERSATION_PREFIX}:${conversationId}`;
94
+ }
95
+ function indexLockKey(indexKey) {
96
+ return `${indexKey}:lock`;
97
+ }
98
+ function mutationLockKey(conversationId) {
99
+ return `${CONVERSATION_PREFIX}:mutation:${conversationId}`;
100
+ }
101
+ function now() {
102
+ return Date.now();
103
+ }
104
+ function compareMessages(left, right) {
105
+ return left.createdAtMs - right.createdAtMs || left.receivedAtMs - right.receivedAtMs || left.inboundMessageId.localeCompare(right.inboundMessageId);
106
+ }
107
+ function inputHasAttachments(input) {
108
+ return Array.isArray(input.attachments) && input.attachments.length > 0;
109
+ }
110
+ function upgradedPendingMessage(stored, duplicate) {
111
+ const promotesInterrupt = stored.delivery === "defer" && duplicate.delivery === "interrupt";
112
+ const delivery = promotesInterrupt ? "interrupt" : stored.delivery;
113
+ const input = promotesInterrupt ? {
114
+ ...duplicate.input,
115
+ ...inputHasAttachments(duplicate.input) || !inputHasAttachments(stored.input) ? {} : { attachments: stored.input.attachments }
116
+ } : inputHasAttachments(duplicate.input) && !inputHasAttachments(stored.input) ? duplicate.input : stored.input;
117
+ if (input === stored.input && delivery === stored.delivery) {
118
+ return stored;
119
+ }
120
+ return { ...stored, delivery, input };
121
+ }
122
+ function compareIndexDescending(left, right) {
123
+ return right.score - left.score || right.conversationId.localeCompare(left.conversationId);
124
+ }
125
+ function compareIndexAscending(left, right) {
126
+ return left.score - right.score || left.conversationId.localeCompare(right.conversationId);
127
+ }
128
+ function uniqueStrings(values) {
129
+ return [...new Set(values)];
130
+ }
131
+ function normalizeSource(value) {
132
+ const parsed = inboundMessageSourceSchema.safeParse(value);
133
+ return parsed.success ? parsed.data : void 0;
134
+ }
135
+ function normalizeExecutionStatus(value) {
136
+ if (value === "awaiting_resume" || value === "failed" || value === "idle" || value === "pending" || value === "running") {
137
+ return value;
138
+ }
139
+ return void 0;
140
+ }
141
+ function normalizeMessage(value, schemaVersion) {
142
+ const candidate = schemaVersion === 1 && isRecord(value) && value.delivery === void 0 ? {
143
+ ...value,
144
+ delivery: "defer"
145
+ } : value;
146
+ const parsed = inboundMessageSchema.safeParse(candidate);
147
+ return parsed.success ? parsed.data : void 0;
148
+ }
149
+ function isFinalAttempt(message) {
150
+ return (message.attemptCount ?? 0) >= CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS - 1;
151
+ }
152
+ function normalizeActor(value) {
153
+ return parseStoredSlackActor(value);
154
+ }
155
+ function normalizeLease(value) {
156
+ if (!isRecord(value)) {
157
+ return void 0;
158
+ }
159
+ const token = toOptionalString(value.token);
160
+ const acquiredAtMs = toOptionalNumber(value.acquiredAtMs);
161
+ const lastCheckInAtMs = toOptionalNumber(value.lastCheckInAtMs);
162
+ const expiresAtMs = toOptionalNumber(value.expiresAtMs);
163
+ if (!token || typeof acquiredAtMs !== "number" || typeof lastCheckInAtMs !== "number" || typeof expiresAtMs !== "number") {
164
+ return void 0;
165
+ }
166
+ return {
167
+ token,
168
+ acquiredAtMs,
169
+ lastCheckInAtMs,
170
+ expiresAtMs
171
+ };
172
+ }
173
+ function normalizeExecution(conversationId, value, schemaVersion) {
174
+ if (!isRecord(value)) {
175
+ return void 0;
176
+ }
177
+ const status = normalizeExecutionStatus(value.status);
178
+ if (!status) {
179
+ return void 0;
180
+ }
181
+ const pendingMessages2 = [];
182
+ if (Array.isArray(value.pendingMessages)) {
183
+ for (const rawMessage of value.pendingMessages) {
184
+ const message = normalizeMessage(rawMessage, schemaVersion);
185
+ if (!message || message.conversationId !== conversationId) {
186
+ return void 0;
187
+ }
188
+ if (message.injectedAtMs !== void 0) {
189
+ continue;
190
+ }
191
+ pendingMessages2.push(message);
192
+ }
193
+ pendingMessages2.sort(compareMessages);
194
+ }
195
+ const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(
196
+ value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))
197
+ ) : [];
198
+ const lease = normalizeLease(value.lease);
199
+ const normalizedStatus = status === "idle" && lease ? "running" : status === "idle" && pendingMessages2.length > 0 ? "pending" : status;
200
+ return {
201
+ status: normalizedStatus,
202
+ inboundMessageIds: uniqueStrings([
203
+ ...inboundMessageIds,
204
+ ...pendingMessages2.map((message) => message.inboundMessageId)
205
+ ]),
206
+ pendingCount: pendingMessages2.length,
207
+ pendingMessages: pendingMessages2,
208
+ lease,
209
+ lastCheckpointAtMs: toOptionalNumber(value.lastCheckpointAtMs),
210
+ lastEnqueuedAtMs: toOptionalNumber(value.lastEnqueuedAtMs),
211
+ lastProgressAtMs: toOptionalNumber(value.lastProgressAtMs),
212
+ retryCount: toOptionalNumber(value.retryCount),
213
+ runId: toOptionalString(value.runId),
214
+ updatedAtMs: toOptionalNumber(value.updatedAtMs)
215
+ };
216
+ }
217
+ function normalizeConversation(conversationId, value) {
218
+ if (!isRecord(value) || value.schemaVersion !== 1 && value.schemaVersion !== CONVERSATION_SCHEMA_VERSION) {
219
+ return void 0;
220
+ }
221
+ const schemaVersion = value.schemaVersion;
222
+ const storedConversationId = toOptionalString(value.conversationId);
223
+ const createdAtMs = toOptionalNumber(value.createdAtMs);
224
+ const lastActivityAtMs = toOptionalNumber(value.lastActivityAtMs);
225
+ const updatedAtMs = toOptionalNumber(value.updatedAtMs);
226
+ const execution = normalizeExecution(
227
+ conversationId,
228
+ value.execution,
229
+ schemaVersion
230
+ );
231
+ const destination = value.destination === void 0 ? void 0 : parseDestination(value.destination);
232
+ if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value.destination !== void 0 && !destination) {
233
+ return void 0;
234
+ }
235
+ if (execution.pendingMessages.length > 0 && execution.pendingMessages.some(
236
+ (message) => message.destination ? !destination || !sameDestination(message.destination, destination) : Boolean(destination)
237
+ )) {
238
+ return void 0;
239
+ }
240
+ return {
241
+ schemaVersion: CONVERSATION_SCHEMA_VERSION,
242
+ conversationId,
243
+ createdAtMs,
244
+ lastActivityAtMs,
245
+ updatedAtMs,
246
+ execution,
247
+ ...destination ? { destination } : {},
248
+ ...toOptionalString(value.title) ? { title: toOptionalString(value.title) } : {},
249
+ ...toOptionalString(value.channelName) ? { channelName: toOptionalString(value.channelName) } : {},
250
+ ...normalizeActor(value.actor) ? { actor: normalizeActor(value.actor) } : {},
251
+ ...normalizeSource(value.source) ? { source: normalizeSource(value.source) } : {}
252
+ };
253
+ }
254
+ function emptyConversation(args) {
255
+ return {
256
+ schemaVersion: CONVERSATION_SCHEMA_VERSION,
257
+ conversationId: args.conversationId,
258
+ createdAtMs: args.nowMs,
259
+ lastActivityAtMs: args.nowMs,
260
+ updatedAtMs: args.nowMs,
261
+ ...args.destination ? { destination: args.destination } : {},
262
+ ...args.source ? { source: args.source } : {},
263
+ execution: {
264
+ status: "idle",
265
+ inboundMessageIds: [],
266
+ pendingCount: 0,
267
+ pendingMessages: [],
268
+ updatedAtMs: args.nowMs
269
+ }
270
+ };
271
+ }
272
+ function isLeaseActive(lease, nowMs) {
273
+ return Boolean(lease && lease.expiresAtMs > nowMs);
274
+ }
275
+ function pendingMessages(conversation) {
276
+ return [...conversation.execution.pendingMessages].sort(compareMessages);
277
+ }
278
+ function isRunnableStatus(status) {
279
+ return status !== "failed" && status !== "idle";
280
+ }
281
+ function hasRunnableWork(conversation) {
282
+ return isRunnableStatus(conversation.execution.status) || pendingMessages(conversation).length > 0;
283
+ }
284
+ function executionWithPendingMessages(execution, pending) {
285
+ const pendingMessages2 = [...pending].sort(compareMessages);
286
+ const status = execution.status === "idle" && execution.lease ? "running" : execution.status === "idle" && pendingMessages2.length > 0 ? "pending" : execution.status;
287
+ return {
288
+ ...execution,
289
+ status,
290
+ inboundMessageIds: uniqueStrings([
291
+ ...execution.inboundMessageIds,
292
+ ...pendingMessages2.map((message) => message.inboundMessageId)
293
+ ]),
294
+ pendingMessages: pendingMessages2,
295
+ pendingCount: pendingMessages2.length
296
+ };
297
+ }
298
+ function withExecutionUpdate(conversation, execution, nowMs) {
299
+ return {
300
+ ...conversation,
301
+ updatedAtMs: nowMs,
302
+ execution: {
303
+ ...executionWithPendingMessages(execution, execution.pendingMessages),
304
+ updatedAtMs: nowMs
305
+ }
306
+ };
307
+ }
308
+ async function getConnectedState(stateAdapter) {
309
+ const state = stateAdapter ?? getStateAdapter();
310
+ await state.connect();
311
+ return state;
312
+ }
313
+ async function sleep(ms) {
314
+ await new Promise((resolve) => {
315
+ const timer = setTimeout(resolve, ms);
316
+ timer.unref?.();
317
+ });
318
+ }
319
+ async function withIndexLock(state, indexKey, callback) {
320
+ const startedAtMs = now();
321
+ let lock;
322
+ while (true) {
323
+ lock = await state.acquireLock(
324
+ indexLockKey(indexKey),
325
+ CONVERSATION_INDEX_LOCK_TTL_MS
326
+ );
327
+ if (lock) {
328
+ break;
329
+ }
330
+ if (now() - startedAtMs >= CONVERSATION_INDEX_LOCK_WAIT_MS) {
331
+ throw new Error(
332
+ `Could not acquire conversation index lock for ${indexKey}`
333
+ );
334
+ }
335
+ await sleep(CONVERSATION_INDEX_LOCK_RETRY_MS);
336
+ }
337
+ try {
338
+ return await callback();
339
+ } finally {
340
+ await state.releaseLock(lock);
341
+ }
342
+ }
343
+ function normalizeIndexEntry(value) {
344
+ if (!isRecord(value)) {
345
+ return void 0;
346
+ }
347
+ const conversationId = toOptionalString(value.conversationId);
348
+ const score = toOptionalNumber(value.score);
349
+ if (!conversationId || typeof score !== "number") {
350
+ return void 0;
351
+ }
352
+ return { conversationId, score };
353
+ }
354
+ function uniqueIndexEntries(value) {
355
+ if (!Array.isArray(value)) {
356
+ return [];
357
+ }
358
+ const entries = /* @__PURE__ */ new Map();
359
+ for (const item of value) {
360
+ const entry = normalizeIndexEntry(item);
361
+ if (!entry) {
362
+ continue;
363
+ }
364
+ const existing = entries.get(entry.conversationId);
365
+ if (!existing || entry.score > existing.score) {
366
+ entries.set(entry.conversationId, entry);
367
+ }
368
+ }
369
+ return [...entries.values()];
370
+ }
371
+ function retainedIndexEntries(indexKey, entries) {
372
+ if (indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
373
+ return entries.sort(compareIndexDescending).slice(0, CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH);
374
+ }
375
+ if (indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
376
+ return entries.sort(compareIndexAscending);
377
+ }
378
+ throw new Error(`Unknown conversation index ${indexKey}`);
379
+ }
380
+ function redisIndexKey(indexKey) {
381
+ const prefix = getChatConfig().state.keyPrefix;
382
+ return [...prefix ? [prefix] : [], indexKey].join(":");
383
+ }
384
+ function parseRedisIndexEntries(values) {
385
+ if (!Array.isArray(values)) {
386
+ return [];
387
+ }
388
+ const entries = [];
389
+ for (let index = 0; index < values.length; index += 2) {
390
+ const conversationId = toOptionalString(values[index]);
391
+ const score = typeof values[index + 1] === "number" ? values[index + 1] : Number(values[index + 1]);
392
+ if (!conversationId || !Number.isFinite(score)) {
393
+ continue;
394
+ }
395
+ entries.push({ conversationId, score });
396
+ }
397
+ return entries;
398
+ }
399
+ function redisConversationIndexStore(client) {
400
+ const upsertBoundedActivityScript = `
401
+ redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
402
+ redis.call("PEXPIRE", KEYS[1], ARGV[3])
403
+ local extra = redis.call("ZCARD", KEYS[1]) - tonumber(ARGV[4])
404
+ if extra > 0 then
405
+ redis.call("ZREMRANGEBYRANK", KEYS[1], 0, extra - 1)
406
+ end
407
+ return 1
408
+ `;
409
+ return {
410
+ async list(args) {
411
+ const key = redisIndexKey(args.indexKey);
412
+ const limit = args.limit;
413
+ const offset = Math.max(0, args.offset ?? 0);
414
+ if (limit === 0) {
415
+ return [];
416
+ }
417
+ const values = args.scoreMax !== void 0 ? await client.sendCommand([
418
+ "ZRANGEBYSCORE",
419
+ key,
420
+ "-inf",
421
+ String(args.scoreMax),
422
+ "WITHSCORES",
423
+ ...limit !== void 0 || offset > 0 ? ["LIMIT", String(offset), String(limit ?? 1e9)] : []
424
+ ]) : await client.sendCommand([
425
+ args.order === "asc" ? "ZRANGE" : "ZREVRANGE",
426
+ key,
427
+ String(offset),
428
+ String(
429
+ limit === void 0 ? -1 : offset + Math.max(0, limit - 1)
430
+ ),
431
+ "WITHSCORES"
432
+ ]);
433
+ return parseRedisIndexEntries(values);
434
+ },
435
+ async remove(args) {
436
+ await client.sendCommand([
437
+ "ZREM",
438
+ redisIndexKey(args.indexKey),
439
+ args.conversationId
440
+ ]);
441
+ },
442
+ async upsert(args) {
443
+ const key = redisIndexKey(args.indexKey);
444
+ if (args.indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
445
+ await client.sendCommand([
446
+ "EVAL",
447
+ upsertBoundedActivityScript,
448
+ "1",
449
+ key,
450
+ String(args.score),
451
+ args.conversationId,
452
+ String(JUNIOR_THREAD_STATE_TTL_MS),
453
+ String(CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH)
454
+ ]);
455
+ return;
456
+ }
457
+ if (args.indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
458
+ await client.sendCommand([
459
+ "ZADD",
460
+ key,
461
+ String(args.score),
462
+ args.conversationId
463
+ ]);
464
+ await client.sendCommand([
465
+ "PEXPIRE",
466
+ key,
467
+ String(JUNIOR_THREAD_STATE_TTL_MS)
468
+ ]);
469
+ return;
470
+ }
471
+ throw new Error(`Unknown conversation index ${args.indexKey}`);
472
+ }
473
+ };
474
+ }
475
+ function emulatedConversationIndexStore(state) {
476
+ const readIndex = async (indexKey) => uniqueIndexEntries(await state.get(indexKey));
477
+ const writeIndex = async (indexKey, entries) => {
478
+ await state.set(indexKey, entries, JUNIOR_THREAD_STATE_TTL_MS);
479
+ };
480
+ return {
481
+ async list(args) {
482
+ const entries = (await readIndex(args.indexKey)).filter(
483
+ (entry) => args.scoreMax === void 0 ? true : entry.score <= args.scoreMax
484
+ ).sort(
485
+ args.order === "asc" ? compareIndexAscending : compareIndexDescending
486
+ );
487
+ const offset = Math.max(0, args.offset ?? 0);
488
+ return entries.slice(
489
+ offset,
490
+ args.limit === void 0 ? entries.length : offset + args.limit
491
+ );
492
+ },
493
+ async remove(args) {
494
+ await withIndexLock(state, args.indexKey, async () => {
495
+ const entries = await readIndex(args.indexKey);
496
+ const next = entries.filter(
497
+ (entry) => entry.conversationId !== args.conversationId
498
+ );
499
+ if (next.length === entries.length) {
500
+ return;
501
+ }
502
+ await writeIndex(args.indexKey, next);
503
+ });
504
+ },
505
+ async upsert(args) {
506
+ await withIndexLock(state, args.indexKey, async () => {
507
+ const entries = await readIndex(args.indexKey);
508
+ const withoutCurrent = entries.filter(
509
+ (entry) => entry.conversationId !== args.conversationId
510
+ );
511
+ const next = retainedIndexEntries(args.indexKey, [
512
+ ...withoutCurrent,
513
+ { conversationId: args.conversationId, score: args.score }
514
+ ]);
515
+ await writeIndex(args.indexKey, next);
516
+ });
517
+ }
518
+ };
519
+ }
520
+ async function getConversationIndexStore(state) {
521
+ const redisStateAdapter = await getDefaultRedisStateAdapterFor(state);
522
+ if (redisStateAdapter) {
523
+ return redisConversationIndexStore(redisStateAdapter.getClient());
524
+ }
525
+ return emulatedConversationIndexStore(state);
526
+ }
527
+ async function upsertIndexEntry(args) {
528
+ const index = await getConversationIndexStore(args.state);
529
+ await index.upsert({
530
+ conversationId: args.conversationId,
531
+ indexKey: args.indexKey,
532
+ score: args.score
533
+ });
534
+ }
535
+ async function removeIndexEntry(args) {
536
+ const index = await getConversationIndexStore(args.state);
537
+ await index.remove({
538
+ conversationId: args.conversationId,
539
+ indexKey: args.indexKey
540
+ });
541
+ }
542
+ async function acquireMutationLock(state, conversationId) {
543
+ const startedAtMs = now();
544
+ while (true) {
545
+ const lock = await state.acquireLock(
546
+ mutationLockKey(conversationId),
547
+ CONVERSATION_MUTATION_LOCK_TTL_MS
548
+ );
549
+ if (lock) {
550
+ return lock;
551
+ }
552
+ if (now() - startedAtMs >= CONVERSATION_MUTATION_WAIT_MS) {
553
+ throw new Error(
554
+ `Could not acquire conversation mutation lock for ${conversationId}`
555
+ );
556
+ }
557
+ await sleep(CONVERSATION_MUTATION_RETRY_MS);
558
+ }
559
+ }
560
+ async function withConversationMutation(args, callback) {
561
+ const state = await getConnectedState(args.state);
562
+ const lock = await acquireMutationLock(state, args.conversationId);
563
+ try {
564
+ return await callback(state, lock);
565
+ } finally {
566
+ await state.releaseLock(lock);
567
+ }
568
+ }
569
+ async function readConversation(state, conversationId) {
570
+ const raw = await state.get(conversationKey(conversationId));
571
+ if (raw == null) {
572
+ return void 0;
573
+ }
574
+ const conversation = normalizeConversation(conversationId, raw);
575
+ if (!conversation) {
576
+ throw new InvalidConversationRecordError(conversationId);
577
+ }
578
+ return conversation;
579
+ }
580
+ async function writeConversation(state, lock, conversation) {
581
+ const execution = executionWithPendingMessages(
582
+ conversation.execution,
583
+ conversation.execution.pendingMessages
584
+ );
585
+ const next = {
586
+ ...conversation,
587
+ execution
588
+ };
589
+ const fenced = await state.extendLock(
590
+ lock,
591
+ CONVERSATION_MUTATION_LOCK_TTL_MS
592
+ );
593
+ if (!fenced) {
594
+ throw new ConversationMutationFencedError(next.conversationId);
595
+ }
596
+ await state.set(
597
+ conversationKey(next.conversationId),
598
+ next,
599
+ JUNIOR_THREAD_STATE_TTL_MS
600
+ );
601
+ await upsertIndexEntry({
602
+ state,
603
+ indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
604
+ conversationId: next.conversationId,
605
+ score: next.lastActivityAtMs
606
+ });
607
+ if (!hasRunnableWork(next)) {
608
+ await removeIndexEntry({
609
+ state,
610
+ indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
611
+ conversationId: next.conversationId
612
+ });
613
+ return;
614
+ }
615
+ await upsertIndexEntry({
616
+ state,
617
+ indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
618
+ conversationId: next.conversationId,
619
+ score: next.execution.updatedAtMs ?? next.updatedAtMs
620
+ });
621
+ }
622
+ function assertSameOptionalConversationDestination(args) {
623
+ if (!args.current && !args.next) {
624
+ return;
625
+ }
626
+ if (args.current && args.next && sameDestination(args.current, args.next)) {
627
+ return;
628
+ }
629
+ throw new Error(
630
+ `Conversation destination changed for ${args.conversationId}`
631
+ );
632
+ }
633
+ function conversationWorkState(conversation) {
634
+ const lease = conversation.execution.lease;
635
+ return {
636
+ ...conversation,
637
+ lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
638
+ ...lease ? {
639
+ lease: {
640
+ acquiredAtMs: lease.acquiredAtMs,
641
+ lastCheckInAtMs: lease.lastCheckInAtMs,
642
+ leaseExpiresAtMs: lease.expiresAtMs,
643
+ leaseToken: lease.token
644
+ }
645
+ } : {},
646
+ messages: pendingMessages(conversation),
647
+ needsRun: hasRunnableWork(conversation)
648
+ };
649
+ }
650
+ async function getConversation(args) {
651
+ const state = await getConnectedState(args.state);
652
+ return await readConversation(state, args.conversationId);
653
+ }
654
+ async function getConversationWorkState(args) {
655
+ const conversation = await getConversation(args);
656
+ return conversation ? conversationWorkState(conversation) : void 0;
657
+ }
658
+ async function appendInboundMessage(args) {
659
+ const nowMs = args.nowMs ?? now();
660
+ return await withConversationMutation(
661
+ { conversationId: args.message.conversationId, state: args.state },
662
+ async (state, lock) => {
663
+ const existing = await readConversation(
664
+ state,
665
+ args.message.conversationId
666
+ );
667
+ const current = existing ?? emptyConversation({
668
+ conversationId: args.message.conversationId,
669
+ destination: args.message.destination,
670
+ nowMs,
671
+ source: args.message.source
672
+ });
673
+ if (existing) {
674
+ assertSameOptionalConversationDestination({
675
+ conversationId: args.message.conversationId,
676
+ current: current.destination,
677
+ next: args.message.destination
678
+ });
679
+ }
680
+ const existingPending = current.execution.pendingMessages.some(
681
+ (message) => message.inboundMessageId === args.message.inboundMessageId
682
+ );
683
+ const existingMessage = current.execution.inboundMessageIds.includes(
684
+ args.message.inboundMessageId
685
+ );
686
+ if (existingMessage) {
687
+ if (!existingPending) {
688
+ return { status: "duplicate" };
689
+ }
690
+ const nextStatus = current.execution.status === "idle" ? "pending" : current.execution.status;
691
+ await writeConversation(
692
+ state,
693
+ lock,
694
+ withExecutionUpdate(
695
+ current,
696
+ {
697
+ ...current.execution,
698
+ status: nextStatus,
699
+ pendingMessages: current.execution.pendingMessages.map(
700
+ (message) => message.inboundMessageId === args.message.inboundMessageId ? upgradedPendingMessage(message, args.message) : message
701
+ )
702
+ },
703
+ nowMs
704
+ )
705
+ );
706
+ return { status: "duplicate" };
707
+ }
708
+ const status = current.execution.lease && current.execution.status === "running" ? "running" : current.execution.lease ? "awaiting_resume" : "pending";
709
+ const next = {
710
+ ...current,
711
+ destination: current.destination ?? args.message.destination,
712
+ source: current.source ?? args.message.source,
713
+ lastActivityAtMs: nowMs
714
+ };
715
+ await writeConversation(
716
+ state,
717
+ lock,
718
+ withExecutionUpdate(
719
+ next,
720
+ {
721
+ ...current.execution,
722
+ status,
723
+ inboundMessageIds: [
724
+ ...current.execution.inboundMessageIds,
725
+ args.message.inboundMessageId
726
+ ],
727
+ pendingMessages: [
728
+ ...current.execution.pendingMessages,
729
+ args.message
730
+ ].sort(compareMessages)
731
+ },
732
+ nowMs
733
+ )
734
+ );
735
+ return { status: "appended" };
736
+ }
737
+ );
738
+ }
739
+ async function requestConversationWork(args) {
740
+ const nowMs = args.nowMs ?? now();
741
+ return await withConversationMutation(args, async (state, lock) => {
742
+ const existing = await readConversation(state, args.conversationId);
743
+ if (existing) {
744
+ assertSameOptionalConversationDestination({
745
+ conversationId: args.conversationId,
746
+ current: existing.destination,
747
+ next: args.destination
748
+ });
749
+ }
750
+ const current = existing ?? emptyConversation({
751
+ conversationId: args.conversationId,
752
+ destination: args.destination,
753
+ nowMs
754
+ });
755
+ const status = current.execution.lease ? "awaiting_resume" : "pending";
756
+ await writeConversation(
757
+ state,
758
+ lock,
759
+ withExecutionUpdate(
760
+ {
761
+ ...current,
762
+ destination: current.destination ?? args.destination
763
+ },
764
+ {
765
+ ...current.execution,
766
+ status
767
+ },
768
+ nowMs
769
+ )
770
+ );
771
+ return { status: existing === void 0 ? "created" : "updated" };
772
+ });
773
+ }
774
+ async function markConversationWorkEnqueued(args) {
775
+ const nowMs = args.nowMs ?? now();
776
+ await withConversationMutation(args, async (state, lock) => {
777
+ const current = await readConversation(state, args.conversationId);
778
+ if (!current) {
779
+ return;
780
+ }
781
+ await writeConversation(
782
+ state,
783
+ lock,
784
+ withExecutionUpdate(
785
+ current,
786
+ {
787
+ ...current.execution,
788
+ lastEnqueuedAtMs: nowMs
789
+ },
790
+ nowMs
791
+ )
792
+ );
793
+ });
794
+ }
795
+ async function clearConsumedConversationWake(args) {
796
+ const nowMs = args.nowMs ?? now();
797
+ return await withConversationMutation(args, async (state, lock) => {
798
+ const current = await readConversation(state, args.conversationId);
799
+ if (!current || hasRunnableWork(current) || current.execution.lastEnqueuedAtMs === void 0) {
800
+ return false;
801
+ }
802
+ await writeConversation(
803
+ state,
804
+ lock,
805
+ withExecutionUpdate(
806
+ current,
807
+ {
808
+ ...current.execution,
809
+ lastEnqueuedAtMs: void 0
810
+ },
811
+ nowMs
812
+ )
813
+ );
814
+ return true;
815
+ });
816
+ }
817
+ async function startConversationWork(args) {
818
+ const nowMs = args.nowMs ?? now();
819
+ return await withConversationMutation(args, async (state, lock) => {
820
+ const current = await readConversation(state, args.conversationId);
821
+ if (!current) {
822
+ return { status: "no_work" };
823
+ }
824
+ if (isLeaseActive(current.execution.lease, nowMs)) {
825
+ return {
826
+ status: "active",
827
+ leaseExpiresAtMs: current.execution.lease.expiresAtMs
828
+ };
829
+ }
830
+ if (!hasRunnableWork(current)) {
831
+ return { status: "no_work" };
832
+ }
833
+ const lease = {
834
+ token: randomUUID(),
835
+ acquiredAtMs: nowMs,
836
+ lastCheckInAtMs: nowMs,
837
+ expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
838
+ };
839
+ const startsNewRun = current.execution.runId === void 0;
840
+ await writeConversation(
841
+ state,
842
+ lock,
843
+ withExecutionUpdate(
844
+ current,
845
+ {
846
+ ...current.execution,
847
+ lease,
848
+ status: current.execution.status === "awaiting_resume" ? "awaiting_resume" : "running",
849
+ runId: current.execution.runId ?? randomUUID(),
850
+ lastEnqueuedAtMs: void 0,
851
+ retryCount: startsNewRun ? 0 : current.execution.retryCount
852
+ },
853
+ nowMs
854
+ )
855
+ );
856
+ return {
857
+ status: "acquired",
858
+ leaseToken: lease.token,
859
+ leaseExpiresAtMs: lease.expiresAtMs
860
+ };
861
+ });
862
+ }
863
+ async function checkInConversationWork(args) {
864
+ const nowMs = args.nowMs ?? now();
865
+ return await withConversationMutation(args, async (state, lock) => {
866
+ const current = await readConversation(state, args.conversationId);
867
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
868
+ return false;
869
+ }
870
+ await writeConversation(
871
+ state,
872
+ lock,
873
+ withExecutionUpdate(
874
+ current,
875
+ {
876
+ ...current.execution,
877
+ lease: {
878
+ ...current.execution.lease,
879
+ lastCheckInAtMs: nowMs,
880
+ expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
881
+ }
882
+ },
883
+ nowMs
884
+ )
885
+ );
886
+ return true;
887
+ });
888
+ }
889
+ async function drainConversationMailbox(args) {
890
+ const nowMs = args.nowMs ?? now();
891
+ const pending = await withConversationMutation(args, async (state) => {
892
+ const current = await readConversation(state, args.conversationId);
893
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
894
+ throw new Error(
895
+ `Conversation lease is not held for ${args.conversationId}`
896
+ );
897
+ }
898
+ return pendingMessages(current);
899
+ });
900
+ if (pending.length === 0) {
901
+ return { changed: false, messages: [] };
902
+ }
903
+ const result = await args.handle(pending);
904
+ const pendingIds = new Set(
905
+ pending.map((message) => message.inboundMessageId)
906
+ );
907
+ const acknowledgedIds = new Set(
908
+ result ?? pending.map((message) => message.inboundMessageId)
909
+ );
910
+ for (const inboundMessageId of acknowledgedIds) {
911
+ if (!pendingIds.has(inboundMessageId)) {
912
+ throw new Error(
913
+ `Conversation mailbox drain result is not pending for ${args.conversationId}`
914
+ );
915
+ }
916
+ }
917
+ if (acknowledgedIds.size === 0) {
918
+ return { changed: false, messages: [] };
919
+ }
920
+ await withConversationMutation(args, async (state, lock) => {
921
+ const current = await readConversation(state, args.conversationId);
922
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
923
+ throw new Error(
924
+ `Conversation lease is not held for ${args.conversationId}`
925
+ );
926
+ }
927
+ const pendingMessages2 = current.execution.pendingMessages.filter(
928
+ (message) => !acknowledgedIds.has(message.inboundMessageId)
929
+ );
930
+ await writeConversation(
931
+ state,
932
+ lock,
933
+ withExecutionUpdate(
934
+ current,
935
+ {
936
+ ...current.execution,
937
+ status: current.execution.status === "pending" && pendingMessages2.length === 0 ? "running" : current.execution.status,
938
+ lastProgressAtMs: nowMs,
939
+ retryCount: 0,
940
+ pendingMessages: pendingMessages2
941
+ },
942
+ nowMs
943
+ )
944
+ );
945
+ });
946
+ return {
947
+ changed: true,
948
+ messages: pending.filter(
949
+ (message) => acknowledgedIds.has(message.inboundMessageId)
950
+ )
951
+ };
952
+ }
953
+ async function ackMessages(args) {
954
+ const nowMs = args.nowMs ?? now();
955
+ const inboundMessageIds = new Set(args.inboundMessageIds);
956
+ return await withConversationMutation(args, async (state, lock) => {
957
+ const current = await readConversation(state, args.conversationId);
958
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
959
+ return false;
960
+ }
961
+ if (inboundMessageIds.size === 0) {
962
+ return true;
963
+ }
964
+ const pendingMessages2 = current.execution.pendingMessages.filter(
965
+ (message) => !inboundMessageIds.has(message.inboundMessageId)
966
+ );
967
+ if (pendingMessages2.length === current.execution.pendingMessages.length) {
968
+ return true;
969
+ }
970
+ await writeConversation(
971
+ state,
972
+ lock,
973
+ withExecutionUpdate(
974
+ current,
975
+ {
976
+ ...current.execution,
977
+ lastProgressAtMs: nowMs,
978
+ retryCount: 0,
979
+ pendingMessages: pendingMessages2
980
+ },
981
+ nowMs
982
+ )
983
+ );
984
+ return true;
985
+ });
986
+ }
987
+ async function requestConversationContinuation(args) {
988
+ const nowMs = args.nowMs ?? now();
989
+ return await withConversationMutation(args, async (state, lock) => {
990
+ const current = await readConversation(state, args.conversationId);
991
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
992
+ return false;
993
+ }
994
+ assertSameOptionalConversationDestination({
995
+ conversationId: args.conversationId,
996
+ current: current.destination,
997
+ next: args.destination
998
+ });
999
+ await writeConversation(
1000
+ state,
1001
+ lock,
1002
+ withExecutionUpdate(
1003
+ current,
1004
+ {
1005
+ ...current.execution,
1006
+ status: "awaiting_resume"
1007
+ },
1008
+ nowMs
1009
+ )
1010
+ );
1011
+ return true;
1012
+ });
1013
+ }
1014
+ async function beginConversationResume(args) {
1015
+ const nowMs = args.nowMs ?? now();
1016
+ return await withConversationMutation(args, async (state, lock) => {
1017
+ const current = await readConversation(state, args.conversationId);
1018
+ if (!current || current.execution.lease?.token !== args.leaseToken || current.execution.status !== "awaiting_resume") {
1019
+ return false;
1020
+ }
1021
+ await writeConversation(
1022
+ state,
1023
+ lock,
1024
+ withExecutionUpdate(
1025
+ current,
1026
+ {
1027
+ ...current.execution,
1028
+ status: "running"
1029
+ },
1030
+ nowMs
1031
+ )
1032
+ );
1033
+ return true;
1034
+ });
1035
+ }
1036
+ async function releaseConversationWork(args) {
1037
+ const nowMs = args.nowMs ?? now();
1038
+ return await withConversationMutation(args, async (state, lock) => {
1039
+ const current = await readConversation(state, args.conversationId);
1040
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
1041
+ return false;
1042
+ }
1043
+ await writeConversation(
1044
+ state,
1045
+ lock,
1046
+ withExecutionUpdate(
1047
+ current,
1048
+ {
1049
+ ...current.execution,
1050
+ lease: void 0,
1051
+ status: current.execution.status === "running" ? "pending" : current.execution.status
1052
+ },
1053
+ nowMs
1054
+ )
1055
+ );
1056
+ return true;
1057
+ });
1058
+ }
1059
+ async function recordConversationRetry(args) {
1060
+ const nowMs = args.nowMs ?? now();
1061
+ return await withConversationMutation(args, async (state, lock) => {
1062
+ const current = await readConversation(state, args.conversationId);
1063
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
1064
+ return "lost_lease";
1065
+ }
1066
+ const count = (current.execution.retryCount ?? 0) + 1;
1067
+ const stopped = count >= CONVERSATION_WORK_MAX_RETRIES;
1068
+ await writeConversation(
1069
+ state,
1070
+ lock,
1071
+ withExecutionUpdate(
1072
+ current,
1073
+ {
1074
+ ...current.execution,
1075
+ lastEnqueuedAtMs: void 0,
1076
+ lease: stopped ? void 0 : current.execution.lease,
1077
+ retryCount: count,
1078
+ pendingMessages: stopped ? [] : current.execution.pendingMessages,
1079
+ runId: stopped ? void 0 : current.execution.runId,
1080
+ status: stopped ? "failed" : "awaiting_resume"
1081
+ },
1082
+ nowMs
1083
+ )
1084
+ );
1085
+ return stopped ? "stopped" : "recorded";
1086
+ });
1087
+ }
1088
+ async function completeConversationWork(args) {
1089
+ const nowMs = args.nowMs ?? now();
1090
+ return await withConversationMutation(args, async (state, lock) => {
1091
+ const current = await readConversation(state, args.conversationId);
1092
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
1093
+ return "lost_lease";
1094
+ }
1095
+ const hasPending = pendingMessages(current).length > 0;
1096
+ const needsRun = current.execution.status === "awaiting_resume";
1097
+ const runnable = needsRun || hasPending;
1098
+ await writeConversation(
1099
+ state,
1100
+ lock,
1101
+ withExecutionUpdate(
1102
+ current,
1103
+ {
1104
+ ...current.execution,
1105
+ lease: void 0,
1106
+ status: needsRun ? "awaiting_resume" : hasPending ? "pending" : "idle",
1107
+ lastProgressAtMs: args.madeProgress === false ? current.execution.lastProgressAtMs : nowMs,
1108
+ retryCount: runnable || args.madeProgress === false ? current.execution.retryCount : 0,
1109
+ runId: runnable ? current.execution.runId : void 0
1110
+ },
1111
+ nowMs
1112
+ )
1113
+ );
1114
+ return runnable ? "pending" : "completed";
1115
+ });
1116
+ }
1117
+ async function recordAttemptFailure(args) {
1118
+ const nowMs = args.nowMs ?? now();
1119
+ return await withConversationMutation(args, async (state, lock) => {
1120
+ const current = await readConversation(state, args.conversationId);
1121
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
1122
+ return {
1123
+ status: "lost_lease",
1124
+ pendingCount: 0,
1125
+ deadLetteredMessages: [],
1126
+ retryCount: 0
1127
+ };
1128
+ }
1129
+ const pendingIds = new Set(
1130
+ current.execution.pendingMessages.map(
1131
+ (message) => message.inboundMessageId
1132
+ )
1133
+ );
1134
+ if (args.inboundMessageIds.length === 0 || args.inboundMessageIds.some((id) => !pendingIds.has(id))) {
1135
+ return {
1136
+ status: "skipped",
1137
+ pendingCount: current.execution.pendingMessages.length,
1138
+ deadLetteredMessages: [],
1139
+ retryCount: current.execution.retryCount ?? 0
1140
+ };
1141
+ }
1142
+ const retryCount = (current.execution.retryCount ?? 0) + 1;
1143
+ const retriesExhausted = retryCount >= CONVERSATION_WORK_MAX_RETRIES;
1144
+ const attemptedIds = new Set(args.inboundMessageIds);
1145
+ const deadLetteredMessages = [];
1146
+ const pendingMessages2 = [];
1147
+ for (const message of current.execution.pendingMessages) {
1148
+ if (!attemptedIds.has(message.inboundMessageId)) {
1149
+ if (retriesExhausted) {
1150
+ deadLetteredMessages.push(message);
1151
+ } else {
1152
+ pendingMessages2.push(message);
1153
+ }
1154
+ continue;
1155
+ }
1156
+ const attempted = {
1157
+ ...message,
1158
+ attemptCount: (message.attemptCount ?? 0) + 1
1159
+ };
1160
+ if (retriesExhausted || attempted.attemptCount >= CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS) {
1161
+ deadLetteredMessages.push(attempted);
1162
+ continue;
1163
+ }
1164
+ pendingMessages2.push(attempted);
1165
+ }
1166
+ await writeConversation(
1167
+ state,
1168
+ lock,
1169
+ withExecutionUpdate(
1170
+ current,
1171
+ {
1172
+ ...current.execution,
1173
+ retryCount,
1174
+ pendingMessages: pendingMessages2
1175
+ },
1176
+ nowMs
1177
+ )
1178
+ );
1179
+ return {
1180
+ status: "recorded",
1181
+ pendingCount: pendingMessages2.length,
1182
+ deadLetteredMessages,
1183
+ retryCount
1184
+ };
1185
+ });
1186
+ }
1187
+ async function deadLetterAttempt(args) {
1188
+ const nowMs = args.nowMs ?? now();
1189
+ return await withConversationMutation(args, async (state, lock) => {
1190
+ const current = await readConversation(state, args.conversationId);
1191
+ if (!current || current.execution.lease?.token !== args.leaseToken) {
1192
+ return "lost_lease";
1193
+ }
1194
+ const runnable = pendingMessages(current).length > 0;
1195
+ await writeConversation(
1196
+ state,
1197
+ lock,
1198
+ withExecutionUpdate(
1199
+ current,
1200
+ {
1201
+ ...current.execution,
1202
+ lease: void 0,
1203
+ status: runnable ? "pending" : "failed",
1204
+ runId: runnable ? current.execution.runId : void 0
1205
+ },
1206
+ nowMs
1207
+ )
1208
+ );
1209
+ return runnable ? "pending" : "failed";
1210
+ });
1211
+ }
1212
+ async function clearExpiredConversationLease(args) {
1213
+ const nowMs = args.nowMs ?? now();
1214
+ return await withConversationMutation(args, async (state, lock) => {
1215
+ const current = await readConversation(state, args.conversationId);
1216
+ if (!current?.execution.lease || current.execution.lease.expiresAtMs > nowMs) {
1217
+ return "not_expired";
1218
+ }
1219
+ const retryCount = (current.execution.retryCount ?? 0) + 1;
1220
+ const stopped = retryCount >= CONVERSATION_WORK_MAX_RETRIES;
1221
+ await writeConversation(
1222
+ state,
1223
+ lock,
1224
+ withExecutionUpdate(
1225
+ current,
1226
+ {
1227
+ ...current.execution,
1228
+ lastEnqueuedAtMs: void 0,
1229
+ lease: void 0,
1230
+ retryCount,
1231
+ pendingMessages: stopped ? [] : current.execution.pendingMessages,
1232
+ runId: stopped ? void 0 : current.execution.runId,
1233
+ status: stopped ? "failed" : "awaiting_resume"
1234
+ },
1235
+ nowMs
1236
+ )
1237
+ );
1238
+ return stopped ? "stopped" : "requeued";
1239
+ });
1240
+ }
1241
+ async function removeActiveConversation(args) {
1242
+ const state = await getConnectedState(args.state);
1243
+ await removeIndexEntry({
1244
+ state,
1245
+ indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
1246
+ conversationId: args.conversationId
1247
+ });
1248
+ }
1249
+ async function listActiveConversationIds(args = {}) {
1250
+ const state = await getConnectedState(args.state);
1251
+ const index = await getConversationIndexStore(state);
1252
+ const entries = await index.list({
1253
+ indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
1254
+ limit: args.limit,
1255
+ order: "asc",
1256
+ scoreMax: args.staleBeforeMs
1257
+ });
1258
+ return entries.map((entry) => entry.conversationId);
1259
+ }
1260
+
1261
+ // src/chat/task-execution/store.ts
1262
+ function metadataStore(options) {
1263
+ return options.conversationStore ?? getConversationStore();
1264
+ }
1265
+ function duplicateInboundNudgeIdempotencyKey(message, nowMs) {
1266
+ return `duplicate:${message.conversationId}:${message.inboundMessageId}:${nowMs}`;
1267
+ }
1268
+ function hasRecentEnqueueMarker(conversation, nowMs) {
1269
+ const lastEnqueuedAtMs = conversation.execution.lastEnqueuedAtMs;
1270
+ return typeof lastEnqueuedAtMs === "number" && lastEnqueuedAtMs + CONVERSATION_WORK_STALE_ENQUEUE_MS > nowMs;
1271
+ }
1272
+ function now2() {
1273
+ return Date.now();
1274
+ }
1275
+ async function recordExecutionMetadata(args) {
1276
+ const conversation = await getConversation({
1277
+ conversationId: args.conversationId,
1278
+ state: args.state
1279
+ });
1280
+ if (!conversation) {
1281
+ return;
1282
+ }
1283
+ await metadataStore(args).recordExecution({
1284
+ channelName: conversation.channelName,
1285
+ conversationId: conversation.conversationId,
1286
+ createdAtMs: conversation.createdAtMs,
1287
+ destination: conversation.destination,
1288
+ execution: {
1289
+ lastCheckpointAtMs: conversation.execution.lastCheckpointAtMs,
1290
+ lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
1291
+ runId: conversation.execution.runId,
1292
+ status: conversation.execution.status,
1293
+ updatedAtMs: conversation.execution.updatedAtMs
1294
+ },
1295
+ lastActivityAtMs: conversation.lastActivityAtMs,
1296
+ metrics: null,
1297
+ actor: conversation.actor,
1298
+ source: conversation.source,
1299
+ title: conversation.title,
1300
+ updatedAtMs: conversation.updatedAtMs
1301
+ });
1302
+ }
1303
+ async function getConversationWorkState2(args) {
1304
+ return await getConversationWorkState(args);
1305
+ }
1306
+ async function recordConversationRetry2(args) {
1307
+ const result = await recordConversationRetry(args);
1308
+ await recordExecutionMetadata(args);
1309
+ return result;
1310
+ }
1311
+ function countPendingConversationMessages(conversation) {
1312
+ return conversation.execution.pendingMessages.length;
1313
+ }
1314
+ function hasRunnableConversationWork(conversation) {
1315
+ return conversation.execution.status !== "idle" || countPendingConversationMessages(conversation) > 0;
1316
+ }
1317
+ async function ensureConversationWake(args) {
1318
+ const nowMs = args.nowMs ?? now2();
1319
+ const conversation = await getConversation({
1320
+ conversationId: args.conversationId,
1321
+ state: args.state
1322
+ });
1323
+ if (!conversation || !hasRunnableConversationWork(conversation)) {
1324
+ return { status: "no_work" };
1325
+ }
1326
+ if (args.replaceExistingWake !== true && conversation.execution.lease && conversation.execution.lease.expiresAtMs > nowMs) {
1327
+ return { status: "lease_active" };
1328
+ }
1329
+ if (args.replaceExistingWake !== true && hasRecentEnqueueMarker(conversation, nowMs)) {
1330
+ return { status: "already_enqueued" };
1331
+ }
1332
+ const queueResult = await args.queue.send(
1333
+ {
1334
+ conversationId: args.conversationId
1335
+ },
1336
+ {
1337
+ delayMs: args.delayMs,
1338
+ idempotencyKey: args.idempotencyKey
1339
+ }
1340
+ );
1341
+ await markConversationWorkEnqueued2({
1342
+ conversationId: args.conversationId,
1343
+ conversationStore: args.conversationStore,
1344
+ nowMs,
1345
+ state: args.state
1346
+ });
1347
+ return { status: "enqueued", queueMessageId: queueResult?.messageId };
1348
+ }
1349
+ async function appendAndEnqueueInboundMessage(args) {
1350
+ const nowMs = args.nowMs ?? now2();
1351
+ const appendResult = await appendInboundMessage({
1352
+ message: args.message,
1353
+ nowMs,
1354
+ state: args.state
1355
+ });
1356
+ let idempotencyKey = args.message.inboundMessageId;
1357
+ if (appendResult.status === "duplicate") {
1358
+ const conversation = await getConversation({
1359
+ conversationId: args.message.conversationId,
1360
+ state: args.state
1361
+ });
1362
+ if (!conversation) {
1363
+ return appendResult;
1364
+ }
1365
+ if (hasRecentEnqueueMarker(conversation, nowMs)) {
1366
+ await recordExecutionMetadata({
1367
+ conversationId: args.message.conversationId,
1368
+ conversationStore: args.conversationStore,
1369
+ state: args.state
1370
+ });
1371
+ return appendResult;
1372
+ }
1373
+ const duplicateStillPending = conversation.execution.pendingMessages.some(
1374
+ (message) => message.inboundMessageId === args.message.inboundMessageId
1375
+ );
1376
+ if (!duplicateStillPending) {
1377
+ await recordExecutionMetadata({
1378
+ conversationId: args.message.conversationId,
1379
+ conversationStore: args.conversationStore,
1380
+ state: args.state
1381
+ });
1382
+ return appendResult;
1383
+ }
1384
+ idempotencyKey = duplicateInboundNudgeIdempotencyKey(args.message, nowMs);
1385
+ }
1386
+ const wake = await ensureConversationWake({
1387
+ conversationId: args.message.conversationId,
1388
+ conversationStore: args.conversationStore,
1389
+ idempotencyKey,
1390
+ nowMs,
1391
+ queue: args.queue,
1392
+ state: args.state
1393
+ });
1394
+ if (wake.status !== "enqueued") {
1395
+ await recordExecutionMetadata({
1396
+ conversationId: args.message.conversationId,
1397
+ conversationStore: args.conversationStore,
1398
+ state: args.state
1399
+ });
1400
+ }
1401
+ return {
1402
+ ...appendResult,
1403
+ ...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : {}
1404
+ };
1405
+ }
1406
+ async function clearConsumedConversationWake2(args) {
1407
+ const result = await clearConsumedConversationWake(args);
1408
+ if (result) {
1409
+ await recordExecutionMetadata(args);
1410
+ }
1411
+ return result;
1412
+ }
1413
+ async function requestConversationWork2(args) {
1414
+ const result = await requestConversationWork(args);
1415
+ await recordExecutionMetadata({
1416
+ conversationId: args.conversationId,
1417
+ conversationStore: args.conversationStore,
1418
+ state: args.state
1419
+ });
1420
+ return result;
1421
+ }
1422
+ async function markConversationWorkEnqueued2(args) {
1423
+ await markConversationWorkEnqueued(args);
1424
+ await recordExecutionMetadata(args);
1425
+ }
1426
+ async function startConversationWork2(args) {
1427
+ const result = await startConversationWork(args);
1428
+ await recordExecutionMetadata(args);
1429
+ return result;
1430
+ }
1431
+ async function checkInConversationWork2(args) {
1432
+ const result = await checkInConversationWork(args);
1433
+ if (result) {
1434
+ await recordExecutionMetadata(args);
1435
+ }
1436
+ return result;
1437
+ }
1438
+ async function drainConversationMailbox2(args) {
1439
+ const result = await drainConversationMailbox(args);
1440
+ if (result.changed) {
1441
+ await recordExecutionMetadata(args);
1442
+ }
1443
+ return result.messages;
1444
+ }
1445
+ async function ackMessages2(args) {
1446
+ const result = await ackMessages(args);
1447
+ await recordExecutionMetadata(args);
1448
+ return result;
1449
+ }
1450
+ async function requestConversationContinuation2(args) {
1451
+ const result = await requestConversationContinuation(args);
1452
+ await recordExecutionMetadata(args);
1453
+ return result;
1454
+ }
1455
+ async function beginConversationResume2(args) {
1456
+ const result = await beginConversationResume(args);
1457
+ if (result) {
1458
+ await recordExecutionMetadata(args);
1459
+ }
1460
+ return result;
1461
+ }
1462
+ async function releaseConversationWork2(args) {
1463
+ const result = await releaseConversationWork(args);
1464
+ await recordExecutionMetadata(args);
1465
+ return result;
1466
+ }
1467
+ async function completeConversationWork2(args) {
1468
+ const result = await completeConversationWork(args);
1469
+ await recordExecutionMetadata(args);
1470
+ return result;
1471
+ }
1472
+ async function recordAttemptFailure2(args) {
1473
+ const result = await recordAttemptFailure(args);
1474
+ if (result.status === "recorded") {
1475
+ await recordExecutionMetadata(args);
1476
+ }
1477
+ return result;
1478
+ }
1479
+ async function deadLetterAttempt2(args) {
1480
+ const result = await deadLetterAttempt(args);
1481
+ await recordExecutionMetadata(args);
1482
+ return result;
1483
+ }
1484
+ async function clearExpiredConversationLease2(args) {
1485
+ const result = await clearExpiredConversationLease(args);
1486
+ await recordExecutionMetadata(args);
1487
+ return result;
1488
+ }
1489
+ async function removeActiveConversation2(args) {
1490
+ return await removeActiveConversation(args);
1491
+ }
1492
+ async function listActiveConversationIds2(args = {}) {
1493
+ return await listActiveConversationIds(args);
1494
+ }
1495
+
1496
+ export {
1497
+ isInvalidConversationRecordError,
1498
+ CONVERSATION_WORK_CHECK_IN_INTERVAL_MS,
1499
+ CONVERSATION_WORK_STALE_ENQUEUE_MS,
1500
+ CONVERSATION_WORK_MAX_RETRIES,
1501
+ isFinalAttempt,
1502
+ getConversationWorkState2 as getConversationWorkState,
1503
+ recordConversationRetry2 as recordConversationRetry,
1504
+ countPendingConversationMessages,
1505
+ hasRunnableConversationWork,
1506
+ ensureConversationWake,
1507
+ appendAndEnqueueInboundMessage,
1508
+ clearConsumedConversationWake2 as clearConsumedConversationWake,
1509
+ requestConversationWork2 as requestConversationWork,
1510
+ startConversationWork2 as startConversationWork,
1511
+ checkInConversationWork2 as checkInConversationWork,
1512
+ drainConversationMailbox2 as drainConversationMailbox,
1513
+ ackMessages2 as ackMessages,
1514
+ requestConversationContinuation2 as requestConversationContinuation,
1515
+ beginConversationResume2 as beginConversationResume,
1516
+ releaseConversationWork2 as releaseConversationWork,
1517
+ completeConversationWork2 as completeConversationWork,
1518
+ recordAttemptFailure2 as recordAttemptFailure,
1519
+ deadLetterAttempt2 as deadLetterAttempt,
1520
+ clearExpiredConversationLease2 as clearExpiredConversationLease,
1521
+ removeActiveConversation2 as removeActiveConversation,
1522
+ listActiveConversationIds2 as listActiveConversationIds
1523
+ };