@sentry/junior 0.94.0 → 0.96.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 (127) hide show
  1. package/dist/{agent-hooks-ZG7IDOIN.js → agent-hooks-5URSMY3O.js} +10 -11
  2. package/dist/api/people/list.js +8 -8
  3. package/dist/api/people/profile.js +8 -8
  4. package/dist/api/people/shared.d.ts +2 -2
  5. package/dist/api-reference.d.ts +2 -2
  6. package/dist/app.js +434 -199
  7. package/dist/{catalog-runtime-NZHMSMYC.js → catalog-runtime-MSMAYYIK.js} +4 -4
  8. package/dist/chat/advisor-request.d.ts +4 -0
  9. package/dist/chat/agent/request.d.ts +2 -0
  10. package/dist/chat/agent/resume.d.ts +2 -0
  11. package/dist/chat/conversations/history.d.ts +128 -0
  12. package/dist/chat/conversations/legacy-import.d.ts +38 -0
  13. package/dist/chat/conversations/messages.d.ts +39 -0
  14. package/dist/chat/conversations/projection.d.ts +94 -0
  15. package/dist/chat/conversations/retention.d.ts +36 -0
  16. package/dist/chat/conversations/sql/conversation-row.d.ts +14 -0
  17. package/dist/chat/conversations/sql/history.d.ts +4 -0
  18. package/dist/chat/conversations/sql/legacy-history-import.d.ts +55 -0
  19. package/dist/chat/conversations/sql/messages.d.ts +4 -0
  20. package/dist/chat/conversations/sql/migrations.d.ts +14 -3
  21. package/dist/chat/conversations/sql/purge.d.ts +53 -0
  22. package/dist/chat/conversations/sql/store.d.ts +7 -2
  23. package/dist/chat/conversations/store.d.ts +19 -0
  24. package/dist/chat/conversations/visible-compactions.d.ts +11 -0
  25. package/dist/chat/conversations/visible-messages.d.ts +47 -0
  26. package/dist/chat/db.d.ts +12 -1
  27. package/dist/chat/identities/sql.d.ts +1 -1
  28. package/dist/chat/logging.d.ts +4 -3
  29. package/dist/chat/plugins/auth/oauth-request.d.ts +2 -0
  30. package/dist/chat/resource-events/notification.d.ts +2 -0
  31. package/dist/chat/resource-events/store.d.ts +2 -1
  32. package/dist/chat/runtime/agent-run-outcome.d.ts +3 -0
  33. package/dist/chat/runtime/reply-executor.d.ts +8 -0
  34. package/dist/chat/runtime/thread-state.d.ts +2 -0
  35. package/dist/chat/sandbox/resources.d.ts +4 -0
  36. package/dist/chat/sentry.d.ts +1 -1
  37. package/dist/chat/services/mcp-auth-orchestration.d.ts +8 -0
  38. package/dist/chat/services/plugin-auth-orchestration.d.ts +12 -0
  39. package/dist/chat/services/turn-session-record.d.ts +14 -2
  40. package/dist/chat/sleep.d.ts +2 -0
  41. package/dist/chat/state/conversation.d.ts +7 -4
  42. package/dist/chat/state/session-log.d.ts +23 -1
  43. package/dist/chat/state/turn-session.d.ts +9 -1
  44. package/dist/chat/tool-support/private-trace-result.d.ts +4 -0
  45. package/dist/chat/tool-support/zod-tool.d.ts +1 -0
  46. package/dist/chat/tools/advisor/tool.d.ts +9 -4
  47. package/dist/chat/tools/definition.d.ts +2 -0
  48. package/dist/chat/tools/execution/tool-error-handler.d.ts +2 -2
  49. package/dist/chat/tools/system-time.d.ts +8 -0
  50. package/dist/chat/usage.d.ts +27 -13
  51. package/dist/chat/xml.d.ts +2 -0
  52. package/dist/{chunk-TNUUATT7.js → chunk-2NAZZPPS.js} +2 -2
  53. package/dist/{chunk-NYWPISSO.js → chunk-2XXEKR44.js} +1 -1
  54. package/dist/chunk-5C6XTTFI.js +1037 -0
  55. package/dist/{chunk-3DA7X2U3.js → chunk-6GWA276C.js} +15 -0
  56. package/dist/{chunk-LFLTJQVR.js → chunk-7FBGKXPE.js} +4 -0
  57. package/dist/{chunk-LNCREA5Z.js → chunk-AAZXTVJT.js} +4 -128
  58. package/dist/{chunk-GHGPTPBL.js → chunk-B7PUBQQM.js} +1 -1
  59. package/dist/{chunk-6H4PP63X.js → chunk-BYZWPRJA.js} +24 -14
  60. package/dist/chunk-CM5EZD5F.js +17 -0
  61. package/dist/{chunk-G3E7SCME.js → chunk-CZEX6KIQ.js} +23 -0
  62. package/dist/{chunk-YJ4OPVNA.js → chunk-DZENG5ML.js} +1 -1
  63. package/dist/{chunk-QGEWC27H.js → chunk-GQ3GK22G.js} +5 -7
  64. package/dist/{chunk-YYBX2BD5.js → chunk-GY34VGP5.js} +1 -1
  65. package/dist/{chunk-S6QKIGRM.js → chunk-I35CTGPO.js} +71 -29
  66. package/dist/{chunk-KRMANDHI.js → chunk-IYM2SIVG.js} +1489 -355
  67. package/dist/{chunk-BTH37NCU.js → chunk-L7CDEIVJ.js} +12 -4
  68. package/dist/chunk-MNTINMWR.js +865 -0
  69. package/dist/{chunk-MAVOJ54A.js → chunk-P3YFQLEN.js} +25 -388
  70. package/dist/{chunk-YTNPU7I2.js → chunk-PMNN6ST4.js} +2 -2
  71. package/dist/{chunk-PFXC67GJ.js → chunk-RAIB6WSG.js} +6 -80
  72. package/dist/{chunk-NFXSLTYG.js → chunk-RITD7E5L.js} +864 -62
  73. package/dist/{chunk-UUB3D2XI.js → chunk-S5KZ5LPG.js} +8 -10
  74. package/dist/{chunk-HDNWZMUN.js → chunk-UKHVMPX5.js} +112 -103
  75. package/dist/chunk-WM6KHPBQ.js +48 -0
  76. package/dist/{chunk-MC4ZZE4Q.js → chunk-YDT7SNCN.js} +1 -1
  77. package/dist/{chunk-NAPITCZ6.js → chunk-YDVEH3SB.js} +251 -6
  78. package/dist/cli/chat.js +25 -24
  79. package/dist/cli/check.js +5 -5
  80. package/dist/cli/main.js +1 -1
  81. package/dist/cli/plugins.js +12 -13
  82. package/dist/cli/snapshot-warmup.js +8 -9
  83. package/dist/cli/upgrade.js +79 -18
  84. package/dist/db/schema/agent-steps.d.ts +134 -0
  85. package/dist/db/schema/conversation-messages.d.ts +153 -0
  86. package/dist/{chat/conversations/sql → db}/schema/conversations.d.ts +34 -0
  87. package/dist/{chat/conversations/sql → db}/schema.d.ts +319 -8
  88. package/dist/db-2D6RMG67.js +24 -0
  89. package/dist/deployment.d.ts +2 -0
  90. package/dist/handlers/retention.d.ts +6 -0
  91. package/dist/instrumentation.js +17 -4
  92. package/dist/legacy-import-VZ2MEGP7.js +17 -0
  93. package/dist/nitro.js +14 -4
  94. package/dist/reporting/conversations/activity.d.ts +40 -0
  95. package/dist/reporting/conversations/context.d.ts +8 -0
  96. package/dist/reporting/conversations/details.d.ts +6 -0
  97. package/dist/reporting/conversations/index.d.ts +4 -0
  98. package/dist/reporting/conversations/shared.d.ts +9 -0
  99. package/dist/reporting/conversations/statistics.d.ts +4 -0
  100. package/dist/reporting/conversations/summaries.d.ts +20 -0
  101. package/dist/reporting/conversations/transcript.d.ts +28 -0
  102. package/dist/reporting/conversations/types.d.ts +191 -0
  103. package/dist/reporting/conversations.d.ts +1 -178
  104. package/dist/reporting.d.ts +5 -4
  105. package/dist/reporting.js +703 -837
  106. package/dist/{runner-XAZPJNAQ.js → runner-JZBRQP4F.js} +36 -42
  107. package/dist/{sentry-EGFOV3DH.js → sentry-JMWTS32N.js} +11 -1
  108. package/dist/{validation-KYAWETI4.js → validation-6XOOQGME.js} +5 -5
  109. package/migrations/README.md +32 -0
  110. package/migrations/meta/0000_snapshot.json +978 -0
  111. package/migrations/meta/_journal.json +13 -0
  112. package/package.json +10 -7
  113. package/dist/chat/sql/schema.d.ts +0 -1049
  114. package/dist/chat/state/conversation-details.d.ts +0 -47
  115. package/dist/chunk-7STN2ZSK.js +0 -250
  116. package/dist/chunk-LE5ANBUZ.js +0 -1040
  117. package/dist/chunk-QL66APYJ.js +0 -1377
  118. package/dist/db-YDN6AFJH.js +0 -18
  119. /package/dist/{chat/sql → db}/db.d.ts +0 -0
  120. /package/dist/{chat/sql → db}/executor.d.ts +0 -0
  121. /package/dist/{chat/sql → db}/neon.d.ts +0 -0
  122. /package/dist/{chat/sql → db}/postgres.d.ts +0 -0
  123. /package/dist/{chat/conversations/sql → db}/schema/destinations.d.ts +0 -0
  124. /package/dist/{chat/conversations/sql → db}/schema/identities.d.ts +0 -0
  125. /package/dist/{chat/conversations/sql → db}/schema/migrations.d.ts +0 -0
  126. /package/dist/{chat/conversations/sql → db}/schema/timestamps.d.ts +0 -0
  127. /package/dist/{chat/conversations/sql → db}/schema/users.d.ts +0 -0
