@sentry/junior 0.137.0 → 0.138.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 (87) hide show
  1. package/dist/{agent-hooks-MZOKEP3J.js → agent-hooks-SCR74Q3E.js} +11 -9
  2. package/dist/api.js +21 -18
  3. package/dist/app.d.ts +7 -0
  4. package/dist/app.js +248 -689
  5. package/dist/{catalog-runtime-MD66YLFV.js → catalog-runtime-IU3QF4GG.js} +5 -5
  6. package/dist/chat/agent/request.d.ts +32 -2
  7. package/dist/chat/agent-dispatch/heartbeat.d.ts +5 -0
  8. package/dist/chat/agent-dispatch/types.d.ts +1 -1
  9. package/dist/chat/agent-invocations/errors.d.ts +8 -0
  10. package/dist/chat/agent-invocations/spawn.d.ts +12 -0
  11. package/dist/chat/agent-invocations/store.d.ts +44 -0
  12. package/dist/chat/agent-invocations/types.d.ts +449 -0
  13. package/dist/chat/agent-invocations/work.d.ts +31 -0
  14. package/dist/chat/config.d.ts +1 -0
  15. package/dist/chat/conversations/sql/store.d.ts +8 -0
  16. package/dist/chat/conversations/store.d.ts +7 -0
  17. package/dist/chat/experimental.d.ts +16 -0
  18. package/dist/chat/runtime/agent-runner.d.ts +2 -1
  19. package/dist/chat/services/auth-pause.d.ts +0 -1
  20. package/dist/chat/services/mcp-auth-orchestration.d.ts +3 -2
  21. package/dist/chat/services/plugin-auth-orchestration.d.ts +3 -2
  22. package/dist/chat/state/turn-session.d.ts +0 -2
  23. package/dist/chat/task-execution/state.d.ts +23 -11
  24. package/dist/chat/task-execution/store.d.ts +20 -11
  25. package/dist/chat/task-execution/worker.d.ts +2 -2
  26. package/dist/chat/tools/runtime/spawn-agent.d.ts +31 -0
  27. package/dist/chat/tools/types.d.ts +2 -0
  28. package/dist/chunk-3Y47VMHV.js +6 -0
  29. package/dist/chunk-5IDFPCON.js +46 -0
  30. package/dist/chunk-5LTJ4ITU.js +1523 -0
  31. package/dist/{chunk-WPPXIAFB.js → chunk-5MXWHTCK.js} +17 -434
  32. package/dist/{chunk-UOXATPSI.js → chunk-A7WCHXZV.js} +7 -5
  33. package/dist/{chunk-5G34IEK2.js → chunk-BOLJOV5T.js} +2 -56
  34. package/dist/{chunk-UG6ZYPBI.js → chunk-BYW4B4PR.js} +73 -60
  35. package/dist/{chunk-XZ7NPXAB.js → chunk-C7ZVPO4Z.js} +1 -1
  36. package/dist/{chunk-RB4NJKEX.js → chunk-DCLLQGS6.js} +119 -50
  37. package/dist/{chunk-DQXAAVTR.js → chunk-E5UYAIKJ.js} +44 -1467
  38. package/dist/{chunk-6QW2RRQT.js → chunk-ELKW5FIB.js} +5 -5
  39. package/dist/chunk-EM225ITJ.js +56 -0
  40. package/dist/{chunk-SYCX4DOK.js → chunk-FEUNPTGV.js} +7 -60
  41. package/dist/{chunk-YRPC6MJY.js → chunk-FNLBTB4K.js} +1 -1
  42. package/dist/chunk-HIWJWWMT.js +668 -0
  43. package/dist/chunk-IUFM5JWV.js +24 -0
  44. package/dist/{chunk-T6Z5S6PQ.js → chunk-JNNJZURV.js} +1 -1
  45. package/dist/{chunk-6ZK6FZIV.js → chunk-KCBZSJRU.js} +6 -27
  46. package/dist/{chunk-5PNJMOY5.js → chunk-KDCHVT25.js} +1 -1
  47. package/dist/{chunk-BZAMASJP.js → chunk-KFRHRSCJ.js} +1 -1
  48. package/dist/chunk-LPVUNO2W.js +320 -0
  49. package/dist/{chunk-EWDSB24B.js → chunk-N7WARMC6.js} +16 -776
  50. package/dist/chunk-PB3CXNVL.js +41 -0
  51. package/dist/chunk-Q6QZTTLS.js +55 -0
  52. package/dist/{chunk-36EG34YI.js → chunk-QS527AV5.js} +1 -1
  53. package/dist/chunk-R776HKPK.js +81 -0
  54. package/dist/{chunk-KJ4HGRHN.js → chunk-RZIBSCYC.js} +507 -596
  55. package/dist/chunk-SD3OFRWY.js +714 -0
  56. package/dist/{chunk-ZFS67WIR.js → chunk-SIPKWSXK.js} +57 -6
  57. package/dist/chunk-TCS76X5D.js +441 -0
  58. package/dist/{chunk-K2NCQJKH.js → chunk-TDJCLNDH.js} +3 -3
  59. package/dist/{chunk-POBSY47Q.js → chunk-TUUDXEXU.js} +336 -302
  60. package/dist/{chunk-YNFERGKP.js → chunk-VPZFVJND.js} +1 -1
  61. package/dist/{chunk-UZQ4VY3M.js → chunk-YU5QUF67.js} +1 -1
  62. package/dist/chunk-ZBSMCXKV.js +710 -0
  63. package/dist/{chunk-3Q342EJJ.js → chunk-ZXNTJJIE.js} +2 -2
  64. package/dist/cli/chat.js +65 -26
  65. package/dist/cli/check.js +6 -6
  66. package/dist/cli/plugins.js +14 -12
  67. package/dist/cli/snapshot-create.js +10 -9
  68. package/dist/cli/upgrade.js +7 -7
  69. package/dist/conversation-work-KATFHLG3.js +56 -0
  70. package/dist/db/schema/agent-invocations.d.ts +544 -0
  71. package/dist/db/schema.d.ts +543 -1
  72. package/dist/{db-66E7VDNC.js → db-UO2IWXGA.js} +7 -7
  73. package/dist/experimental-HH6OM6UH.js +13 -0
  74. package/dist/instrumentation.js +4 -4
  75. package/dist/nitro.js +4 -3
  76. package/dist/{oauth-callback-server-7QPD4Q7P.js → oauth-callback-server-MAQI43LX.js} +26 -18
  77. package/dist/{runner-L2BKJKOD.js → runner-PIUQEXKE.js} +26 -14
  78. package/dist/{skills-HOQ2NSPW.js → skills-4ARJADHQ.js} +6 -6
  79. package/dist/spawn-G2AWPMCT.js +38 -0
  80. package/dist/{validation-ENHI7S2C.js → validation-S3EE3HWL.js} +6 -6
  81. package/dist/version.js +1 -1
  82. package/dist/work-UARRUAW3.js +46 -0
  83. package/dist/worker-DOCIRVD3.js +24 -0
  84. package/migrations/0021_first_warhawk.sql +35 -0
  85. package/migrations/meta/0021_snapshot.json +2176 -0
  86. package/migrations/meta/_journal.json +8 -1
  87. package/package.json +5 -5
@@ -2,7 +2,10 @@ import {
2
2
  relayLocalOAuthCallback
3
3
  } from "./chunk-FA6POGLH.js";
4
4
  import {
5
- ConversationTurnLifecycleService,
5
+ ensureConversationWake,
6
+ requestConversationWork
7
+ } from "./chunk-5LTJ4ITU.js";
8
+ import {
6
9
  buildDeliveredTurnStatePatch,
7
10
  finalizeFailedTurnReplyWithEvent,
8
11
  getInterruptionMarker,
@@ -14,36 +17,42 @@ import {
14
17
  requireTurnFailureEventId,
15
18
  resolveTurnSessionRouting,
16
19
  scheduleSessionCompletedPluginTasks
17
- } from "./chunk-SYCX4DOK.js";
20
+ } from "./chunk-FEUNPTGV.js";
21
+ import {
22
+ ConversationTurnLifecycleService
23
+ } from "./chunk-Q6QZTTLS.js";
18
24
  import {
19
25
  buildSentryConversationUrl
20
26
  } from "./chunk-4CODA7P5.js";
