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