@sentry/junior 0.107.1 → 0.109.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 (68) hide show
  1. package/dist/{agent-hooks-ICPIJAFY.js → agent-hooks-FHHVLNPA.js} +12 -12
  2. package/dist/api/conversations/events.d.ts +1 -1
  3. package/dist/api/conversations/list.d.ts +1 -0
  4. package/dist/api/conversations/schema.d.ts +57 -6
  5. package/dist/api/schema.js +1 -1
  6. package/dist/api.js +116 -27
  7. package/dist/app.d.ts +1 -0
  8. package/dist/app.js +1741 -458
  9. package/dist/{catalog-runtime-FOFNPR3P.js → catalog-runtime-DMGJSLV2.js} +6 -4
  10. package/dist/chat/conversations/history.d.ts +16 -5
  11. package/dist/chat/conversations/message-projection.d.ts +3 -5
  12. package/dist/chat/conversations/sql/store.d.ts +0 -7
  13. package/dist/chat/log-context.d.ts +40 -0
  14. package/dist/chat/logging.d.ts +3 -26
  15. package/dist/chat/resource-events/store.d.ts +6 -0
  16. package/dist/chat/runtime/slack-resume.d.ts +2 -2
  17. package/dist/chat/runtime/slack-runtime.d.ts +3 -0
  18. package/dist/chat/services/turn-session-record.d.ts +0 -2
  19. package/dist/chat/slack/reply.d.ts +7 -19
  20. package/dist/chat/state/conversation.d.ts +1 -0
  21. package/dist/chat/task-execution/slack-work.d.ts +237 -10
  22. package/dist/chat/tool-support/turn-deadline-result.d.ts +3 -0
  23. package/dist/chunk-3SXUV423.js +10 -0
  24. package/dist/{chunk-YFQ7CQDE.js → chunk-72OMGPDS.js} +1017 -39
  25. package/dist/{chunk-2XXEKR44.js → chunk-7Q6WCISF.js} +1 -1
  26. package/dist/{chunk-NVOTGWYX.js → chunk-FENLIFJD.js} +97 -601
  27. package/dist/{chunk-IGHMVDWI.js → chunk-FWJRXN4F.js} +3 -3
  28. package/dist/{chunk-PUAMO4PI.js → chunk-HHVY4SMP.js} +41 -7
  29. package/dist/{chunk-SPUAJVVH.js → chunk-HO5NT6OE.js} +5 -7
  30. package/dist/{chunk-O24R4DCK.js → chunk-ISMWX44P.js} +93 -55
  31. package/dist/{chunk-7FBGKXPE.js → chunk-IVVGFRQQ.js} +5 -0
  32. package/dist/{chunk-EDLNHZH3.js → chunk-IXKSQGIO.js} +226 -191
  33. package/dist/{chunk-SS67LUOK.js → chunk-JNAVF45E.js} +6 -7
  34. package/dist/{chunk-DY7TRYB5.js → chunk-MGUMR35T.js} +1 -1
  35. package/dist/{chunk-CQ7KSO2B.js → chunk-MXW4GL53.js} +11 -15
  36. package/dist/{chunk-RT5BUHR5.js → chunk-O3JMSZLI.js} +1 -1
  37. package/dist/chunk-OCD3OZRK.js +125 -0
  38. package/dist/{chunk-B2Z2H66D.js → chunk-OUHNWH46.js} +60 -5
  39. package/dist/{chunk-VIXFG2VC.js → chunk-PLB7MRCQ.js} +1 -2
  40. package/dist/{chunk-RMVOAJRL.js → chunk-QY636HZU.js} +114 -12
  41. package/dist/{chunk-VH6KWKG2.js → chunk-RGX4V75M.js} +3 -3
  42. package/dist/{chunk-B7PUBQQM.js → chunk-SYAQIR5Z.js} +1 -1
  43. package/dist/chunk-TMBRFULF.js +471 -0
  44. package/dist/{chunk-YIPD3L6L.js → chunk-TT6GMXNA.js} +8 -10
  45. package/dist/{chunk-YT72TOEK.js → chunk-WHMOBKT7.js} +2 -2
  46. package/dist/cli/chat.js +23 -23
  47. package/dist/cli/check.js +8 -6
  48. package/dist/cli/plugins.js +16 -16
  49. package/dist/cli/snapshot-warmup.js +10 -9
  50. package/dist/cli/upgrade.js +314 -3505
  51. package/dist/db/db.d.ts +1 -1
  52. package/dist/{db-DIGO4TGW.js → db-V3NU72O2.js} +8 -6
  53. package/dist/instrumentation.js +3 -2
  54. package/dist/nitro.js +5 -4
  55. package/dist/{runner-ACR2HAIC.js → runner-JYBCQBLK.js} +17 -20
  56. package/dist/{skills-ITNHBARB.js → skills-U6MDAST7.js} +7 -5
  57. package/dist/{validation-AGQ46ZGV.js → validation-72N3JVRU.js} +7 -5
  58. package/dist/version.d.ts +2 -0
  59. package/dist/version.js +7 -0
  60. package/migrations/0006_drop_legacy_conversation_messages.sql +1 -0
  61. package/migrations/README.md +12 -9
  62. package/migrations/meta/0006_snapshot.json +948 -0
  63. package/migrations/meta/_journal.json +7 -0
  64. package/package.json +11 -7
  65. package/dist/chunk-4YF7Z6IA.js +0 -1061
  66. package/dist/chunk-AUUOHQAT.js +0 -115
  67. package/dist/chunk-G3E7SCME.js +0 -28
  68. package/dist/chunk-YNP2ATQX.js +0 -1282