21
27
  import {
22
28
  getVercelConversationWorkQueue
23
- } from "./chunk-6ZK6FZIV.js";
29
+ } from "./chunk-KCBZSJRU.js";
24
30
  import {
25
- RetryableDeliveryError,
26
- addReactionToMessage,
27
31
  createUserTokenStore,
28
32
  deleteMcpAuthSession,
29
- escapeSlackMrkdwnText,
30
33
  finalizeMcpAuthorization,
31
- formatProviderLabel,
32
- formatSlackLink,
33
34
  getMcpAuthSession,
34
35
  getMcpProviderErrorAttributes,
35
36
  getMcpStoredOAuthCredentials,
37
+ resolvePluginOAuthAccount
38
+ } from "./chunk-N7WARMC6.js";
39
+ import {
40
+ RetryableDeliveryError
41
+ } from "./chunk-R776HKPK.js";
42
+ import {
43
+ addReactionToMessage,
44
+ escapeSlackMrkdwnText,
45
+ formatProviderLabel,
46
+ formatSlackLink,
36
47
  normalizeSlackReplyMarkdown,
37
48
  normalizeSlackStatusText,
38
49
  parseOAuthStatePayload,
39
50
  postSlackMessage,
40
51
  removeReactionFromMessage,
41
52
  resolveBaseUrl,
42
- resolvePluginOAuthAccount,
43
53
  truncateStatusText
44
- } from "./chunk-EWDSB24B.js";
54
+ } from "./chunk-SD3OFRWY.js";
45
55
  import {
46
- JUNIOR_THREAD_STATE_TTL_MS,
47
56
  TurnSliceLimitExceededError,
48
57
  abandonAgentTurnSessionRecord,
49
58
  buildConversationContext,
@@ -73,34 +82,32 @@ import {
73
82
  recordDeliveredAssistantMessage,
74
83
  turnHasReply,
75
84
  updateConversationStats
76
- } from "./chunk-POBSY47Q.js";
85
+ } from "./chunk-TUUDXEXU.js";
77
86
  import {
78
87
  parseSlackThreadId,
79
88
  readSlackRawMessageContext,
80
89
  resolveSlackChannelIdFromMessage,
81
90
  resolveSlackChannelIdFromThreadId
82
- } from "./chunk-YRPC6MJY.js";
91
+ } from "./chunk-FNLBTB4K.js";
83
92
  import {
84
- SlackActionError,
85
93
  getDashboardConversationLink,
94
+ getPluginSlackConversationLink
95
+ } from "./chunk-5MXWHTCK.js";
96
+ import {
97
+ SlackActionError,
86
98
  getHeaderString,
87
- getPluginSlackConversationLink,
88
99
  getSlackClient,
89
100
  isDmChannel,
90
101
  normalizeSlackConversationId
91
- } from "./chunk-WPPXIAFB.js";
102
+ } from "./chunk-TCS76X5D.js";
92
103
  import {
93
104
  getConversationEventStore,
94
- getConversationStore,
95
- parseDestination,
96
- requireSlackDestination,
97
- sameDestination
98
- } from "./chunk-ZFS67WIR.js";
105
+ requireSlackDestination
106
+ } from "./chunk-SIPKWSXK.js";
99
107
  import {
100
108
  acquireActiveLock,
101
- getDefaultRedisStateAdapterFor,
102
109
  getStateAdapter
103
- } from "./chunk-5G34IEK2.js";
110
+ } from "./chunk-BOLJOV5T.js";
104
111
  import {
105
112
  FUNCTION_TIMEOUT_BUFFER_SECONDS,
106
113
  botConfig,
@@ -109,37 +116,34 @@ import {
109
116
  getRuntimeMetadata,
110
117
  normalizeSlackEmojiName,
111
118
  standardModelId
112
- } from "./chunk-UG6ZYPBI.js";
119
+ } from "./chunk-BYW4B4PR.js";
113
120
  import {
114
121
  discoverSkills
115
- } from "./chunk-3Q342EJJ.js";
122
+ } from "./chunk-ZXNTJJIE.js";
116
123
  import {
117
124
  pluginCatalogRuntime
118
- } from "./chunk-36EG34YI.js";
125
+ } from "./chunk-QS527AV5.js";
119
126
  import {
120
127
  buildOAuthTokenRequest,
121
128
  hasRequiredOAuthScope,
122
129
  parseOAuthTokenResponse
123
- } from "./chunk-BZAMASJP.js";
130
+ } from "./chunk-KFRHRSCJ.js";
124
131
  import {
125
132
  createSlackResumeActor,
126
- isUserActor,
127
- parseStoredSlackActor
133
+ isUserActor
128
134
  } from "./chunk-HZF5P5UN.js";
129
135
  import {
130
136
  parseSlackMessageTs
131
137
  } from "./chunk-F3B2YJ76.js";
132
138
  import {
133
139
  buildTurnFailureResponse,
134
- isRecord,
135
140
  logException,
136
141
  logInfo,
137
142
  logWarn,
138
143
  setTags,
139
- toOptionalNumber,
140
144
  toOptionalString,
141
145
  withLogContext
142
- } from "./chunk-T6Z5S6PQ.js";
146
+ } from "./chunk-JNNJZURV.js";
143
147
  import {
144
148
  homeDir
145
149
  } from "./chunk-H4HBKISO.js";
@@ -204,7 +208,7 @@ var STATUS_UPDATE_DEBOUNCE_MS = 1e3;
204
208
  var STATUS_MIN_VISIBLE_MS = 1200;
205
209
  var STATUS_ROTATION_INTERVAL_MS = 3e4;
