@sentry/junior 0.245.0 → 0.247.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.
- package/dist/{admin-BEbNsG87.js → admin-BGwaqDMs.js} +1 -1
- package/dist/{agent-hooks-Caa0Qh_Q.js → agent-hooks-C72ByH0C.js} +11 -11
- package/dist/{agent-invocations-BO6ddZax.js → agent-invocations-D_YoNnAn.js} +8 -2
- package/dist/{agent-runner-BEuPFbbv.js → agent-runner-DsAFAKKs.js} +822 -2524
- package/dist/api/schema.d.ts +23 -1
- package/dist/api/schema.js +3 -3
- package/dist/api.js +82 -21
- package/dist/{app-BYB7szGb.d.ts → app-4t4mPTdS.d.ts} +8 -1
- package/dist/app.d.ts +1 -1
- package/dist/app.js +37 -68
- package/dist/assistant-reply-ChOzcTBS.js +45 -0
- package/dist/{briefs-DFAh_jTW.js → briefs-Dc7qZrhc.js} +4 -4
- package/dist/{catalog-runtime-wmq_fqff.js → catalog-runtime-DS1k7fUG.js} +1 -1
- package/dist/cli/chat.js +25 -15
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +3 -3
- package/dist/cli/upgrade.js +3 -3
- package/dist/{client-Bn9SRFCi.js → client-BVnfNd3D.js} +2 -2
- package/dist/{config-_XAINZMN.js → config-CgWvImQL.js} +2 -2
- package/dist/{conversation-CvBG57Io.js → conversation-CYsbVFLx.js} +71 -1
- package/dist/{conversation-privacy-BN5SGxsF.js → conversation-privacy-D3TdVM9H.js} +1 -1
- package/dist/{credential-sync-BvaUm6HQ.js → credential-sync-DLw3jkv-.js} +14 -14
- package/dist/{executor-CFIqoCNJ.js → executor-DQazjeGA.js} +3 -3
- package/dist/{images-Ci43I3ek.js → images-C3e5E-p_.js} +4 -21
- package/dist/instrumentation.js +2 -2
- package/dist/{job-queue-CGicV7x6.js → job-queue-BEUqRhjC.js} +1 -1
- package/dist/{logging-Bs3dV81s.js → logging-CZEc8_v4.js} +1 -1
- package/dist/message-BIJa7lKh.js +59 -0
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -3
- package/dist/{oauth-authorization-COzWmMjO.js → oauth-authorization-BA4Dt6a7.js} +1 -45
- package/dist/{oauth-callback-server-17c9_39v.js → oauth-callback-server-R9OSdLP1.js} +2 -2
- package/dist/{pending-auth-Bnhg7Q9k.js → pending-auth-Oo5AQhaf.js} +2 -2
- package/dist/{profile-BA471c-l.js → profile-aVLDAirh.js} +4 -4
- package/dist/{prompt-C9Q9cjD3.js → prompt-ZG1UCxjF.js} +1 -1
- package/dist/{registry-BYNOFO6e.js → registry-CtaDOOM5.js} +1 -1
- package/dist/{resolve-rpz8No2i.js → resolve-Bdw4hu7s.js} +2 -2
- package/dist/result-DNgmkASh.js +463 -0
- package/dist/{runner-C8DRk9X6.js → runner-BUSScEu5.js} +11 -10
- package/dist/{sandbox-egress-signals-B8hurjFt.js → sandbox-egress-signals-E9r8bf9G.js} +1 -1
- package/dist/{schema-WRgR9EL6.js → schema-tyd6hALh.js} +23 -3
- package/dist/session-stop-CAhBfBUT.js +782 -0
- package/dist/{skills-C4yrD2NR.js → skills-DQy-mmBC.js} +2 -2
- package/dist/{spawn-CdAaTXrY.js → spawn-DQ_MVWZ6.js} +3 -2
- package/dist/store-DjLA8GKs.js +1417 -0
- package/dist/{task-queue-BBxHzlIB.js → task-queue-BT2h_t8I.js} +3 -3
- package/dist/{task-runner-BqFapTjs.js → task-runner-CiPepjIB.js} +11 -11
- package/dist/{tasks-Ddd7OAkp.js → tasks-DMmRrIVl.js} +9 -9
- package/dist/{thread-state-DqErwbA8.js → thread-state-ehZYGpX9.js} +7 -7
- package/dist/{turn-failure-response-DtL1-fOl.js → turn-failure-response-D7J10z7l.js} +9 -9
- package/dist/{turn-lifecycle-B5pzyD6W.js → turn-lifecycle-Buswqs90.js} +1 -1
- package/dist/{turn-session-routing-D6pTU5uF.js → turn-session-routing-Bw-yiSb4.js} +1 -1
- package/dist/{validation-BAzlyNIc.js → validation-DTguegIe.js} +1 -1
- package/dist/{version-CiXDH3oe.js → version-BrZSE5du.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-wCn8xneI.js → viewer-BlAozHer.js} +4 -4
- package/dist/{web-authorization-d5MtGpfG.js → web-authorization-DwyTlkAg.js} +6 -6
- package/dist/{web-input-BZTiCtvP.js → web-input-DSYxI7Wi.js} +77 -378
- package/dist/{work-4QPqTd5_.js → work-CRBXkJoU.js} +96 -13
- package/dist/{worker-mc62tybz.js → worker-BVJKM9Ja.js} +7 -7
- package/migrations/0053_conversation_stopped_at.sql +1 -0
- package/migrations/0054_flowery_rage.sql +1 -0
- package/migrations/meta/0053_snapshot.json +3771 -0
- package/migrations/meta/0054_snapshot.json +3777 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +5 -4
|
@@ -0,0 +1,1417 @@
|
|
|
1
|
+
import { I as isRecord, L as toOptionalNumber, R as toOptionalString } from "./logging-CZEc8_v4.js";
|
|
2
|
+
import { i as getChatConfig } from "./config-CgWvImQL.js";
|
|
3
|
+
import { s as parseStoredSlackActor } from "./actor-BTtLaeWy.js";
|
|
4
|
+
import { F as sameDestination, N as parseDestination, u as getConversationStore } from "./viewer-BlAozHer.js";
|
|
5
|
+
import { tt as JUNIOR_THREAD_STATE_TTL_MS } from "./agent-hooks-C72ByH0C.js";
|
|
6
|
+
import { C as getDefaultRedisStateAdapterFor, w as getStateAdapter } from "./profile-aVLDAirh.js";
|
|
7
|
+
import "./job-queue-BEUqRhjC.js";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { destinationSchema } from "@sentry/junior-plugin-api";
|
|
11
|
+
//#region src/chat/task-execution/state.ts
|
|
12
|
+
/**
|
|
13
|
+
* Expiring conversation mailbox and execution index store.
|
|
14
|
+
*
|
|
15
|
+
* The conversation record owns pending inbound work, execution status, and the
|
|
16
|
+
* lease. `conversation:active` feeds heartbeat recovery and contains every
|
|
17
|
+
* non-idle conversation until the lease/status path makes it idle.
|
|
18
|
+
* `conversation:by-activity` supports legacy SQL import only; SQL owns durable
|
|
19
|
+
* conversation metadata in configured runtime.
|
|
20
|
+
*/
|
|
21
|
+
const CONVERSATION_PREFIX = "junior:conversation:v2";
|
|
22
|
+
const CONVERSATION_SCHEMA_VERSION = 2;
|
|
23
|
+
const CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH = 1e4;
|
|
24
|
+
const CONVERSATION_INDEX_LOCK_TTL_MS = 1e4;
|
|
25
|
+
const CONVERSATION_INDEX_LOCK_WAIT_MS = 2e3;
|
|
26
|
+
const CONVERSATION_INDEX_LOCK_RETRY_MS = 25;
|
|
27
|
+
const CONVERSATION_MUTATION_LOCK_TTL_MS = 1e4;
|
|
28
|
+
const CONVERSATION_MUTATION_WAIT_MS = 1e4;
|
|
29
|
+
const CONVERSATION_MUTATION_RETRY_MS = 25;
|
|
30
|
+
var InvalidConversationRecordError = class extends Error {
|
|
31
|
+
constructor(conversationId) {
|
|
32
|
+
super(`Conversation record is invalid for ${conversationId}`);
|
|
33
|
+
this.name = "InvalidConversationRecordError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** Return whether an error means a stored conversation record failed validation. */
|
|
37
|
+
function isInvalidConversationRecordError(error) {
|
|
38
|
+
return error instanceof InvalidConversationRecordError;
|
|
39
|
+
}
|
|
40
|
+
var ConversationMutationFencedError = class extends Error {
|
|
41
|
+
constructor(conversationId) {
|
|
42
|
+
super(`Conversation mutation lock was lost before write for ${conversationId}`);
|
|
43
|
+
this.name = "ConversationMutationFencedError";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const CONVERSATION_BY_ACTIVITY_INDEX_KEY = `${CONVERSATION_PREFIX}:by-activity`;
|
|
47
|
+
const CONVERSATION_ACTIVE_INDEX_KEY = `${CONVERSATION_PREFIX}:active`;
|
|
48
|
+
const CONVERSATION_WORK_LEASE_TTL_MS = 9e4;
|
|
49
|
+
const CONVERSATION_WORK_CHECK_IN_INTERVAL_MS = 15e3;
|
|
50
|
+
const CONVERSATION_WORK_STALE_ENQUEUE_MS = 6e4;
|
|
51
|
+
const inboundMessageSourceSchema = z.enum([
|
|
52
|
+
"api",
|
|
53
|
+
"internal",
|
|
54
|
+
"local",
|
|
55
|
+
"plugin",
|
|
56
|
+
"event",
|
|
57
|
+
"scheduler",
|
|
58
|
+
"slack",
|
|
59
|
+
"web"
|
|
60
|
+
]);
|
|
61
|
+
const agentInputSchema = z.object({
|
|
62
|
+
attachments: z.array(z.unknown()).optional(),
|
|
63
|
+
authorId: z.string().min(1).optional(),
|
|
64
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
65
|
+
text: z.string()
|
|
66
|
+
}).strict().refine((input) => input.text.trim() || input.attachments?.length, { message: "agent input requires text or attachments" });
|
|
67
|
+
/** Durable delivery modes for pending inbound mailbox work. */
|
|
68
|
+
const inboundMessageDeliverySchema = z.enum(["defer", "interrupt"]);
|
|
69
|
+
/** Redis mailbox shape kept for deployed workers that still require this field. */
|
|
70
|
+
const storedInboundMessageSchema = z.object({
|
|
71
|
+
attemptCount: z.number().finite().optional(),
|
|
72
|
+
conversationId: z.string().refine((value) => value.trim().length > 0),
|
|
73
|
+
createdAtMs: z.number().finite(),
|
|
74
|
+
delivery: inboundMessageDeliverySchema,
|
|
75
|
+
destination: destinationSchema.optional(),
|
|
76
|
+
inboundMessageId: z.string().refine((value) => value.trim().length > 0),
|
|
77
|
+
injectedAtMs: z.number().finite().optional(),
|
|
78
|
+
input: agentInputSchema,
|
|
79
|
+
receivedAtMs: z.number().finite(),
|
|
80
|
+
source: inboundMessageSourceSchema
|
|
81
|
+
}).strict().extend({ publishExternally: z.boolean() });
|
|
82
|
+
function conversationKey(conversationId) {
|
|
83
|
+
return `${CONVERSATION_PREFIX}:${conversationId}`;
|
|
84
|
+
}
|
|
85
|
+
function conversationStopKey(conversationId) {
|
|
86
|
+
return `${CONVERSATION_PREFIX}:stop:${conversationId}`;
|
|
87
|
+
}
|
|
88
|
+
function indexLockKey(indexKey) {
|
|
89
|
+
return `${indexKey}:lock`;
|
|
90
|
+
}
|
|
91
|
+
function mutationLockKey(conversationId) {
|
|
92
|
+
return `${CONVERSATION_PREFIX}:mutation:${conversationId}`;
|
|
93
|
+
}
|
|
94
|
+
function now$1() {
|
|
95
|
+
return Date.now();
|
|
96
|
+
}
|
|
97
|
+
function compareMessages(left, right) {
|
|
98
|
+
return left.createdAtMs - right.createdAtMs || left.receivedAtMs - right.receivedAtMs || left.inboundMessageId.localeCompare(right.inboundMessageId);
|
|
99
|
+
}
|
|
100
|
+
function inputHasAttachments(input) {
|
|
101
|
+
return Array.isArray(input.attachments) && input.attachments.length > 0;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Upgrade a still-pending payload when a duplicate source event carries file
|
|
105
|
+
* attachments the stored copy lacks (Slack `app_mention`/`message` twins),
|
|
106
|
+
* keeping the stored ordering timestamps and delivery attempts.
|
|
107
|
+
*/
|
|
108
|
+
function upgradedPendingMessage(stored, duplicate) {
|
|
109
|
+
const promotesInterrupt = stored.delivery === "defer" && duplicate.delivery === "interrupt";
|
|
110
|
+
const delivery = promotesInterrupt ? "interrupt" : stored.delivery;
|
|
111
|
+
const input = promotesInterrupt ? {
|
|
112
|
+
...duplicate.input,
|
|
113
|
+
...inputHasAttachments(duplicate.input) || !inputHasAttachments(stored.input) ? void 0 : { attachments: stored.input.attachments }
|
|
114
|
+
} : inputHasAttachments(duplicate.input) && !inputHasAttachments(stored.input) ? duplicate.input : stored.input;
|
|
115
|
+
if (input === stored.input && delivery === stored.delivery) return stored;
|
|
116
|
+
return {
|
|
117
|
+
...stored,
|
|
118
|
+
delivery,
|
|
119
|
+
input
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function compareIndexDescending(left, right) {
|
|
123
|
+
return right.score - left.score || right.conversationId.localeCompare(left.conversationId);
|
|
124
|
+
}
|
|
125
|
+
function compareIndexAscending(left, right) {
|
|
126
|
+
return left.score - right.score || left.conversationId.localeCompare(right.conversationId);
|
|
127
|
+
}
|
|
128
|
+
function uniqueStrings(values) {
|
|
129
|
+
return [...new Set(values)];
|
|
130
|
+
}
|
|
131
|
+
function normalizeSource(value) {
|
|
132
|
+
const parsed = inboundMessageSourceSchema.safeParse(value);
|
|
133
|
+
return parsed.success ? parsed.data : void 0;
|
|
134
|
+
}
|
|
135
|
+
function normalizeExecutionStatus(value) {
|
|
136
|
+
if (value === "paused") return value;
|
|
137
|
+
if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
|
|
138
|
+
}
|
|
139
|
+
function normalizeMessage(value) {
|
|
140
|
+
const parsed = storedInboundMessageSchema.safeParse(value);
|
|
141
|
+
if (!parsed.success) return;
|
|
142
|
+
const { publishExternally: _publishExternally, ...message } = parsed.data;
|
|
143
|
+
return message;
|
|
144
|
+
}
|
|
145
|
+
function storeMessage(message, publishExternally) {
|
|
146
|
+
return {
|
|
147
|
+
...message,
|
|
148
|
+
publishExternally
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** Whether this is the final attempt before an unacked message is dead-lettered. */
|
|
152
|
+
function isFinalAttempt(message) {
|
|
153
|
+
return (message.attemptCount ?? 0) >= 4;
|
|
154
|
+
}
|
|
155
|
+
function normalizeActor(value) {
|
|
156
|
+
return parseStoredSlackActor(value);
|
|
157
|
+
}
|
|
158
|
+
function normalizeLease(value) {
|
|
159
|
+
if (!isRecord(value)) return;
|
|
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") return;
|
|
165
|
+
return {
|
|
166
|
+
token,
|
|
167
|
+
acquiredAtMs,
|
|
168
|
+
lastCheckInAtMs,
|
|
169
|
+
expiresAtMs
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function normalizeStop(value) {
|
|
173
|
+
if (!isRecord(value)) return;
|
|
174
|
+
const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.filter((id) => typeof id === "string")) : [];
|
|
175
|
+
const runId = toOptionalString(value.runId);
|
|
176
|
+
return runId ? {
|
|
177
|
+
inboundMessageIds,
|
|
178
|
+
runId
|
|
179
|
+
} : void 0;
|
|
180
|
+
}
|
|
181
|
+
/** Decode execution state and repair idle records that still own work. */
|
|
182
|
+
function normalizeExecution(conversationId, value) {
|
|
183
|
+
if (!isRecord(value)) return;
|
|
184
|
+
const status = normalizeExecutionStatus(value.status);
|
|
185
|
+
if (!status) return;
|
|
186
|
+
const pendingMessages = [];
|
|
187
|
+
if (Array.isArray(value.pendingMessages)) {
|
|
188
|
+
for (const rawMessage of value.pendingMessages) {
|
|
189
|
+
const message = normalizeMessage(rawMessage);
|
|
190
|
+
if (!message || message.conversationId !== conversationId) return;
|
|
191
|
+
if (message.injectedAtMs !== void 0) continue;
|
|
192
|
+
pendingMessages.push(message);
|
|
193
|
+
}
|
|
194
|
+
pendingMessages.sort(compareMessages);
|
|
195
|
+
}
|
|
196
|
+
const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))) : [];
|
|
197
|
+
const lease = normalizeLease(value.lease);
|
|
198
|
+
const runId = toOptionalString(value.runId);
|
|
199
|
+
return {
|
|
200
|
+
status: status === "idle" && lease ? "running" : status === "idle" && pendingMessages.length > 0 ? "pending" : status,
|
|
201
|
+
inboundMessageIds: uniqueStrings([...inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
|
|
202
|
+
pendingCount: pendingMessages.length,
|
|
203
|
+
pendingMessages,
|
|
204
|
+
lease,
|
|
205
|
+
lastCheckpointAtMs: toOptionalNumber(value.lastCheckpointAtMs),
|
|
206
|
+
lastEnqueuedAtMs: toOptionalNumber(value.lastEnqueuedAtMs),
|
|
207
|
+
lastProgressAtMs: toOptionalNumber(value.lastProgressAtMs),
|
|
208
|
+
retryCount: toOptionalNumber(value.retryCount),
|
|
209
|
+
runId,
|
|
210
|
+
updatedAtMs: toOptionalNumber(value.updatedAtMs)
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/** Decode current conversation records. */
|
|
214
|
+
function normalizeConversation(conversationId, value) {
|
|
215
|
+
if (!isRecord(value) || value.schemaVersion !== CONVERSATION_SCHEMA_VERSION) return;
|
|
216
|
+
const storedConversationId = toOptionalString(value.conversationId);
|
|
217
|
+
const createdAtMs = toOptionalNumber(value.createdAtMs);
|
|
218
|
+
const lastActivityAtMs = toOptionalNumber(value.lastActivityAtMs);
|
|
219
|
+
const updatedAtMs = toOptionalNumber(value.updatedAtMs);
|
|
220
|
+
const execution = normalizeExecution(conversationId, value.execution);
|
|
221
|
+
const destination = value.destination === void 0 ? void 0 : parseDestination(value.destination);
|
|
222
|
+
if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value.destination !== void 0 && !destination) return;
|
|
223
|
+
if (execution.pendingMessages.length > 0 && execution.pendingMessages.some((message) => {
|
|
224
|
+
if (!message.destination) return false;
|
|
225
|
+
return !destination || !sameDestination(message.destination, destination);
|
|
226
|
+
})) return;
|
|
227
|
+
return {
|
|
228
|
+
schemaVersion: CONVERSATION_SCHEMA_VERSION,
|
|
229
|
+
conversationId,
|
|
230
|
+
createdAtMs,
|
|
231
|
+
lastActivityAtMs,
|
|
232
|
+
updatedAtMs,
|
|
233
|
+
execution,
|
|
234
|
+
...destination ? { destination } : void 0,
|
|
235
|
+
...toOptionalString(value.title) ? { title: toOptionalString(value.title) } : void 0,
|
|
236
|
+
...toOptionalString(value.channelName) ? { channelName: toOptionalString(value.channelName) } : void 0,
|
|
237
|
+
...normalizeActor(value.actor) ? { actor: normalizeActor(value.actor) } : void 0,
|
|
238
|
+
...normalizeSource(value.source) ? { source: normalizeSource(value.source) } : void 0
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function emptyConversation(args) {
|
|
242
|
+
return {
|
|
243
|
+
schemaVersion: CONVERSATION_SCHEMA_VERSION,
|
|
244
|
+
conversationId: args.conversationId,
|
|
245
|
+
createdAtMs: args.nowMs,
|
|
246
|
+
lastActivityAtMs: args.nowMs,
|
|
247
|
+
updatedAtMs: args.nowMs,
|
|
248
|
+
...args.destination ? { destination: args.destination } : void 0,
|
|
249
|
+
...args.source ? { source: args.source } : void 0,
|
|
250
|
+
execution: {
|
|
251
|
+
status: "idle",
|
|
252
|
+
inboundMessageIds: [],
|
|
253
|
+
pendingCount: 0,
|
|
254
|
+
pendingMessages: [],
|
|
255
|
+
updatedAtMs: args.nowMs
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
function isLeaseActive(lease, nowMs) {
|
|
260
|
+
return Boolean(lease && lease.expiresAtMs > nowMs);
|
|
261
|
+
}
|
|
262
|
+
function pendingMessages(conversation) {
|
|
263
|
+
return [...conversation.execution.pendingMessages].sort(compareMessages);
|
|
264
|
+
}
|
|
265
|
+
function isRunnableStatus(status) {
|
|
266
|
+
return status !== "failed" && status !== "idle";
|
|
267
|
+
}
|
|
268
|
+
function hasRunnableWork(conversation) {
|
|
269
|
+
return isRunnableStatus(conversation.execution.status) || pendingMessages(conversation).length > 0;
|
|
270
|
+
}
|
|
271
|
+
function executionWithPendingMessages(execution, pending) {
|
|
272
|
+
const pendingMessages = [...pending].sort(compareMessages);
|
|
273
|
+
const status = execution.status === "idle" && execution.lease ? "running" : execution.status === "idle" && pendingMessages.length > 0 ? "pending" : execution.status;
|
|
274
|
+
return {
|
|
275
|
+
...execution,
|
|
276
|
+
status,
|
|
277
|
+
inboundMessageIds: uniqueStrings([...execution.inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
|
|
278
|
+
pendingMessages,
|
|
279
|
+
pendingCount: pendingMessages.length
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function withExecutionUpdate(conversation, execution, nowMs) {
|
|
283
|
+
return {
|
|
284
|
+
...conversation,
|
|
285
|
+
updatedAtMs: nowMs,
|
|
286
|
+
execution: {
|
|
287
|
+
...executionWithPendingMessages(execution, execution.pendingMessages),
|
|
288
|
+
updatedAtMs: nowMs
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
async function getConnectedState(stateAdapter) {
|
|
293
|
+
const state = stateAdapter ?? getStateAdapter();
|
|
294
|
+
await state.connect();
|
|
295
|
+
return state;
|
|
296
|
+
}
|
|
297
|
+
async function sleep(ms) {
|
|
298
|
+
await new Promise((resolve) => {
|
|
299
|
+
setTimeout(resolve, ms).unref?.();
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
async function withIndexLock(state, indexKey, callback) {
|
|
303
|
+
const startedAtMs = now$1();
|
|
304
|
+
let lock;
|
|
305
|
+
while (true) {
|
|
306
|
+
lock = await state.acquireLock(indexLockKey(indexKey), CONVERSATION_INDEX_LOCK_TTL_MS);
|
|
307
|
+
if (lock) break;
|
|
308
|
+
if (now$1() - startedAtMs >= CONVERSATION_INDEX_LOCK_WAIT_MS) throw new Error(`Could not acquire conversation index lock for ${indexKey}`);
|
|
309
|
+
await sleep(CONVERSATION_INDEX_LOCK_RETRY_MS);
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
return await callback();
|
|
313
|
+
} finally {
|
|
314
|
+
await state.releaseLock(lock);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function normalizeIndexEntry(value) {
|
|
318
|
+
if (!isRecord(value)) return;
|
|
319
|
+
const conversationId = toOptionalString(value.conversationId);
|
|
320
|
+
const score = toOptionalNumber(value.score);
|
|
321
|
+
if (!conversationId || typeof score !== "number") return;
|
|
322
|
+
return {
|
|
323
|
+
conversationId,
|
|
324
|
+
score
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function uniqueIndexEntries(value) {
|
|
328
|
+
if (!Array.isArray(value)) return [];
|
|
329
|
+
const entries = /* @__PURE__ */ new Map();
|
|
330
|
+
for (const item of value) {
|
|
331
|
+
const entry = normalizeIndexEntry(item);
|
|
332
|
+
if (!entry) continue;
|
|
333
|
+
const existing = entries.get(entry.conversationId);
|
|
334
|
+
if (!existing || entry.score > existing.score) entries.set(entry.conversationId, entry);
|
|
335
|
+
}
|
|
336
|
+
return [...entries.values()];
|
|
337
|
+
}
|
|
338
|
+
function retainedIndexEntries(indexKey, entries) {
|
|
339
|
+
if (indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) return entries.sort(compareIndexDescending).slice(0, CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH);
|
|
340
|
+
if (indexKey === CONVERSATION_ACTIVE_INDEX_KEY) return entries.sort(compareIndexAscending);
|
|
341
|
+
throw new Error(`Unknown conversation index ${indexKey}`);
|
|
342
|
+
}
|
|
343
|
+
function redisIndexKey(indexKey) {
|
|
344
|
+
const prefix = getChatConfig().state.keyPrefix;
|
|
345
|
+
return [...prefix ? [prefix] : [], indexKey].join(":");
|
|
346
|
+
}
|
|
347
|
+
function parseRedisIndexEntries(values) {
|
|
348
|
+
if (!Array.isArray(values)) return [];
|
|
349
|
+
const entries = [];
|
|
350
|
+
for (let index = 0; index < values.length; index += 2) {
|
|
351
|
+
const conversationId = toOptionalString(values[index]);
|
|
352
|
+
const score = typeof values[index + 1] === "number" ? values[index + 1] : Number(values[index + 1]);
|
|
353
|
+
if (!conversationId || !Number.isFinite(score)) continue;
|
|
354
|
+
entries.push({
|
|
355
|
+
conversationId,
|
|
356
|
+
score
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
return entries;
|
|
360
|
+
}
|
|
361
|
+
function redisConversationIndexStore(client) {
|
|
362
|
+
const upsertBoundedActivityScript = `
|
|
363
|
+
redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
|
|
364
|
+
redis.call("PEXPIRE", KEYS[1], ARGV[3])
|
|
365
|
+
local extra = redis.call("ZCARD", KEYS[1]) - tonumber(ARGV[4])
|
|
366
|
+
if extra > 0 then
|
|
367
|
+
redis.call("ZREMRANGEBYRANK", KEYS[1], 0, extra - 1)
|
|
368
|
+
end
|
|
369
|
+
return 1
|
|
370
|
+
`;
|
|
371
|
+
return {
|
|
372
|
+
async list(args) {
|
|
373
|
+
const key = redisIndexKey(args.indexKey);
|
|
374
|
+
const limit = args.limit;
|
|
375
|
+
const offset = Math.max(0, args.offset ?? 0);
|
|
376
|
+
if (limit === 0) return [];
|
|
377
|
+
return parseRedisIndexEntries(args.scoreMax !== void 0 ? await client.sendCommand([
|
|
378
|
+
"ZRANGEBYSCORE",
|
|
379
|
+
key,
|
|
380
|
+
"-inf",
|
|
381
|
+
String(args.scoreMax),
|
|
382
|
+
"WITHSCORES",
|
|
383
|
+
...limit !== void 0 || offset > 0 ? [
|
|
384
|
+
"LIMIT",
|
|
385
|
+
String(offset),
|
|
386
|
+
String(limit ?? 1e9)
|
|
387
|
+
] : []
|
|
388
|
+
]) : await client.sendCommand([
|
|
389
|
+
args.order === "asc" ? "ZRANGE" : "ZREVRANGE",
|
|
390
|
+
key,
|
|
391
|
+
String(offset),
|
|
392
|
+
String(limit === void 0 ? -1 : offset + Math.max(0, limit - 1)),
|
|
393
|
+
"WITHSCORES"
|
|
394
|
+
]));
|
|
395
|
+
},
|
|
396
|
+
async remove(args) {
|
|
397
|
+
await client.sendCommand([
|
|
398
|
+
"ZREM",
|
|
399
|
+
redisIndexKey(args.indexKey),
|
|
400
|
+
args.conversationId
|
|
401
|
+
]);
|
|
402
|
+
},
|
|
403
|
+
async upsert(args) {
|
|
404
|
+
const key = redisIndexKey(args.indexKey);
|
|
405
|
+
if (args.indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
|
|
406
|
+
await client.sendCommand([
|
|
407
|
+
"EVAL",
|
|
408
|
+
upsertBoundedActivityScript,
|
|
409
|
+
"1",
|
|
410
|
+
key,
|
|
411
|
+
String(args.score),
|
|
412
|
+
args.conversationId,
|
|
413
|
+
String(JUNIOR_THREAD_STATE_TTL_MS),
|
|
414
|
+
String(CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH)
|
|
415
|
+
]);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (args.indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
|
|
419
|
+
await client.sendCommand([
|
|
420
|
+
"ZADD",
|
|
421
|
+
key,
|
|
422
|
+
String(args.score),
|
|
423
|
+
args.conversationId
|
|
424
|
+
]);
|
|
425
|
+
await client.sendCommand([
|
|
426
|
+
"PEXPIRE",
|
|
427
|
+
key,
|
|
428
|
+
String(JUNIOR_THREAD_STATE_TTL_MS)
|
|
429
|
+
]);
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
throw new Error(`Unknown conversation index ${args.indexKey}`);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
function emulatedConversationIndexStore(state) {
|
|
437
|
+
const readIndex = async (indexKey) => uniqueIndexEntries(await state.get(indexKey));
|
|
438
|
+
const writeIndex = async (indexKey, entries) => {
|
|
439
|
+
await state.set(indexKey, entries, JUNIOR_THREAD_STATE_TTL_MS);
|
|
440
|
+
};
|
|
441
|
+
return {
|
|
442
|
+
async list(args) {
|
|
443
|
+
const entries = (await readIndex(args.indexKey)).filter((entry) => args.scoreMax === void 0 ? true : entry.score <= args.scoreMax).sort(args.order === "asc" ? compareIndexAscending : compareIndexDescending);
|
|
444
|
+
const offset = Math.max(0, args.offset ?? 0);
|
|
445
|
+
return entries.slice(offset, args.limit === void 0 ? entries.length : offset + args.limit);
|
|
446
|
+
},
|
|
447
|
+
async remove(args) {
|
|
448
|
+
await withIndexLock(state, args.indexKey, async () => {
|
|
449
|
+
const entries = await readIndex(args.indexKey);
|
|
450
|
+
const next = entries.filter((entry) => entry.conversationId !== args.conversationId);
|
|
451
|
+
if (next.length === entries.length) return;
|
|
452
|
+
await writeIndex(args.indexKey, next);
|
|
453
|
+
});
|
|
454
|
+
},
|
|
455
|
+
async upsert(args) {
|
|
456
|
+
await withIndexLock(state, args.indexKey, async () => {
|
|
457
|
+
const withoutCurrent = (await readIndex(args.indexKey)).filter((entry) => entry.conversationId !== args.conversationId);
|
|
458
|
+
const next = retainedIndexEntries(args.indexKey, [...withoutCurrent, {
|
|
459
|
+
conversationId: args.conversationId,
|
|
460
|
+
score: args.score
|
|
461
|
+
}]);
|
|
462
|
+
await writeIndex(args.indexKey, next);
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
async function getConversationIndexStore(state) {
|
|
468
|
+
const redisStateAdapter = await getDefaultRedisStateAdapterFor(state);
|
|
469
|
+
if (redisStateAdapter) return redisConversationIndexStore(redisStateAdapter.getClient());
|
|
470
|
+
return emulatedConversationIndexStore(state);
|
|
471
|
+
}
|
|
472
|
+
async function upsertIndexEntry(args) {
|
|
473
|
+
await (await getConversationIndexStore(args.state)).upsert({
|
|
474
|
+
conversationId: args.conversationId,
|
|
475
|
+
indexKey: args.indexKey,
|
|
476
|
+
score: args.score
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
async function removeIndexEntry(args) {
|
|
480
|
+
await (await getConversationIndexStore(args.state)).remove({
|
|
481
|
+
conversationId: args.conversationId,
|
|
482
|
+
indexKey: args.indexKey
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
async function acquireMutationLock(state, conversationId) {
|
|
486
|
+
const startedAtMs = now$1();
|
|
487
|
+
while (true) {
|
|
488
|
+
const lock = await state.acquireLock(mutationLockKey(conversationId), CONVERSATION_MUTATION_LOCK_TTL_MS);
|
|
489
|
+
if (lock) return lock;
|
|
490
|
+
if (now$1() - startedAtMs >= CONVERSATION_MUTATION_WAIT_MS) throw new Error(`Could not acquire conversation mutation lock for ${conversationId}`);
|
|
491
|
+
await sleep(CONVERSATION_MUTATION_RETRY_MS);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async function withConversationMutation(args, callback) {
|
|
495
|
+
const state = await getConnectedState(args.state);
|
|
496
|
+
const lock = await acquireMutationLock(state, args.conversationId);
|
|
497
|
+
try {
|
|
498
|
+
return await callback(state, lock);
|
|
499
|
+
} finally {
|
|
500
|
+
await state.releaseLock(lock);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
async function readConversation(state, conversationId) {
|
|
504
|
+
const raw = await state.get(conversationKey(conversationId));
|
|
505
|
+
if (raw == null) return;
|
|
506
|
+
const conversation = normalizeConversation(conversationId, raw);
|
|
507
|
+
if (!conversation) throw new InvalidConversationRecordError(conversationId);
|
|
508
|
+
return conversation;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Persist a conversation and refresh its reporting and active-recovery indexes.
|
|
512
|
+
*
|
|
513
|
+
* Conversation writes are lock-serialized blind whole-record writes, so the
|
|
514
|
+
* mutation lock is re-validated (and extended) immediately before the write:
|
|
515
|
+
* a stalled mutator that lost its lock must fail loudly instead of clobbering
|
|
516
|
+
* a newer record with a stale copy.
|
|
517
|
+
*/
|
|
518
|
+
async function writeConversation(state, lock, conversation) {
|
|
519
|
+
const execution = executionWithPendingMessages(conversation.execution, conversation.execution.pendingMessages);
|
|
520
|
+
const next = {
|
|
521
|
+
...conversation,
|
|
522
|
+
execution
|
|
523
|
+
};
|
|
524
|
+
await fenceConversationMutation(state, lock, next.conversationId);
|
|
525
|
+
const hasSlackDestination = next.destination?.platform === "slack";
|
|
526
|
+
const stored = {
|
|
527
|
+
...next,
|
|
528
|
+
execution: {
|
|
529
|
+
...next.execution,
|
|
530
|
+
pendingMessages: next.execution.pendingMessages.map((message) => storeMessage(message, hasSlackDestination && (message.source === "slack" || message.source === "event" || message.source === "plugin" || message.source === "scheduler")))
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
await state.set(conversationKey(next.conversationId), stored, JUNIOR_THREAD_STATE_TTL_MS);
|
|
534
|
+
await upsertIndexEntry({
|
|
535
|
+
state,
|
|
536
|
+
indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
|
|
537
|
+
conversationId: next.conversationId,
|
|
538
|
+
score: next.lastActivityAtMs
|
|
539
|
+
});
|
|
540
|
+
if (!hasRunnableWork(next)) {
|
|
541
|
+
await removeIndexEntry({
|
|
542
|
+
state,
|
|
543
|
+
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
544
|
+
conversationId: next.conversationId
|
|
545
|
+
});
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
await upsertIndexEntry({
|
|
549
|
+
state,
|
|
550
|
+
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
551
|
+
conversationId: next.conversationId,
|
|
552
|
+
score: next.execution.updatedAtMs ?? next.updatedAtMs
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
function assertSameOptionalConversationDestination(args) {
|
|
556
|
+
if (!args.next || !args.current) return;
|
|
557
|
+
if (sameDestination(args.current, args.next)) return;
|
|
558
|
+
throw new Error(`Conversation destination changed for ${args.conversationId}`);
|
|
559
|
+
}
|
|
560
|
+
function conversationWorkState(conversation) {
|
|
561
|
+
const lease = conversation.execution.lease;
|
|
562
|
+
return {
|
|
563
|
+
...conversation,
|
|
564
|
+
lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
|
|
565
|
+
...lease ? { lease: {
|
|
566
|
+
acquiredAtMs: lease.acquiredAtMs,
|
|
567
|
+
lastCheckInAtMs: lease.lastCheckInAtMs,
|
|
568
|
+
leaseExpiresAtMs: lease.expiresAtMs,
|
|
569
|
+
leaseToken: lease.token
|
|
570
|
+
} } : void 0,
|
|
571
|
+
messages: pendingMessages(conversation),
|
|
572
|
+
needsRun: hasRunnableWork(conversation)
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** Return a persisted conversation record, if one exists. */
|
|
576
|
+
async function getConversation$1(args) {
|
|
577
|
+
return await readConversation(await getConnectedState(args.state), args.conversationId);
|
|
578
|
+
}
|
|
579
|
+
/** Return a persisted conversation work record, if one exists. */
|
|
580
|
+
async function getConversationWorkState$1(args) {
|
|
581
|
+
const conversation = await getConversation$1(args);
|
|
582
|
+
return conversation ? conversationWorkState(conversation) : void 0;
|
|
583
|
+
}
|
|
584
|
+
/** Return whether a conversation has pending or resumable execution work. */
|
|
585
|
+
function hasRunnableConversationWork$1(conversation) {
|
|
586
|
+
return hasRunnableWork(conversation);
|
|
587
|
+
}
|
|
588
|
+
async function appendInboundMessageWithAdmission(args) {
|
|
589
|
+
const nowMs = args.nowMs ?? now$1();
|
|
590
|
+
return await withConversationMutation({
|
|
591
|
+
conversationId: args.message.conversationId,
|
|
592
|
+
state: args.state
|
|
593
|
+
}, async (state, lock) => {
|
|
594
|
+
const existing = await readConversation(state, args.message.conversationId);
|
|
595
|
+
const current = existing ?? emptyConversation({
|
|
596
|
+
conversationId: args.message.conversationId,
|
|
597
|
+
destination: args.message.destination,
|
|
598
|
+
nowMs,
|
|
599
|
+
source: args.message.source
|
|
600
|
+
});
|
|
601
|
+
if (existing) assertSameOptionalConversationDestination({
|
|
602
|
+
conversationId: args.message.conversationId,
|
|
603
|
+
current: current.destination,
|
|
604
|
+
next: args.message.destination
|
|
605
|
+
});
|
|
606
|
+
const existingPending = current.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId);
|
|
607
|
+
if (current.execution.inboundMessageIds.includes(args.message.inboundMessageId)) {
|
|
608
|
+
if (!existingPending) return { status: "duplicate" };
|
|
609
|
+
const nextStatus = current.execution.status === "idle" ? "pending" : current.execution.status;
|
|
610
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
611
|
+
...current.execution,
|
|
612
|
+
status: nextStatus,
|
|
613
|
+
pendingMessages: current.execution.pendingMessages.map((message) => message.inboundMessageId === args.message.inboundMessageId ? upgradedPendingMessage(message, args.message) : message)
|
|
614
|
+
}, nowMs));
|
|
615
|
+
return { status: "duplicate" };
|
|
616
|
+
}
|
|
617
|
+
if (args.exclusive && hasRunnableWork(current)) return { status: "active" };
|
|
618
|
+
let status;
|
|
619
|
+
if (current.execution.lease) status = current.execution.status === "running" ? "running" : "paused";
|
|
620
|
+
else if (current.execution.status === "paused" && args.message.delivery === "defer") status = "paused";
|
|
621
|
+
else status = "pending";
|
|
622
|
+
await writeConversation(state, lock, withExecutionUpdate({
|
|
623
|
+
...current,
|
|
624
|
+
destination: current.destination ?? args.message.destination,
|
|
625
|
+
source: current.source ?? args.message.source,
|
|
626
|
+
lastActivityAtMs: nowMs
|
|
627
|
+
}, {
|
|
628
|
+
...current.execution,
|
|
629
|
+
status,
|
|
630
|
+
inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId],
|
|
631
|
+
pendingMessages: [...current.execution.pendingMessages, args.message].sort(compareMessages)
|
|
632
|
+
}, nowMs));
|
|
633
|
+
return { status: "appended" };
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
/** Persist one inbound message idempotently in its conversation mailbox. */
|
|
637
|
+
async function appendInboundMessage(args) {
|
|
638
|
+
const result = await appendInboundMessageWithAdmission({
|
|
639
|
+
...args,
|
|
640
|
+
exclusive: false
|
|
641
|
+
});
|
|
642
|
+
if (result.status === "active") throw new Error("Non-exclusive mailbox append returned active");
|
|
643
|
+
return result;
|
|
644
|
+
}
|
|
645
|
+
/** Append only when the Conversation has no other runnable work. */
|
|
646
|
+
async function appendExclusiveInboundMessage(args) {
|
|
647
|
+
return await appendInboundMessageWithAdmission({
|
|
648
|
+
...args,
|
|
649
|
+
exclusive: true
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
/** Mark a conversation runnable when there is no new mailbox message. */
|
|
653
|
+
async function requestConversationWork$1(args) {
|
|
654
|
+
const nowMs = args.nowMs ?? now$1();
|
|
655
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
656
|
+
const existing = await readConversation(state, args.conversationId);
|
|
657
|
+
if (existing) assertSameOptionalConversationDestination({
|
|
658
|
+
conversationId: args.conversationId,
|
|
659
|
+
current: existing.destination,
|
|
660
|
+
next: args.destination
|
|
661
|
+
});
|
|
662
|
+
const current = existing ?? emptyConversation({
|
|
663
|
+
conversationId: args.conversationId,
|
|
664
|
+
destination: args.destination,
|
|
665
|
+
nowMs
|
|
666
|
+
});
|
|
667
|
+
const status = current.execution.lease ? "paused" : "pending";
|
|
668
|
+
await writeConversation(state, lock, withExecutionUpdate({
|
|
669
|
+
...current,
|
|
670
|
+
destination: current.destination ?? args.destination
|
|
671
|
+
}, {
|
|
672
|
+
...current.execution,
|
|
673
|
+
status
|
|
674
|
+
}, nowMs));
|
|
675
|
+
return { status: existing === void 0 ? "created" : "updated" };
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
/** Record that a wake-up nudge was accepted for the conversation. */
|
|
679
|
+
async function markConversationWorkEnqueued$1(args) {
|
|
680
|
+
const nowMs = args.nowMs ?? now$1();
|
|
681
|
+
await withConversationMutation(args, async (state, lock) => {
|
|
682
|
+
const current = await readConversation(state, args.conversationId);
|
|
683
|
+
if (!current) return;
|
|
684
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
685
|
+
...current.execution,
|
|
686
|
+
lastEnqueuedAtMs: nowMs
|
|
687
|
+
}, nowMs));
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
/** Clear a wake marker after its queue delivery finds no runnable work. */
|
|
691
|
+
async function clearConsumedConversationWake$1(args) {
|
|
692
|
+
const nowMs = args.nowMs ?? now$1();
|
|
693
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
694
|
+
const current = await readConversation(state, args.conversationId);
|
|
695
|
+
if (!current || hasRunnableWork(current) || current.execution.lastEnqueuedAtMs === void 0) return false;
|
|
696
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
697
|
+
...current.execution,
|
|
698
|
+
lastEnqueuedAtMs: void 0
|
|
699
|
+
}, nowMs));
|
|
700
|
+
return true;
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
/** Try to acquire the durable execution lease for one conversation. */
|
|
704
|
+
async function startConversationWork$1(args) {
|
|
705
|
+
const nowMs = args.nowMs ?? now$1();
|
|
706
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
707
|
+
const current = await readConversation(state, args.conversationId);
|
|
708
|
+
if (!current) return { status: "no_work" };
|
|
709
|
+
if (isLeaseActive(current.execution.lease, nowMs)) return {
|
|
710
|
+
status: "active",
|
|
711
|
+
leaseExpiresAtMs: current.execution.lease.expiresAtMs
|
|
712
|
+
};
|
|
713
|
+
if (!hasRunnableWork(current)) return { status: "no_work" };
|
|
714
|
+
const lease = {
|
|
715
|
+
token: randomUUID(),
|
|
716
|
+
acquiredAtMs: nowMs,
|
|
717
|
+
lastCheckInAtMs: nowMs,
|
|
718
|
+
expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
|
|
719
|
+
};
|
|
720
|
+
const startsNewRun = current.execution.runId === void 0;
|
|
721
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
722
|
+
...current.execution,
|
|
723
|
+
lease,
|
|
724
|
+
status: current.execution.status === "paused" ? "paused" : "running",
|
|
725
|
+
runId: current.execution.runId ?? randomUUID(),
|
|
726
|
+
lastEnqueuedAtMs: void 0,
|
|
727
|
+
retryCount: startsNewRun ? 0 : current.execution.retryCount
|
|
728
|
+
}, nowMs));
|
|
729
|
+
return {
|
|
730
|
+
status: "acquired",
|
|
731
|
+
leaseToken: lease.token,
|
|
732
|
+
leaseExpiresAtMs: lease.expiresAtMs
|
|
733
|
+
};
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
/** Extend the durable execution lease when the worker checks in. */
|
|
737
|
+
async function checkInConversationWork$1(args) {
|
|
738
|
+
const nowMs = args.nowMs ?? now$1();
|
|
739
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
740
|
+
const current = await readConversation(state, args.conversationId);
|
|
741
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
742
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
743
|
+
...current.execution,
|
|
744
|
+
lease: {
|
|
745
|
+
...current.execution.lease,
|
|
746
|
+
lastCheckInAtMs: nowMs,
|
|
747
|
+
expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
|
|
748
|
+
}
|
|
749
|
+
}, nowMs));
|
|
750
|
+
return true;
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Resolve pending mailbox entries after the caller accepts responsibility.
|
|
755
|
+
*
|
|
756
|
+
* Returning ids acknowledges only that subset; returning nothing acknowledges
|
|
757
|
+
* every pending entry passed to the handler.
|
|
758
|
+
*/
|
|
759
|
+
async function drainConversationMailbox$1(args) {
|
|
760
|
+
const nowMs = args.nowMs ?? now$1();
|
|
761
|
+
const pending = await withConversationMutation(args, async (state) => {
|
|
762
|
+
const current = await readConversation(state, args.conversationId);
|
|
763
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) throw new Error(`Conversation lease is not held for ${args.conversationId}`);
|
|
764
|
+
return pendingMessages(current);
|
|
765
|
+
});
|
|
766
|
+
if (pending.length === 0) return {
|
|
767
|
+
changed: false,
|
|
768
|
+
messages: []
|
|
769
|
+
};
|
|
770
|
+
const result = await args.handle(pending);
|
|
771
|
+
const pendingIds = new Set(pending.map((message) => message.inboundMessageId));
|
|
772
|
+
const acknowledgedIds = new Set(result ?? pending.map((message) => message.inboundMessageId));
|
|
773
|
+
for (const inboundMessageId of acknowledgedIds) if (!pendingIds.has(inboundMessageId)) throw new Error(`Conversation mailbox drain result is not pending for ${args.conversationId}`);
|
|
774
|
+
if (acknowledgedIds.size === 0) return {
|
|
775
|
+
changed: false,
|
|
776
|
+
messages: []
|
|
777
|
+
};
|
|
778
|
+
await withConversationMutation(args, async (state, lock) => {
|
|
779
|
+
const current = await readConversation(state, args.conversationId);
|
|
780
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) throw new Error(`Conversation lease is not held for ${args.conversationId}`);
|
|
781
|
+
const pendingMessages = current.execution.pendingMessages.filter((message) => !acknowledgedIds.has(message.inboundMessageId));
|
|
782
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
783
|
+
...current.execution,
|
|
784
|
+
status: current.execution.status === "pending" && pendingMessages.length === 0 ? "running" : current.execution.status,
|
|
785
|
+
lastProgressAtMs: nowMs,
|
|
786
|
+
retryCount: 0,
|
|
787
|
+
pendingMessages
|
|
788
|
+
}, nowMs));
|
|
789
|
+
});
|
|
790
|
+
return {
|
|
791
|
+
changed: true,
|
|
792
|
+
messages: pending.filter((message) => acknowledgedIds.has(message.inboundMessageId))
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
/** Acknowledge leased mailbox entries after the handler accepts responsibility. */
|
|
796
|
+
async function ackMessages$1(args) {
|
|
797
|
+
const nowMs = args.nowMs ?? now$1();
|
|
798
|
+
const inboundMessageIds = new Set(args.inboundMessageIds);
|
|
799
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
800
|
+
const current = await readConversation(state, args.conversationId);
|
|
801
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
802
|
+
if (inboundMessageIds.size === 0) return true;
|
|
803
|
+
const pendingMessages = current.execution.pendingMessages.filter((message) => !inboundMessageIds.has(message.inboundMessageId));
|
|
804
|
+
if (pendingMessages.length === current.execution.pendingMessages.length) return true;
|
|
805
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
806
|
+
...current.execution,
|
|
807
|
+
lastProgressAtMs: nowMs,
|
|
808
|
+
retryCount: 0,
|
|
809
|
+
pendingMessages
|
|
810
|
+
}, nowMs));
|
|
811
|
+
return true;
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
function isHumanFacingMessage(message) {
|
|
815
|
+
return message.source === "web" || message.source === "slack";
|
|
816
|
+
}
|
|
817
|
+
async function readConversationStop(state, conversationId) {
|
|
818
|
+
return normalizeStop(await state.get(conversationStopKey(conversationId)));
|
|
819
|
+
}
|
|
820
|
+
async function fenceConversationMutation(state, lock, conversationId) {
|
|
821
|
+
if (!await state.extendLock(lock, CONVERSATION_MUTATION_LOCK_TTL_MS)) throw new ConversationMutationFencedError(conversationId);
|
|
822
|
+
}
|
|
823
|
+
/** Return whether one Conversation run has a durable stop request. */
|
|
824
|
+
async function hasConversationStop(args) {
|
|
825
|
+
return (await readConversationStop(await getConnectedState(args.state), args.conversationId))?.runId === args.runId;
|
|
826
|
+
}
|
|
827
|
+
/** Persist a stop request for the current run without process affinity. */
|
|
828
|
+
async function stopConversationWork$1(args) {
|
|
829
|
+
const nowMs = args.nowMs ?? now$1();
|
|
830
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
831
|
+
const current = await readConversation(state, args.conversationId);
|
|
832
|
+
if (!current || !hasRunnableWork(current)) return { status: "no_work" };
|
|
833
|
+
const runId = current.execution.runId ?? randomUUID();
|
|
834
|
+
const pendingMessages = current.execution.pendingMessages.filter(isHumanFacingMessage);
|
|
835
|
+
const inboundMessageIds = pendingMessages.map((message) => message.inboundMessageId);
|
|
836
|
+
if (current.execution.runId === void 0) await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
837
|
+
...current.execution,
|
|
838
|
+
runId
|
|
839
|
+
}, nowMs));
|
|
840
|
+
await fenceConversationMutation(state, lock, args.conversationId);
|
|
841
|
+
await state.set(conversationStopKey(args.conversationId), {
|
|
842
|
+
inboundMessageIds,
|
|
843
|
+
runId
|
|
844
|
+
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
845
|
+
return {
|
|
846
|
+
runId,
|
|
847
|
+
status: "requested",
|
|
848
|
+
pendingMessages
|
|
849
|
+
};
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
/** Clear one observed stop request and discard older human-facing mailbox work. */
|
|
853
|
+
async function completeConversationStop$1(args) {
|
|
854
|
+
const nowMs = args.nowMs ?? now$1();
|
|
855
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
856
|
+
const current = await readConversation(state, args.conversationId);
|
|
857
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return {
|
|
858
|
+
status: "lost_lease",
|
|
859
|
+
removedInboundMessageIds: []
|
|
860
|
+
};
|
|
861
|
+
const stop = await readConversationStop(state, args.conversationId);
|
|
862
|
+
if (!stop || stop.runId !== args.runId) return {
|
|
863
|
+
status: "none",
|
|
864
|
+
removedInboundMessageIds: []
|
|
865
|
+
};
|
|
866
|
+
const stoppedInboundMessageIds = new Set(stop.inboundMessageIds);
|
|
867
|
+
const removedInboundMessageIds = [];
|
|
868
|
+
const pendingMessages = current.execution.pendingMessages.filter((message) => {
|
|
869
|
+
const shouldStop = stoppedInboundMessageIds.has(message.inboundMessageId);
|
|
870
|
+
if (shouldStop) removedInboundMessageIds.push(message.inboundMessageId);
|
|
871
|
+
return !shouldStop;
|
|
872
|
+
});
|
|
873
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
874
|
+
...current.execution,
|
|
875
|
+
lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
|
|
876
|
+
pendingMessages
|
|
877
|
+
}, nowMs));
|
|
878
|
+
await fenceConversationMutation(state, lock, args.conversationId);
|
|
879
|
+
await state.delete(conversationStopKey(args.conversationId));
|
|
880
|
+
return {
|
|
881
|
+
status: "cleared",
|
|
882
|
+
removedInboundMessageIds
|
|
883
|
+
};
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
/** Cancel human-facing pending mailbox rows without requiring a worker lease. */
|
|
887
|
+
async function cancelHumanFacingPendingMessages$1(args) {
|
|
888
|
+
const nowMs = args.nowMs ?? now$1();
|
|
889
|
+
const requestedIds = args.inboundMessageIds === void 0 ? void 0 : new Set(args.inboundMessageIds);
|
|
890
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
891
|
+
const current = await readConversation(state, args.conversationId);
|
|
892
|
+
if (!current) return {
|
|
893
|
+
cancelledInboundMessageIds: [],
|
|
894
|
+
cancelledMessages: []
|
|
895
|
+
};
|
|
896
|
+
const cancelledInboundMessageIds = [];
|
|
897
|
+
const cancelledMessages = [];
|
|
898
|
+
const pendingMessages = [];
|
|
899
|
+
for (const message of current.execution.pendingMessages) {
|
|
900
|
+
const isRequested = requestedIds === void 0 || requestedIds.has(message.inboundMessageId);
|
|
901
|
+
const isInSnapshot = args.receivedBeforeMs === void 0 || message.receivedAtMs <= args.receivedBeforeMs;
|
|
902
|
+
if (isHumanFacingMessage(message) && isRequested && isInSnapshot) {
|
|
903
|
+
cancelledInboundMessageIds.push(message.inboundMessageId);
|
|
904
|
+
cancelledMessages.push(message);
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
pendingMessages.push(message);
|
|
908
|
+
}
|
|
909
|
+
if (cancelledInboundMessageIds.length === 0) return {
|
|
910
|
+
cancelledInboundMessageIds,
|
|
911
|
+
cancelledMessages
|
|
912
|
+
};
|
|
913
|
+
const becomesIdle = current.execution.status === "pending" && pendingMessages.length === 0;
|
|
914
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
915
|
+
...current.execution,
|
|
916
|
+
lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
|
|
917
|
+
pendingMessages,
|
|
918
|
+
retryCount: becomesIdle ? 0 : current.execution.retryCount,
|
|
919
|
+
runId: becomesIdle ? void 0 : current.execution.runId,
|
|
920
|
+
status: becomesIdle ? "idle" : current.execution.status
|
|
921
|
+
}, nowMs));
|
|
922
|
+
return {
|
|
923
|
+
cancelledInboundMessageIds,
|
|
924
|
+
cancelledMessages
|
|
925
|
+
};
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
/** Mark the leased conversation as needing another queue-delivered slice. */
|
|
929
|
+
async function requestAnotherSlice$1(args) {
|
|
930
|
+
const nowMs = args.nowMs ?? now$1();
|
|
931
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
932
|
+
const current = await readConversation(state, args.conversationId);
|
|
933
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
934
|
+
assertSameOptionalConversationDestination({
|
|
935
|
+
conversationId: args.conversationId,
|
|
936
|
+
current: current.destination,
|
|
937
|
+
next: args.destination
|
|
938
|
+
});
|
|
939
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
940
|
+
...current.execution,
|
|
941
|
+
status: "paused"
|
|
942
|
+
}, nowMs));
|
|
943
|
+
return true;
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
/** Begin a requested turn resume under the worker's existing lease. */
|
|
947
|
+
async function beginConversationResume$1(args) {
|
|
948
|
+
const nowMs = args.nowMs ?? now$1();
|
|
949
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
950
|
+
const current = await readConversation(state, args.conversationId);
|
|
951
|
+
if (!current || current.execution.lease?.token !== args.leaseToken || current.execution.status !== "paused") return false;
|
|
952
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
953
|
+
...current.execution,
|
|
954
|
+
status: "running"
|
|
955
|
+
}, nowMs));
|
|
956
|
+
return true;
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
/** Release the durable execution lease without changing completion state. */
|
|
960
|
+
async function releaseConversationWork$1(args) {
|
|
961
|
+
const nowMs = args.nowMs ?? now$1();
|
|
962
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
963
|
+
const current = await readConversation(state, args.conversationId);
|
|
964
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
965
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
966
|
+
...current.execution,
|
|
967
|
+
lease: void 0,
|
|
968
|
+
status: current.execution.status === "running" ? "pending" : current.execution.status
|
|
969
|
+
}, nowMs));
|
|
970
|
+
return true;
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
/** Count one failed execution attempt and stop the conversation when retries are exhausted. */
|
|
974
|
+
async function recordConversationRetry$1(args) {
|
|
975
|
+
const nowMs = args.nowMs ?? now$1();
|
|
976
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
977
|
+
const current = await readConversation(state, args.conversationId);
|
|
978
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
979
|
+
const count = (current.execution.retryCount ?? 0) + 1;
|
|
980
|
+
const stopped = count >= 5;
|
|
981
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
982
|
+
...current.execution,
|
|
983
|
+
lastEnqueuedAtMs: void 0,
|
|
984
|
+
lease: stopped ? void 0 : current.execution.lease,
|
|
985
|
+
retryCount: count,
|
|
986
|
+
pendingMessages: stopped ? [] : current.execution.pendingMessages,
|
|
987
|
+
runId: stopped ? void 0 : current.execution.runId,
|
|
988
|
+
status: stopped ? "failed" : "paused"
|
|
989
|
+
}, nowMs));
|
|
990
|
+
return stopped ? "stopped" : "recorded";
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
/** Finish a leased conversation and report whether runnable work remains. */
|
|
994
|
+
async function completeConversationWork$1(args) {
|
|
995
|
+
const nowMs = args.nowMs ?? now$1();
|
|
996
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
997
|
+
const current = await readConversation(state, args.conversationId);
|
|
998
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
999
|
+
const hasPending = pendingMessages(current).length > 0;
|
|
1000
|
+
const stopped = args.resumeIfStopped === true && (await readConversationStop(state, args.conversationId))?.runId === current.execution.runId;
|
|
1001
|
+
const needsRun = current.execution.status === "paused" || stopped;
|
|
1002
|
+
const runnable = needsRun || hasPending;
|
|
1003
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
1004
|
+
...current.execution,
|
|
1005
|
+
lease: void 0,
|
|
1006
|
+
status: needsRun ? "paused" : hasPending ? "pending" : "idle",
|
|
1007
|
+
lastProgressAtMs: args.madeProgress === false ? current.execution.lastProgressAtMs : nowMs,
|
|
1008
|
+
retryCount: runnable || args.madeProgress === false ? current.execution.retryCount : 0,
|
|
1009
|
+
runId: runnable ? current.execution.runId : void 0
|
|
1010
|
+
}, nowMs));
|
|
1011
|
+
return runnable ? "pending" : "completed";
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Record one failed execution attempt for pending messages, dead-lettering
|
|
1016
|
+
* the conversation when its retry budget or the legacy message delivery limit
|
|
1017
|
+
* is exhausted.
|
|
1018
|
+
*
|
|
1019
|
+
* Retries are counted only when the run made no durable progress: if any
|
|
1020
|
+
* attempted message left the mailbox, the remaining pending entries may be
|
|
1021
|
+
* deliberate deferrals and are left untouched. Consumed message ids stay in
|
|
1022
|
+
* `inboundMessageIds` so source retries remain duplicates.
|
|
1023
|
+
*/
|
|
1024
|
+
async function recordAttemptFailure$1(args) {
|
|
1025
|
+
const nowMs = args.nowMs ?? now$1();
|
|
1026
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
1027
|
+
const current = await readConversation(state, args.conversationId);
|
|
1028
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return {
|
|
1029
|
+
status: "lost_lease",
|
|
1030
|
+
pendingCount: 0,
|
|
1031
|
+
deadLetteredMessages: [],
|
|
1032
|
+
retryCount: 0
|
|
1033
|
+
};
|
|
1034
|
+
const pendingIds = new Set(current.execution.pendingMessages.map((message) => message.inboundMessageId));
|
|
1035
|
+
if (args.inboundMessageIds.length === 0 || args.inboundMessageIds.some((id) => !pendingIds.has(id))) return {
|
|
1036
|
+
status: "skipped",
|
|
1037
|
+
pendingCount: current.execution.pendingMessages.length,
|
|
1038
|
+
deadLetteredMessages: [],
|
|
1039
|
+
retryCount: current.execution.retryCount ?? 0
|
|
1040
|
+
};
|
|
1041
|
+
const retryCount = (current.execution.retryCount ?? 0) + 1;
|
|
1042
|
+
const retriesExhausted = retryCount >= 5;
|
|
1043
|
+
const attemptedIds = new Set(args.inboundMessageIds);
|
|
1044
|
+
const deadLetteredMessages = [];
|
|
1045
|
+
const pendingMessages = [];
|
|
1046
|
+
for (const message of current.execution.pendingMessages) {
|
|
1047
|
+
if (!attemptedIds.has(message.inboundMessageId)) {
|
|
1048
|
+
if (retriesExhausted) deadLetteredMessages.push(message);
|
|
1049
|
+
else pendingMessages.push(message);
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
const attempted = {
|
|
1053
|
+
...message,
|
|
1054
|
+
attemptCount: (message.attemptCount ?? 0) + 1
|
|
1055
|
+
};
|
|
1056
|
+
if (retriesExhausted || attempted.attemptCount >= 5) {
|
|
1057
|
+
deadLetteredMessages.push(attempted);
|
|
1058
|
+
continue;
|
|
1059
|
+
}
|
|
1060
|
+
pendingMessages.push(attempted);
|
|
1061
|
+
}
|
|
1062
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
1063
|
+
...current.execution,
|
|
1064
|
+
retryCount,
|
|
1065
|
+
pendingMessages
|
|
1066
|
+
}, nowMs));
|
|
1067
|
+
return {
|
|
1068
|
+
status: "recorded",
|
|
1069
|
+
pendingCount: pendingMessages.length,
|
|
1070
|
+
deadLetteredMessages,
|
|
1071
|
+
retryCount
|
|
1072
|
+
};
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
/** Record a terminal failure completion for a leased conversation. */
|
|
1076
|
+
async function deadLetterAttempt$1(args) {
|
|
1077
|
+
const nowMs = args.nowMs ?? now$1();
|
|
1078
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
1079
|
+
const current = await readConversation(state, args.conversationId);
|
|
1080
|
+
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
1081
|
+
const runnable = pendingMessages(current).length > 0;
|
|
1082
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
1083
|
+
...current.execution,
|
|
1084
|
+
lease: void 0,
|
|
1085
|
+
status: runnable ? "pending" : "failed",
|
|
1086
|
+
runId: runnable ? current.execution.runId : void 0
|
|
1087
|
+
}, nowMs));
|
|
1088
|
+
return runnable ? "pending" : "failed";
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
/** Recover an expired lease, consuming the retry budget under the mutation lock. */
|
|
1092
|
+
async function clearExpiredConversationLease$1(args) {
|
|
1093
|
+
const nowMs = args.nowMs ?? now$1();
|
|
1094
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
1095
|
+
const current = await readConversation(state, args.conversationId);
|
|
1096
|
+
if (!current?.execution.lease || current.execution.lease.expiresAtMs > nowMs) return "not_expired";
|
|
1097
|
+
const retryCount = (current.execution.retryCount ?? 0) + 1;
|
|
1098
|
+
const stopped = retryCount >= 5;
|
|
1099
|
+
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
1100
|
+
...current.execution,
|
|
1101
|
+
lastEnqueuedAtMs: void 0,
|
|
1102
|
+
lease: void 0,
|
|
1103
|
+
retryCount,
|
|
1104
|
+
pendingMessages: stopped ? [] : current.execution.pendingMessages,
|
|
1105
|
+
runId: stopped ? void 0 : current.execution.runId,
|
|
1106
|
+
status: stopped ? "failed" : "paused"
|
|
1107
|
+
}, nowMs));
|
|
1108
|
+
return stopped ? "stopped" : "requeued";
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
/** Remove one conversation from the active index after it is missing or idle. */
|
|
1112
|
+
async function removeActiveConversation$1(args) {
|
|
1113
|
+
await removeIndexEntry({
|
|
1114
|
+
state: await getConnectedState(args.state),
|
|
1115
|
+
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
1116
|
+
conversationId: args.conversationId
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
/** List active conversation ids by oldest execution update first. */
|
|
1120
|
+
async function listActiveConversationIds$1(args = {}) {
|
|
1121
|
+
return (await (await getConversationIndexStore(await getConnectedState(args.state))).list({
|
|
1122
|
+
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
1123
|
+
limit: args.limit,
|
|
1124
|
+
order: "asc",
|
|
1125
|
+
scoreMax: args.staleBeforeMs
|
|
1126
|
+
})).map((entry) => entry.conversationId);
|
|
1127
|
+
}
|
|
1128
|
+
//#endregion
|
|
1129
|
+
//#region src/chat/task-execution/store.ts
|
|
1130
|
+
function metadataStore(options) {
|
|
1131
|
+
return options.conversationStore ?? getConversationStore();
|
|
1132
|
+
}
|
|
1133
|
+
function duplicateInboundNudgeIdempotencyKey(message, nowMs) {
|
|
1134
|
+
return `duplicate:${message.conversationId}:${message.inboundMessageId}:${nowMs}`;
|
|
1135
|
+
}
|
|
1136
|
+
function hasRecentEnqueueMarker(conversation, nowMs) {
|
|
1137
|
+
const lastEnqueuedAtMs = conversation.execution.lastEnqueuedAtMs;
|
|
1138
|
+
return typeof lastEnqueuedAtMs === "number" && lastEnqueuedAtMs + 6e4 > nowMs;
|
|
1139
|
+
}
|
|
1140
|
+
function now() {
|
|
1141
|
+
return Date.now();
|
|
1142
|
+
}
|
|
1143
|
+
async function recordExecutionMetadata(args) {
|
|
1144
|
+
const conversation = await getConversation$1({
|
|
1145
|
+
conversationId: args.conversationId,
|
|
1146
|
+
state: args.state
|
|
1147
|
+
});
|
|
1148
|
+
if (!conversation) return;
|
|
1149
|
+
await metadataStore(args).recordExecution({
|
|
1150
|
+
channelName: conversation.channelName,
|
|
1151
|
+
conversationId: conversation.conversationId,
|
|
1152
|
+
createdAtMs: conversation.createdAtMs,
|
|
1153
|
+
destination: conversation.destination,
|
|
1154
|
+
execution: {
|
|
1155
|
+
lastCheckpointAtMs: conversation.execution.lastCheckpointAtMs,
|
|
1156
|
+
lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
|
|
1157
|
+
runId: conversation.execution.runId,
|
|
1158
|
+
status: conversation.execution.status,
|
|
1159
|
+
updatedAtMs: conversation.execution.updatedAtMs
|
|
1160
|
+
},
|
|
1161
|
+
lastActivityAtMs: conversation.lastActivityAtMs,
|
|
1162
|
+
metrics: null,
|
|
1163
|
+
actor: conversation.actor,
|
|
1164
|
+
source: conversation.source,
|
|
1165
|
+
title: conversation.title,
|
|
1166
|
+
updatedAtMs: conversation.updatedAtMs
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
/** Return a persisted conversation record, if one exists. */
|
|
1170
|
+
async function getConversation(args) {
|
|
1171
|
+
return await getConversation$1(args);
|
|
1172
|
+
}
|
|
1173
|
+
/** Return a persisted conversation work record, if one exists. */
|
|
1174
|
+
async function getConversationWorkState(args) {
|
|
1175
|
+
return await getConversationWorkState$1(args);
|
|
1176
|
+
}
|
|
1177
|
+
/** Count one failed conversation execution and persist its terminal retry state. */
|
|
1178
|
+
async function recordConversationRetry(args) {
|
|
1179
|
+
const result = await recordConversationRetry$1(args);
|
|
1180
|
+
await recordExecutionMetadata(args);
|
|
1181
|
+
return result;
|
|
1182
|
+
}
|
|
1183
|
+
/** Count mailbox messages that have not yet reached the conversation event log. */
|
|
1184
|
+
function countPendingConversationMessages(conversation) {
|
|
1185
|
+
return conversation.execution.pendingMessages.length;
|
|
1186
|
+
}
|
|
1187
|
+
/** Return whether a conversation has pending or resumable execution work. */
|
|
1188
|
+
function hasRunnableConversationWork(conversation) {
|
|
1189
|
+
return conversation.execution.status !== "idle" || countPendingConversationMessages(conversation) > 0;
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Ensure runnable conversation work has one accepted queue wake-up nudge.
|
|
1193
|
+
*
|
|
1194
|
+
* Ordinary wakes coalesce on a recent accepted marker. A caller can ignore the
|
|
1195
|
+
* marker without replacing an active lease. Replacement is only for consumed
|
|
1196
|
+
* or known-stale deliveries where another queue nudge must exist.
|
|
1197
|
+
*/
|
|
1198
|
+
async function ensureConversationWake(args) {
|
|
1199
|
+
const nowMs = args.nowMs ?? now();
|
|
1200
|
+
const conversation = await getConversation$1({
|
|
1201
|
+
conversationId: args.conversationId,
|
|
1202
|
+
state: args.state
|
|
1203
|
+
});
|
|
1204
|
+
if (!conversation || !hasRunnableConversationWork(conversation)) return { status: "no_work" };
|
|
1205
|
+
if (args.replaceExistingWake !== true && conversation.execution.lease && conversation.execution.lease.expiresAtMs > nowMs) return { status: "lease_active" };
|
|
1206
|
+
if (args.ignoreEnqueueMarker !== true && args.replaceExistingWake !== true && hasRecentEnqueueMarker(conversation, nowMs)) return { status: "already_enqueued" };
|
|
1207
|
+
const queueResult = await args.queue.send({
|
|
1208
|
+
schemaVersion: 2,
|
|
1209
|
+
conversationId: args.conversationId
|
|
1210
|
+
}, {
|
|
1211
|
+
delayMs: args.delayMs,
|
|
1212
|
+
idempotencyKey: args.idempotencyKey
|
|
1213
|
+
});
|
|
1214
|
+
await markConversationWorkEnqueued({
|
|
1215
|
+
conversationId: args.conversationId,
|
|
1216
|
+
conversationStore: args.conversationStore,
|
|
1217
|
+
nowMs,
|
|
1218
|
+
state: args.state
|
|
1219
|
+
});
|
|
1220
|
+
return {
|
|
1221
|
+
status: "enqueued",
|
|
1222
|
+
queueMessageId: queueResult?.messageId
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
async function enqueueAfterAppend(args) {
|
|
1226
|
+
const nowMs = args.nowMs ?? now();
|
|
1227
|
+
const appendResult = args.appendResult;
|
|
1228
|
+
if (appendResult.status === "active") return appendResult;
|
|
1229
|
+
let idempotencyKey = args.message.inboundMessageId;
|
|
1230
|
+
if (appendResult.status === "duplicate") {
|
|
1231
|
+
const conversation = await getConversation$1({
|
|
1232
|
+
conversationId: args.message.conversationId,
|
|
1233
|
+
state: args.state
|
|
1234
|
+
});
|
|
1235
|
+
if (!conversation) return appendResult;
|
|
1236
|
+
if (hasRecentEnqueueMarker(conversation, nowMs)) {
|
|
1237
|
+
await recordExecutionMetadata({
|
|
1238
|
+
conversationId: args.message.conversationId,
|
|
1239
|
+
conversationStore: args.conversationStore,
|
|
1240
|
+
state: args.state
|
|
1241
|
+
});
|
|
1242
|
+
return appendResult;
|
|
1243
|
+
}
|
|
1244
|
+
if (!conversation.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId)) {
|
|
1245
|
+
await recordExecutionMetadata({
|
|
1246
|
+
conversationId: args.message.conversationId,
|
|
1247
|
+
conversationStore: args.conversationStore,
|
|
1248
|
+
state: args.state
|
|
1249
|
+
});
|
|
1250
|
+
return appendResult;
|
|
1251
|
+
}
|
|
1252
|
+
idempotencyKey = duplicateInboundNudgeIdempotencyKey(args.message, nowMs);
|
|
1253
|
+
}
|
|
1254
|
+
const wake = await ensureConversationWake({
|
|
1255
|
+
conversationId: args.message.conversationId,
|
|
1256
|
+
conversationStore: args.conversationStore,
|
|
1257
|
+
delayMs: args.queueDelayMs,
|
|
1258
|
+
idempotencyKey,
|
|
1259
|
+
ignoreEnqueueMarker: args.message.source === "event" ? void 0 : true,
|
|
1260
|
+
nowMs,
|
|
1261
|
+
queue: args.queue,
|
|
1262
|
+
replaceExistingWake: args.replaceExistingWake,
|
|
1263
|
+
state: args.state
|
|
1264
|
+
});
|
|
1265
|
+
if (wake.status !== "enqueued") await recordExecutionMetadata({
|
|
1266
|
+
conversationId: args.message.conversationId,
|
|
1267
|
+
conversationStore: args.conversationStore,
|
|
1268
|
+
state: args.state
|
|
1269
|
+
});
|
|
1270
|
+
return {
|
|
1271
|
+
...appendResult,
|
|
1272
|
+
...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : void 0
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
/** Persist inbound work and ensure a worker wake-up. */
|
|
1276
|
+
async function appendAndEnqueueInboundMessage(args) {
|
|
1277
|
+
const nowMs = args.nowMs ?? now();
|
|
1278
|
+
const result = await enqueueAfterAppend({
|
|
1279
|
+
...args,
|
|
1280
|
+
appendResult: await appendInboundMessage({
|
|
1281
|
+
message: args.message,
|
|
1282
|
+
nowMs,
|
|
1283
|
+
state: args.state
|
|
1284
|
+
}),
|
|
1285
|
+
nowMs
|
|
1286
|
+
});
|
|
1287
|
+
if (result.status === "active") throw new Error("Non-exclusive mailbox enqueue returned active");
|
|
1288
|
+
return result;
|
|
1289
|
+
}
|
|
1290
|
+
/** Persist exclusive inbound work and wake its worker when admitted. */
|
|
1291
|
+
async function appendAndEnqueueExclusiveInboundMessage(args) {
|
|
1292
|
+
const nowMs = args.nowMs ?? now();
|
|
1293
|
+
return await enqueueAfterAppend({
|
|
1294
|
+
...args,
|
|
1295
|
+
appendResult: await appendExclusiveInboundMessage({
|
|
1296
|
+
message: args.message,
|
|
1297
|
+
nowMs,
|
|
1298
|
+
state: args.state
|
|
1299
|
+
}),
|
|
1300
|
+
nowMs
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
/** Persist a stop request for the current Conversation run. */
|
|
1304
|
+
async function stopConversationWork(args) {
|
|
1305
|
+
const result = await stopConversationWork$1(args);
|
|
1306
|
+
if (result.status === "requested") await recordExecutionMetadata(args);
|
|
1307
|
+
return result;
|
|
1308
|
+
}
|
|
1309
|
+
/** Finish an observed stop request under the current worker lease. */
|
|
1310
|
+
async function completeConversationStop(args) {
|
|
1311
|
+
const result = await completeConversationStop$1(args);
|
|
1312
|
+
if (result.status === "cleared") await recordExecutionMetadata(args);
|
|
1313
|
+
return result;
|
|
1314
|
+
}
|
|
1315
|
+
/** Clear an accepted wake marker after its delivery finds no runnable work. */
|
|
1316
|
+
async function clearConsumedConversationWake(args) {
|
|
1317
|
+
const result = await clearConsumedConversationWake$1(args);
|
|
1318
|
+
if (result) await recordExecutionMetadata(args);
|
|
1319
|
+
return result;
|
|
1320
|
+
}
|
|
1321
|
+
/** Mark a conversation runnable when there is no new mailbox message. */
|
|
1322
|
+
async function requestConversationWork(args) {
|
|
1323
|
+
const result = await requestConversationWork$1(args);
|
|
1324
|
+
await recordExecutionMetadata({
|
|
1325
|
+
conversationId: args.conversationId,
|
|
1326
|
+
conversationStore: args.conversationStore,
|
|
1327
|
+
state: args.state
|
|
1328
|
+
});
|
|
1329
|
+
return result;
|
|
1330
|
+
}
|
|
1331
|
+
/** Record that a wake-up nudge was accepted for the conversation. */
|
|
1332
|
+
async function markConversationWorkEnqueued(args) {
|
|
1333
|
+
await markConversationWorkEnqueued$1(args);
|
|
1334
|
+
await recordExecutionMetadata(args);
|
|
1335
|
+
}
|
|
1336
|
+
/** Try to acquire the durable execution lease for one conversation. */
|
|
1337
|
+
async function startConversationWork(args) {
|
|
1338
|
+
const result = await startConversationWork$1(args);
|
|
1339
|
+
await recordExecutionMetadata(args);
|
|
1340
|
+
return result;
|
|
1341
|
+
}
|
|
1342
|
+
/** Extend the durable execution lease when the worker checks in. */
|
|
1343
|
+
async function checkInConversationWork(args) {
|
|
1344
|
+
const result = await checkInConversationWork$1(args);
|
|
1345
|
+
if (result) await recordExecutionMetadata(args);
|
|
1346
|
+
return result;
|
|
1347
|
+
}
|
|
1348
|
+
/** Drain pending mailbox entries after the caller accepts responsibility. */
|
|
1349
|
+
async function drainConversationMailbox(args) {
|
|
1350
|
+
const result = await drainConversationMailbox$1(args);
|
|
1351
|
+
if (result.changed) await recordExecutionMetadata(args);
|
|
1352
|
+
return result.messages;
|
|
1353
|
+
}
|
|
1354
|
+
/** Acknowledge leased mailbox entries after the handler accepts responsibility. */
|
|
1355
|
+
async function ackMessages(args) {
|
|
1356
|
+
const result = await ackMessages$1(args);
|
|
1357
|
+
await recordExecutionMetadata(args);
|
|
1358
|
+
return result;
|
|
1359
|
+
}
|
|
1360
|
+
/** Cancel human-facing pending mailbox rows without requiring a worker lease. */
|
|
1361
|
+
async function cancelHumanFacingPendingMessages(args) {
|
|
1362
|
+
const result = await cancelHumanFacingPendingMessages$1(args);
|
|
1363
|
+
if (result.cancelledInboundMessageIds.length > 0) await recordExecutionMetadata(args);
|
|
1364
|
+
return result;
|
|
1365
|
+
}
|
|
1366
|
+
/** Mark the leased conversation as needing another queue-delivered slice. */
|
|
1367
|
+
async function requestAnotherSlice(args) {
|
|
1368
|
+
const result = await requestAnotherSlice$1(args);
|
|
1369
|
+
await recordExecutionMetadata(args);
|
|
1370
|
+
return result;
|
|
1371
|
+
}
|
|
1372
|
+
/** Begin a requested turn resume without releasing the current lease. */
|
|
1373
|
+
async function beginConversationResume(args) {
|
|
1374
|
+
const result = await beginConversationResume$1(args);
|
|
1375
|
+
if (result) await recordExecutionMetadata(args);
|
|
1376
|
+
return result;
|
|
1377
|
+
}
|
|
1378
|
+
/** Release the durable execution lease without changing completion state. */
|
|
1379
|
+
async function releaseConversationWork(args) {
|
|
1380
|
+
const result = await releaseConversationWork$1(args);
|
|
1381
|
+
await recordExecutionMetadata(args);
|
|
1382
|
+
return result;
|
|
1383
|
+
}
|
|
1384
|
+
/** Finish a leased conversation and report whether runnable work remains. */
|
|
1385
|
+
async function completeConversationWork(args) {
|
|
1386
|
+
const result = await completeConversationWork$1(args);
|
|
1387
|
+
await recordExecutionMetadata(args);
|
|
1388
|
+
return result;
|
|
1389
|
+
}
|
|
1390
|
+
/** Record one failed delivery attempt and dead-letter messages at their limit. */
|
|
1391
|
+
async function recordAttemptFailure(args) {
|
|
1392
|
+
const result = await recordAttemptFailure$1(args);
|
|
1393
|
+
if (result.status === "recorded") await recordExecutionMetadata(args);
|
|
1394
|
+
return result;
|
|
1395
|
+
}
|
|
1396
|
+
/** Record a terminal failure completion for a leased conversation. */
|
|
1397
|
+
async function deadLetterAttempt(args) {
|
|
1398
|
+
const result = await deadLetterAttempt$1(args);
|
|
1399
|
+
await recordExecutionMetadata(args);
|
|
1400
|
+
return result;
|
|
1401
|
+
}
|
|
1402
|
+
/** Recover an expired lease and persist the resulting retry state. */
|
|
1403
|
+
async function clearExpiredConversationLease(args) {
|
|
1404
|
+
const result = await clearExpiredConversationLease$1(args);
|
|
1405
|
+
await recordExecutionMetadata(args);
|
|
1406
|
+
return result;
|
|
1407
|
+
}
|
|
1408
|
+
/** Remove one conversation from the active index after it is missing or idle. */
|
|
1409
|
+
async function removeActiveConversation(args) {
|
|
1410
|
+
return await removeActiveConversation$1(args);
|
|
1411
|
+
}
|
|
1412
|
+
/** List active conversation ids by oldest execution update first. */
|
|
1413
|
+
async function listActiveConversationIds(args = {}) {
|
|
1414
|
+
return await listActiveConversationIds$1(args);
|
|
1415
|
+
}
|
|
1416
|
+
//#endregion
|
|
1417
|
+
export { hasRunnableConversationWork$1 as A, requestAnotherSlice as C, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as D, stopConversationWork as E, isInvalidConversationRecordError as M, CONVERSATION_WORK_STALE_ENQUEUE_MS as O, removeActiveConversation as S, startConversationWork as T, hasRunnableConversationWork as _, cancelHumanFacingPendingMessages as a, recordConversationRetry as b, clearExpiredConversationLease as c, countPendingConversationMessages as d, deadLetterAttempt as f, getConversationWorkState as g, getConversation as h, beginConversationResume as i, isFinalAttempt as j, hasConversationStop as k, completeConversationStop as l, ensureConversationWake as m, appendAndEnqueueExclusiveInboundMessage as n, checkInConversationWork as o, drainConversationMailbox as p, appendAndEnqueueInboundMessage as r, clearConsumedConversationWake as s, ackMessages as t, completeConversationWork as u, listActiveConversationIds as v, requestConversationWork as w, releaseConversationWork as x, recordAttemptFailure as y };
|