@sentry/junior 0.297.0 → 0.299.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 (94) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-DFnmLmfn.js → adapter-AgCNqqsG.js} +49 -133
  3. package/dist/{admin-tmGIw4KS.js → admin-1VwEXztm.js} +2 -2
  4. package/dist/{agent-runner-CneTquAE.js → agent-runner-Ciet8_nn.js} +1067 -1353
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +125 -43
  9. package/dist/{app-BJojZ7HL.d.ts → app--ky-Eu33.d.ts} +6 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +126 -299
  12. package/dist/{automation-BrP6ImrC.js → automation-M3RFJUBf.js} +1 -1
  13. package/dist/{background-compaction-queue-CwfJy3Cd.js → background-compaction-queue-CnimvRdk.js} +4 -4
  14. package/dist/{briefs-uFTuhMqA.js → briefs-CwzvgdCa.js} +4 -4
  15. package/dist/{catalog-runtime-0kuQqYL4.js → catalog-runtime-DaBaHY7u.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-Dj9M_nqB.js → config-CAXIpWQb.js} +80 -6
  24. package/dist/{connections-B96JUM5o.js → connections-Dy0hPdUq.js} +6 -6
  25. package/dist/continue-in-slack-DIOjFj76.js +176 -0
  26. package/dist/{conversation-CvcBU1z2.js → conversation-fCWD9Az3.js} +73 -13
  27. package/dist/{conversation-feed-BSMlGZnS.js → conversation-feed-BPK8vkkZ.js} +88 -3
  28. package/dist/{conversation-privacy-DI29jbZV.js → conversation-privacy-DUgtRkf8.js} +1 -1
  29. package/dist/{conversation-turn-CZWBr091.js → conversation-turn-DkJB6yMF.js} +85 -68
  30. package/dist/{credential-sync-Blhx4_xf.js → credential-sync-RX24Y8aY.js} +18 -18
  31. package/dist/{db-CrtyFRz7.d.ts → db-B07FtU9g.d.ts} +1 -1
  32. package/dist/{db-Br0tfAo7.js → db-COYOGzYS.js} +171 -12
  33. package/dist/{executor-BMPipFVA.js → executor-BWmAgSyi.js} +40 -11
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/lineage-D-5jm_oj.js +37 -0
  37. package/dist/{logging-CQjlDQYX.js → logging-DPLEa8Bn.js} +1 -1
  38. package/dist/media-BAHvgkok.js +85 -0
  39. package/dist/{message-BOZEIuxy.js → message-BIHR1yRk.js} +9 -10
  40. package/dist/model-input-BPZYH8Nd.js +82 -0
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +17 -9
  43. package/dist/{oauth-callback-server-V_DuMuNX.js → oauth-callback-server-R7qvSzFG.js} +2 -2
  44. package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
  45. package/dist/{projection-B08mfi0u.js → projection-DEdP1q6f.js} +261 -36
  46. package/dist/{prompt-BlutWLNt.js → prompt-4M98h_tC.js} +4 -4
  47. package/dist/{registry-BDWgCJDf.js → registry-BTKmKM-r.js} +3 -3
  48. package/dist/{resolve-2Z_o_SsI.js → resolve-B8hXNVZ3.js} +3 -3
  49. package/dist/{result-CAujiaci.js → result-g-XAaOj6.js} +158 -69
  50. package/dist/{runner-D2Chc02N.js → runner-BlPSA5A8.js} +9 -9
  51. package/dist/{sandbox-egress-signals-CFoJduFj.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
  52. package/dist/{schema-Bqa5NbcP.js → schema-BNnY_trV.js} +47 -7
  53. package/dist/{schema-Ce2XCS7O.d.ts → schema-DbuWR-DN.d.ts} +663 -346
  54. package/dist/{service-account-C9kRQEb_.js → service-account-9OLNQMyz.js} +4 -4
  55. package/dist/{service-account-CERfXEVU.js → service-account-BYGZ08DQ.js} +3 -3
  56. package/dist/session-stop-2XJrcNCy.js +3356 -0
  57. package/dist/{skills-B0m1nZ_j.js → skills-DpBQoeHV.js} +3 -3
  58. package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
  59. package/dist/spawn-09GssFod.js +73 -0
  60. package/dist/state-Cufq0_rH.js +132 -0
  61. package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
  62. package/dist/{stop-BCH9VNGf.js → stop-U7iUrR1g.js} +6011 -5773
  63. package/dist/{store-B59rOYbS.js → store-BHiaHCQu.js} +24 -4
  64. package/dist/{store-m5bmdmsP.js → store-CSgUTMdv.js} +10 -10
  65. package/dist/{task-queue-N0kuCknH.js → task-queue-bMNq0clp.js} +4 -4
  66. package/dist/{task-runner-COOwR8qm.js → task-runner-B__rxwxU.js} +10 -10
  67. package/dist/{thread-context-Cd44z_W5.js → thread-context-d0ceWbVT.js} +18 -18
  68. package/dist/{turn-session-routing-BlCtVFRN.js → turn-session-routing-BVZHBFCF.js} +5 -5
  69. package/dist/turn-user-message-BEw7acTP.js +355 -0
  70. package/dist/users-BK3dbxZL.js +424 -0
  71. package/dist/{validation-Ba2OcUse.js → validation-BDVJjO2E.js} +1 -1
  72. package/dist/{version-KNDzIAh6.js → version-DQgZoQ3D.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-BPpuN2f9.js → viewer-CAWfFo29.js} +25 -54
  75. package/dist/{warmup-Bskrwmk1.js → warmup-9ySPacF9.js} +1137 -143
  76. package/dist/{worker-B1skZlit.js → worker-D8jJO-WO.js} +8 -7
  77. package/migrations/0104_code_change_draft.sql +1 -0
  78. package/migrations/0105_attachment_uploads.sql +14 -0
  79. package/migrations/0106_conversation_agent_config.sql +1 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +4 -4
  85. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  86. package/dist/locks-D-0h111u.js +0 -48
  87. package/dist/notification-gusCgdQ6.js +0 -1284
  88. package/dist/prompt-input-Dxn8cDC0.js +0 -1424
  89. package/dist/session-stop-B-I1rAS1.js +0 -181
  90. package/dist/spawn-CwMjRRtn.js +0 -80
  91. package/dist/turn-cancel-DDu8TOwt.js +0 -201
  92. package/dist/turn-user-message-ygLG3ylQ.js +0 -641
  93. package/dist/turn-wake-DmQec4AG.js +0 -161
  94. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,5 +1,88 @@
1
- import { G as briefOutcomeStatusSchema, M as reviewItemChangeRecordSchema, V as messageAttachmentSchema, i as actorIdentitySchema, l as conversationDetailReportSchema, y as conversationSummaryReportSchema } from "./conversation-CvcBU1z2.js";
1
+ import { L as reviewItemChangeRecordSchema, Z as briefOutcomeStatusSchema, i as actorIdentitySchema, l as conversationDetailReportSchema, q as messageAttachmentSchema, y as conversationSummaryReportSchema } from "./conversation-fCWD9Az3.js";
2
2
  import * as z from "zod";
3
+ // src/api/objects/cards.ts
4
+ const MAX_LABEL_CHARS = 256;
5
+ const MAX_FACT_CHARS = 160;
6
+ const conversationStates = {
7
+ active: "running",
8
+ completed: "idle",
9
+ failed: "failed",
10
+ stopped: "stopped"
11
+ };
12
+ function personName(person) {
13
+ return person.fullName ?? person.slackUserName ?? person.email;
14
+ }
15
+ /**
16
+ * Build the card of one Conversation that the viewer may read. Give `brief`
17
+ * only when the viewer may see the Brief.
18
+ */
19
+ function conversationObjectCard(args) {
20
+ const { summary } = args;
21
+ const participants = args.participants.flatMap((person) => personName(person)?.slice(0, MAX_FACT_CHARS) ?? []).slice(0, 5);
22
+ return {
23
+ kind: "object",
24
+ objectType: "conversation",
25
+ key: summary.conversationId.slice(0, 256),
26
+ label: summary.displayTitle.slice(0, MAX_LABEL_CHARS),
27
+ title: summary.displayTitle.slice(0, 512),
28
+ url: args.url,
29
+ status: summary.archivedAt ? "archived" : conversationStates[summary.status],
30
+ ...args.brief ? { description: args.brief.slice(0, 4e3) } : void 0,
31
+ facts: {
32
+ type: "conversation",
33
+ ...participants.length > 0 ? { participants } : void 0,
34
+ lastActivityAt: summary.lastSeenAt
35
+ }
36
+ };
37
+ }
38
+ /** Build the card of one known person from what the People pages show. */
39
+ function personObjectCard(args) {
40
+ const { person } = args;
41
+ const name = personName(person) ?? person.email;
42
+ return {
43
+ kind: "object",
44
+ objectType: "person",
45
+ key: person.email.toLowerCase().slice(0, 256),
46
+ label: name.slice(0, MAX_LABEL_CHARS),
47
+ title: name.slice(0, 512),
48
+ url: args.url,
49
+ facts: {
50
+ type: "person",
51
+ email: person.email.slice(0, MAX_FACT_CHARS),
52
+ ...person.slackUserName ? { slackHandle: person.slackUserName.slice(0, MAX_FACT_CHARS) } : void 0,
53
+ ...args.githubHandle ? { githubHandle: args.githubHandle } : void 0,
54
+ ...person.avatarUrl ? { avatarUrl: person.avatarUrl } : void 0
55
+ }
56
+ };
57
+ }
58
+ const MAX_SNIPPET_CHARS = 280;
59
+ const MAX_TITLE_CHARS = 100;
60
+ function truncate(text, max) {
61
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
62
+ }
63
+ /**
64
+ * Build the card of one chat message. Give `text` only when the viewer may
65
+ * read the message: the card shows a short snippet of it, never all of it.
66
+ */
67
+ function messageObjectCard(args) {
68
+ const snippet = args.text?.replace(/\s+/g, " ").trim();
69
+ const title = snippet ? truncate(snippet, MAX_TITLE_CHARS) : `Message in ${args.channel}`;
70
+ return {
71
+ kind: "object",
72
+ objectType: "message",
73
+ key: args.key.slice(0, 256),
74
+ label: args.channel.slice(0, MAX_LABEL_CHARS),
75
+ title,
76
+ url: args.url,
77
+ ...snippet && snippet.length > title.length ? { description: truncate(snippet, MAX_SNIPPET_CHARS) } : void 0,
78
+ facts: {
79
+ type: "message",
80
+ channel: args.channel.slice(0, MAX_FACT_CHARS),
81
+ ...args.author ? { author: args.author.slice(0, MAX_FACT_CHARS) } : void 0,
82
+ ...args.sentAt ? { sentAt: args.sentAt } : void 0
83
+ }
84
+ };
85
+ }
3
86
  // src/reporting-schema.ts
4
87
  const healthReportSchema = z.object({
5
88
  status: z.literal("ok"),
@@ -201,6 +284,8 @@ const conversationFeedItemSchema = conversationSummaryReportSchema.extend({
201
284
  const conversationFeedSchema = z.object({
202
285
  conversations: z.array(conversationFeedItemSchema),
203
286
  source: z.literal("conversation_index"),
204
- generatedAt: z.string()
287
+ generatedAt: z.string(),
288
+ /** Present when older conversations follow this page. */
289
+ nextCursor: z.string().optional()
205
290
  }).strict();
206
- export { skillReportsSchema as C, skillReportSchema as S, pluginPackageContentReportSchema as _, conversationDetailWithMailboxReportSchema as a, runtimeInfoReportSchema as b, conversationPendingMessageSchema as c, steerConversationPendingMessagesBodySchema as d, steerConversationPendingMessagesResponseSchema as f, pluginPackageContentItemReportSchema as g, pluginOperationalReportSchema as h, cancelConversationPendingMessagesResponseSchema as i, conversationPendingMessagesReportSchema as l, pluginOperationalReportFeedSchema as m, conversationFeedSchema as n, conversationPendingAuthorizationSchema as o, healthReportSchema as p, cancelConversationPendingMessagesBodySchema as r, conversationPendingMessageDeliverySchema as s, conversationFeedBriefSchema as t, conversationUnchangedDetailWithMailboxSchema as u, pluginSchema as v, skillDetailReportSchema as x, pluginsSchema as y };
291
+ export { skillReportsSchema as C, personObjectCard as E, skillReportSchema as S, messageObjectCard as T, pluginPackageContentReportSchema as _, conversationDetailWithMailboxReportSchema as a, runtimeInfoReportSchema as b, conversationPendingMessageSchema as c, steerConversationPendingMessagesBodySchema as d, steerConversationPendingMessagesResponseSchema as f, pluginPackageContentItemReportSchema as g, pluginOperationalReportSchema as h, cancelConversationPendingMessagesResponseSchema as i, conversationPendingMessagesReportSchema as l, pluginOperationalReportFeedSchema as m, conversationFeedSchema as n, conversationPendingAuthorizationSchema as o, healthReportSchema as p, cancelConversationPendingMessagesBodySchema as r, conversationPendingMessageDeliverySchema as s, conversationFeedBriefSchema as t, conversationUnchangedDetailWithMailboxSchema as u, pluginSchema as v, conversationObjectCard as w, skillDetailReportSchema as x, pluginsSchema as y };
@@ -1,4 +1,4 @@
1
- import { h as logWarn } from "./logging-CQjlDQYX.js";
1
+ import { h as logWarn } from "./logging-DPLEa8Bn.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  // src/chat/conversation-privacy.ts
4
4
  const SAFE_METADATA_KEY_LIMIT = 20;
@@ -1,54 +1,25 @@
1
1
  import { i as getActiveSpan, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { A as latestConversationMessageSeq, I as upsertConversationMessage, M as normalizeConversationText, N as recordDeliveredAssistantMessage, _i as verifyTimerWatchCredentialSubject, a as loadProjection, an as getAssistantReplyText, at as failTurnRecord, b as persistConversationMessages, j as markConversationMessage, mn as persistWithRetry, nt as saveTurnCheckpoint, ot as getTurnRecord, t as commitAcceptedReply, v as hydrateConversationMessages } from "./projection-B08mfi0u.js";
3
- import { n as botConfig } from "./config-Dj9M_nqB.js";
4
- import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-CQjlDQYX.js";
5
- import { D as turnBehavior, T as isTopLevelKind, a as getConversationStore, et as nextDetailVersion, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isPersonInput } from "./db-Br0tfAo7.js";
6
- import { A as juniorConversations } from "./executor-BMPipFVA.js";
7
- import { _ as instructionProvenanceFor } from "./media-BepyEUNm.js";
8
- import { f as credentialContextForActor } from "./registry-BDWgCJDf.js";
9
- import { gt as resolveConversationDestination, i as measureTurnCompactionWait } from "./agent-runner-CneTquAE.js";
10
- import { o as isEventConversationMessage } from "./prompt-BlutWLNt.js";
11
- import { H as readMessageAttachments } from "./conversation-CvcBU1z2.js";
12
- import { C as legacyWebMailboxMetadataSchema, S as turnInputFactsFromConversationMessage, _ as getEventBatchDelayMs, l as withoutSavedSteeringMessages, n as loadReviewItemInput, o as buildSteeringPiMessage, s as instructionForInputs, t as eventReviewItemInputs, x as sourceFromTurnInput } from "./prompt-input-Dxn8cDC0.js";
13
- import { _ as ConversationTurnLifecycleService, d as isTurnInputCommitLostError, g as startActiveTurn, h as markTurnFailed, l as getConversationTurnBoundaryError, mt as buildDeterministicTurnId, s as TurnInputCommitLostError, t as getTurnUserMessage } from "./turn-user-message-ygLG3ylQ.js";
14
- import { T as recordFinishedTurnForAutomatedLimit, a as renderEventBatchInputs, i as isEventMailboxMetadata, o as timerWatchCredentialSubject, r as eventBatchMessageMeta, y as maybePostAutomatedTurnLimitNotice } from "./notification-gusCgdQ6.js";
15
- import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-BlCtVFRN.js";
16
- import { a as AgentRunError, n as completeCancelledConversationTurn, o as executeTurn, r as supersedeOpenMailboxTurns } from "./turn-cancel-DDu8TOwt.js";
17
- import { o as createWebAuthorization } from "./turn-wake-DmQec4AG.js";
18
- import { H as blockEventAutomation, M as blockScheduledAutomation, c as getDispatchRecord, o as getDispatchIdForConversation, v as notifyAutomationBlocked, x as readAutomationExecutionByConversationId } from "./store-m5bmdmsP.js";
19
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-COOwR8qm.js";
20
- import { c as buildDeliveredTurnStatePatch, l as loadPendingMessageCards, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, t as buildTurnThreadContext } from "./thread-context-Cd44z_W5.js";
2
+ import { A as latestConversationMessageSeq, Ei as verifyTimerWatchCredentialSubject, I as upsertConversationMessage, M as normalizeConversationText, N as recordDeliveredAssistantMessage, a as loadProjection, at as failTurnRecord, b as persistConversationMessages, bn as persistWithRetry, j as markConversationMessage, nt as saveTurnCheckpoint, st as getTurnRecord, t as commitAcceptedReply, un as getAssistantReplyText, v as hydrateConversationMessages } from "./projection-DEdP1q6f.js";
3
+ import { n as botConfig } from "./config-CAXIpWQb.js";
4
+ import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-DPLEa8Bn.js";
5
+ import { C as isPersonInput, E as turnBehavior, a as getConversationStore, nt as nextDetailVersion, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isTopLevelKind } from "./db-COYOGzYS.js";
6
+ import { j as juniorConversations } from "./executor-BWmAgSyi.js";
7
+ import { p as instructionProvenanceFor } from "./history-IjdmO_r6.js";
8
+ import { f as credentialContextForActor } from "./registry-BTKmKM-r.js";
9
+ import { i as measureTurnCompactionWait, lt as resolveConversationDestination } from "./agent-runner-Ciet8_nn.js";
10
+ import { o as isEventConversationMessage } from "./prompt-4M98h_tC.js";
11
+ import { J as readMessageAttachments } from "./conversation-fCWD9Az3.js";
12
+ import { A as turnInputFactsFromConversationMessage, F as isEventMailboxMetadata, I as renderEventBatchInputs, L as timerWatchCredentialSubject, P as eventBatchMessageMeta, X as maybePostAutomatedTurnLimitNotice, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, j as legacyWebMailboxMetadataSchema, k as sourceFromTurnInput, m as instructionForInputs, nt as recordFinishedTurnForAutomatedLimit, p as instructionActorFor, s as eventReviewItemInputs, w as getEventBatchDelayMs } from "./session-stop-2XJrcNCy.js";
13
+ import { Et as executeTurn, L as readParentMessage, M as childAgentTurnOptions, N as isParentMessageMeta, St as createWebAuthorization, Tt as AgentRunError, Y as completeCancelledConversationTurn, dt as supersedeOpenMailboxTurns } from "./warmup-9ySPacF9.js";
14
+ import { R as buildDeterministicTurnId, _ as ConversationTurnLifecycleService, d as isTurnInputCommitLostError, g as startActiveTurn, h as markTurnFailed, l as getConversationTurnBoundaryError, s as TurnInputCommitLostError, t as getTurnUserMessage } from "./turn-user-message-BEw7acTP.js";
15
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-BVZHBFCF.js";
16
+ import { H as blockEventAutomation, M as blockScheduledAutomation, c as getDispatchRecord, o as getDispatchIdForConversation, v as notifyAutomationBlocked, x as readAutomationExecutionByConversationId } from "./store-CSgUTMdv.js";
17
+ import { t as readConversationLineage } from "./lineage-D-5jm_oj.js";
18
+ import { c as buildDeliveredTurnStatePatch, l as loadPendingMessageCards, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, t as buildTurnThreadContext } from "./thread-context-d0ceWbVT.js";
19
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-B__rxwxU.js";
21
20
  import { isDeepStrictEqual } from "node:util";
22
21
  import { createHash } from "node:crypto";
23
22
  import { and, eq, isNotNull, isNull } from "drizzle-orm";
24
- // src/chat/conversations/delivery-pause.ts
25
- /** True when the Conversation is a root that delivers to a Location. */
26
- function canPauseConversationDelivery(conversation) {
27
- return isTopLevelKind(conversation.kind) && conversation.location !== void 0;
28
- }
29
- const rootConversation = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId));
30
- /**
31
- * Stop Delivery of a root's Event Turn replies to its Location. Returns false
32
- * when Delivery was already paused or the root does not exist.
33
- */
34
- async function pauseConversationDelivery(conversationId) {
35
- return (await getSqlExecutor().db().update(juniorConversations).set({
36
- deliveryPausedAt: /* @__PURE__ */ new Date(),
37
- detailVersion: nextDetailVersion
38
- }).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
39
- }
40
- /** Deliver a root's Event Turn replies to its Location again. */
41
- async function resumeConversationDelivery(conversationId) {
42
- await getSqlExecutor().db().update(juniorConversations).set({
43
- deliveryPausedAt: null,
44
- detailVersion: nextDetailVersion
45
- }).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
46
- }
47
- /** True while a root's Event Turn replies stay out of its Location. */
48
- async function isConversationDeliveryPaused(conversationId) {
49
- const [row] = await getSqlExecutor().db().select({ pausedAt: juniorConversations.deliveryPausedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
50
- return Boolean(row?.pausedAt);
51
- }
52
23
  // src/chat/task-execution/turn-telemetry.ts
53
24
  /** Read the turn input timing facts from a mailbox batch, oldest first. */
54
25
  function turnInputTelemetry(messages) {
@@ -142,6 +113,34 @@ async function blockRunAutomation(conversationId, blocked) {
142
113
  reason: blocked.missing
143
114
  });
144
115
  }
116
+ // src/chat/conversations/delivery-pause.ts
117
+ /** True when the Conversation is a root that delivers to a Location. */
118
+ function canPauseConversationDelivery(conversation) {
119
+ return isTopLevelKind(conversation.kind) && conversation.location !== void 0;
120
+ }
121
+ const rootConversation = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId));
122
+ /**
123
+ * Stop Delivery of a root's Event Turn replies to its Location. Returns false
124
+ * when Delivery was already paused or the root does not exist.
125
+ */
126
+ async function pauseConversationDelivery(conversationId) {
127
+ return (await getSqlExecutor().db().update(juniorConversations).set({
128
+ deliveryPausedAt: /* @__PURE__ */ new Date(),
129
+ detailVersion: nextDetailVersion
130
+ }).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
131
+ }
132
+ /** Deliver a root's Event Turn replies to its Location again. */
133
+ async function resumeConversationDelivery(conversationId) {
134
+ await getSqlExecutor().db().update(juniorConversations).set({
135
+ deliveryPausedAt: null,
136
+ detailVersion: nextDetailVersion
137
+ }).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
138
+ }
139
+ /** True while a root's Event Turn replies stay out of its Location. */
140
+ async function isConversationDeliveryPaused(conversationId) {
141
+ const [row] = await getSqlExecutor().db().select({ pausedAt: juniorConversations.deliveryPausedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
142
+ return Boolean(row?.pausedAt);
143
+ }
145
144
  // src/chat/task-execution/assistant-message.ts
146
145
  /** Store one assistant Message and its Agent history. */
147
146
  async function commitAssistantMessage(args) {
@@ -229,10 +228,7 @@ async function steeringMessageFromWeb(message, actor) {
229
228
  const storedAttachments = readMessageAttachments(message.input.attachments);
230
229
  const reviewItemInput = await loadReviewItemInput(message.input.reviewItemChange);
231
230
  return {
232
- actor: {
233
- authorId: actor.userId,
234
- ...actor.fullName ? { authorName: actor.fullName } : void 0
235
- },
231
+ actor: instructionActorFor(actor),
236
232
  ...reviewItemInput ? { kind: "runtime" } : void 0,
237
233
  provenance: instructionProvenanceFor(actor),
238
234
  text: reviewItemInput ?? message.input.text.trim(),
@@ -270,6 +266,29 @@ function createWebSteeringDrain(args) {
270
266
  return accepted;
271
267
  };
272
268
  }
269
+ // src/chat/task-execution/turn-credentials.ts
270
+ /**
271
+ * Return a saved timer creator subject when it is still valid here. The
272
+ * timer's Watch belongs to this Conversation. It may also belong to an
273
+ * ancestor when `fromParent`: the input is a parent message that passed its
274
+ * sender check, so the child continues the work of the parent's timer Turn.
275
+ */
276
+ async function verifiedTimerWatchSubject(conversationId, subject, fromParent) {
277
+ if (subject?.binding.type !== "timer-watch") return void 0;
278
+ const watchConversationId = subject.binding.conversationId;
279
+ if (watchConversationId !== conversationId && !(fromParent && (await readConversationLineage(conversationId)).some((entry) => entry.conversationId === watchConversationId))) return;
280
+ return verifyTimerWatchCredentialSubject({
281
+ conversationId: watchConversationId,
282
+ subject,
283
+ watchId: subject.binding.watchId
284
+ }) ? subject : void 0;
285
+ }
286
+ /** Return the delegated subject that every input of a batch carries, if any. */
287
+ function sharedDelegatedSubject(batch) {
288
+ const subjects = batch.map((entry) => entry.credentialContext && "subject" in entry.credentialContext ? entry.credentialContext.subject : void 0);
289
+ const first = subjects[0];
290
+ return first && subjects.every((subject) => isDeepStrictEqual(subject, first)) ? first : void 0;
291
+ }
273
292
  // src/chat/task-execution/conversation-turn.ts
274
293
  /** Run a mailbox Turn and store its assistant Messages. */
275
294
  var conversation_turn_exports = /* @__PURE__ */ __exportAll({ createConversationTurnWorker: () => createConversationTurnWorker });
@@ -284,20 +303,6 @@ function captureConversationTurnFailure(args) {
284
303
  });
285
304
  return typeof eventId === "string" ? eventId : void 0;
286
305
  }
287
- /** Return the saved timer creator subject when it is still valid here. */
288
- function resumedTimerWatchCredentialSubject(conversationId, subject) {
289
- if (subject?.binding.type !== "timer-watch") return void 0;
290
- return verifyTimerWatchCredentialSubject({
291
- conversationId,
292
- subject,
293
- watchId: subject.binding.watchId
294
- }) ? subject : void 0;
295
- }
296
- function sharedDelegatedSubject(batch) {
297
- const subjects = batch.map((entry) => entry.credentialContext && "subject" in entry.credentialContext ? entry.credentialContext.subject : void 0);
298
- const first = subjects[0];
299
- return first && subjects.every((subject) => isDeepStrictEqual(subject, first)) ? first : void 0;
300
- }
301
306
  function hasLostTurnInputCommit(error) {
302
307
  const cause = getConversationTurnBoundaryError(error)?.cause ?? error;
303
308
  return isTurnInputCommitLostError(error) || isTurnInputCommitLostError(cause);
@@ -374,10 +379,12 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
374
379
  });
375
380
  const savedTurn = isResume ? await getTurnRecord(context.conversationId, turnId) : void 0;
376
381
  let savedMessageIsEvent = false;
382
+ let savedParentMessage = false;
377
383
  if (isResume) {
378
384
  const userMessage = getTurnUserMessage(conversation, turnId);
379
385
  if (!userMessage) throw new Error(`Unable to locate the persisted user message for Turn "${turnId}"`);
380
386
  savedMessageIsEvent = isEventConversationMessage(userMessage);
387
+ savedParentMessage = isParentMessageMeta(userMessage.meta);
381
388
  turnInputFacts = turnInputFactsFromConversationMessage(userMessage, {
382
389
  conversationId: context.conversationId,
383
390
  location: storedConversation?.location,
@@ -402,8 +409,9 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
402
409
  const { actor, author } = turnInputFacts;
403
410
  const instructionInputs = instructionForInputs(inputs);
404
411
  const { text } = instructionInputs;
412
+ const instructionActor = instructionActorFor(actor);
405
413
  let credentialSubject;
406
- if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) ?? resumedTimerWatchCredentialSubject(context.conversationId, sharedDelegatedSubject(resolved.batch)) : resumedTimerWatchCredentialSubject(context.conversationId, savedTurn?.credentialSubject);
414
+ if (actor.platform === "system") credentialSubject = resolved.kind === "mailbox" ? timerWatchCredentialSubject(context.conversationId, resolved.batch.map((entry) => entry.message)) ?? await verifiedTimerWatchSubject(context.conversationId, sharedDelegatedSubject(resolved.batch), resolved.batch.every((entry) => readParentMessage(entry.message))) : await verifiedTimerWatchSubject(context.conversationId, savedTurn?.credentialSubject, savedParentMessage);
407
415
  const source = sourceFromTurnInput({
408
416
  conversationId: context.conversationId,
409
417
  source: turnInputFacts.source,
@@ -560,7 +568,13 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
560
568
  })) return await completeCancelledTurn();
561
569
  await persistThreadStateById(context.conversationId, { conversation });
562
570
  if (stopSignal?.aborted) return await completeCancelledTurn();
563
- const piMessages = await loadProjection({ conversationId: context.conversationId });
571
+ const childTurn = await childAgentTurnOptions({
572
+ conversationId: context.conversationId,
573
+ history: await loadProjection({ conversationId: context.conversationId }),
574
+ inputs: resolved.kind === "mailbox" ? resolved.batch.map((entry) => entry.message) : [],
575
+ savedParentMessage
576
+ });
577
+ const piMessages = childTurn.history;
564
578
  failureCode = "agent_run_failed";
565
579
  currentRunId = `conversation-run:${stableHex(turnId, String(startedAtMs))}`;
566
580
  setTags({ runId: currentRunId });
@@ -571,6 +585,8 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
571
585
  runId: currentRunId,
572
586
  instruction: {
573
587
  ...instructionInputs,
588
+ ...instructionActor ? { actor: instructionActor } : void 0,
589
+ ...childTurn.instruction,
574
590
  storedAttachments: attachments,
575
591
  context: await buildTurnThreadContext({
576
592
  conversation,
@@ -581,6 +597,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
581
597
  })
582
598
  },
583
599
  history: piMessages,
600
+ ...childTurn.run,
584
601
  actor,
585
602
  credentialContext: credentialContextForActor(actor, credentialSubject),
586
603
  destination,
@@ -802,4 +819,4 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
802
819
  });
803
820
  };
804
821
  }
805
- export { withTurnSpan as a, resumeConversationDelivery as c, turnInputTelemetry as i, createConversationTurnWorker as n, canPauseConversationDelivery as o, getTurnInputSpanAttributes as r, pauseConversationDelivery as s, conversation_turn_exports as t };
822
+ export { resumeConversationDelivery as a, withTurnSpan as c, pauseConversationDelivery as i, createConversationTurnWorker as n, getTurnInputSpanAttributes as o, canPauseConversationDelivery as r, turnInputTelemetry as s, conversation_turn_exports as t };
@@ -1,25 +1,25 @@
1
- import { Hn as createUserTokenStore, Kn as resolvePluginOAuthAccount, Sa as getSlackClient, Xi as parseOAuthStatePayload, Yi as formatProviderLabel, Z as getConversationPendingAuth, Zi as resolveBaseUrl, d as recordAuthorizationCompleted, da as postSlackMessage, ot as getTurnRecord, u as recordAuthenticationLinked } from "./projection-B08mfi0u.js";
2
- import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-Dj9M_nqB.js";
3
- import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-CQjlDQYX.js";
4
- import { p as parseSlackUserId } from "./actor-6jsm_v96.js";
5
- import { H as upsertLinkedIdentity, P as resolveActorIdentityId, R as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-Br0tfAo7.js";
1
+ import { Fa as getSlackClient, Z as getConversationPendingAuth, Zn as createUserTokenStore, ca as resolveBaseUrl, d as recordAuthorizationCompleted, oa as formatProviderLabel, sa as parseOAuthStatePayload, st as getTurnRecord, tr as resolvePluginOAuthAccount, u as recordAuthenticationLinked, wa as postSlackMessage } from "./projection-DEdP1q6f.js";
2
+ import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-CAXIpWQb.js";
3
+ import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-DPLEa8Bn.js";
4
+ import { p as parseSlackUserId } from "./actor-D2iXzvlN.js";
5
+ import { L as findUserByVerifiedEmails, N as resolveActorIdentityId, V as upsertLinkedIdentity, s as getSqlExecutor } from "./db-COYOGzYS.js";
6
+ import { r as getStateAdapter, s as acquireActiveLock } from "./adapter-AgCNqqsG.js";
6
7
  import { i as homeDir } from "./package-discovery-DJhGdS4c.js";
7
- import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-BDWgCJDf.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-0kuQqYL4.js";
9
- import { t as discoverSkills } from "./skills-B0m1nZ_j.js";
10
- import { b as lookupSlackUserProfile, d as getMcpAuthSession, f as getMcpStoredOAuthCredentials, o as finalizeMcpAuthorization, p as putMcpStoredOAuthCredentials, s as deleteMcpAuthSession } from "./agent-runner-CneTquAE.js";
11
- import { r as acquireActiveLock } from "./locks-D-0h111u.js";
12
- import { o as readIdentityById } from "./viewer-BPpuN2f9.js";
13
- import { a as getStateAdapter } from "./state-DFnmLmfn.js";
8
+ import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-BTKmKM-r.js";
9
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DaBaHY7u.js";
10
+ import { t as discoverSkills } from "./skills-DpBQoeHV.js";
11
+ import { d as getMcpAuthSession, f as getMcpStoredOAuthCredentials, o as finalizeMcpAuthorization, p as putMcpStoredOAuthCredentials, s as deleteMcpAuthSession } from "./agent-runner-Ciet8_nn.js";
12
+ import { o as readIdentityById } from "./viewer-CAWfFo29.js";
14
13
  import { t as readJuniorSecret } from "./secrets-DebYU866.js";
15
- import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-BlCtVFRN.js";
16
- import { i as wakePausedTurn, r as wakeAuthorizedTurn, s as deleteWebAuthorization } from "./turn-wake-DmQec4AG.js";
17
- import { _ as getMcpProviderErrorAttributes } from "./service-account-C9kRQEb_.js";
18
- import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-B96JUM5o.js";
19
- import { n as relayLocalOAuthCallback } from "./oauth-relay-CsfIazeF.js";
14
+ import { Ct as deleteWebAuthorization, gt as wakePausedTurn, ht as wakeAuthorizedTurn } from "./warmup-9ySPacF9.js";
15
+ import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-BVZHBFCF.js";
16
+ import { _ as getMcpProviderErrorAttributes } from "./service-account-9OLNQMyz.js";
17
+ import { r as lookupSlackUserProfile } from "./users-BK3dbxZL.js";
18
+ import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-Dy0hPdUq.js";
19
+ import { n as relayLocalOAuthCallback } from "./oauth-relay-DRzq73b6.js";
20
+ import * as z from "zod";
20
21
  import path from "node:path";
21
22
  import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
22
- import * as z from "zod";
23
23
  import { pluginStoredTokensSchema } from "@sentry/junior-plugin-api";
24
24
  import fs from "node:fs";
25
25
  // src/handlers/mcp-oauth-callback.ts
@@ -1,4 +1,4 @@
1
- import "./schema-Ce2XCS7O.js";
1
+ import "./schema-DbuWR-DN.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -1,9 +1,11 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-Dj9M_nqB.js";
3
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CQjlDQYX.js";
4
- import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-6jsm_v96.js";
5
- import { A as juniorConversations, C as isUserInstruction, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-BMPipFVA.js";
6
- import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-BepyEUNm.js";
2
+ import { i as getChatConfig } from "./config-CAXIpWQb.js";
3
+ import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-DPLEa8Bn.js";
4
+ import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-D2iXzvlN.js";
5
+ import { C as isUserInstruction, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, S as juniorConversationMetrics, j as juniorConversations, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-BWmAgSyi.js";
6
+ import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-IjdmO_r6.js";
7
+ import { l as withLock, r as getStateAdapter } from "./adapter-AgCNqqsG.js";
8
+ import * as z from "zod";
7
9
  import { randomUUID } from "node:crypto";
8
10
  import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
9
11
  import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
@@ -395,6 +397,167 @@ async function claimProviderConversation(executor, args) {
395
397
  async function bindProviderConversation(executor, args) {
396
398
  if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
397
399
  }
400
+ // src/chat/state/cache.ts
401
+ const MAX_CACHE_KEY_LENGTH = 512;
402
+ const LOAD_WAIT_MS = 1e4;
403
+ /**
404
+ * Create a cache in the state adapter under `junior:cache:{namespace}:`.
405
+ * Entries are wrapped, so `null` and `false` values are cache hits.
406
+ */
407
+ function createCache(state, namespace) {
408
+ return { async getOrLoad(key, load, options) {
409
+ if (!key.trim()) throw new Error("Cache key is required");
410
+ if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
411
+ const cacheKey = `junior:cache:${namespace}:${key}`;
412
+ const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
413
+ await state.connect();
414
+ const hit = await cached();
415
+ if (hit) return hit.value;
416
+ const attempt = await withLock(state, `${cacheKey}:load`, async () => {
417
+ const loadedMeanwhile = await cached();
418
+ if (loadedMeanwhile) return loadedMeanwhile.value;
419
+ const entry = await load();
420
+ if (entry.ttlMs !== void 0) {
421
+ if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
422
+ await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
423
+ }
424
+ return entry.value;
425
+ }, {
426
+ keepAlive: true,
427
+ waitMs: LOAD_WAIT_MS
428
+ });
429
+ if (attempt.acquired) return attempt.value;
430
+ return (await load()).value;
431
+ } };
432
+ }
433
+ // src/chat/identities/user-cache.ts
434
+ /**
435
+ * Cache of each User and their user Identities. Every signed-in request
436
+ * resolves its viewer, and person cards read the people that a message
437
+ * links to, so these reads go to the state cache instead of the database.
438
+ *
439
+ * Every write to a cached column or to a user Identity must call
440
+ * `clearCachedUser`. The other columns of a User, such as the timezone or
441
+ * the customization, are not in the cache.
442
+ */
443
+ const USER_TTL_MS = 864e5;
444
+ const MISSING_TTL_MS = 6e4;
445
+ const SETTLE_MS = 1e4;
446
+ const CACHE_NAMESPACE = "identities";
447
+ const cachedUserSchema = z.object({
448
+ identities: z.array(z.object({
449
+ avatarUrl: z.string().nullable(),
450
+ displayName: z.string().nullable(),
451
+ handle: z.string().nullable(),
452
+ id: z.string(),
453
+ provider: z.string(),
454
+ providerSubjectId: z.string(),
455
+ providerTenantId: z.string(),
456
+ updatedAt: z.coerce.date()
457
+ })),
458
+ user: z.object({
459
+ displayName: z.string().nullable(),
460
+ id: z.string(),
461
+ isAdmin: z.boolean(),
462
+ primaryEmail: z.string()
463
+ })
464
+ });
465
+ const versionSchema = z.object({
466
+ token: z.string(),
467
+ writtenAtMs: z.number()
468
+ });
469
+ function versionKey(userId) {
470
+ return `junior:cache:${CACHE_NAMESPACE}:version:${userId}`;
471
+ }
472
+ function cache() {
473
+ return createCache(getStateAdapter(), CACHE_NAMESPACE);
474
+ }
475
+ async function readVersion(userId) {
476
+ const state = getStateAdapter();
477
+ const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
478
+ if (stored.success) return stored.data;
479
+ const created = {
480
+ token: randomUUID(),
481
+ writtenAtMs: 0
482
+ };
483
+ if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
484
+ return versionSchema.parse(await state.get(versionKey(userId)));
485
+ }
486
+ async function loadUser(db, userId) {
487
+ const rows = await db.select({
488
+ avatarUrl: juniorIdentities.avatarUrl,
489
+ displayName: juniorIdentities.displayName,
490
+ handle: juniorIdentities.handle,
491
+ identityId: juniorIdentities.id,
492
+ provider: juniorIdentities.provider,
493
+ providerSubjectId: juniorIdentities.providerSubjectId,
494
+ providerTenantId: juniorIdentities.providerTenantId,
495
+ updatedAt: juniorIdentities.updatedAt,
496
+ userDisplayName: juniorUsers.displayName,
497
+ userId: juniorUsers.id,
498
+ userIsAdmin: juniorUsers.isAdmin,
499
+ userPrimaryEmail: juniorUsers.primaryEmail
500
+ }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.id, userId)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
501
+ const first = rows[0];
502
+ if (!first) return null;
503
+ return {
504
+ identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
505
+ avatarUrl: row.avatarUrl,
506
+ displayName: row.displayName,
507
+ handle: row.handle,
508
+ id: row.identityId,
509
+ provider: row.provider,
510
+ providerSubjectId: row.providerSubjectId,
511
+ providerTenantId: row.providerTenantId,
512
+ updatedAt: row.updatedAt
513
+ }] : []),
514
+ user: {
515
+ displayName: first.userDisplayName,
516
+ id: first.userId,
517
+ isAdmin: first.userIsAdmin,
518
+ primaryEmail: first.userPrimaryEmail
519
+ }
520
+ };
521
+ }
522
+ /** Read one User and their user Identities by User id. */
523
+ async function readCachedUser(db, userId) {
524
+ const version = await readVersion(userId);
525
+ const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
526
+ const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
527
+ const value = await loadUser(db, userId);
528
+ if (!settled) return { value };
529
+ return {
530
+ value,
531
+ ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
532
+ };
533
+ });
534
+ return cached ? cachedUserSchema.parse(cached) : void 0;
535
+ }
536
+ /**
537
+ * Read one User and their user Identities by normalized primary email. A
538
+ * primary email never changes, so the email to User id entry stays valid.
539
+ * A missing User is not cached: a first sign-in can create it at any time.
540
+ */
541
+ async function readCachedUserByEmail(db, normalizedEmail) {
542
+ const userId = await cache().getOrLoad(emailKey(normalizedEmail), async () => {
543
+ const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
544
+ return id ? {
545
+ value: id,
546
+ ttlMs: USER_TTL_MS
547
+ } : { value: null };
548
+ });
549
+ return userId ? await readCachedUser(db, userId) : void 0;
550
+ }
551
+ function emailKey(normalizedEmail) {
552
+ return `email:${normalizedEmail}`;
553
+ }
554
+ /** Clear the cached User after a write to their row or user Identities. */
555
+ async function clearCachedUser(userId) {
556
+ await getStateAdapter().set(versionKey(userId), {
557
+ token: randomUUID(),
558
+ writtenAtMs: Date.now()
559
+ }, 2 * USER_TTL_MS);
560
+ }
398
561
  // src/chat/identities/sql.ts
399
562
  function dateFromMs$1(ms) {
400
563
  return new Date(ms);
@@ -482,6 +645,7 @@ async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
482
645
  if (linkedUserId) throw new Error("Identity conflicts with linked user");
483
646
  throw new Error("Identity upsert returned no row");
484
647
  }
648
+ for (const changedUserId of /* @__PURE__ */ new Set([existing?.userId, row.userId])) if (changedUserId) await clearCachedUser(changedUserId);
485
649
  if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
486
650
  identityId: row.id,
487
651
  userId: row.userId
@@ -537,6 +701,7 @@ async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUs
537
701
  /** Remove one exact provider identity owned by a user. */
538
702
  async function deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId) {
539
703
  await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
704
+ await clearCachedUser(userId);
540
705
  }
541
706
  /**
542
707
  * Save one Google sign-in. Link the Google identity to the user of its
@@ -1970,12 +2135,6 @@ function treeHasAnnotationKey(rootConversationId, key) {
1970
2135
  where ${and(eq(annotated.rootConversationId, rootConversationId), annotationKeyMatches(key))}
1971
2136
  )`;
1972
2137
  }
1973
- /** Return the IDs in `conversationIds` that have an Annotation with `key`. */
1974
- async function conversationIdsWithAnnotation(db, conversationIds, key) {
1975
- if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
1976
- const rows = await db.selectDistinct({ conversationId: juniorConversationAnnotations.conversationId }).from(juniorConversationAnnotations).where(and(inArray(juniorConversationAnnotations.conversationId, [...conversationIds]), annotationKeyMatches(key)));
1977
- return new Set(rows.map((row) => row.conversationId));
1978
- }
1979
2138
  // src/chat/conversations/sql/message-search.ts
1980
2139
  const EXCERPT_WITHOUT_QUERY_CHARS = 240;
1981
2140
  var SqlConversationMessageSearchStore = class {
@@ -2100,4 +2259,4 @@ async function closeDb() {
2100
2259
  current = void 0;
2101
2260
  await previous?.db.close();
2102
2261
  }
2103
- export { conversationDetailTouch as $, setFirstConversationLocation as A, recordGoogleSignIn as B, deliversFinalText as C, turnBehavior as D, postsRunNotices as E, saveActorAvatar as F, parseSessionSource as G, upsertLinkedIdentity as H, deleteProviderIdentityForSlackUser as I, agentTurnTotalTokens as J, addAgentTurnUsage as K, deleteProviderIdentityForUser as L, SYSTEM_IDENTITY_ID as M, findActorIdentityId as N, conversationKindFromRow as O, resolveActorIdentityId as P, rootConversationIsArchived as Q, findUserByVerifiedEmails as R, withConversationMutationLock as S, isTopLevelKind as T, claimProviderConversation as U, saveUserTimezone as V, getConversationIdByProviderConversation as W, hasAgentTurnUsage as X, agentTurnUsageSchema as Y, resolveRootConversationId as Z, setArchivedAt as _, getConversationStore as a, sameDestination as at, userMessageQueries as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, nextDetailVersion as et, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, requireSlackDestination as it, startLocationThread as j, locationFromRow as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, createSlackDestination as nt, getDb as o, withConversationEventLock as p, agentTurnCostUsd as q, getConversationEventStore as r, parseDestination as rt, getSqlExecutor as s, closeDb as t, touchConversationDetail as tt, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, isPersonInput as w, createSqlStore as x, lastMessageAtSql as y, readUserTimezone as z };
2262
+ export { resolveRootConversationId as $, startLocationThread as A, saveUserTimezone as B, isPersonInput as C, conversationKindFromRow as D, turnBehavior as E, deleteProviderIdentityForSlackUser as F, claimProviderConversation as G, clearCachedUser as H, deleteProviderIdentityForUser as I, addAgentTurnUsage as J, getConversationIdByProviderConversation as K, findUserByVerifiedEmails as L, findActorIdentityId as M, resolveActorIdentityId as N, locationFromRow as O, saveActorAvatar as P, hasAgentTurnUsage as Q, readUserTimezone as R, deliversFinalText as S, postsRunNotices as T, readCachedUserByEmail as U, upsertLinkedIdentity as V, createCache as W, agentTurnTotalTokens as X, agentTurnCostUsd as Y, agentTurnUsageSchema as Z, loadConversationSlackTenantIds as _, getConversationStore as a, parseDestination as at, createSqlStore as b, hasAnnotationKey as c, eventFromRow as d, rootConversationIsArchived as et, withConversationEventLock as f, setArchivedAt as g, readConversationTrees as h, getConversationMessageSearchStore as i, createSlackDestination as it, SYSTEM_IDENTITY_ID as j, setFirstConversationLocation as k, treeHasAnnotationKey as l, conversationDescendants as m, db_exports as n, nextDetailVersion as nt, getDb as o, requireSlackDestination as ot, conversationAncestors as p, parseSessionSource as q, getConversationEventStore as r, touchConversationDetail as rt, getSqlExecutor as s, sameDestination as st, closeDb as t, conversationDetailTouch as tt, createSqlConversationEventStore as u, lastMessageAtSql as v, isTopLevelKind as w, withConversationMutationLock as x, userMessageQueries as y, recordGoogleSignIn as z };