206
210
  function createAssistantStatusScheduler(args) {
207
- const now3 = args.now ?? (() => Date.now());
211
+ const now = args.now ?? (() => Date.now());
208
212
  const setTimer = args.setTimer ?? ((callback, delayMs) => setTimeout(callback, delayMs));
209
213
  const clearTimer = args.clearTimer ?? ((timer) => clearTimeout(timer));
210
214
  const random = args.random ?? Math.random;
@@ -268,7 +272,7 @@ function createAssistantStatusScheduler(args) {
268
272
  }
269
273
  currentVisibleStatus = text;
270
274
  currentLoadingMessages = nextLoadingMessages;
271
- lastStatusAt = now3();
275
+ lastStatusAt = now();
272
276
  scheduleRotation();
273
277
  await enqueueStatusUpdate(async () => {
274
278
  await args.sendStatus(text, nextLoadingMessages);
@@ -355,7 +359,7 @@ function createAssistantStatusScheduler(args) {
355
359
  }
356
360
  return;
357
361
  }
358
- const elapsed = now3() - lastStatusAt;
362
+ const elapsed = now() - lastStatusAt;
359
363
  const waitMs = Math.max(
360
364
  STATUS_UPDATE_DEBOUNCE_MS - elapsed,
361
365
  STATUS_MIN_VISIBLE_MS - elapsed,
@@ -1740,1410 +1744,6 @@ async function resumeSlackTurnInContext(args) {
1740
1744
  return true;
1741
1745
  }
1742
1746
 
1743
- // src/chat/task-execution/state.ts
1744
- import { randomUUID } from "crypto";
1745
- import { destinationSchema } from "@sentry/junior-plugin-api";
1746
- import { z } from "zod";
1747
- var CONVERSATION_PREFIX = "junior:conversation";
1748
- var CONVERSATION_SCHEMA_VERSION = 2;
1749
- var CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH = 1e4;
1750
- var CONVERSATION_INDEX_LOCK_TTL_MS = 1e4;
1751
- var CONVERSATION_INDEX_LOCK_WAIT_MS = 2e3;
1752
- var CONVERSATION_INDEX_LOCK_RETRY_MS = 25;
1753
- var CONVERSATION_MUTATION_LOCK_TTL_MS = 1e4;
1754
- var CONVERSATION_MUTATION_WAIT_MS = 1e4;
1755
- var CONVERSATION_MUTATION_RETRY_MS = 25;
1756
- var InvalidConversationRecordError = class extends Error {
1757
- constructor(conversationId) {
1758
- super(`Conversation record is invalid for ${conversationId}`);
1759
- this.name = "InvalidConversationRecordError";
1760
- }
1761
- };
1762
- function isInvalidConversationRecordError(error) {
1763
- return error instanceof InvalidConversationRecordError;
1764
- }
1765
- var ConversationMutationFencedError = class extends Error {
1766
- constructor(conversationId) {
1767
- super(
1768
- `Conversation mutation lock was lost before write for ${conversationId}`
1769
- );
1770
- this.name = "ConversationMutationFencedError";
1771
- }
1772
- };
1773
- var CONVERSATION_BY_ACTIVITY_INDEX_KEY = `${CONVERSATION_PREFIX}:by-activity`;
1774
- var CONVERSATION_ACTIVE_INDEX_KEY = `${CONVERSATION_PREFIX}:active`;
1775
- var CONVERSATION_WORK_LEASE_TTL_MS = 9e4;
1776
- var CONVERSATION_WORK_CHECK_IN_INTERVAL_MS = 15e3;
1777
- var CONVERSATION_WORK_STALE_ENQUEUE_MS = 6e4;
1778
- var CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS = 5;
1779
- var inboundMessageSourceSchema = z.enum([
1780
- "api",
1781
- "internal",
1782
- "local",
1783
- "plugin",
1784
- "resource_event",
1785
- "scheduler",
1786
- "slack"
1787
- ]);
1788
- var agentInputSchema = z.object({
1789
- attachments: z.array(z.unknown()).optional(),
1790
- authorId: z.string().min(1).optional(),
1791
- metadata: z.record(z.string(), z.unknown()).optional(),
1792
- text: z.string()
1793
- }).strict().refine((input) => input.text.trim() || input.attachments?.length, {
1794
- message: "agent input requires text or attachments"
1795
- });
1796
- var inboundMessageDeliverySchema = z.enum(["defer", "interrupt"]);
1797
- var inboundMessageSchema = z.object({
1798
- attemptCount: z.number().finite().optional(),
1799
- conversationId: z.string().refine((value) => value.trim().length > 0),
1800
- createdAtMs: z.number().finite(),
1801
- delivery: inboundMessageDeliverySchema,
1802
- destination: destinationSchema,
1803
- inboundMessageId: z.string().refine((value) => value.trim().length > 0),
1804
- injectedAtMs: z.number().finite().optional(),
1805
- input: agentInputSchema,
1806
- receivedAtMs: z.number().finite(),
1807
- source: inboundMessageSourceSchema
1808
- }).strict();
1809
- function conversationKey(conversationId) {
1810
- return `${CONVERSATION_PREFIX}:${conversationId}`;
1811
- }
1812
- function indexLockKey(indexKey) {
1813
- return `${indexKey}:lock`;
1814
- }
1815
- function mutationLockKey(conversationId) {
1816
- return `${CONVERSATION_PREFIX}:mutation:${conversationId}`;
1817
- }
1818
- function now() {
1819
- return Date.now();
1820
- }
1821
- function compareMessages(left, right) {
1822
- return left.createdAtMs - right.createdAtMs || left.receivedAtMs - right.receivedAtMs || left.inboundMessageId.localeCompare(right.inboundMessageId);
1823
- }
1824
- function inputHasAttachments(input) {
1825
- return Array.isArray(input.attachments) && input.attachments.length > 0;
1826
- }
1827
- function upgradedPendingMessage(stored, duplicate) {
1828
- const promotesInterrupt = stored.delivery === "defer" && duplicate.delivery === "interrupt";
1829
- const delivery = promotesInterrupt ? "interrupt" : stored.delivery;
1830
- const input = promotesInterrupt ? {
1831
- ...duplicate.input,
1832
- ...inputHasAttachments(duplicate.input) || !inputHasAttachments(stored.input) ? {} : { attachments: stored.input.attachments }
1833
- } : inputHasAttachments(duplicate.input) && !inputHasAttachments(stored.input) ? duplicate.input : stored.input;
1834
- if (input === stored.input && delivery === stored.delivery) {
1835
- return stored;
1836
- }
1837
- return { ...stored, delivery, input };
1838
- }
1839
- function compareIndexDescending(left, right) {
1840
- return right.score - left.score || right.conversationId.localeCompare(left.conversationId);
1841
- }
1842
- function compareIndexAscending(left, right) {
1843
- return left.score - right.score || left.conversationId.localeCompare(right.conversationId);
1844
- }
1845
- function uniqueStrings(values) {
1846
- return [...new Set(values)];
1847
- }
1848
- function normalizeSource(value) {
1849
- const parsed = inboundMessageSourceSchema.safeParse(value);
1850
- return parsed.success ? parsed.data : void 0;
1851
- }
1852
- function normalizeExecutionStatus(value) {
1853
- if (value === "awaiting_resume" || value === "failed" || value === "idle" || value === "pending" || value === "running") {
1854
- return value;
1855
- }
1856
- return void 0;
1857
- }
1858
- function normalizeMessage(value, schemaVersion) {
1859
- const candidate = schemaVersion === 1 && isRecord(value) && value.delivery === void 0 ? {
1860
- ...value,
1861
- delivery: "defer"
1862
- } : value;
1863
- const parsed = inboundMessageSchema.safeParse(candidate);
1864
- return parsed.success ? parsed.data : void 0;
1865
- }
1866
- function isFinalAttempt(message) {
1867
- return (message.attemptCount ?? 0) >= CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS - 1;
1868
- }
1869
- function normalizeActor(value) {
1870
- return parseStoredSlackActor(value);
1871
- }
1872
- function normalizeLease(value) {
1873
- if (!isRecord(value)) {
1874
- return void 0;
1875
- }
1876
- const token = toOptionalString(value.token);
1877
- const acquiredAtMs = toOptionalNumber(value.acquiredAtMs);
1878
- const lastCheckInAtMs = toOptionalNumber(value.lastCheckInAtMs);
1879
- const expiresAtMs = toOptionalNumber(value.expiresAtMs);
1880
- if (!token || typeof acquiredAtMs !== "number" || typeof lastCheckInAtMs !== "number" || typeof expiresAtMs !== "number") {
1881
- return void 0;
1882
- }
1883
- return {
1884
- token,
1885
- acquiredAtMs,
1886
- lastCheckInAtMs,
1887
- expiresAtMs
1888
- };
1889
- }
1890
- function normalizeExecution(conversationId, value, schemaVersion) {
1891
- if (!isRecord(value)) {
1892
- return void 0;
1893
- }
1894
- const status = normalizeExecutionStatus(value.status);
1895
- if (!status) {
1896
- return void 0;
1897
- }
1898
- const pendingMessages2 = [];
1899
- if (Array.isArray(value.pendingMessages)) {
1900
- for (const rawMessage of value.pendingMessages) {
1901
- const message = normalizeMessage(rawMessage, schemaVersion);
1902
- if (!message || message.conversationId !== conversationId) {
1903
- return void 0;
1904
- }
1905
- if (message.injectedAtMs !== void 0) {
1906
- continue;
1907
- }
1908
- pendingMessages2.push(message);
1909
- }
1910
- pendingMessages2.sort(compareMessages);
1911
- }
1912
- const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(
1913
- value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))
1914
- ) : [];
1915
- const lease = normalizeLease(value.lease);
1916
- const normalizedStatus = status === "idle" && lease ? "running" : status === "idle" && pendingMessages2.length > 0 ? "pending" : status;
1917
- return {
1918
- status: normalizedStatus,
1919
- inboundMessageIds: uniqueStrings([
1920
- ...inboundMessageIds,
1921
- ...pendingMessages2.map((message) => message.inboundMessageId)
1922
- ]),
1923
- pendingCount: pendingMessages2.length,
1924
- pendingMessages: pendingMessages2,
1925
- lease,
1926
- lastCheckpointAtMs: toOptionalNumber(value.lastCheckpointAtMs),
1927
- lastEnqueuedAtMs: toOptionalNumber(value.lastEnqueuedAtMs),
1928
- runId: toOptionalString(value.runId),
1929
- updatedAtMs: toOptionalNumber(value.updatedAtMs)
1930
- };
1931
- }
1932
- function normalizeConversation(conversationId, value) {
1933
- if (!isRecord(value) || value.schemaVersion !== 1 && value.schemaVersion !== CONVERSATION_SCHEMA_VERSION) {
1934
- return void 0;
1935
- }
1936
- const schemaVersion = value.schemaVersion;
1937
- const storedConversationId = toOptionalString(value.conversationId);
1938
- const createdAtMs = toOptionalNumber(value.createdAtMs);
1939
- const lastActivityAtMs = toOptionalNumber(value.lastActivityAtMs);
1940
- const updatedAtMs = toOptionalNumber(value.updatedAtMs);
1941
- const execution = normalizeExecution(
1942
- conversationId,
1943
- value.execution,
1944
- schemaVersion
1945
- );
1946
- const destination = value.destination === void 0 ? void 0 : parseDestination(value.destination);
1947
- if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value.destination !== void 0 && !destination) {
1948
- return void 0;
1949
- }
1950
- if (execution.pendingMessages.length > 0 && (!destination || execution.pendingMessages.some(
1951
- (message) => !sameDestination(message.destination, destination)
1952
- ))) {
1953
- return void 0;
1954
- }
1955
- return {
1956
- schemaVersion: CONVERSATION_SCHEMA_VERSION,
1957
- conversationId,
1958
- createdAtMs,
1959
- lastActivityAtMs,
1960
- updatedAtMs,
1961
- execution,
1962
- ...destination ? { destination } : {},
1963
- ...toOptionalString(value.title) ? { title: toOptionalString(value.title) } : {},
1964
- ...toOptionalString(value.channelName) ? { channelName: toOptionalString(value.channelName) } : {},
1965
- ...normalizeActor(value.actor) ? { actor: normalizeActor(value.actor) } : {},
1966
- ...normalizeSource(value.source) ? { source: normalizeSource(value.source) } : {}
1967
- };
1968
- }
1969
- function emptyConversation(args) {
1970
- return {
1971
- schemaVersion: CONVERSATION_SCHEMA_VERSION,
1972
- conversationId: args.conversationId,
1973
- createdAtMs: args.nowMs,
1974
- lastActivityAtMs: args.nowMs,
1975
- updatedAtMs: args.nowMs,
1976
- ...args.destination ? { destination: args.destination } : {},
1977
- ...args.source ? { source: args.source } : {},
1978
- execution: {
1979
- status: "idle",
1980
- inboundMessageIds: [],
1981
- pendingCount: 0,
1982
- pendingMessages: [],
1983
- updatedAtMs: args.nowMs
1984
- }
1985
- };
1986
- }
1987
- function isLeaseActive(lease, nowMs) {
1988
- return Boolean(lease && lease.expiresAtMs > nowMs);
1989
- }
1990
- function pendingMessages(conversation) {
1991
- return [...conversation.execution.pendingMessages].sort(compareMessages);
1992
- }
1993
- function isRunnableStatus(status) {
1994
- return status !== "failed" && status !== "idle";
1995
- }
1996
- function hasRunnableWork(conversation) {
1997
- return isRunnableStatus(conversation.execution.status) || pendingMessages(conversation).length > 0;
1998
- }
1999
- function executionWithPendingMessages(execution, pending) {
2000
- const pendingMessages2 = [...pending].sort(compareMessages);
2001
- const status = execution.status === "idle" && execution.lease ? "running" : execution.status === "idle" && pendingMessages2.length > 0 ? "pending" : execution.status;
2002
- return {
2003
- ...execution,
2004
- status,
2005
- inboundMessageIds: uniqueStrings([
2006
- ...execution.inboundMessageIds,
2007
- ...pendingMessages2.map((message) => message.inboundMessageId)
2008
- ]),
2009
- pendingMessages: pendingMessages2,
2010
- pendingCount: pendingMessages2.length
2011
- };
2012
- }
2013
- function withExecutionUpdate(conversation, execution, nowMs) {
2014
- return {
2015
- ...conversation,
2016
- updatedAtMs: nowMs,
2017
- execution: {
2018
- ...executionWithPendingMessages(execution, execution.pendingMessages),
2019
- updatedAtMs: nowMs
2020
- }
2021
- };
2022
- }
2023
- async function getConnectedState(stateAdapter) {
2024
- const state = stateAdapter ?? getStateAdapter();
2025
- await state.connect();
2026
- return state;
2027
- }
2028
- async function sleep(ms) {
2029
- await new Promise((resolve) => {
2030
- const timer = setTimeout(resolve, ms);
2031
- timer.unref?.();
2032
- });
2033
- }
2034
- async function withIndexLock(state, indexKey, callback) {
2035
- const startedAtMs = now();
2036
- let lock;
2037
- while (true) {
2038
- lock = await state.acquireLock(
2039
- indexLockKey(indexKey),
2040
- CONVERSATION_INDEX_LOCK_TTL_MS
2041
- );
2042
- if (lock) {
2043
- break;
2044
- }
2045
- if (now() - startedAtMs >= CONVERSATION_INDEX_LOCK_WAIT_MS) {
2046
- throw new Error(
2047
- `Could not acquire conversation index lock for ${indexKey}`
2048
- );
2049
- }
2050
- await sleep(CONVERSATION_INDEX_LOCK_RETRY_MS);
2051
- }
2052
- try {
2053
- return await callback();
2054
- } finally {
2055
- await state.releaseLock(lock);
2056
- }
2057
- }
2058
- function normalizeIndexEntry(value) {
2059
- if (!isRecord(value)) {
2060
- return void 0;
2061
- }
2062
- const conversationId = toOptionalString(value.conversationId);
2063
- const score = toOptionalNumber(value.score);
2064
- if (!conversationId || typeof score !== "number") {
2065
- return void 0;
2066
- }
2067
- return { conversationId, score };
2068
- }
2069
- function uniqueIndexEntries(value) {
2070
- if (!Array.isArray(value)) {
2071
- return [];
2072
- }
2073
- const entries = /* @__PURE__ */ new Map();
2074
- for (const item of value) {
2075
- const entry = normalizeIndexEntry(item);
2076
- if (!entry) {
2077
- continue;
2078
- }
2079
- const existing = entries.get(entry.conversationId);
2080
- if (!existing || entry.score > existing.score) {
2081
- entries.set(entry.conversationId, entry);
2082
- }
2083
- }
2084
- return [...entries.values()];
2085
- }
2086
- function retainedIndexEntries(indexKey, entries) {
2087
- if (indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
2088
- return entries.sort(compareIndexDescending).slice(0, CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH);
2089
- }
2090
- if (indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
2091
- return entries.sort(compareIndexAscending);
2092
- }
2093
- throw new Error(`Unknown conversation index ${indexKey}`);
2094
- }
2095
- function redisIndexKey(indexKey) {
2096
- const prefix = getChatConfig().state.keyPrefix;
2097
- return [...prefix ? [prefix] : [], indexKey].join(":");
2098
- }
2099
- function parseRedisIndexEntries(values) {
2100
- if (!Array.isArray(values)) {
2101
- return [];
2102
- }
2103
- const entries = [];
2104
- for (let index = 0; index < values.length; index += 2) {
2105
- const conversationId = toOptionalString(values[index]);
2106
- const score = typeof values[index + 1] === "number" ? values[index + 1] : Number(values[index + 1]);
2107
- if (!conversationId || !Number.isFinite(score)) {
2108
- continue;
2109
- }
2110
- entries.push({ conversationId, score });
2111
- }
2112
- return entries;
2113
- }
2114
- function redisConversationIndexStore(client) {
2115
- const upsertBoundedActivityScript = `
2116
- redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
2117
- redis.call("PEXPIRE", KEYS[1], ARGV[3])
2118
- local extra = redis.call("ZCARD", KEYS[1]) - tonumber(ARGV[4])
2119
- if extra > 0 then
2120
- redis.call("ZREMRANGEBYRANK", KEYS[1], 0, extra - 1)
2121
- end
2122
- return 1
2123
- `;
2124
- return {
2125
- async list(args) {
2126
- const key = redisIndexKey(args.indexKey);
2127
- const limit = args.limit;
2128
- const offset = Math.max(0, args.offset ?? 0);
2129
- if (limit === 0) {
2130
- return [];
2131
- }
2132
- const values = args.scoreMax !== void 0 ? await client.sendCommand([
2133
- "ZRANGEBYSCORE",
2134
- key,
2135
- "-inf",
2136
- String(args.scoreMax),
2137
- "WITHSCORES",
2138
- ...limit !== void 0 || offset > 0 ? ["LIMIT", String(offset), String(limit ?? 1e9)] : []
2139
- ]) : await client.sendCommand([
2140
- args.order === "asc" ? "ZRANGE" : "ZREVRANGE",
2141
- key,
2142
- String(offset),
2143
- String(
2144
- limit === void 0 ? -1 : offset + Math.max(0, limit - 1)
2145
- ),
2146
- "WITHSCORES"
2147
- ]);
2148
- return parseRedisIndexEntries(values);
2149
- },
2150
- async remove(args) {
2151
- await client.sendCommand([
2152
- "ZREM",
2153
- redisIndexKey(args.indexKey),
2154
- args.conversationId
2155
- ]);
2156
- },
2157
- async upsert(args) {
2158
- const key = redisIndexKey(args.indexKey);
2159
- if (args.indexKey === CONVERSATION_BY_ACTIVITY_INDEX_KEY) {
2160
- await client.sendCommand([
2161
- "EVAL",
2162
- upsertBoundedActivityScript,
2163
- "1",
2164
- key,
2165
- String(args.score),
2166
- args.conversationId,
2167
- String(JUNIOR_THREAD_STATE_TTL_MS),
2168
- String(CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH)
2169
- ]);
2170
- return;
2171
- }
2172
- if (args.indexKey === CONVERSATION_ACTIVE_INDEX_KEY) {
2173
- await client.sendCommand([
2174
- "ZADD",
2175
- key,
2176
- String(args.score),
2177
- args.conversationId
2178
- ]);
2179
- await client.sendCommand([
2180
- "PEXPIRE",
2181
- key,
2182
- String(JUNIOR_THREAD_STATE_TTL_MS)
2183
- ]);
2184
- return;
2185
- }
2186
- throw new Error(`Unknown conversation index ${args.indexKey}`);
2187
- }
2188
- };
2189
- }
2190
- function emulatedConversationIndexStore(state) {
2191
- const readIndex = async (indexKey) => uniqueIndexEntries(await state.get(indexKey));
2192
- const writeIndex = async (indexKey, entries) => {
2193
- await state.set(indexKey, entries, JUNIOR_THREAD_STATE_TTL_MS);
2194
- };
2195
- return {
2196
- async list(args) {
2197
- const entries = (await readIndex(args.indexKey)).filter(
2198
- (entry) => args.scoreMax === void 0 ? true : entry.score <= args.scoreMax
2199
- ).sort(
2200
- args.order === "asc" ? compareIndexAscending : compareIndexDescending
2201
- );
2202
- const offset = Math.max(0, args.offset ?? 0);
2203
- return entries.slice(
2204
- offset,
2205
- args.limit === void 0 ? entries.length : offset + args.limit
2206
- );
2207
- },
2208
- async remove(args) {
2209
- await withIndexLock(state, args.indexKey, async () => {
2210
- const entries = await readIndex(args.indexKey);
2211
- const next = entries.filter(
2212
- (entry) => entry.conversationId !== args.conversationId
2213
- );
2214
- if (next.length === entries.length) {
2215
- return;
2216
- }
2217
- await writeIndex(args.indexKey, next);
2218
- });
2219
- },
2220
- async upsert(args) {
2221
- await withIndexLock(state, args.indexKey, async () => {
2222
- const entries = await readIndex(args.indexKey);
2223
- const withoutCurrent = entries.filter(
2224
- (entry) => entry.conversationId !== args.conversationId
2225
- );
2226
- const next = retainedIndexEntries(args.indexKey, [
2227
- ...withoutCurrent,
2228
- { conversationId: args.conversationId, score: args.score }
2229
- ]);
2230
- await writeIndex(args.indexKey, next);
2231
- });
2232
- }
2233
- };
2234
- }
2235
- async function getConversationIndexStore(state) {
2236
- const redisStateAdapter = await getDefaultRedisStateAdapterFor(state);
2237
- if (redisStateAdapter) {
2238
- return redisConversationIndexStore(redisStateAdapter.getClient());
2239
- }
2240
- return emulatedConversationIndexStore(state);
2241
- }
2242
- async function upsertIndexEntry(args) {
2243
- const index = await getConversationIndexStore(args.state);
2244
- await index.upsert({
2245
- conversationId: args.conversationId,
2246
- indexKey: args.indexKey,
2247
- score: args.score
2248
- });
2249
- }
2250
- async function removeIndexEntry(args) {
2251
- const index = await getConversationIndexStore(args.state);
2252
- await index.remove({
2253
- conversationId: args.conversationId,
2254
- indexKey: args.indexKey
2255
- });
2256
- }
2257
- async function acquireMutationLock(state, conversationId) {
2258
- const startedAtMs = now();
2259
- while (true) {
2260
- const lock = await state.acquireLock(
2261
- mutationLockKey(conversationId),
2262
- CONVERSATION_MUTATION_LOCK_TTL_MS
2263
- );
2264
- if (lock) {
2265
- return lock;
2266
- }
2267
- if (now() - startedAtMs >= CONVERSATION_MUTATION_WAIT_MS) {
2268
- throw new Error(
2269
- `Could not acquire conversation mutation lock for ${conversationId}`
2270
- );
2271
- }
2272
- await sleep(CONVERSATION_MUTATION_RETRY_MS);
2273
- }
2274
- }
2275
- async function withConversationMutation(args, callback) {
2276
- const state = await getConnectedState(args.state);
2277
- const lock = await acquireMutationLock(state, args.conversationId);
2278
- try {
2279
- return await callback(state, lock);
2280
- } finally {
2281
- await state.releaseLock(lock);
2282
- }
2283
- }
2284
- async function readConversation(state, conversationId) {
2285
- const raw = await state.get(conversationKey(conversationId));
2286
- if (raw == null) {
2287
- return void 0;
2288
- }
2289
- const conversation = normalizeConversation(conversationId, raw);
2290
- if (!conversation) {
2291
- throw new InvalidConversationRecordError(conversationId);
2292
- }
2293
- return conversation;
2294
- }
2295
- async function writeConversation(state, lock, conversation) {
2296
- const execution = executionWithPendingMessages(
2297
- conversation.execution,
2298
- conversation.execution.pendingMessages
2299
- );
2300
- const next = {
2301
- ...conversation,
2302
- execution
2303
- };
2304
- const fenced = await state.extendLock(
2305
- lock,
2306
- CONVERSATION_MUTATION_LOCK_TTL_MS
2307
- );
2308
- if (!fenced) {
2309
- throw new ConversationMutationFencedError(next.conversationId);
2310
- }
2311
- await state.set(
2312
- conversationKey(next.conversationId),
2313
- next,
2314
- JUNIOR_THREAD_STATE_TTL_MS
2315
- );
2316
- await upsertIndexEntry({
2317
- state,
2318
- indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
2319
- conversationId: next.conversationId,
2320
- score: next.lastActivityAtMs
2321
- });
2322
- if (!hasRunnableWork(next)) {
2323
- await removeIndexEntry({
2324
- state,
2325
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
2326
- conversationId: next.conversationId
2327
- });
2328
- return;
2329
- }
2330
- await upsertIndexEntry({
2331
- state,
2332
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
2333
- conversationId: next.conversationId,
2334
- score: next.execution.updatedAtMs ?? next.updatedAtMs
2335
- });
2336
- }
2337
- function assertSameConversationDestination(args) {
2338
- if (!args.current || sameDestination(args.current, args.next)) {
2339
- return;
2340
- }
2341
- throw new Error(
2342
- `Conversation destination changed for ${args.conversationId}`
2343
- );
2344
- }
2345
- function conversationWorkState(conversation) {
2346
- const lease = conversation.execution.lease;
2347
- return {
2348
- ...conversation,
2349
- lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
2350
- ...lease ? {
2351
- lease: {
2352
- acquiredAtMs: lease.acquiredAtMs,
2353
- lastCheckInAtMs: lease.lastCheckInAtMs,
2354
- leaseExpiresAtMs: lease.expiresAtMs,
2355
- leaseToken: lease.token
2356
- }
2357
- } : {},
2358
- messages: pendingMessages(conversation),
2359
- needsRun: hasRunnableWork(conversation)
2360
- };
2361
- }
2362
- async function getConversation(args) {
2363
- const state = await getConnectedState(args.state);
2364
- return await readConversation(state, args.conversationId);
2365
- }
2366
- async function getConversationWorkState(args) {
2367
- const conversation = await getConversation(args);
2368
- return conversation ? conversationWorkState(conversation) : void 0;
2369
- }
2370
- async function appendInboundMessage(args) {
2371
- const nowMs = args.nowMs ?? now();
2372
- return await withConversationMutation(
2373
- { conversationId: args.message.conversationId, state: args.state },
2374
- async (state, lock) => {
2375
- const current = await readConversation(state, args.message.conversationId) ?? emptyConversation({
2376
- conversationId: args.message.conversationId,
2377
- destination: args.message.destination,
2378
- nowMs,
2379
- source: args.message.source
2380
- });
2381
- assertSameConversationDestination({
2382
- conversationId: args.message.conversationId,
2383
- current: current.destination,
2384
- next: args.message.destination
2385
- });
2386
- const existingPending = current.execution.pendingMessages.some(
2387
- (message) => message.inboundMessageId === args.message.inboundMessageId
2388
- );
2389
- const existing = current.execution.inboundMessageIds.includes(
2390
- args.message.inboundMessageId
2391
- );
2392
- if (existing) {
2393
- if (!existingPending) {
2394
- return { status: "duplicate" };
2395
- }
2396
- const nextStatus = current.execution.status === "idle" ? "pending" : current.execution.status;
2397
- await writeConversation(
2398
- state,
2399
- lock,
2400
- withExecutionUpdate(
2401
- current,
2402
- {
2403
- ...current.execution,
2404
- status: nextStatus,
2405
- pendingMessages: current.execution.pendingMessages.map(
2406
- (message) => message.inboundMessageId === args.message.inboundMessageId ? upgradedPendingMessage(message, args.message) : message
2407
- )
2408
- },
2409
- nowMs
2410
- )
2411
- );
2412
- return { status: "duplicate" };
2413
- }
2414
- const status = current.execution.lease && current.execution.status === "running" ? "running" : current.execution.lease ? "awaiting_resume" : "pending";
2415
- const next = {
2416
- ...current,
2417
- destination: current.destination ?? args.message.destination,
2418
- source: current.source ?? args.message.source,
2419
- lastActivityAtMs: nowMs
2420
- };
2421
- await writeConversation(
2422
- state,
2423
- lock,
2424
- withExecutionUpdate(
2425
- next,
2426
- {
2427
- ...current.execution,
2428
- status,
2429
- inboundMessageIds: [
2430
- ...current.execution.inboundMessageIds,
2431
- args.message.inboundMessageId
2432
- ],
2433
- pendingMessages: [
2434
- ...current.execution.pendingMessages,
2435
- args.message
2436
- ].sort(compareMessages)
2437
- },
2438
- nowMs
2439
- )
2440
- );
2441
- return { status: "appended" };
2442
- }
2443
- );
2444
- }
2445
- async function requestConversationWork(args) {
2446
- const nowMs = args.nowMs ?? now();
2447
- return await withConversationMutation(args, async (state, lock) => {
2448
- const existing = await readConversation(state, args.conversationId);
2449
- if (existing) {
2450
- assertSameConversationDestination({
2451
- conversationId: args.conversationId,
2452
- current: existing.destination,
2453
- next: args.destination
2454
- });
2455
- }
2456
- const current = existing ?? emptyConversation({
2457
- conversationId: args.conversationId,
2458
- destination: args.destination,
2459
- nowMs
2460
- });
2461
- const status = current.execution.lease ? "awaiting_resume" : "pending";
2462
- await writeConversation(
2463
- state,
2464
- lock,
2465
- withExecutionUpdate(
2466
- {
2467
- ...current,
2468
- destination: current.destination ?? args.destination
2469
- },
2470
- {
2471
- ...current.execution,
2472
- status
2473
- },
2474
- nowMs
2475
- )
2476
- );
2477
- return { status: existing === void 0 ? "created" : "updated" };
2478
- });
2479
- }
2480
- async function markConversationWorkEnqueued(args) {
2481
- const nowMs = args.nowMs ?? now();
2482
- await withConversationMutation(args, async (state, lock) => {
2483
- const current = await readConversation(state, args.conversationId);
2484
- if (!current) {
2485
- return;
2486
- }
2487
- await writeConversation(
2488
- state,
2489
- lock,
2490
- withExecutionUpdate(
2491
- current,
2492
- {
2493
- ...current.execution,
2494
- lastEnqueuedAtMs: nowMs
2495
- },
2496
- nowMs
2497
- )
2498
- );
2499
- });
2500
- }
2501
- async function clearConsumedConversationWake(args) {
2502
- const nowMs = args.nowMs ?? now();
2503
- return await withConversationMutation(args, async (state, lock) => {
2504
- const current = await readConversation(state, args.conversationId);
2505
- if (!current || hasRunnableWork(current) || current.execution.lastEnqueuedAtMs === void 0) {
2506
- return false;
2507
- }
2508
- await writeConversation(
2509
- state,
2510
- lock,
2511
- withExecutionUpdate(
2512
- current,
2513
- {
2514
- ...current.execution,
2515
- lastEnqueuedAtMs: void 0
2516
- },
2517
- nowMs
2518
- )
2519
- );
2520
- return true;
2521
- });
2522
- }
2523
- async function startConversationWork(args) {
2524
- const nowMs = args.nowMs ?? now();
2525
- return await withConversationMutation(args, async (state, lock) => {
2526
- const current = await readConversation(state, args.conversationId);
2527
- if (!current) {
2528
- return { status: "no_work" };
2529
- }
2530
- if (isLeaseActive(current.execution.lease, nowMs)) {
2531
- return {
2532
- status: "active",
2533
- leaseExpiresAtMs: current.execution.lease.expiresAtMs
2534
- };
2535
- }
2536
- if (!hasRunnableWork(current)) {
2537
- return { status: "no_work" };
2538
- }
2539
- const lease = {
2540
- token: randomUUID(),
2541
- acquiredAtMs: nowMs,
2542
- lastCheckInAtMs: nowMs,
2543
- expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
2544
- };
2545
- await writeConversation(
2546
- state,
2547
- lock,
2548
- withExecutionUpdate(
2549
- current,
2550
- {
2551
- ...current.execution,
2552
- lease,
2553
- status: current.execution.status === "awaiting_resume" ? "awaiting_resume" : "running",
2554
- runId: current.execution.runId ?? randomUUID(),
2555
- lastEnqueuedAtMs: void 0
2556
- },
2557
- nowMs
2558
- )
2559
- );
2560
- return {
2561
- status: "acquired",
2562
- leaseToken: lease.token,
2563
- leaseExpiresAtMs: lease.expiresAtMs
2564
- };
2565
- });
2566
- }
2567
- async function checkInConversationWork(args) {
2568
- const nowMs = args.nowMs ?? now();
2569
- return await withConversationMutation(args, async (state, lock) => {
2570
- const current = await readConversation(state, args.conversationId);
2571
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2572
- return false;
2573
- }
2574
- await writeConversation(
2575
- state,
2576
- lock,
2577
- withExecutionUpdate(
2578
- current,
2579
- {
2580
- ...current.execution,
2581
- lease: {
2582
- ...current.execution.lease,
2583
- lastCheckInAtMs: nowMs,
2584
- expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
2585
- }
2586
- },
2587
- nowMs
2588
- )
2589
- );
2590
- return true;
2591
- });
2592
- }
2593
- async function drainConversationMailbox(args) {
2594
- const nowMs = args.nowMs ?? now();
2595
- const pending = await withConversationMutation(args, async (state) => {
2596
- const current = await readConversation(state, args.conversationId);
2597
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2598
- throw new Error(
2599
- `Conversation lease is not held for ${args.conversationId}`
2600
- );
2601
- }
2602
- return pendingMessages(current);
2603
- });
2604
- if (pending.length === 0) {
2605
- return { changed: false, messages: [] };
2606
- }
2607
- const result = await args.handle(pending);
2608
- const pendingIds = new Set(
2609
- pending.map((message) => message.inboundMessageId)
2610
- );
2611
- const acknowledgedIds = new Set(
2612
- result ?? pending.map((message) => message.inboundMessageId)
2613
- );
2614
- for (const inboundMessageId of acknowledgedIds) {
2615
- if (!pendingIds.has(inboundMessageId)) {
2616
- throw new Error(
2617
- `Conversation mailbox drain result is not pending for ${args.conversationId}`
2618
- );
2619
- }
2620
- }
2621
- if (acknowledgedIds.size === 0) {
2622
- return { changed: false, messages: [] };
2623
- }
2624
- await withConversationMutation(args, async (state, lock) => {
2625
- const current = await readConversation(state, args.conversationId);
2626
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2627
- throw new Error(
2628
- `Conversation lease is not held for ${args.conversationId}`
2629
- );
2630
- }
2631
- const pendingMessages2 = current.execution.pendingMessages.filter(
2632
- (message) => !acknowledgedIds.has(message.inboundMessageId)
2633
- );
2634
- await writeConversation(
2635
- state,
2636
- lock,
2637
- withExecutionUpdate(
2638
- current,
2639
- {
2640
- ...current.execution,
2641
- status: current.execution.status === "pending" && pendingMessages2.length === 0 ? "running" : current.execution.status,
2642
- pendingMessages: pendingMessages2
2643
- },
2644
- nowMs
2645
- )
2646
- );
2647
- });
2648
- return {
2649
- changed: true,
2650
- messages: pending.filter(
2651
- (message) => acknowledgedIds.has(message.inboundMessageId)
2652
- )
2653
- };
2654
- }
2655
- async function ackMessages(args) {
2656
- const nowMs = args.nowMs ?? now();
2657
- const inboundMessageIds = new Set(args.inboundMessageIds);
2658
- return await withConversationMutation(args, async (state, lock) => {
2659
- const current = await readConversation(state, args.conversationId);
2660
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2661
- return false;
2662
- }
2663
- if (inboundMessageIds.size === 0) {
2664
- return true;
2665
- }
2666
- const pendingMessages2 = current.execution.pendingMessages.filter(
2667
- (message) => !inboundMessageIds.has(message.inboundMessageId)
2668
- );
2669
- if (pendingMessages2.length === current.execution.pendingMessages.length) {
2670
- return true;
2671
- }
2672
- await writeConversation(
2673
- state,
2674
- lock,
2675
- withExecutionUpdate(
2676
- current,
2677
- {
2678
- ...current.execution,
2679
- pendingMessages: pendingMessages2
2680
- },
2681
- nowMs
2682
- )
2683
- );
2684
- return true;
2685
- });
2686
- }
2687
- async function requestConversationContinuation(args) {
2688
- const nowMs = args.nowMs ?? now();
2689
- return await withConversationMutation(args, async (state, lock) => {
2690
- const current = await readConversation(state, args.conversationId);
2691
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2692
- return false;
2693
- }
2694
- assertSameConversationDestination({
2695
- conversationId: args.conversationId,
2696
- current: current.destination,
2697
- next: args.destination
2698
- });
2699
- await writeConversation(
2700
- state,
2701
- lock,
2702
- withExecutionUpdate(
2703
- current,
2704
- {
2705
- ...current.execution,
2706
- status: "awaiting_resume"
2707
- },
2708
- nowMs
2709
- )
2710
- );
2711
- return true;
2712
- });
2713
- }
2714
- async function beginConversationResume(args) {
2715
- const nowMs = args.nowMs ?? now();
2716
- return await withConversationMutation(args, async (state, lock) => {
2717
- const current = await readConversation(state, args.conversationId);
2718
- if (!current || current.execution.lease?.token !== args.leaseToken || current.execution.status !== "awaiting_resume") {
2719
- return false;
2720
- }
2721
- await writeConversation(
2722
- state,
2723
- lock,
2724
- withExecutionUpdate(
2725
- current,
2726
- {
2727
- ...current.execution,
2728
- status: "running"
2729
- },
2730
- nowMs
2731
- )
2732
- );
2733
- return true;
2734
- });
2735
- }
2736
- async function releaseConversationWork(args) {
2737
- const nowMs = args.nowMs ?? now();
2738
- return await withConversationMutation(args, async (state, lock) => {
2739
- const current = await readConversation(state, args.conversationId);
2740
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2741
- return false;
2742
- }
2743
- await writeConversation(
2744
- state,
2745
- lock,
2746
- withExecutionUpdate(
2747
- current,
2748
- {
2749
- ...current.execution,
2750
- lease: void 0,
2751
- status: current.execution.status === "running" ? "pending" : current.execution.status
2752
- },
2753
- nowMs
2754
- )
2755
- );
2756
- return true;
2757
- });
2758
- }
2759
- async function completeConversationWork(args) {
2760
- const nowMs = args.nowMs ?? now();
2761
- return await withConversationMutation(args, async (state, lock) => {
2762
- const current = await readConversation(state, args.conversationId);
2763
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2764
- return "lost_lease";
2765
- }
2766
- const hasPending = pendingMessages(current).length > 0;
2767
- const needsRun = current.execution.status === "awaiting_resume";
2768
- const runnable = needsRun || hasPending;
2769
- await writeConversation(
2770
- state,
2771
- lock,
2772
- withExecutionUpdate(
2773
- current,
2774
- {
2775
- ...current.execution,
2776
- lease: void 0,
2777
- status: needsRun ? "awaiting_resume" : hasPending ? "pending" : "idle",
2778
- runId: runnable ? current.execution.runId : void 0
2779
- },
2780
- nowMs
2781
- )
2782
- );
2783
- return runnable ? "pending" : "completed";
2784
- });
2785
- }
2786
- async function recordAttemptFailure(args) {
2787
- const nowMs = args.nowMs ?? now();
2788
- return await withConversationMutation(args, async (state, lock) => {
2789
- const current = await readConversation(state, args.conversationId);
2790
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2791
- return {
2792
- status: "lost_lease",
2793
- pendingCount: 0,
2794
- deadLetteredMessages: []
2795
- };
2796
- }
2797
- const pendingIds = new Set(
2798
- current.execution.pendingMessages.map(
2799
- (message) => message.inboundMessageId
2800
- )
2801
- );
2802
- if (args.inboundMessageIds.length === 0 || args.inboundMessageIds.some((id) => !pendingIds.has(id))) {
2803
- return {
2804
- status: "skipped",
2805
- pendingCount: current.execution.pendingMessages.length,
2806
- deadLetteredMessages: []
2807
- };
2808
- }
2809
- const attemptedIds = new Set(args.inboundMessageIds);
2810
- const deadLetteredMessages = [];
2811
- const pendingMessages2 = [];
2812
- for (const message of current.execution.pendingMessages) {
2813
- if (!attemptedIds.has(message.inboundMessageId)) {
2814
- pendingMessages2.push(message);
2815
- continue;
2816
- }
2817
- const attempted = {
2818
- ...message,
2819
- attemptCount: (message.attemptCount ?? 0) + 1
2820
- };
2821
- if (attempted.attemptCount >= CONVERSATION_WORK_MAX_DELIVERY_ATTEMPTS) {
2822
- deadLetteredMessages.push(attempted);
2823
- continue;
2824
- }
2825
- pendingMessages2.push(attempted);
2826
- }
2827
- await writeConversation(
2828
- state,
2829
- lock,
2830
- withExecutionUpdate(
2831
- current,
2832
- {
2833
- ...current.execution,
2834
- pendingMessages: pendingMessages2
2835
- },
2836
- nowMs
2837
- )
2838
- );
2839
- return {
2840
- status: "recorded",
2841
- pendingCount: pendingMessages2.length,
2842
- deadLetteredMessages
2843
- };
2844
- });
2845
- }
2846
- async function deadLetterAttempt(args) {
2847
- const nowMs = args.nowMs ?? now();
2848
- return await withConversationMutation(args, async (state, lock) => {
2849
- const current = await readConversation(state, args.conversationId);
2850
- if (!current || current.execution.lease?.token !== args.leaseToken) {
2851
- return "lost_lease";
2852
- }
2853
- const runnable = pendingMessages(current).length > 0;
2854
- await writeConversation(
2855
- state,
2856
- lock,
2857
- withExecutionUpdate(
2858
- current,
2859
- {
2860
- ...current.execution,
2861
- lease: void 0,
2862
- status: runnable ? "pending" : "failed",
2863
- runId: runnable ? current.execution.runId : void 0
2864
- },
2865
- nowMs
2866
- )
2867
- );
2868
- return runnable ? "pending" : "failed";
2869
- });
2870
- }
2871
- async function clearExpiredConversationLease(args) {
2872
- const nowMs = args.nowMs ?? now();
2873
- return await withConversationMutation(args, async (state, lock) => {
2874
- const current = await readConversation(state, args.conversationId);
2875
- if (!current?.execution.lease || current.execution.lease.expiresAtMs > nowMs) {
2876
- return false;
2877
- }
2878
- await writeConversation(
2879
- state,
2880
- lock,
2881
- withExecutionUpdate(
2882
- current,
2883
- {
2884
- ...current.execution,
2885
- lease: void 0,
2886
- status: "awaiting_resume"
2887
- },
2888
- nowMs
2889
- )
2890
- );
2891
- return true;
2892
- });
2893
- }
2894
- async function removeActiveConversation(args) {
2895
- const state = await getConnectedState(args.state);
2896
- await removeIndexEntry({
2897
- state,
2898
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
2899
- conversationId: args.conversationId
2900
- });
2901
- }
2902
- async function listActiveConversationIds(args = {}) {
2903
- const state = await getConnectedState(args.state);
2904
- const index = await getConversationIndexStore(state);
2905
- const entries = await index.list({
2906
- indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
2907
- limit: args.limit,
2908
- order: "asc",
2909
- scoreMax: args.staleBeforeMs
2910
- });
2911
- return entries.map((entry) => entry.conversationId);
2912
- }
2913
-
2914
- // src/chat/task-execution/store.ts
2915
- function metadataStore(options) {
2916
- return options.conversationStore ?? getConversationStore();
2917
- }
2918
- function duplicateInboundNudgeIdempotencyKey(message, nowMs) {
2919
- return `duplicate:${message.conversationId}:${message.inboundMessageId}:${nowMs}`;
2920
- }
2921
- function hasRecentEnqueueMarker(conversation, nowMs) {
2922
- const lastEnqueuedAtMs = conversation.execution.lastEnqueuedAtMs;
2923
- return typeof lastEnqueuedAtMs === "number" && lastEnqueuedAtMs + CONVERSATION_WORK_STALE_ENQUEUE_MS > nowMs;
2924
- }
2925
- function now2() {
2926
- return Date.now();
2927
- }
2928
- async function recordExecutionMetadata(args) {
2929
- const conversation = await getConversation({
2930
- conversationId: args.conversationId,
2931
- state: args.state
2932
- });
2933
- if (!conversation) {
2934
- return;
2935
- }
2936
- await metadataStore(args).recordExecution({
2937
- channelName: conversation.channelName,
2938
- conversationId: conversation.conversationId,
2939
- createdAtMs: conversation.createdAtMs,
2940
- destination: conversation.destination,
2941
- execution: {
2942
- lastCheckpointAtMs: conversation.execution.lastCheckpointAtMs,
2943
- lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
2944
- runId: conversation.execution.runId,
2945
- status: conversation.execution.status,
2946
- updatedAtMs: conversation.execution.updatedAtMs
2947
- },
2948
- lastActivityAtMs: conversation.lastActivityAtMs,
2949
- metrics: null,
2950
- actor: conversation.actor,
2951
- source: conversation.source,
2952
- title: conversation.title,
2953
- updatedAtMs: conversation.updatedAtMs
2954
- });
2955
- }
2956
- async function getConversationWorkState2(args) {
2957
- return await getConversationWorkState(args);
2958
- }
2959
- function countPendingConversationMessages(conversation) {
2960
- return conversation.execution.pendingMessages.length;
2961
- }
2962
- function hasRunnableConversationWork(conversation) {
2963
- return conversation.execution.status !== "idle" || countPendingConversationMessages(conversation) > 0;
2964
- }
2965
- async function ensureConversationWake(args) {
2966
- const nowMs = args.nowMs ?? now2();
2967
- const conversation = await getConversation({
2968
- conversationId: args.conversationId,
2969
- state: args.state
2970
- });
2971
- if (!conversation || !hasRunnableConversationWork(conversation)) {
2972
- return { status: "no_work" };
2973
- }
2974
- if (!conversation.destination) {
2975
- return { status: "no_work" };
2976
- }
2977
- if (args.replaceExistingWake !== true && conversation.execution.lease && conversation.execution.lease.expiresAtMs > nowMs) {
2978
- return { status: "lease_active" };
2979
- }
2980
- if (args.replaceExistingWake !== true && hasRecentEnqueueMarker(conversation, nowMs)) {
2981
- return { status: "already_enqueued" };
2982
- }
2983
- const queueResult = await args.queue.send(
2984
- {
2985
- conversationId: args.conversationId
2986
- },
2987
- {
2988
- delayMs: args.delayMs,
2989
- idempotencyKey: args.idempotencyKey
2990
- }
2991
- );
2992
- await markConversationWorkEnqueued2({
2993
- conversationId: args.conversationId,
2994
- conversationStore: args.conversationStore,
2995
- nowMs,
2996
- state: args.state
2997
- });
2998
- return { status: "enqueued", queueMessageId: queueResult?.messageId };
2999
- }
3000
- async function appendAndEnqueueInboundMessage(args) {
3001
- const nowMs = args.nowMs ?? now2();
3002
- const appendResult = await appendInboundMessage({
3003
- message: args.message,
3004
- nowMs,
3005
- state: args.state
3006
- });
3007
- let idempotencyKey = args.message.inboundMessageId;
3008
- if (appendResult.status === "duplicate") {
3009
- const conversation = await getConversation({
3010
- conversationId: args.message.conversationId,
3011
- state: args.state
3012
- });
3013
- if (!conversation) {
3014
- return appendResult;
3015
- }
3016
- if (hasRecentEnqueueMarker(conversation, nowMs)) {
3017
- await recordExecutionMetadata({
3018
- conversationId: args.message.conversationId,
3019
- conversationStore: args.conversationStore,
3020
- state: args.state
3021
- });
3022
- return appendResult;
3023
- }
3024
- const duplicateStillPending = conversation.execution.pendingMessages.some(
3025
- (message) => message.inboundMessageId === args.message.inboundMessageId
3026
- );
3027
- if (!duplicateStillPending) {
3028
- await recordExecutionMetadata({
3029
- conversationId: args.message.conversationId,
3030
- conversationStore: args.conversationStore,
3031
- state: args.state
3032
- });
3033
- return appendResult;
3034
- }
3035
- idempotencyKey = duplicateInboundNudgeIdempotencyKey(args.message, nowMs);
3036
- }
3037
- const wake = await ensureConversationWake({
3038
- conversationId: args.message.conversationId,
3039
- conversationStore: args.conversationStore,
3040
- idempotencyKey,
3041
- nowMs,
3042
- queue: args.queue,
3043
- state: args.state
3044
- });
3045
- if (wake.status !== "enqueued") {
3046
- await recordExecutionMetadata({
3047
- conversationId: args.message.conversationId,
3048
- conversationStore: args.conversationStore,
3049
- state: args.state
3050
- });
3051
- }
3052
- return {
3053
- ...appendResult,
3054
- ...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : {}
3055
- };
3056
- }
3057
- async function clearConsumedConversationWake2(args) {
3058
- const result = await clearConsumedConversationWake(args);
3059
- if (result) {
3060
- await recordExecutionMetadata(args);
3061
- }
3062
- return result;
3063
- }
3064
- async function requestConversationWork2(args) {
3065
- const result = await requestConversationWork(args);
3066
- await recordExecutionMetadata({
3067
- conversationId: args.conversationId,
3068
- conversationStore: args.conversationStore,
3069
- state: args.state
3070
- });
3071
- return result;
3072
- }
3073
- async function markConversationWorkEnqueued2(args) {
3074
- await markConversationWorkEnqueued(args);
3075
- await recordExecutionMetadata(args);
3076
- }
3077
- async function startConversationWork2(args) {
3078
- const result = await startConversationWork(args);
3079
- await recordExecutionMetadata(args);
3080
- return result;
3081
- }
3082
- async function checkInConversationWork2(args) {
3083
- const result = await checkInConversationWork(args);
3084
- if (result) {
3085
- await recordExecutionMetadata(args);
3086
- }
3087
- return result;
3088
- }
3089
- async function drainConversationMailbox2(args) {
3090
- const result = await drainConversationMailbox(args);
3091
- if (result.changed) {
3092
- await recordExecutionMetadata(args);
3093
- }
3094
- return result.messages;
3095
- }
3096
- async function ackMessages2(args) {
3097
- const result = await ackMessages(args);
3098
- await recordExecutionMetadata(args);
3099
- return result;
3100
- }
3101
- async function requestConversationContinuation2(args) {
3102
- const result = await requestConversationContinuation(args);
3103
- await recordExecutionMetadata(args);
3104
- return result;
3105
- }
3106
- async function beginConversationResume2(args) {
3107
- const result = await beginConversationResume(args);
3108
- if (result) {
3109
- await recordExecutionMetadata(args);
3110
- }
3111
- return result;
3112
- }
3113
- async function releaseConversationWork2(args) {
3114
- const result = await releaseConversationWork(args);
3115
- await recordExecutionMetadata(args);
3116
- return result;
3117
- }
3118
- async function completeConversationWork2(args) {
3119
- const result = await completeConversationWork(args);
3120
- await recordExecutionMetadata(args);
3121
- return result;
3122
- }
3123
- async function recordAttemptFailure2(args) {
3124
- const result = await recordAttemptFailure(args);
3125
- if (result.status === "recorded") {
3126
- await recordExecutionMetadata(args);
3127
- }
3128
- return result;
3129
- }
3130
- async function deadLetterAttempt2(args) {
3131
- const result = await deadLetterAttempt(args);
3132
- await recordExecutionMetadata(args);
3133
- return result;
3134
- }
3135
- async function clearExpiredConversationLease2(args) {
3136
- const result = await clearExpiredConversationLease(args);
3137
- await recordExecutionMetadata(args);
3138
- return result;
3139
- }
3140
- async function removeActiveConversation2(args) {
3141
- return await removeActiveConversation(args);
3142
- }
3143
- async function listActiveConversationIds2(args = {}) {
3144
- return await listActiveConversationIds(args);
3145
- }
3146
-
3147
1747
  // src/chat/services/agent-continue.ts