@@ -1,1282 +0,0 @@
1
- import {
2
- JUNIOR_THREAD_STATE_TTL_MS
3
- } from "./chunk-4YF7Z6IA.js";
4
- import {
5
- getDefaultRedisStateAdapterFor,
6
- getStateAdapter
7
- } from "./chunk-B2Z2H66D.js";
8
- import {
9
- getChatConfig
10
- } from "./chunk-SS67LUOK.js";
11
- import {
12
- parseDestination,
13
- sameDestination
14
- } from "./chunk-B7PUBQQM.js";
15
- import {
16
- parseStoredSlackActor
17
- } from "./chunk-VIXFG2VC.js";
18
- import {
19
- isRecord,
20
- toOptionalNumber,
21
- toOptionalString
22
- } from "./chunk-OB42YVAE.js";
23
-
24
- // src/chat/task-execution/state.ts
25
- import { randomUUID } from "crypto";
26
- var CONVERSATION_PREFIX = "junior:conversation";
27
- var CONVERSATION_SCHEMA_VERSION = 1;
28
- var CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH = 1e4;
29
- var CONVERSATION_INDEX_LOCK_TTL_MS = 1e4;
30
- var CONVERSATION_INDEX_LOCK_WAIT_MS = 2e3;
31
- var CONVERSATION_INDEX_LOCK_RETRY_MS = 25;
32
- var CONVERSATION_MUTATION_LOCK_TTL_MS = 1e4;
33
- var CONVERSATION_MUTATION_WAIT_MS = 1e4;
34
- var CONVERSATION_MUTATION_RETRY_MS = 25;
35
- var InvalidConversationRecordError = class extends Error {
36
- constructor(conversationId) {
37
- super(`Conversation record is invalid for ${conversationId}`);
38
- this.name = "InvalidConversationRecordError";
39
- }
40
- };
41
- function isInvalidConversationRecordError(error) {
42
- return error instanceof InvalidConversationRecordError;
43
- }
44
- var ConversationMutationFencedError = class extends Error {
45
- constructor(conversationId) {
46
- super(
47
- `Conversation mutation lock was lost before write for ${conversationId}`
48
- );
49
- this.name = "ConversationMutationFencedError";
50
- }
51
- };
52
- var CONVERSATION_BY_ACTIVITY_INDEX_KEY = `${CONVERSATION_PREFIX}:by-activity`;
53
- var CONVERSATION_ACTIVE_INDEX_KEY = `${CONVERSATION_PREFIX}:active`;
54
- var CONVERSATION_WORK_LEASE_TTL_MS = 9e4;
55
- var CONVERSATION_WORK_CHECK_IN_INTERVAL_MS = 15e3;
56
- var CONVERSATION_WORK_STALE_ENQUEUE_MS = 6e4;
57
- var CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS = 5;
58
- function conversationKey(conversationId) {
59
- return `${CONVERSATION_PREFIX}:${conversationId}`;
60
- }
61
- function indexLockKey(indexKey) {
62
- return `${indexKey}:lock`;
63
- }
64
- function mutationLockKey(conversationId) {
65
- return `${CONVERSATION_PREFIX}:mutation:${conversationId}`;
66
- }
67
- function now() {
68
- return Date.now();
69
- }
70
- function compareMessages(left, right) {
71
- return left.createdAtMs - right.createdAtMs || left.receivedAtMs - right.receivedAtMs || left.inboundMessageId.localeCompare(right.inboundMessageId);
72
- }
73
- function inputHasAttachments(input) {
74
- return Array.isArray(input.attachments) && input.attachments.length > 0;
75
- }
76
- function upgradedPendingMessage(stored, duplicate) {
77
- if (!inputHasAttachments(duplicate.input) || inputHasAttachments(stored.input)) {
78
- return stored;
79
- }
80
- return { ...stored, input: duplicate.input };
81
- }
82
- function compareIndexDescending(left, right) {
83
- return right.score - left.score || right.conversationId.localeCompare(left.conversationId);
84
- }
85
- function compareIndexAscending(left, right) {
86
- return left.score - right.score || left.conversationId.localeCompare(right.conversationId);
87
- }
88
- function uniqueStrings(values) {
89
- return [...new Set(values)];
90
- }
91
- function normalizeSource(value) {
92
- if (value === "api" || value === "internal" || value === "local" || value === "plugin" || value === "resource_event" || value === "scheduler" || value === "slack") {
93
- return value;
94
- }
95
- return void 0;
96
- }
97
- function normalizeExecutionStatus(value) {
98
- if (value === "awaiting_resume" || value === "failed" || value === "idle" || value === "pending" || value === "running") {
99
- return value;
100
- }
101
- return void 0;
102
- }
103
- function normalizeMetadata(value) {
104
- if (!isRecord(value)) {
105
- return void 0;
106
- }
107
- return value;
108
- }
109
- function normalizeInput(value) {
110
- if (!isRecord(value)) {
111
- return void 0;
112
- }
113
- const text = toOptionalString(value.text);
114
- if (!text) {
115
- return void 0;
116
- }
117
- return {
118
- text,
119
- authorId: toOptionalString(value.authorId),
120
- attachments: Array.isArray(value.attachments) ? [...value.attachments] : void 0,
121
- metadata: normalizeMetadata(value.metadata)
122
- };
123
- }
124
- function normalizeMessage(value) {
125
- if (!isRecord(value)) {
126
- return void 0;
127
- }
128
- const conversationId = toOptionalString(value.conversationId);
129
- const inboundMessageId = toOptionalString(value.inboundMessageId);
130
- const source = normalizeSource(value.source);
131
- const destination = parseDestination(value.destination);
132
- const createdAtMs = toOptionalNumber(value.createdAtMs);
133
- const receivedAtMs = toOptionalNumber(value.receivedAtMs);
134
- const input = normalizeInput(value.input);
135
- if (!conversationId || !destination || !inboundMessageId || !source || typeof createdAtMs !== "number" || typeof receivedAtMs !== "number" || !input) {
136
- return void 0;
137
- }
138
- return {
139
- conversationId,
140
- destination,
141
- inboundMessageId,
142
- source,
143
- createdAtMs,
144
- receivedAtMs,
145
- input,
146
- injectedAtMs: toOptionalNumber(value.injectedAtMs),
147
- attemptCount: toOptionalNumber(value.attemptCount)
148
- };
149
- }
150
- function isFinalAttempt(message) {
151
- return (message.attemptCount ?? 0) >= CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS - 1;
152
- }
153
- function normalizeActor(value) {
154
- return parseStoredSlackActor(value);
155
- }
156
- function normalizeLease(value) {
157
- if (!isRecord(value)) {
158
- return void 0;
159
- }
160
- const token = toOptionalString(value.token);
161
- const acquiredAtMs = toOptionalNumber(value.acquiredAtMs);
162
- const lastCheckInAtMs = toOptionalNumber(value.lastCheckInAtMs);
163
- const expiresAtMs = toOptionalNumber(value.expiresAtMs);
164
- if (!token || typeof acquiredAtMs !== "number" || typeof lastCheckInAtMs !== "number" || typeof expiresAtMs !== "number") {
165
- return void 0;
166
- }
167
- return {
168
- token,
169
- acquiredAtMs,
170
- lastCheckInAtMs,
171
- expiresAtMs
172
- };
173
- }
174
- function normalizeExecution(conversationId, value) {
175
- if (!isRecord(value)) {
176
- return void 0;
177
- }
178
- const status = normalizeExecutionStatus(value.status);
179
- if (!status) {
180
- return void 0;
181
- }
182
- const pendingMessages2 = Array.isArray(value.pendingMessages) ? value.pendingMessages.map(normalizeMessage).filter((message) => Boolean(message)).filter((message) => message.conversationId === conversationId).filter((message) => message.injectedAtMs === void 0).sort(compareMessages) : [];
183
- const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(
184
- value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))
185
- ) : [];
186
- const lease = normalizeLease(value.lease);
187
- const normalizedStatus = status === "idle" && lease ? "running" : status === "idle" && pendingMessages2.length > 0 ? "pending" : status;
188
- return {
189
- status: normalizedStatus,
190
- inboundMessageIds: uniqueStrings([
191
- ...inboundMessageIds,
192
- ...pendingMessages2.map((message) => message.inboundMessageId)
193
- ]),
194
- pendingCount: pendingMessages2.length,
195
- pendingMessages: pendingMessages2,
196
- lease,
197
- lastCheckpointAtMs: toOptionalNumber(value.lastCheckpointAtMs),
198
- lastEnqueuedAtMs: toOptionalNumber(value.lastEnqueuedAtMs),
199
- runId: toOptionalString(value.runId),
200
- updatedAtMs: toOptionalNumber(value.updatedAtMs)
201
- };
202
- }
203
- function normalizeConversation(conversationId, value) {
204
- if (!isRecord(value) || value.schemaVersion !== CONVERSATION_SCHEMA_VERSION) {
205
- return void 0;
206
- }
207
- const storedConversationId = toOptionalString(value.conversationId);
208
- const createdAtMs = toOptionalNumber(value.createdAtMs);
209
- const lastActivityAtMs = toOptionalNumber(value.lastActivityAtMs);
210
- const updatedAtMs = toOptionalNumber(value.updatedAtMs);
211
- const execution = normalizeExecution(conversationId, value.execution);
212
- const destination = value.destination === void 0 ? void 0 : parseDestination(value.destination);
213
- if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value.destination !== void 0 && !destination) {
214
- return void 0;
215
- }
216
- if (execution.pendingMessages.length > 0 && (!destination || execution.pendingMessages.some(
217
- (message) => !sameDestination(message.destination, destination)
218
- ))) {
219
- return void 0;
220
- }
221
- return {
222
- schemaVersion: CONVERSATION_SCHEMA_VERSION,
223
- conversationId,
224
- createdAtMs,
225
- lastActivityAtMs,
226
- updatedAtMs,
227
- execution,
228
- ...destination ? { destination } : {},
229
- ...toOptionalString(value.title) ? { title: toOptionalString(value.title) } : {},
230
- ...toOptionalString(value.channelName) ? { channelName: toOptionalString(value.channelName) } : {},
231
- ...normalizeActor(value.actor) ? { actor: normalizeActor(value.actor) } : {},
232
- ...normalizeSource(value.source) ? { source: normalizeSource(value.source) } : {}
233
- };
234
- }
235
- function emptyConversation(args) {
236
- return {
237
- schemaVersion: CONVERSATION_SCHEMA_VERSION,
238
- conversationId: args.conversationId,
239
- createdAtMs: args.nowMs,
240
- lastActivityAtMs: args.nowMs,
241
- updatedAtMs: args.nowMs,
242
- ...args.destination ? { destination: args.destination } : {},
243
- ...args.source ? { source: args.source } : {},
244
- execution: {
245
- status: "idle",
246
- inboundMessageIds: [],
247
- pendingCount: 0,
248
- pendingMessages: [],
249
- updatedAtMs: args.nowMs
250
- }
251
- };
252
- }
253
- function isLeaseActive(lease, nowMs) {
254
- return Boolean(lease && lease.expiresAtMs > nowMs);
255
- }
256
- function pendingMessages(conversation) {
257
- return [...conversation.execution.pendingMessages].sort(compareMessages);
258
- }
259
- function isRunnableStatus(status) {
260
- return status !== "failed" && status !== "idle";
261
- }
262
- function hasRunnableWork(conversation) {
263
- return isRunnableStatus(conversation.execution.status) || pendingMessages(conversation).length > 0;
264
- }
265
- function executionWithPendingMessages(execution, pending) {
266
- const pendingMessages2 = [...pending].sort(compareMessages);
267
- const status = execution.status === "idle" && execution.lease ? "running" : execution.status === "idle" && pendingMessages2.length > 0 ? "pending" : execution.status;
268
- return {
269
- ...execution,
270
- status,
271
- inboundMessageIds: uniqueStrings([
272
- ...execution.inboundMessageIds,
273
- ...pendingMessages2.map((message) => message.inboundMessageId)
274
- ]),
275
- pendingMessages: pendingMessages2,
276
- pendingCount: pendingMessages2.length
277
- };
278
- }
279
- function withExecutionUpdate(conversation, execution, nowMs) {
280
- return {
281
- ...conversation,
282
- updatedAtMs: nowMs,
283
- execution: {
284
- ...executionWithPendingMessages(execution, execution.pendingMessages),
285
- updatedAtMs: nowMs
286
- }
287
- };
288
- }
289
- async function getConnectedState(stateAdapter) {
290
- const state = stateAdapter ?? getStateAdapter();
291
- await state.connect();
292
- return state;
293
- }
294
- async function sleep(ms) {
295
- await new Promise((resolve) => {
296
- const timer = setTimeout(resolve, ms);
297
- timer.unref?.();
298
- });
299
- }
300
- async function withIndexLock(state, indexKey, callback) {
301
- const startedAtMs = now();
302
- let lock;
303
- while (true) {
304
- lock = await state.acquireLock(
305
- indexLockKey(indexKey),
306
- CONVERSATION_INDEX_LOCK_TTL_MS
307
- );
308
- if (lock) {
309
- break;
310
- }
311
- if (now() - startedAtMs >= CONVERSATION_INDEX_LOCK_WAIT_MS) {
312
- throw new Error(
313
- `Could not acquire conversation index lock for ${indexKey}`
314
- );
315
- }
316
- await sleep(CONVERSATION_INDEX_LOCK_RETRY_MS);
317
- }
318
- try {
319
- return await callback();
320
- } finally {
321
- await state.releaseLock(lock);
322
- }
323
- }
324
- function normalizeIndexEntry(value) {
325
- if (!isRecord(value)) {
326
- return void 0;
327
- }
328
- const conversationId = toOptionalString(value.conversationId);
329
- const score = toOptionalNumber(value.score);
330
- if (!conversationId || typeof score !== "number") {
331
- return void 0;
332
- }
333
- return { conversationId, score };
334
- }
335
- function uniqueIndexEntries(value) {
336
- if (!Array.isArray(value)) {
337
- return [];
338
- }
339
- const entries = /* @__PURE__ */ new Map();
340
- for (const item of value) {
341
- const entry = normalizeIndexEntry(item);
342
- if (!entry) {
343
- continue;
344
- }
345
- const existing = entries.get(entry.conversationId);
346
- if (!existing || entry.score > existing.score) {
347
- entries.set(entry.conversationId, entry);
348
- }
349
- }
350
- return [...entries.values()];
351
- }
352
- function retainedIndexEntries(indexKey, entries) {
353
- if (indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
354
- return entries.sort(compareIndexDescending).slice(0, CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH);
355
- }
356
- if (indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
357
- return entries.sort(compareIndexAscending);
358
- }
359
- throw new Error(`Unknown conversation index ${indexKey}`);
360
- }
361
- function redisIndexKey(indexKey) {
362
- const prefix = getChatConfig().state.keyPrefix;
363
- return [...prefix ? [prefix] : [], indexKey].join(":");
364
- }
365
- function parseRedisIndexEntries(values) {
366
- if (!Array.isArray(values)) {
367
- return [];
368
- }
369
- const entries = [];
370
- for (let index = 0; index < values.length; index += 2) {
371
- const conversationId = toOptionalString(values[index]);
372
- const score = typeof values[index + 1] === "number" ? values[index + 1] : Number(values[index + 1]);
373
- if (!conversationId || !Number.isFinite(score)) {
374
- continue;
375
- }
376
- entries.push({ conversationId, score });
377
- }
378
- return entries;
379
- }
380
- function redisConversationIndexStore(client) {
381
- const upsertBoundedActivityScript = `
382
- redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
383
- redis.call("PEXPIRE", KEYS[1], ARGV[3])
384
- local extra = redis.call("ZCARD", KEYS[1]) - tonumber(ARGV[4])
385
- if extra > 0 then
386
- redis.call("ZREMRANGEBYRANK", KEYS[1], 0, extra - 1)
387
- end
388
- return 1
389
- `;
390
- return {
391
- async list(args) {
392
- const key = redisIndexKey(args.indexKey);
393
- const limit = args.limit;
394
- const offset = Math.max(0, args.offset ?? 0);
395
- if (limit === 0) {
396
- return [];
397
- }
398
- const values = args.scoreMax !== void 0 ? await client.sendCommand([
399
- "ZRANGEBYSCORE",
400
- key,
401
- "-inf",
402
- String(args.scoreMax),
403
- "WITHSCORES",
404
- ...limit !== void 0 || offset > 0 ? ["LIMIT", String(offset), String(limit ?? 1e9)] : []
405
- ]) : await client.sendCommand([
406
- args.order === "asc" ? "ZRANGE" : "ZREVRANGE",
407
- key,
408
- String(offset),
409
- String(
410
- limit === void 0 ? -1 : offset + Math.max(0, limit - 1)
411
- ),
412
- "WITHSCORES"
413
- ]);
414
- return parseRedisIndexEntries(values);
415
- },
416
- async remove(args) {
417
- await client.sendCommand([
418
- "ZREM",
419
- redisIndexKey(args.indexKey),
420
- args.conversationId
421
- ]);
422
- },
423
- async upsert(args) {
424
- const key = redisIndexKey(args.indexKey);
425
- if (args.indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
426
- await client.sendCommand([
427
- "EVAL",
428
- upsertBoundedActivityScript,
429
- "1",
430
- key,
431
- String(args.score),
432
- args.conversationId,
433
- String(JUNIOR_THREAD_STATE_TTL_MS),
434
- String(CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH)
435
- ]);
436
- return;
437
- }
438
- if (args.indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
439
- await client.sendCommand([
440
- "ZADD",
441
- key,
442
- String(args.score),
443
- args.conversationId
444
- ]);
445
- await client.sendCommand([
446
- "PEXPIRE",
447
- key,
448
- String(JUNIOR_THREAD_STATE_TTL_MS)
449
- ]);
450
- return;
451
- }
452
- throw new Error(`Unknown conversation index ${args.indexKey}`);
453
- }
454
- };
455
- }
456
- function emulatedConversationIndexStore(state) {
457
- const readIndex = async (indexKey) => uniqueIndexEntries(await state.get(indexKey));
458
- const writeIndex = async (indexKey, entries) => {
459
- await state.set(indexKey, entries, JUNIOR_THREAD_STATE_TTL_MS);
460
- };
461
- return {
462
- async list(args) {
463
- const entries = (await readIndex(args.indexKey)).filter(
464
- (entry) => args.scoreMax === void 0 ? true : entry.score <= args.scoreMax
465
- ).sort(
466
- args.order === "asc" ? compareIndexAscending : compareIndexDescending
467
- );
468
- const offset = Math.max(0, args.offset ?? 0);
469
- return entries.slice(
470
- offset,
471
- args.limit === void 0 ? entries.length : offset + args.limit
472
- );
473
- },
474
- async remove(args) {
475
- await withIndexLock(state, args.indexKey, async () => {
476
- const entries = await readIndex(args.indexKey);
477
- const next = entries.filter(
478
- (entry) => entry.conversationId !== args.conversationId
479
- );
480
- if (next.length === entries.length) {
481
- return;
482
- }
483
- await writeIndex(args.indexKey, next);
484
- });
485
- },
486
- async upsert(args) {
487
- await withIndexLock(state, args.indexKey, async () => {
488
- const entries = await readIndex(args.indexKey);
489
- const withoutCurrent = entries.filter(
490
- (entry) => entry.conversationId !== args.conversationId
491
- );
492
- const next = retainedIndexEntries(args.indexKey, [
493
- ...withoutCurrent,
494
- { conversationId: args.conversationId, score: args.score }
495
- ]);
496
- await writeIndex(args.indexKey, next);
497
- });
498
- }
499
- };
500
- }
501
- async function getConversationIndexStore(state) {
502
- const redisStateAdapter = await getDefaultRedisStateAdapterFor(state);
503
- if (redisStateAdapter) {
504
- return redisConversationIndexStore(redisStateAdapter.getClient());
505
- }
506
- return emulatedConversationIndexStore(state);
507
- }
508
- async function upsertIndexEntry(args) {
509
- const index = await getConversationIndexStore(args.state);
510
- await index.upsert({
511
- conversationId: args.conversationId,
512
- indexKey: args.indexKey,
513
- score: args.score
514
- });
515
- }
516
- async function removeIndexEntry(args) {
517
- const index = await getConversationIndexStore(args.state);
518
- await index.remove({
519
- conversationId: args.conversationId,
520
- indexKey: args.indexKey
521
- });
522
- }
523
- async function acquireMutationLock(state, conversationId) {
524
- const startedAtMs = now();
525
- while (true) {
526
- const lock = await state.acquireLock(
527
- mutationLockKey(conversationId),
528
- CONVERSATION_MUTATION_LOCK_TTL_MS
529
- );
530
- if (lock) {
531
- return lock;
532
- }
533
- if (now() - startedAtMs >= CONVERSATION_MUTATION_WAIT_MS) {
534
- throw new Error(
535
- `Could not acquire conversation mutation lock for ${conversationId}`
536
- );
537
- }
538
- await sleep(CONVERSATION_MUTATION_RETRY_MS);
539
- }
540
- }
541
- async function withConversationMutation(args, callback) {
542
- const state = await getConnectedState(args.state);
543
- const lock = await acquireMutationLock(state, args.conversationId);
544
- try {
545
- return await callback(state, lock);
546
- } finally {
547
- await state.releaseLock(lock);
548
- }
549
- }
550
- async function readConversation(state, conversationId) {
551
- const raw = await state.get(conversationKey(conversationId));
552
- if (raw == null) {
553
- return void 0;
554
- }
555
- const conversation = normalizeConversation(conversationId, raw);
556
- if (!conversation) {
557
- throw new InvalidConversationRecordError(conversationId);
558
- }
559
- return conversation;
560
- }
561
- async function writeConversation(state, lock, conversation) {
562
- const execution = executionWithPendingMessages(
563
- conversation.execution,
564
- conversation.execution.pendingMessages
565
- );
566
- const next = {
567
- ...conversation,
568
- execution
569
- };
570
- const fenced = await state.extendLock(
571
- lock,
572
- CONVERSATION_MUTATION_LOCK_TTL_MS
573
- );
574
- if (!fenced) {
575
- throw new ConversationMutationFencedError(next.conversationId);
576
- }
577
- await state.set(
578
- conversationKey(next.conversationId),
579
- next,
580
- JUNIOR_THREAD_STATE_TTL_MS
581
- );
582
- await upsertIndexEntry({
583
- state,
584
- indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
585
- conversationId: next.conversationId,
586
- score: next.lastActivityAtMs
587
- });
588
- if (!hasRunnableWork(next)) {
589
- await removeIndexEntry({
590
- state,
591
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
592
- conversationId: next.conversationId
593
- });
594
- return;
595
- }
596
- await upsertIndexEntry({
597
- state,
598
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
599
- conversationId: next.conversationId,
600
- score: next.execution.updatedAtMs ?? next.updatedAtMs
601
- });
602
- }
603
- function assertSameConversationDestination(args) {
604
- if (!args.current || sameDestination(args.current, args.next)) {
605
- return;
606
- }
607
- throw new Error(
608
- `Conversation destination changed for ${args.conversationId}`
609
- );
610
- }
611
- function conversationWorkState(conversation) {
612
- const lease = conversation.execution.lease;
613
- return {
614
- ...conversation,
615
- lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
616
- ...lease ? {
617
- lease: {
618
- acquiredAtMs: lease.acquiredAtMs,
619
- lastCheckInAtMs: lease.lastCheckInAtMs,
620
- leaseExpiresAtMs: lease.expiresAtMs,
621
- leaseToken: lease.token
622
- }
623
- } : {},
624
- messages: pendingMessages(conversation),
625
- needsRun: hasRunnableWork(conversation)
626
- };
627
- }
628
- async function getConversation(args) {
629
- const state = await getConnectedState(args.state);
630
- return await readConversation(state, args.conversationId);
631
- }
632
- async function getConversationWorkState(args) {
633
- const conversation = await getConversation(args);
634
- return conversation ? conversationWorkState(conversation) : void 0;
635
- }
636
- async function appendInboundMessage(args) {
637
- const nowMs = args.nowMs ?? now();
638
- return await withConversationMutation(
639
- { conversationId: args.message.conversationId, state: args.state },
640
- async (state, lock) => {
641
- const current = await readConversation(state, args.message.conversationId) ?? emptyConversation({
642
- conversationId: args.message.conversationId,
643
- destination: args.message.destination,
644
- nowMs,
645
- source: args.message.source
646
- });
647
- assertSameConversationDestination({
648
- conversationId: args.message.conversationId,
649
- current: current.destination,
650
- next: args.message.destination
651
- });
652
- const existingPending = current.execution.pendingMessages.some(
653
- (message) => message.inboundMessageId === args.message.inboundMessageId
654
- );
655
- const existing = current.execution.inboundMessageIds.includes(
656
- args.message.inboundMessageId
657
- );
658
- if (existing) {
659
- if (!existingPending) {
660
- return { status: "duplicate" };
661
- }
662
- const nextStatus = current.execution.status === "idle" ? "pending" : current.execution.status;
663
- await writeConversation(
664
- state,
665
- lock,
666
- withExecutionUpdate(
667
- current,
668
- {
669
- ...current.execution,
670
- status: nextStatus,
671
- pendingMessages: current.execution.pendingMessages.map(
672
- (message) => message.inboundMessageId === args.message.inboundMessageId ? upgradedPendingMessage(message, args.message) : message
673
- )
674
- },
675
- nowMs
676
- )
677
- );
678
- return { status: "duplicate" };
679
- }
680
- const status = current.execution.lease && current.execution.status === "running" ? "running" : current.execution.lease ? "awaiting_resume" : "pending";
681
- const next = {
682
- ...current,
683
- destination: current.destination ?? args.message.destination,
684
- source: current.source ?? args.message.source,
685
- lastActivityAtMs: nowMs
686
- };
687
- await writeConversation(
688
- state,
689
- lock,
690
- withExecutionUpdate(
691
- next,
692
- {
693
- ...current.execution,
694
- status,
695
- inboundMessageIds: [
696
- ...current.execution.inboundMessageIds,
697
- args.message.inboundMessageId
698
- ],
699
- pendingMessages: [
700
- ...current.execution.pendingMessages,
701
- args.message
702
- ].sort(compareMessages)
703
- },
704
- nowMs
705
- )
706
- );
707
- return { status: "appended" };
708
- }
709
- );
710
- }
711
- async function requestConversationWork(args) {
712
- const nowMs = args.nowMs ?? now();
713
- return await withConversationMutation(args, async (state, lock) => {
714
- const existing = await readConversation(state, args.conversationId);
715
- if (existing) {
716
- assertSameConversationDestination({
717
- conversationId: args.conversationId,
718
- current: existing.destination,
719
- next: args.destination
720
- });
721
- }
722
- const current = existing ?? emptyConversation({
723
- conversationId: args.conversationId,
724
- destination: args.destination,
725
- nowMs
726
- });
727
- const status = current.execution.lease ? "awaiting_resume" : "pending";
728
- await writeConversation(
729
- state,
730
- lock,
731
- withExecutionUpdate(
732
- {
733
- ...current,
734
- destination: current.destination ?? args.destination
735
- },
736
- {
737
- ...current.execution,
738
- status
739
- },
740
- nowMs
741
- )
742
- );
743
- return { status: existing === void 0 ? "created" : "updated" };
744
- });
745
- }
746
- async function recordConversationActivity(args) {
747
- const nowMs = args.nowMs ?? now();
748
- const activityAtMs = args.activityAtMs ?? nowMs;
749
- await withConversationMutation(args, async (state, lock) => {
750
- const existing = await readConversation(state, args.conversationId);
751
- if (existing && args.destination) {
752
- assertSameConversationDestination({
753
- conversationId: args.conversationId,
754
- current: existing.destination,
755
- next: args.destination
756
- });
757
- }
758
- const current = existing ?? emptyConversation({
759
- conversationId: args.conversationId,
760
- destination: args.destination,
761
- nowMs,
762
- source: args.source
763
- });
764
- await writeConversation(state, lock, {
765
- ...current,
766
- ...current.destination ?? args.destination ? { destination: current.destination ?? args.destination } : {},
767
- ...current.source ?? args.source ? { source: current.source ?? args.source } : {},
768
- ...current.channelName ?? args.channelName ? { channelName: current.channelName ?? args.channelName } : {},
769
- ...current.actor ?? args.actor ? { actor: current.actor ?? args.actor } : {},
770
- ...current.title ?? args.title ? { title: current.title ?? args.title } : {},
771
- lastActivityAtMs: Math.max(current.lastActivityAtMs, activityAtMs),
772
- updatedAtMs: nowMs,
773
- execution: executionWithPendingMessages(
774
- current.execution,
775
- current.execution.pendingMessages
776
- )
777
- });
778
- });
779
- }
780
- async function recordConversationExecution(args) {
781
- const nowMs = args.updatedAtMs;
782
- await withConversationMutation(args, async (state, lock) => {
783
- const existing = await readConversation(state, args.conversationId);
784
- if (existing && args.destination) {
785
- assertSameConversationDestination({
786
- conversationId: args.conversationId,
787
- current: existing.destination,
788
- next: args.destination
789
- });
790
- }
791
- const current = existing ?? emptyConversation({
792
- conversationId: args.conversationId,
793
- destination: args.destination,
794
- nowMs,
795
- source: args.source
796
- });
797
- await writeConversation(
798
- state,
799
- lock,
800
- withExecutionUpdate(
801
- {
802
- ...current,
803
- ...current.destination ?? args.destination ? { destination: current.destination ?? args.destination } : {},
804
- ...current.source ?? args.source ? { source: current.source ?? args.source } : {},
805
- ...current.channelName ?? args.channelName ? { channelName: current.channelName ?? args.channelName } : {},
806
- ...current.actor ?? args.actor ? { actor: current.actor ?? args.actor } : {},
807
- ...current.title ?? args.title ? { title: current.title ?? args.title } : {},
808
- createdAtMs: Math.min(current.createdAtMs, args.createdAtMs),
809
- lastActivityAtMs: Math.max(
810
- current.lastActivityAtMs,
811
- args.lastActivityAtMs
812
- )
813
- },
814
- {
815
- ...current.execution,
816
- ...args.execution
817
- },
818
- nowMs
819
- )
820
- );
821
- });
822
- }
823
- async function markConversationWorkEnqueued(args) {
824
- const nowMs = args.nowMs ?? now();
825
- await withConversationMutation(args, async (state, lock) => {
826
- const current = await readConversation(state, args.conversationId);
827
- if (!current) {
828
- return;
829
- }
830
- await writeConversation(
831
- state,
832
- lock,
833
- withExecutionUpdate(
834
- current,
835
- {
836
- ...current.execution,
837
- lastEnqueuedAtMs: nowMs
838
- },
839
- nowMs
840
- )
841
- );
842
- });
843
- }
844
- async function clearConsumedConversationWake(args) {
845
- const nowMs = args.nowMs ?? now();
846
- return await withConversationMutation(args, async (state, lock) => {
847
- const current = await readConversation(state, args.conversationId);
848
- if (!current || hasRunnableWork(current) || current.execution.lastEnqueuedAtMs === void 0) {
849
- return false;
850
- }
851
- await writeConversation(
852
- state,
853
- lock,
854
- withExecutionUpdate(
855
- current,
856
- {
857
- ...current.execution,
858
- lastEnqueuedAtMs: void 0
859
- },
860
- nowMs
861
- )
862
- );
863
- return true;
864
- });
865
- }
866
- async function startConversationWork(args) {
867
- const nowMs = args.nowMs ?? now();
868
- return await withConversationMutation(args, async (state, lock) => {
869
- const current = await readConversation(state, args.conversationId);
870
- if (!current) {
871
- return { status: "no_work" };
872
- }
873
- if (isLeaseActive(current.execution.lease, nowMs)) {
874
- return {
875
- status: "active",
876
- leaseExpiresAtMs: current.execution.lease.expiresAtMs
877
- };
878
- }
879
- if (!hasRunnableWork(current)) {
880
- return { status: "no_work" };
881
- }
882
- const lease = {
883
- token: randomUUID(),
884
- acquiredAtMs: nowMs,
885
- lastCheckInAtMs: nowMs,
886
- expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
887
- };
888
- await writeConversation(
889
- state,
890
- lock,
891
- withExecutionUpdate(
892
- current,
893
- {
894
- ...current.execution,
895
- lease,
896
- status: "running",
897
- runId: current.execution.runId ?? randomUUID(),
898
- lastEnqueuedAtMs: void 0
899
- },
900
- nowMs
901
- )
902
- );
903
- return {
904
- status: "acquired",
905
- leaseToken: lease.token,
906
- leaseExpiresAtMs: lease.expiresAtMs
907
- };
908
- });
909
- }
910
- async function checkInConversationWork(args) {
911
- const nowMs = args.nowMs ?? now();
912
- return await withConversationMutation(args, async (state, lock) => {
913
- const current = await readConversation(state, args.conversationId);
914
- if (!current || current.execution.lease?.token !== args.leaseToken) {
915
- return false;
916
- }
917
- await writeConversation(
918
- state,
919
- lock,
920
- withExecutionUpdate(
921
- current,
922
- {
923
- ...current.execution,
924
- lease: {
925
- ...current.execution.lease,
926
- lastCheckInAtMs: nowMs,
927
- expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
928
- }
929
- },
930
- nowMs
931
- )
932
- );
933
- return true;
934
- });
935
- }
936
- async function drainConversationMailbox(args) {
937
- const nowMs = args.nowMs ?? now();
938
- const pending = await withConversationMutation(args, async (state) => {
939
- const current = await readConversation(state, args.conversationId);
940
- if (!current || current.execution.lease?.token !== args.leaseToken) {
941
- throw new Error(
942
- `Conversation lease is not held for ${args.conversationId}`
943
- );
944
- }
945
- return pendingMessages(current);
946
- });
947
- if (pending.length === 0) {
948
- return [];
949
- }
950
- const acknowledgedIds = await args.handle(pending);
951
- const pendingIds = new Set(
952
- pending.map((message) => message.inboundMessageId)
953
- );
954
- for (const inboundMessageId of acknowledgedIds ?? []) {
955
- if (!pendingIds.has(inboundMessageId)) {
956
- throw new Error(
957
- `Conversation mailbox acknowledgement is not pending for ${args.conversationId}`
958
- );
959
- }
960
- }
961
- const drainedIds = new Set(
962
- acknowledgedIds ?? pending.map((message) => message.inboundMessageId)
963
- );
964
- await withConversationMutation(args, async (state, lock) => {
965
- const current = await readConversation(state, args.conversationId);
966
- if (!current || current.execution.lease?.token !== args.leaseToken) {
967
- throw new Error(
968
- `Conversation lease is not held for ${args.conversationId}`
969
- );
970
- }
971
- const pendingMessages2 = current.execution.pendingMessages.filter(
972
- (message) => !drainedIds.has(message.inboundMessageId)
973
- );
974
- await writeConversation(
975
- state,
976
- lock,
977
- withExecutionUpdate(
978
- current,
979
- {
980
- ...current.execution,
981
- status: current.execution.status === "pending" && pendingMessages2.length === 0 ? "running" : current.execution.status,
982
- pendingMessages: pendingMessages2
983
- },
984
- nowMs
985
- )
986
- );
987
- });
988
- return pending.filter((message) => drainedIds.has(message.inboundMessageId));
989
- }
990
- async function ackMessages(args) {
991
- const nowMs = args.nowMs ?? now();
992
- const inboundMessageIds = new Set(args.inboundMessageIds);
993
- return await withConversationMutation(args, async (state, lock) => {
994
- const current = await readConversation(state, args.conversationId);
995
- if (!current || current.execution.lease?.token !== args.leaseToken) {
996
- return false;
997
- }
998
- if (inboundMessageIds.size === 0) {
999
- return true;
1000
- }
1001
- const pendingMessages2 = current.execution.pendingMessages.filter(
1002
- (message) => !inboundMessageIds.has(message.inboundMessageId)
1003
- );
1004
- if (pendingMessages2.length === current.execution.pendingMessages.length) {
1005
- return true;
1006
- }
1007
- await writeConversation(
1008
- state,
1009
- lock,
1010
- withExecutionUpdate(
1011
- current,
1012
- {
1013
- ...current.execution,
1014
- pendingMessages: pendingMessages2
1015
- },
1016
- nowMs
1017
- )
1018
- );
1019
- return true;
1020
- });
1021
- }
1022
- async function requestConversationContinuation(args) {
1023
- const nowMs = args.nowMs ?? now();
1024
- return await withConversationMutation(args, async (state, lock) => {
1025
- const current = await readConversation(state, args.conversationId);
1026
- if (!current || current.execution.lease?.token !== args.leaseToken) {
1027
- return false;
1028
- }
1029
- assertSameConversationDestination({
1030
- conversationId: args.conversationId,
1031
- current: current.destination,
1032
- next: args.destination
1033
- });
1034
- await writeConversation(
1035
- state,
1036
- lock,
1037
- withExecutionUpdate(
1038
- current,
1039
- {
1040
- ...current.execution,
1041
- status: "awaiting_resume"
1042
- },
1043
- nowMs
1044
- )
1045
- );
1046
- return true;
1047
- });
1048
- }
1049
- async function releaseConversationWork(args) {
1050
- const nowMs = args.nowMs ?? now();
1051
- return await withConversationMutation(args, async (state, lock) => {
1052
- const current = await readConversation(state, args.conversationId);
1053
- if (!current || current.execution.lease?.token !== args.leaseToken) {
1054
- return false;
1055
- }
1056
- await writeConversation(
1057
- state,
1058
- lock,
1059
- withExecutionUpdate(
1060
- current,
1061
- {
1062
- ...current.execution,
1063
- lease: void 0,
1064
- status: current.execution.status === "running" ? "pending" : current.execution.status
1065
- },
1066
- nowMs
1067
- )
1068
- );
1069
- return true;
1070
- });
1071
- }
1072
- async function completeConversationWork(args) {
1073
- const nowMs = args.nowMs ?? now();
1074
- return await withConversationMutation(args, async (state, lock) => {
1075
- const current = await readConversation(state, args.conversationId);
1076
- if (!current || current.execution.lease?.token !== args.leaseToken) {
1077
- return "lost_lease";
1078
- }
1079
- const hasPending = pendingMessages(current).length > 0;
1080
- const needsRun = current.execution.status === "awaiting_resume";
1081
- const runnable = needsRun || hasPending;
1082
- await writeConversation(
1083
- state,
1084
- lock,
1085
- withExecutionUpdate(
1086
- current,
1087
- {
1088
- ...current.execution,
1089
- lease: void 0,
1090
- status: runnable ? "pending" : "idle",
1091
- runId: runnable ? current.execution.runId : void 0
1092
- },
1093
- nowMs
1094
- )
1095
- );
1096
- return runnable ? "pending" : "completed";
1097
- });
1098
- }
1099
- async function recordAttemptFailure(args) {
1100
- const nowMs = args.nowMs ?? now();
1101
- return await withConversationMutation(args, async (state, lock) => {
1102
- const current = await readConversation(state, args.conversationId);
1103
- if (!current || current.execution.lease?.token !== args.leaseToken) {
1104
- return {
1105
- status: "lost_lease",
1106
- pendingCount: 0,
1107
- deadLetteredMessages: []
1108
- };
1109
- }
1110
- const pendingIds = new Set(
1111
- current.execution.pendingMessages.map(
1112
- (message) => message.inboundMessageId
1113
- )
1114
- );
1115
- if (args.inboundMessageIds.length === 0 || args.inboundMessageIds.some((id) => !pendingIds.has(id))) {
1116
- return {
1117
- status: "skipped",
1118
- pendingCount: current.execution.pendingMessages.length,
1119
- deadLetteredMessages: []
1120
- };
1121
- }
1122
- const attemptedIds = new Set(args.inboundMessageIds);
1123
- const deadLetteredMessages = [];
1124
- const pendingMessages2 = [];
1125
- for (const message of current.execution.pendingMessages) {
1126
- if (!attemptedIds.has(message.inboundMessageId)) {
1127
- pendingMessages2.push(message);
1128
- continue;
1129
- }
1130
- const attempted = {
1131
- ...message,
1132
- attemptCount: (message.attemptCount ?? 0) + 1
1133
- };
1134
- if (attempted.attemptCount >= CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS) {
1135
- deadLetteredMessages.push(attempted);
1136
- continue;
1137
- }
1138
- pendingMessages2.push(attempted);
1139
- }
1140
- await writeConversation(
1141
- state,
1142
- lock,
1143
- withExecutionUpdate(
1144
- current,
1145
- {
1146
- ...current.execution,
1147
- pendingMessages: pendingMessages2
1148
- },
1149
- nowMs
1150
- )
1151
- );
1152
- return {
1153
- status: "recorded",
1154
- pendingCount: pendingMessages2.length,
1155
- deadLetteredMessages
1156
- };
1157
- });
1158
- }
1159
- async function deadLetterAttempt(args) {
1160
- const nowMs = args.nowMs ?? now();
1161
- return await withConversationMutation(args, async (state, lock) => {
1162
- const current = await readConversation(state, args.conversationId);
1163
- if (!current || current.execution.lease?.token !== args.leaseToken) {
1164
- return "lost_lease";
1165
- }
1166
- const runnable = pendingMessages(current).length > 0;
1167
- await writeConversation(
1168
- state,
1169
- lock,
1170
- withExecutionUpdate(
1171
- current,
1172
- {
1173
- ...current.execution,
1174
- lease: void 0,
1175
- status: runnable ? "pending" : "failed",
1176
- runId: runnable ? current.execution.runId : void 0
1177
- },
1178
- nowMs
1179
- )
1180
- );
1181
- return runnable ? "pending" : "failed";
1182
- });
1183
- }
1184
- async function clearExpiredConversationLease(args) {
1185
- const nowMs = args.nowMs ?? now();
1186
- return await withConversationMutation(args, async (state, lock) => {
1187
- const current = await readConversation(state, args.conversationId);
1188
- if (!current?.execution.lease || current.execution.lease.expiresAtMs > nowMs) {
1189
- return false;
1190
- }
1191
- await writeConversation(
1192
- state,
1193
- lock,
1194
- withExecutionUpdate(
1195
- current,
1196
- {
1197
- ...current.execution,
1198
- lease: void 0,
1199
- status: "pending"
1200
- },
1201
- nowMs
1202
- )
1203
- );
1204
- return true;
1205
- });
1206
- }
1207
- async function removeActiveConversation(args) {
1208
- const state = await getConnectedState(args.state);
1209
- await removeIndexEntry({
1210
- state,
1211
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
1212
- conversationId: args.conversationId
1213
- });
1214
- }
1215
- async function listActiveConversationIds(args = {}) {
1216
- const state = await getConnectedState(args.state);
1217
- const index = await getConversationIndexStore(state);
1218
- const entries = await index.list({
1219
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
1220
- limit: args.limit,
1221
- order: "asc",
1222
- scoreMax: args.staleBeforeMs
1223
- });
1224
- return entries.map((entry) => entry.conversationId);
1225
- }
1226
- async function listConversationsByActivity(args = {}) {
1227
- const state = await getConnectedState(args.state);
1228
- const index = await getConversationIndexStore(state);
1229
- const entries = await index.list({
1230
- indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
1231
- limit: args.limit ?? CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH,
1232
- offset: args.offset,
1233
- order: "desc"
1234
- });
1235
- const conversations = [];
1236
- for (const entry of entries) {
1237
- try {
1238
- const conversation = await readConversation(state, entry.conversationId);
1239
- if (conversation) {
1240
- conversations.push(conversation);
1241
- }
1242
- } catch (error) {
1243
- if (!(error instanceof InvalidConversationRecordError)) {
1244
- throw error;
1245
- }
1246
- await removeIndexEntry({
1247
- state,
1248
- indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
1249
- conversationId: entry.conversationId
1250
- });
1251
- }
1252
- }
1253
- return conversations;
1254
- }
1255
-
1256
- export {
1257
- isInvalidConversationRecordError,
1258
- CONVERSATION_WORK_CHECK_IN_INTERVAL_MS,
1259
- CONVERSATION_WORK_STALE_ENQUEUE_MS,
1260
- isFinalAttempt,
1261
- getConversation,
1262
- getConversationWorkState,
1263
- appendInboundMessage,
1264
- requestConversationWork,
1265
- recordConversationActivity,
1266
- recordConversationExecution,
1267
- markConversationWorkEnqueued,
1268
- clearConsumedConversationWake,
1269
- startConversationWork,
1270
- checkInConversationWork,
1271
- drainConversationMailbox,
1272
- ackMessages,
1273
- requestConversationContinuation,
1274
- releaseConversationWork,
1275
- completeConversationWork,
1276
- recordAttemptFailure,
1277
- deadLetterAttempt,
1278
- clearExpiredConversationLease,
1279
- removeActiveConversation,
1280
- listActiveConversationIds,
1281
- listConversationsByActivity
1282
- };