@@ -0,0 +1,1037 @@
1
+ import {
2
+ agentStepEntrySchema,
3
+ contextProvenance,
4
+ createSqlAgentStepStore,
5
+ getAgentStepStore,
6
+ getConversationMessageStore,
7
+ getSqlExecutor,
8
+ juniorAgentSteps,
9
+ juniorConversationMessages,
10
+ juniorConversations,
11
+ legacyActorProvenance,
12
+ readSessionLogEntries
13
+ } from "./chunk-RITD7E5L.js";
14
+ import {
15
+ botConfig,
16
+ escapeXml,
17
+ getStateAdapter,
18
+ resolveGatewayModel
19
+ } from "./chunk-YDVEH3SB.js";
20
+ import {
21
+ logWarn,
22
+ setSpanAttributes
23
+ } from "./chunk-I35CTGPO.js";
24
+ import {
25
+ parseSlackMessageTs
26
+ } from "./chunk-7FBGKXPE.js";
27
+
28
+ // src/chat/conversations/legacy-import.ts
29
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
30
+ import { eq as eq2 } from "drizzle-orm";
31
+ import { z } from "zod";
32
+
33
+ // src/chat/conversations/visible-compactions.ts
34
+ import { isDeepStrictEqual } from "util";
35
+ function latestSnapshot(steps) {
36
+ for (let index = steps.length - 1; index >= 0; index -= 1) {
37
+ const entry = steps[index]?.entry;
38
+ if (entry?.type === "visible_context_compacted") {
39
+ return entry.compactions;
40
+ }
41
+ }
42
+ return [];
43
+ }
44
+ async function hydrateConversationCompactions(args) {
45
+ const steps = await getAgentStepStore().loadHistory(args.conversationId);
46
+ args.conversation.compactions = latestSnapshot(steps);
47
+ }
48
+ async function persistConversationCompactions(args) {
49
+ const stepStore = getAgentStepStore();
50
+ const existing = latestSnapshot(
51
+ await stepStore.loadHistory(args.conversationId)
52
+ );
53
+ if (isDeepStrictEqual(existing, args.conversation.compactions)) {
54
+ return;
55
+ }
56
+ await stepStore.append(args.conversationId, [
57
+ {
58
+ entry: {
59
+ type: "visible_context_compacted",
60
+ compactions: args.conversation.compactions
61
+ },
62
+ createdAtMs: args.conversation.compactions.at(-1)?.createdAtMs ?? Date.now()
63
+ }
64
+ ]);
65
+ }
66
+
67
+ // src/chat/services/context-budget.ts
68
+ var COMPACTION_TRIGGER_INPUT_RATIO = 0.75;
69
+ var COMPACTION_OUTPUT_RESERVE_RATIO = 0.25;
70
+ var COMPACTION_TARGET_RATIO = 0.8;
71
+ var FALLBACK_CONTEXT_WINDOW_TOKENS = 4e5;
72
+ var FALLBACK_MAX_OUTPUT_TOKENS = 128e3;
73
+ function positiveInteger(value, fallback) {
74
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
75
+ }
76
+ function estimateTextTokens(text) {
77
+ return Math.ceil(text.length / 4);
78
+ }
79
+ function calculateContextCompactionTriggerTokens(model) {
80
+ const contextWindow = positiveInteger(
81
+ model.contextWindow,
82
+ FALLBACK_CONTEXT_WINDOW_TOKENS
83
+ );
84
+ const maxTokens = positiveInteger(
85
+ model.maxTokens,
86
+ FALLBACK_MAX_OUTPUT_TOKENS
87
+ );
88
+ const outputReserve = Math.min(
89
+ maxTokens,
90
+ Math.floor(contextWindow * COMPACTION_OUTPUT_RESERVE_RATIO)
91
+ );
92
+ const usableInputTokens = Math.max(1, contextWindow - outputReserve);
93
+ return Math.max(
94
+ 1,
95
+ Math.floor(usableInputTokens * COMPACTION_TRIGGER_INPUT_RATIO)
96
+ );
97
+ }
98
+ function calculateContextCompactionTargetTokens(triggerTokens) {
99
+ return Math.max(1, Math.floor(triggerTokens * COMPACTION_TARGET_RATIO));
100
+ }
101
+ function getAgentContextCompactionTriggerTokens() {
102
+ const model = resolveGatewayModel(botConfig.modelId);
103
+ return calculateContextCompactionTriggerTokens({
104
+ contextWindow: botConfig.modelContextWindowTokens ?? model.contextWindow,
105
+ maxTokens: model.maxTokens
106
+ });
107
+ }
108
+ function getConversationContextCompactionTriggerTokens() {
109
+ const model = resolveGatewayModel(botConfig.fastModelId);
110
+ return calculateContextCompactionTriggerTokens({
111
+ contextWindow: model.contextWindow,
112
+ maxTokens: model.maxTokens
113
+ });
114
+ }
115
+
116
+ // src/chat/services/conversation-memory.ts
117
+ var CONTEXT_MIN_LIVE_MESSAGES = 12;
118
+ var CONTEXT_COMPACTION_BATCH_SIZE = 24;
119
+ var CONTEXT_MAX_COMPACTIONS = 16;
120
+ var CONTEXT_MAX_MESSAGE_CHARS = 3200;
121
+ var SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
122
+ function generateConversationId(prefix) {
123
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
124
+ }
125
+ function normalizeConversationText(text) {
126
+ return text.trim().replace(/\s+/g, " ").slice(0, CONTEXT_MAX_MESSAGE_CHARS);
127
+ }
128
+ function buildImageContextSuffix(message, conversation) {
129
+ const byFileId = conversation?.vision.byFileId;
130
+ const imageFileIds = message.meta?.imageFileIds ?? [];
131
+ if (!byFileId || imageFileIds.length === 0) {
132
+ return "";
133
+ }
134
+ const summaries = imageFileIds.map((fileId) => byFileId[fileId]?.summary?.trim()).filter((summary) => Boolean(summary));
135
+ if (summaries.length === 0) {
136
+ return "";
137
+ }
138
+ return ` [image context: ${summaries.join(" | ")}]`;
139
+ }
140
+ function renderConversationMessageLine(message, conversation) {
141
+ const displayName = conversationAuthorDisplayName(message);
142
+ const markers = [];
143
+ if (message.meta?.replied === false) {
144
+ markers.push(
145
+ `assistant skipped: ${message.meta?.skippedReason ?? "no-reply route"}`
146
+ );
147
+ }
148
+ if (message.meta?.explicitMention) {
149
+ markers.push("explicit mention");
150
+ }
151
+ const markerSuffix = markers.length > 0 ? ` (${markers.join("; ")})` : "";
152
+ const imageContext = buildImageContextSuffix(message, conversation);
153
+ return `[${message.role}] ${displayName}: ${message.text}${imageContext}${markerSuffix}`;
154
+ }
155
+ function conversationAuthorDisplayName(message) {
156
+ const author = message.author;
157
+ const fullName = authorDisplayField(author?.fullName, author?.userId);
158
+ const userName = authorDisplayField(author?.userName, author?.userId);
159
+ return fullName ?? userName ?? (message.role === "assistant" ? botConfig.userName : message.role);
160
+ }
161
+ function authorDisplayField(value, userId) {
162
+ if (!value || value === userId || SLACK_USER_ID_DISPLAY_PATTERN.test(value)) {
163
+ return void 0;
164
+ }
165
+ return value;
166
+ }
167
+ function updateConversationStats(conversation) {
168
+ const contextText = buildConversationContext(conversation);
169
+ conversation.stats.estimatedContextTokens = estimateTextTokens(
170
+ contextText ?? ""
171
+ );
172
+ conversation.stats.totalMessageCount = conversation.messages.length;
173
+ conversation.stats.updatedAtMs = Date.now();
174
+ }
175
+ function upsertConversationMessage(conversation, message) {
176
+ const existingIndex = conversation.messages.findIndex(
177
+ (entry) => entry.id === message.id
178
+ );
179
+ if (existingIndex >= 0) {
180
+ conversation.messages[existingIndex] = {
181
+ ...conversation.messages[existingIndex],
182
+ ...message,
183
+ meta: {
184
+ ...conversation.messages[existingIndex]?.meta,
185
+ ...message.meta
186
+ }
187
+ };
188
+ updateConversationStats(conversation);
189
+ return message.id;
190
+ }
191
+ conversation.messages.push(message);
192
+ updateConversationStats(conversation);
193
+ return message.id;
194
+ }
195
+ function markConversationMessage(conversation, messageId, patch) {
196
+ if (!messageId) return;
197
+ const messageIndex = conversation.messages.findIndex(
198
+ (entry) => entry.id === messageId
199
+ );
200
+ if (messageIndex < 0) return;
201
+ const current = conversation.messages[messageIndex];
202
+ conversation.messages[messageIndex] = {
203
+ ...current,
204
+ meta: {
205
+ ...current.meta ?? {},
206
+ ...patch
207
+ }
208
+ };
209
+ updateConversationStats(conversation);
210
+ }
211
+ function buildConversationContext(conversation, options = {}) {
212
+ const messages = conversation.messages.filter(
213
+ (entry) => entry.id !== options.excludeMessageId
214
+ );
215
+ if (messages.length === 0 && conversation.compactions.length === 0) {
216
+ return void 0;
217
+ }
218
+ const lines = [];
219
+ if (conversation.compactions.length > 0) {
220
+ lines.push("<thread-compactions>");
221
+ for (const [index, compaction] of conversation.compactions.entries()) {
222
+ lines.push(
223
+ ` <compaction index="${index + 1}" covered_messages="${compaction.coveredMessageIds.length}" created_at="${new Date(compaction.createdAtMs).toISOString()}">`,
224
+ compaction.summary,
225
+ " </compaction>"
226
+ );
227
+ }
228
+ lines.push("</thread-compactions>");
229
+ }
230
+ if (messages.length > 0) {
231
+ if (lines.length > 0) {
232
+ lines.push("");
233
+ }
234
+ lines.push("<thread-transcript>");
235
+ for (const [index, message] of messages.entries()) {
236
+ const author = escapeXml(conversationAuthorDisplayName(message));
237
+ const actorIdAttr = message.author?.userId ? ` actor_id="${escapeXml(message.author.userId)}"` : "";
238
+ const ts = new Date(message.createdAtMs).toISOString();
239
+ const slackTsAttr = message.meta?.slackTs ? ` slack_ts="${escapeXml(message.meta.slackTs)}"` : "";
240
+ lines.push(
241
+ ` <message index="${index + 1}" ts="${ts}" role="${message.role}" author="${author}"${actorIdAttr}${slackTsAttr}>`,
242
+ renderConversationMessageLine(message, conversation),
243
+ " </message>"
244
+ );
245
+ }
246
+ lines.push("</thread-transcript>");
247
+ }
248
+ return lines.join("\n");
249
+ }
250
+ function pruneCompactions(compactions) {
251
+ if (compactions.length <= CONTEXT_MAX_COMPACTIONS) {
252
+ return compactions;
253
+ }
254
+ const overflowCount = compactions.length - CONTEXT_MAX_COMPACTIONS + 1;
255
+ const merged = compactions.slice(0, overflowCount);
256
+ const mergedSummary = merged.map((entry) => entry.summary).join("\n").slice(0, 3500);
257
+ const mergedIds = merged.flatMap((entry) => entry.coveredMessageIds).slice(0, 500);
258
+ const compacted = {
259
+ id: generateConversationId("compaction"),
260
+ createdAtMs: Date.now(),
261
+ summary: mergedSummary,
262
+ coveredMessageIds: mergedIds
263
+ };
264
+ return [compacted, ...compactions.slice(overflowCount)];
265
+ }
266
+ async function summarizeConversationChunk(messages, conversation, context, deps) {
267
+ const transcript = messages.map((message) => renderConversationMessageLine(message, conversation)).join("\n");
268
+ try {
269
+ const result = await deps.completeText({
270
+ modelId: botConfig.fastModelId,
271
+ temperature: 0,
272
+ messages: [
273
+ {
274
+ role: "user",
275
+ content: [
276
+ "Summarize the following older Slack thread transcript segment for future assistant turns.",
277
+ "Keep the summary factual and concise. Do not invent details.",
278
+ "",
279
+ "Output exactly three XML sections in this order:",
280
+ "<active-asks> one bullet per outstanding user ask that has not been narrowed, answered, or replaced by a later turn. Omit the section body if none. </active-asks>",
281
+ "<resolved-or-replaced-asks> one bullet per ask that has been replaced, narrowed, answered, or already acted on in this segment. Include the replacement/outcome inline. Omit the section body if none. </resolved-or-replaced-asks>",
282
+ "<facts> one bullet per durable fact useful regardless of scope: names, ids, URLs, decisions, locations, preferences, constraints that remain true. Omit the section body if none. </facts>",
283
+ "",
284
+ "Do not output any text outside the three sections.",
285
+ "",
286
+ transcript
287
+ ].join("\n"),
288
+ timestamp: Date.now()
289
+ }
290
+ ],
291
+ metadata: {
292
+ modelId: botConfig.fastModelId,
293
+ threadId: context.threadId ?? "",
294
+ channelId: context.channelId ?? "",
295
+ actorId: context.actorId ?? "",
296
+ runId: context.runId ?? ""
297
+ }
298
+ });
299
+ const summary = result.text.trim();
300
+ if (summary.length > 0) {
301
+ return summary.slice(0, 3500);
302
+ }
303
+ } catch (error) {
304
+ logWarn(
305
+ "conversation_compaction_summary_failed",
306
+ {
307
+ slackThreadId: context.threadId,
308
+ slackUserId: context.actorId,
309
+ slackChannelId: context.channelId,
310
+ runId: context.runId,
311
+ assistantUserName: botConfig.userName,
312
+ modelId: botConfig.fastModelId
313
+ },
314
+ {
315
+ "exception.message": error instanceof Error ? error.message : String(error),
316
+ "app.compaction_messages_covered": messages.length
317
+ },
318
+ "Compaction summarization failed; using fallback summary"
319
+ );
320
+ }
321
+ return transcript.slice(0, 2800);
322
+ }
323
+ async function generateThreadTitleWithDeps(sourceText, deps) {
324
+ const result = await deps.completeText({
325
+ modelId: botConfig.fastModelId,
326
+ temperature: 0,
327
+ messages: [
328
+ {
329
+ role: "user",
330
+ content: [
331
+ "Generate a concise 5-8 word Slack conversation title from the first user message below.",
332
+ "Capture the user's main request.",
333
+ "Reply with ONLY the title, with no quotes or trailing punctuation.",
334
+ "",
335
+ `First user message: ${sourceText.slice(0, 500)}`
336
+ ].join("\n"),
337
+ timestamp: Date.now()
338
+ }
339
+ ],
340
+ metadata: {
341
+ modelId: botConfig.fastModelId
342
+ }
343
+ });
344
+ return result.text.trim().slice(0, 60);
345
+ }
346
+ function getThreadTitleSourceMessage(conversation) {
347
+ let firstMessage;
348
+ for (const message of conversation.messages) {
349
+ if (!isHumanConversationMessage(message)) {
350
+ continue;
351
+ }
352
+ if (!firstMessage) {
353
+ firstMessage = message;
354
+ continue;
355
+ }
356
+ if (message.createdAtMs < firstMessage.createdAtMs) {
357
+ firstMessage = message;
358
+ continue;
359
+ }
360
+ if (message.createdAtMs === firstMessage.createdAtMs && message.id < firstMessage.id) {
361
+ firstMessage = message;
362
+ }
363
+ }
364
+ return firstMessage;
365
+ }
366
+ async function compactConversationIfNeededWithDeps(conversation, context, deps) {
367
+ updateConversationStats(conversation);
368
+ let estimatedTokens = conversation.stats.estimatedContextTokens;
369
+ setSpanAttributes({
370
+ "app.context_tokens_estimated": estimatedTokens
371
+ });
372
+ const triggerTokens = getConversationContextCompactionTriggerTokens();
373
+ const targetTokens = calculateContextCompactionTargetTokens(triggerTokens);
374
+ while (estimatedTokens > triggerTokens && conversation.messages.length > CONTEXT_MIN_LIVE_MESSAGES) {
375
+ const compactCount = Math.min(
376
+ CONTEXT_COMPACTION_BATCH_SIZE,
377
+ conversation.messages.length - CONTEXT_MIN_LIVE_MESSAGES
378
+ );
379
+ if (compactCount <= 0) {
380
+ break;
381
+ }
382
+ const compactedChunk = conversation.messages.slice(0, compactCount);
383
+ const summary = await summarizeConversationChunk(
384
+ compactedChunk,
385
+ conversation,
386
+ context,
387
+ deps
388
+ );
389
+ conversation.compactions.push({
390
+ id: generateConversationId("compaction"),
391
+ createdAtMs: Date.now(),
392
+ summary,
393
+ coveredMessageIds: compactedChunk.map((entry) => entry.id)
394
+ });
395
+ conversation.compactions = pruneCompactions(conversation.compactions);
396
+ conversation.messages = conversation.messages.slice(compactCount);
397
+ conversation.stats.compactedMessageCount += compactCount;
398
+ updateConversationStats(conversation);
399
+ estimatedTokens = conversation.stats.estimatedContextTokens;
400
+ setSpanAttributes({
401
+ "app.compaction_messages_covered": compactCount,
402
+ "app.compaction.trigger_tokens": triggerTokens,
403
+ "app.compaction.target_tokens": targetTokens,
404
+ "app.context_tokens_estimated": estimatedTokens
405
+ });
406
+ if (estimatedTokens <= targetTokens) {
407
+ break;
408
+ }
409
+ }
410
+ }
411
+ function createConversationMemoryService(deps) {
412
+ return {
413
+ compactConversationIfNeeded: async (conversation, context) => await compactConversationIfNeededWithDeps(conversation, context, deps),
414
+ generateThreadTitle: async (sourceText) => await generateThreadTitleWithDeps(sourceText, deps)
415
+ };
416
+ }
417
+ function isHumanConversationMessage(message) {
418
+ return message.role === "user" && message.author?.isBot !== true;
419
+ }
420
+ function getConversationMessageSlackTs(message) {
421
+ return parseSlackMessageTs(message.meta?.slackTs);
422
+ }
423
+
424
+ // src/chat/conversations/visible-messages.ts
425
+ function toStoredConversationMessage(message) {
426
+ const meta = {};
427
+ if (message.author) {
428
+ meta.author = message.author;
429
+ }
430
+ const { replied, ...restMeta } = message.meta ?? {};
431
+ Object.assign(meta, restMeta);
432
+ if (replied === false) {
433
+ meta.replied = false;
434
+ }
435
+ return {
436
+ messageId: message.id,
437
+ role: message.role,
438
+ text: message.text,
439
+ ...Object.keys(meta).length > 0 ? { meta } : {},
440
+ createdAtMs: message.createdAtMs
441
+ };
442
+ }
443
+ function fromStoredMessage(row) {
444
+ const rawMeta = { ...row.meta ?? {} };
445
+ const author = rawMeta.author;
446
+ delete rawMeta.author;
447
+ const meta = { ...rawMeta };
448
+ if (row.repliedAtMs !== void 0) {
449
+ meta.replied = true;
450
+ }
451
+ return {
452
+ id: row.messageId,
453
+ role: row.role,
454
+ text: row.text,
455
+ createdAtMs: row.createdAtMs,
456
+ ...author ? { author } : {},
457
+ ...Object.keys(meta).length > 0 ? { meta } : {}
458
+ };
459
+ }
460
+ async function hydrateConversationMessages(args) {
461
+ if (!args.conversationId) {
462
+ args.conversation.messages = [];
463
+ return;
464
+ }
465
+ const { ensureLegacyConversationImport: ensureLegacyConversationImport2 } = await import("./legacy-import-VZ2MEGP7.js");
466
+ await ensureLegacyConversationImport2({ conversationId: args.conversationId });
467
+ await hydrateConversationCompactions({
468
+ conversation: args.conversation,
469
+ conversationId: args.conversationId
470
+ });
471
+ const store = getConversationMessageStore();
472
+ const rows = await store.list(args.conversationId);
473
+ const coveredIds = new Set(
474
+ args.conversation.compactions.flatMap(
475
+ (compaction) => compaction.coveredMessageIds
476
+ )
477
+ );
478
+ args.conversation.messages = rows.filter((row) => !coveredIds.has(row.messageId)).map(fromStoredMessage);
479
+ updateConversationStats(args.conversation);
480
+ }
481
+ async function persistConversationMessages(args) {
482
+ if (!args.conversationId || args.conversation.messages.length === 0) {
483
+ return;
484
+ }
485
+ const store = getConversationMessageStore();
486
+ await store.record(
487
+ args.conversationId,
488
+ args.conversation.messages.map(toStoredConversationMessage)
489
+ );
490
+ const repliedAtMs = args.repliedAtMs ?? Date.now();
491
+ for (const message of args.conversation.messages) {
492
+ if (message.meta?.replied === true) {
493
+ await store.markReplied(args.conversationId, message.id, repliedAtMs);
494
+ }
495
+ }
496
+ }
497
+
498
+ // src/chat/state/ttl.ts
499
+ var JUNIOR_THREAD_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
500
+
501
+ // src/chat/tools/advisor/session-store.ts
502
+ var ADVISOR_SESSION_TTL_MS = JUNIOR_THREAD_STATE_TTL_MS;
503
+ function cloneMessages(messages) {
504
+ return structuredClone(messages);
505
+ }
506
+ function getAdvisorSessionKey(conversationId) {
507
+ return `junior:${conversationId}:advisor_session`;
508
+ }
509
+ function createStateAdvisorSessionStore() {
510
+ return {
511
+ load: async (conversationId) => {
512
+ const stateAdapter = getStateAdapter();
513
+ await stateAdapter.connect();
514
+ const messages = await stateAdapter.get(
515
+ getAdvisorSessionKey(conversationId)
516
+ ) ?? [];
517
+ return cloneMessages(messages);
518
+ },
519
+ save: async (conversationId, messages) => {
520
+ const stateAdapter = getStateAdapter();
521
+ await stateAdapter.connect();
522
+ await stateAdapter.set(
523
+ getAdvisorSessionKey(conversationId),
524
+ cloneMessages(messages),
525
+ ADVISOR_SESSION_TTL_MS
526
+ );
527
+ }
528
+ };
529
+ }
530
+
531
+ // src/chat/conversations/sql/legacy-history-import.ts
532
+ import { eq, sql } from "drizzle-orm";
533
+ var INITIAL_SESSION_ID = "session_0";
534
+ function importedAdvisorChildConversationId(parentConversationId) {
535
+ return `advisor:${parentConversationId}`;
536
+ }
537
+ function epochFromSessionId(sessionId) {
538
+ const match = /^session_(\d+)$/.exec(sessionId);
539
+ return match ? Number(match[1]) : 0;
540
+ }
541
+ function messageTimestampMs(message) {
542
+ const timestamp = message.timestamp;
543
+ return typeof timestamp === "number" ? timestamp : void 0;
544
+ }
545
+ function piEntryProvenance(entry) {
546
+ if (entry.provenance) {
547
+ return entry.provenance;
548
+ }
549
+ if (entry.actor) {
550
+ return legacyActorProvenance(entry.actor);
551
+ }
552
+ return contextProvenance;
553
+ }
554
+ function convertLegacySessionLog(args) {
555
+ const steps = [];
556
+ const fallback = args.fallbackCreatedAtMs;
557
+ let advisorChildConversationId;
558
+ let seq = 0;
559
+ const push = (contextEpoch, entry, createdAtMs) => {
560
+ steps.push({ seq, contextEpoch, entry, createdAtMs });
561
+ seq += 1;
562
+ };
563
+ for (const entry of args.entries) {
564
+ const epoch = epochFromSessionId(entry.sessionId ?? INITIAL_SESSION_ID);
565
+ switch (entry.type) {
566
+ case "pi_message": {
567
+ push(
568
+ epoch,
569
+ {
570
+ type: "pi_message",
571
+ message: entry.message,
572
+ provenance: piEntryProvenance(entry)
573
+ },
574
+ messageTimestampMs(entry.message) ?? fallback
575
+ );
576
+ break;
577
+ }
578
+ case "projection_reset": {
579
+ const provenance = entry.provenance ?? entry.messages.map(() => contextProvenance);
580
+ if (provenance.length !== entry.messages.length) {
581
+ throw new Error(
582
+ "projection_reset provenance must align one-to-one with messages"
583
+ );
584
+ }
585
+ push(
586
+ epoch,
587
+ { type: "context_epoch_started", reason: "compaction" },
588
+ fallback
589
+ );
590
+ entry.messages.forEach((message, index) => {
591
+ push(
592
+ epoch,
593
+ {
594
+ type: "pi_message",
595
+ message,
596
+ provenance: provenance[index]
597
+ },
598
+ messageTimestampMs(message) ?? fallback
599
+ );
600
+ });
601
+ break;
602
+ }
603
+ case "mcp_provider_connected": {
604
+ push(
605
+ epoch,
606
+ { type: "mcp_provider_connected", provider: entry.provider },
607
+ fallback
608
+ );
609
+ break;
610
+ }
611
+ case "authorization_requested": {
612
+ push(
613
+ epoch,
614
+ {
615
+ type: "authorization_requested",
616
+ kind: entry.kind,
617
+ provider: entry.provider,
618
+ actorId: entry.actorId,
619
+ authorizationId: entry.authorizationId,
620
+ delivery: entry.delivery
621
+ },
622
+ entry.createdAtMs
623
+ );
624
+ break;
625
+ }
626
+ case "authorization_completed": {
627
+ push(
628
+ epoch,
629
+ {
630
+ type: "authorization_completed",
631
+ kind: entry.kind,
632
+ provider: entry.provider,
633
+ actorId: entry.actorId,
634
+ authorizationId: entry.authorizationId
635
+ },
636
+ entry.createdAtMs
637
+ );
638
+ break;
639
+ }
640
+ case "tool_execution_started": {
641
+ push(
642
+ epoch,
643
+ {
644
+ type: "tool_execution_started",
645
+ toolCallId: entry.toolCallId,
646
+ toolName: entry.toolName,
647
+ ...entry.args !== void 0 ? { args: entry.args } : {}
648
+ },
649
+ entry.createdAtMs
650
+ );
651
+ break;
652
+ }
653
+ case "subagent_started": {
654
+ const childConversationId = importedAdvisorChildConversationId(
655
+ args.conversationId
656
+ );
657
+ advisorChildConversationId = childConversationId;
658
+ push(
659
+ epoch,
660
+ {
661
+ type: "subagent_started",
662
+ subagentInvocationId: entry.subagentInvocationId,
663
+ subagentKind: entry.subagentKind,
664
+ ...entry.parentToolCallId ? { parentToolCallId: entry.parentToolCallId } : {},
665
+ childConversationId,
666
+ historyMode: "shared"
667
+ },
668
+ entry.createdAtMs
669
+ );
670
+ break;
671
+ }
672
+ case "subagent_ended": {
673
+ push(
674
+ epoch,
675
+ {
676
+ type: "subagent_ended",
677
+ subagentInvocationId: entry.subagentInvocationId,
678
+ outcome: entry.outcome,
679
+ ...entry.errorCode ? { errorCode: entry.errorCode } : {}
680
+ },
681
+ entry.createdAtMs
682
+ );
683
+ break;
684
+ }
685
+ case "actor_recorded": {
686
+ break;
687
+ }
688
+ }
689
+ }
690
+ return {
691
+ steps,
692
+ ...advisorChildConversationId ? { advisorChildConversationId } : {}
693
+ };
694
+ }
695
+ function convertAdvisorMessages(messages, fallbackCreatedAtMs) {
696
+ return messages.map((message, seq) => ({
697
+ seq,
698
+ contextEpoch: 0,
699
+ entry: { type: "pi_message", message, provenance: contextProvenance },
700
+ createdAtMs: messageTimestampMs(message) ?? fallbackCreatedAtMs
701
+ }));
702
+ }
703
+ function messageRole(entry) {
704
+ if (entry.type !== "pi_message") {
705
+ return null;
706
+ }
707
+ const role = entry.message.role;
708
+ return typeof role === "string" ? role : null;
709
+ }
710
+ function insertRow(conversationId, step) {
711
+ const { type, ...payload } = agentStepEntrySchema.parse(step.entry);
712
+ return {
713
+ conversationId,
714
+ seq: step.seq,
715
+ contextEpoch: step.contextEpoch,
716
+ type,
717
+ role: messageRole(step.entry),
718
+ payload,
719
+ createdAt: new Date(step.createdAtMs)
720
+ };
721
+ }
722
+ async function writeLegacyImport(executor, args) {
723
+ return executor.withLock(
724
+ `junior_conversation:legacy-import:${args.conversationId}`,
725
+ () => executor.transaction(async () => {
726
+ const db = executor.db();
727
+ const conversations = await db.select({
728
+ transcriptPurgedAt: juniorConversations.transcriptPurgedAt
729
+ }).from(juniorConversations).where(eq(juniorConversations.conversationId, args.conversationId)).for("update");
730
+ if (conversations[0]?.transcriptPurgedAt) {
731
+ return false;
732
+ }
733
+ const existing = await db.select({ seq: juniorAgentSteps.seq }).from(juniorAgentSteps).where(eq(juniorAgentSteps.conversationId, args.conversationId)).limit(1);
734
+ if (existing.length > 0) {
735
+ return false;
736
+ }
737
+ const createdAt = new Date(args.fallbackCreatedAtMs);
738
+ await ensureConversationRow(
739
+ executor,
740
+ args.conversationId,
741
+ createdAt,
742
+ new Date(args.lastActivityAtMs)
743
+ );
744
+ if (args.messages && args.messages.length > 0) {
745
+ await db.insert(juniorConversationMessages).values(
746
+ args.messages.map((message) => ({
747
+ conversationId: args.conversationId,
748
+ messageId: message.messageId,
749
+ role: message.role,
750
+ authorIdentityId: message.authorIdentityId ?? null,
751
+ text: message.text,
752
+ meta: message.meta ?? null,
753
+ repliedAt: message.repliedAtMs === void 0 ? null : new Date(message.repliedAtMs),
754
+ createdAt: new Date(message.createdAtMs)
755
+ }))
756
+ ).onConflictDoUpdate({
757
+ target: [
758
+ juniorConversationMessages.conversationId,
759
+ juniorConversationMessages.messageId
760
+ ],
761
+ set: {
762
+ meta: sql`nullif(coalesce(${juniorConversationMessages.meta}, '{}'::jsonb) || coalesce(excluded.meta, '{}'::jsonb), '{}'::jsonb)`,
763
+ repliedAt: sql`coalesce(${juniorConversationMessages.repliedAt}, excluded.replied_at)`
764
+ }
765
+ });
766
+ }
767
+ if (args.steps.length > 0) {
768
+ await db.insert(juniorAgentSteps).values(
769
+ args.steps.map((step) => insertRow(args.conversationId, step))
770
+ );
771
+ }
772
+ if (args.child) {
773
+ const childCreatedAtMs = args.child.steps.length > 0 ? Math.min(...args.child.steps.map((step) => step.createdAtMs)) : args.fallbackCreatedAtMs;
774
+ const childLastActivityAtMs = args.child.steps.length > 0 ? Math.max(...args.child.steps.map((step) => step.createdAtMs)) : childCreatedAtMs;
775
+ await ensureChildConversationRow(
776
+ executor,
777
+ args.child.conversationId,
778
+ args.conversationId,
779
+ new Date(childCreatedAtMs),
780
+ new Date(childLastActivityAtMs)
781
+ );
782
+ if (args.child.steps.length > 0) {
783
+ await db.insert(juniorAgentSteps).values(
784
+ args.child.steps.map(
785
+ (step) => insertRow(args.child.conversationId, step)
786
+ )
787
+ );
788
+ }
789
+ }
790
+ return true;
791
+ })
792
+ );
793
+ }
794
+ async function ensureConversationRow(executor, conversationId, createdAt, lastActivityAt) {
795
+ await executor.db().insert(juniorConversations).values({
796
+ conversationId,
797
+ schemaVersion: 1,
798
+ createdAt,
799
+ lastActivityAt,
800
+ updatedAt: lastActivityAt,
801
+ executionStatus: "idle"
802
+ }).onConflictDoUpdate({
803
+ target: juniorConversations.conversationId,
804
+ set: {
805
+ createdAt: sql`least(${juniorConversations.createdAt}, excluded.created_at)`,
806
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
807
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`
808
+ }
809
+ });
810
+ }
811
+ async function ensureChildConversationRow(executor, childConversationId, parentConversationId, createdAt, lastActivityAt) {
812
+ await ensureConversationRow(
813
+ executor,
814
+ parentConversationId,
815
+ createdAt,
816
+ lastActivityAt
817
+ );
818
+ await executor.db().insert(juniorConversations).values({
819
+ conversationId: childConversationId,
820
+ schemaVersion: 1,
821
+ parentConversationId,
822
+ createdAt,
823
+ lastActivityAt,
824
+ updatedAt: lastActivityAt,
825
+ executionStatus: "idle"
826
+ }).onConflictDoUpdate({
827
+ target: juniorConversations.conversationId,
828
+ set: {
829
+ parentConversationId: sql`coalesce(${juniorConversations.parentConversationId}, excluded.parent_conversation_id)`,
830
+ createdAt: sql`least(${juniorConversations.createdAt}, excluded.created_at)`,
831
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
832
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`
833
+ }
834
+ });
835
+ }
836
+
837
+ // src/chat/conversations/legacy-import.ts
838
+ var legacyVisibleMessageSchema = z.object({
839
+ id: z.string(),
840
+ role: z.enum(["user", "assistant", "system"]),
841
+ text: z.string(),
842
+ createdAtMs: z.number().finite(),
843
+ author: z.object({}).passthrough().optional(),
844
+ meta: z.object({}).passthrough().optional()
845
+ });
846
+ var legacyCompactionSchema = z.object({
847
+ coveredMessageIds: z.array(z.string()),
848
+ createdAtMs: z.number().finite(),
849
+ id: z.string(),
850
+ summary: z.string()
851
+ });
852
+ var legacyThreadStateSnapshotSchema = z.object({
853
+ conversation: z.object({
854
+ compactions: z.array(legacyCompactionSchema).optional(),
855
+ messages: z.array(legacyVisibleMessageSchema).optional(),
856
+ stats: z.object({ updatedAtMs: z.number().finite().optional() }).passthrough().optional()
857
+ }).passthrough().optional()
858
+ });
859
+ async function loadThreadStateSnapshot(conversationId) {
860
+ const stateAdapter = getStateAdapter();
861
+ await stateAdapter.connect();
862
+ const raw = await stateAdapter.get(`thread-state:${conversationId}`);
863
+ if (!raw) {
864
+ return { compactions: [], messages: [] };
865
+ }
866
+ const conversation = legacyThreadStateSnapshotSchema.parse(raw).conversation;
867
+ return {
868
+ compactions: conversation?.compactions ?? [],
869
+ messages: conversation?.messages ?? [],
870
+ ...conversation?.stats?.updatedAtMs !== void 0 ? { lastActivityAtMs: conversation.stats.updatedAtMs } : {}
871
+ };
872
+ }
873
+ function intrinsicTimestamps(entries, visible, compactions) {
874
+ const candidates = [];
875
+ const pushMessageTs = (message) => {
876
+ const timestamp = message.timestamp;
877
+ if (typeof timestamp === "number") {
878
+ candidates.push(timestamp);
879
+ }
880
+ };
881
+ for (const entry of entries) {
882
+ if (entry.type === "pi_message") {
883
+ pushMessageTs(entry.message);
884
+ } else if (entry.type === "projection_reset") {
885
+ entry.messages.forEach(pushMessageTs);
886
+ } else if ("createdAtMs" in entry) {
887
+ candidates.push(entry.createdAtMs);
888
+ }
889
+ }
890
+ for (const message of visible) {
891
+ candidates.push(message.createdAtMs);
892
+ }
893
+ for (const compaction of compactions) {
894
+ candidates.push(compaction.createdAtMs);
895
+ }
896
+ return candidates;
897
+ }
898
+ async function importConversationFromLegacy(conversationId, deps) {
899
+ const stepStore = createSqlAgentStepStore(deps.executor);
900
+ const existing = await stepStore.loadCurrentEpoch(conversationId);
901
+ if (existing.length > 0) {
902
+ return { imported: false };
903
+ }
904
+ const entries = deps.sessionLogStore ? await deps.sessionLogStore.read({ conversationId }) : await readSessionLogEntries({ conversationId });
905
+ const snapshot = deps.loadVisibleMessages ? {
906
+ compactions: deps.legacyCompactions ?? [],
907
+ messages: await deps.loadVisibleMessages(conversationId)
908
+ } : await loadThreadStateSnapshot(conversationId);
909
+ const { compactions, messages: visible } = snapshot;
910
+ if (entries.length === 0 && visible.length === 0 && compactions.length === 0) {
911
+ return { imported: false };
912
+ }
913
+ const hasAdvisor = entries.some((entry) => entry.type === "subagent_started");
914
+ const advisorMessages = hasAdvisor ? await (deps.advisorSessionStore ?? createStateAdvisorSessionStore()).load(
915
+ conversationId
916
+ ) : [];
917
+ const intrinsic = intrinsicTimestamps(entries, visible, compactions);
918
+ for (const message of advisorMessages) {
919
+ const timestamp = message.timestamp;
920
+ if (typeof timestamp === "number") {
921
+ intrinsic.push(timestamp);
922
+ }
923
+ }
924
+ const fallbackCreatedAtMs = deps.conversationRecord?.createdAtMs ?? (intrinsic.length > 0 ? Math.min(...intrinsic) : void 0) ?? 0;
925
+ const lastActivityAtMs = Math.max(
926
+ fallbackCreatedAtMs,
927
+ deps.conversationRecord?.lastActivityAtMs ?? 0,
928
+ deps.legacyLastActivityAtMs ?? 0,
929
+ intrinsic.length > 0 ? Math.max(...intrinsic) : 0
930
+ );
931
+ const converted = convertLegacySessionLog({
932
+ conversationId,
933
+ entries,
934
+ fallbackCreatedAtMs
935
+ });
936
+ if (compactions.length > 0) {
937
+ converted.steps.push({
938
+ seq: converted.steps.length,
939
+ contextEpoch: converted.steps.at(-1)?.contextEpoch ?? 0,
940
+ entry: { type: "visible_context_compacted", compactions },
941
+ createdAtMs: compactions.at(-1)?.createdAtMs ?? fallbackCreatedAtMs
942
+ });
943
+ }
944
+ if (converted.steps.length === 0 && visible.length > 0) {
945
+ const existingMessages = new Map(
946
+ (await deps.messageStore.list(conversationId)).map((message) => [
947
+ message.messageId,
948
+ message
949
+ ])
950
+ );
951
+ const fullyImported = visible.every((message) => {
952
+ const existingMessage = existingMessages.get(message.id);
953
+ const projected = toStoredConversationMessage(message);
954
+ return existingMessage !== void 0 && Object.entries(projected.meta ?? {}).every(
955
+ ([key, value]) => isDeepStrictEqual2(existingMessage.meta?.[key], value)
956
+ ) && (message.meta?.replied !== true || existingMessage.repliedAtMs !== void 0);
957
+ });
958
+ if (fullyImported) {
959
+ await writeLegacyImport(deps.executor, {
960
+ conversationId,
961
+ fallbackCreatedAtMs,
962
+ lastActivityAtMs,
963
+ steps: []
964
+ });
965
+ return { imported: false };
966
+ }
967
+ }
968
+ let child;
969
+ if (converted.advisorChildConversationId) {
970
+ child = {
971
+ conversationId: converted.advisorChildConversationId,
972
+ steps: convertAdvisorMessages(advisorMessages, fallbackCreatedAtMs)
973
+ };
974
+ }
975
+ const messages = visible.map((message) => ({
976
+ ...toStoredConversationMessage(message),
977
+ ...message.meta?.replied ? { repliedAtMs: message.createdAtMs } : {}
978
+ }));
979
+ const imported = await writeLegacyImport(deps.executor, {
980
+ conversationId,
981
+ fallbackCreatedAtMs,
982
+ lastActivityAtMs,
983
+ ...messages.length > 0 ? { messages } : {},
984
+ steps: converted.steps,
985
+ ...child ? { child } : {}
986
+ });
987
+ return { imported };
988
+ }
989
+ async function ensureLegacyConversationImport(args) {
990
+ const stepStore = getAgentStepStore();
991
+ if ((await stepStore.loadCurrentEpoch(args.conversationId)).length > 0) {
992
+ return;
993
+ }
994
+ const entries = await readSessionLogEntries({
995
+ conversationId: args.conversationId
996
+ });
997
+ const snapshot = await loadThreadStateSnapshot(args.conversationId);
998
+ const visible = snapshot.messages;
999
+ if (entries.length === 0 && visible.length === 0 && snapshot.compactions.length === 0) {
1000
+ return;
1001
+ }
1002
+ const executor = getSqlExecutor();
1003
+ const purged = await executor.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq2(juniorConversations.conversationId, args.conversationId));
1004
+ if (purged[0]?.transcriptPurgedAt) {
1005
+ return;
1006
+ }
1007
+ await importConversationFromLegacy(args.conversationId, {
1008
+ executor,
1009
+ messageStore: getConversationMessageStore(),
1010
+ sessionLogStore: { read: async () => entries, append: async () => {
1011
+ } },
1012
+ loadVisibleMessages: async () => visible,
1013
+ legacyCompactions: snapshot.compactions,
1014
+ ...snapshot.lastActivityAtMs === void 0 ? {} : { legacyLastActivityAtMs: snapshot.lastActivityAtMs }
1015
+ });
1016
+ }
1017
+
1018
+ export {
1019
+ persistConversationCompactions,
1020
+ estimateTextTokens,
1021
+ getAgentContextCompactionTriggerTokens,
1022
+ generateConversationId,
1023
+ normalizeConversationText,
1024
+ updateConversationStats,
1025
+ upsertConversationMessage,
1026
+ markConversationMessage,
1027
+ buildConversationContext,
1028
+ getThreadTitleSourceMessage,
1029
+ createConversationMemoryService,
1030
+ isHumanConversationMessage,
1031
+ getConversationMessageSlackTs,
1032
+ hydrateConversationMessages,
1033
+ persistConversationMessages,
1034
+ JUNIOR_THREAD_STATE_TTL_MS,
1035
+ importConversationFromLegacy,
1036
+ ensureLegacyConversationImport
1037
+ };