3148
1748
  async function getAwaitingAgentContinueRequest(args) {
3149
1749
  const sessionRecord = await getAgentTurnSessionRecord(
@@ -3177,7 +1777,7 @@ async function getAwaitingAgentContinueRequest(args) {
3177
1777
  }
3178
1778
  async function scheduleAgentContinue(request, options = {}) {
3179
1779
  const nowMs = options.nowMs ?? Date.now();
3180
- await requestConversationWork2({
1780
+ await requestConversationWork({
3181
1781
  conversationId: request.conversationId,
3182
1782
  destination: request.destination,
3183
1783
  nowMs,
@@ -4459,12 +3059,12 @@ import { createHmac, createSecretKey, timingSafeEqual } from "crypto";
4459
3059
  import {
4460
3060
  pluginStoredTokensSchema
4461
3061
  } from "@sentry/junior-plugin-api";
4462
- import { z as z2 } from "zod";
3062
+ import { z } from "zod";
4463
3063
  var LOCAL_CREDENTIAL_SYNC_CONTEXT = "junior.local-credential-sync.v1";
4464
3064
  var LOCAL_CREDENTIAL_SYNC_MAX_AGE_MS = 6e4;
4465
- var localCredentialSyncSchema = z2.object({
4466
- createdAtMs: z2.number().finite(),
4467
- provider: z2.string().regex(/^[a-z][a-z0-9-]*$/),
3065
+ var localCredentialSyncSchema = z.object({
3066
+ createdAtMs: z.number().finite(),
3067
+ provider: z.string().regex(/^[a-z][a-z0-9-]*$/),
4468
3068
  tokens: pluginStoredTokensSchema
4469
3069
  }).strict();
4470
3070
  function syncSecret() {
@@ -4538,29 +3138,6 @@ async function receiveLocalOAuthCredential(request) {
4538
3138
  }
4539
3139
 
4540
3140
  export {
4541
- isInvalidConversationRecordError,
4542
- CONVERSATION_WORK_CHECK_IN_INTERVAL_MS,
4543
- CONVERSATION_WORK_STALE_ENQUEUE_MS,
4544
- isFinalAttempt,
4545
- getConversationWorkState2 as getConversationWorkState,
4546
- countPendingConversationMessages,
4547
- hasRunnableConversationWork,
4548
- ensureConversationWake,
4549
- appendAndEnqueueInboundMessage,
4550
- clearConsumedConversationWake2 as clearConsumedConversationWake,
4551
- startConversationWork2 as startConversationWork,
4552
- checkInConversationWork2 as checkInConversationWork,
4553
- drainConversationMailbox2 as drainConversationMailbox,
4554
- ackMessages2 as ackMessages,
4555
- requestConversationContinuation2 as requestConversationContinuation,
4556
- beginConversationResume2 as beginConversationResume,
4557
- releaseConversationWork2 as releaseConversationWork,
4558
- completeConversationWork2 as completeConversationWork,
4559
- recordAttemptFailure2 as recordAttemptFailure,
4560
- deadLetterAttempt2 as deadLetterAttempt,
4561
- clearExpiredConversationLease2 as clearExpiredConversationLease,
4562
- removeActiveConversation2 as removeActiveConversation,
4563
- listActiveConversationIds2 as listActiveConversationIds,
4564
3141
  createSlackAdapterAssistantStatusSession,
4565
3142
  splitSlackReplyText,
4566
3143
  buildSlackOutputMessage,