@sentry/junior 0.302.0 → 0.304.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 (100) hide show
  1. package/dist/{adapter-context-Cx9fn9B3.js → adapter-context-B1IpoELr.js} +2 -2
  2. package/dist/{admin-_poE5NKL.js → admin-BnVFGo_z.js} +5 -5
  3. package/dist/{agent-runner-CY9RvsTX.js → agent-runner-CoEeZSRh.js} +1461 -1248
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -6
  6. package/dist/api.d.ts +13 -12
  7. package/dist/api.js +230 -105
  8. package/dist/{app-BpY3wtRP.d.ts → app-Cs157Zc5.d.ts} +17 -15
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +108 -96
  11. package/dist/{automation-Cva5ZOwW.js → automation-CuA3yEcD.js} +3 -1
  12. package/dist/{background-compaction-queue-CXFq1_Cz.js → background-compaction-queue-WLPNSF_b.js} +6 -6
  13. package/dist/{briefs-B3NG-pid.js → briefs-CagVVefw.js} +12 -9
  14. package/dist/{catalog-runtime-Dss0lSV6.js → catalog-runtime-B8ZXvXWm.js} +2 -2
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +21 -21
  17. package/dist/cli/check.js +10 -10
  18. package/dist/cli/env.d.ts +1 -0
  19. package/dist/cli/env.js +8 -7
  20. package/dist/cli/init.js +13 -4
  21. package/dist/cli/main.js +4 -4
  22. package/dist/cli/plugins.js +6 -6
  23. package/dist/cli/snapshot-create.js +7 -5
  24. package/dist/cli/upgrade.d.ts +2 -2
  25. package/dist/cli/upgrade.js +6 -6
  26. package/dist/{config-CzeZiMKs.js → config-DdO1BNcw.js} +142 -67
  27. package/dist/{connections-CDYhMfrs.js → connections-D20kp0j5.js} +6 -6
  28. package/dist/{continue-in-slack-7Uf05ndC.js → continue-in-slack-BKEVMBj1.js} +8 -8
  29. package/dist/{conversation-BNXfq6Lb.js → conversation-BOqdRtUx.js} +4 -12
  30. package/dist/{conversation-feed-Clf_cv0n.js → conversation-feed-CgpgP7yi.js} +35 -2
  31. package/dist/{conversation-privacy-D9xnM5mK.js → conversation-privacy-L1SK_v0V.js} +16 -8
  32. package/dist/{conversation-turn-D7SEZgTG.js → conversation-turn-BptVJylj.js} +20 -23
  33. package/dist/{credential-sync-DoD0gW-j.js → credential-sync-D1J1CGzL.js} +19 -19
  34. package/dist/{db-B-gtnNjr.js → db-EKJnkrIb.js} +180 -17
  35. package/dist/{db-BdsCzytP.d.ts → db-zbN5ZV_o.d.ts} +26 -26
  36. package/dist/{executor-DZg20EqU.js → executor-CoIZmFK8.js} +55 -15
  37. package/dist/{history-IjdmO_r6.js → history-m2-ceTTX.js} +21 -12
  38. package/dist/{install-t1KQyTUs.js → install-BT2Pf6HP.js} +3 -3
  39. package/dist/instrumentation.d.ts +4 -4
  40. package/dist/instrumentation.js +15 -11
  41. package/dist/{lineage-C79GjoQr.js → lineage-C5DGQCS_.js} +2 -2
  42. package/dist/{logging-C9oDAg4M.js → logging-QSZuMcvo.js} +19 -19
  43. package/dist/{message-BLUCzJXN.js → message-TtxftRHj.js} +9 -9
  44. package/dist/{model-input-5jwNC45G.js → model-input-BHXfA29g.js} +4 -9
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +8 -8
  47. package/dist/{oauth-callback-server-BBl66vCb.js → oauth-callback-server-B0enqHtZ.js} +5 -4
  48. package/dist/{oauth-relay-DRzq73b6.js → oauth-relay-DAmfVmJu.js} +3 -6
  49. package/dist/{package-discovery-DJhGdS4c.js → package-discovery-x4AvVhMj.js} +1 -1
  50. package/dist/{plugin-module-Cf5gVPWP.js → plugin-module-Cv2ETe8Y.js} +1 -1
  51. package/dist/{plugins-BBX07Jzt.js → plugins-Bkk0XRo2.js} +3 -3
  52. package/dist/{projection-CIBwgD3s.js → projection-CNKK7doO.js} +755 -221
  53. package/dist/{prompt-CRQbzp5e.js → prompt-DSjhoKu5.js} +185 -12
  54. package/dist/{queue-DtCDaIct.js → queue-CDxkit82.js} +4 -4
  55. package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
  56. package/dist/{registry-DdFQHZ_d.js → registry-DBDNUUmz.js} +37 -37
  57. package/dist/{resolve-CdW4BdrK.js → resolve-CQLhMWSu.js} +3 -3
  58. package/dist/{result-oOMv1t4O.js → result-B-pauj42.js} +10 -15
  59. package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
  60. package/dist/{runner-DqitLtm-.js → runner-B3KxKks5.js} +10 -10
  61. package/dist/{sandbox-egress-signals-Bw9I0yfJ.js → sandbox-egress-signals-DJJX9ClG.js} +1 -1
  62. package/dist/{schema-DnVQepWP.js → schema-Bx0Mlo32.js} +77 -13
  63. package/dist/{schema-BIFM-U1a.d.ts → schema-CKcu-IK6.d.ts} +562 -23
  64. package/dist/{secrets-DebYU866.js → secrets-DHaJ5TTn.js} +4 -4
  65. package/dist/{sentry-BRTJqumy.js → sentry-CPbZjomA.js} +3 -28
  66. package/dist/{sentry-route-name-BhwWnfqj.js → sentry-route-name-C6EIzAGP.js} +1 -1
  67. package/dist/{service-account-CrZftRTb.js → service-account-2HmlNPvy.js} +49 -48
  68. package/dist/{service-account-B6mKAPVo.js → service-account-DQLqkSVv.js} +5 -5
  69. package/dist/{session-stop-DW63Z3kj.js → session-stop-DEeZKqbX.js} +132 -74
  70. package/dist/{skills-C16fz60Z.js → skills-2UrD7JkN.js} +6 -9
  71. package/dist/{slack-conversation-unfurl-BHhefEb7.js → slack-conversation-unfurl-Dd129Uov.js} +14 -18
  72. package/dist/{spawn-D_RnFYfy.js → spawn-eMho9HDJ.js} +7 -7
  73. package/dist/{legacy-web-actor-id-C-cEeWqL.js → state-Bveuc4Zh.js} +32 -32
  74. package/dist/{stop-7p1i08CY.js → stop-D_ltJLDS.js} +359 -171
  75. package/dist/{store-C28I0CVW.js → store-COeYnPL_.js} +5 -5
  76. package/dist/{task-queue-BVUJbQ28.js → task-queue-CBIDXZpV.js} +3 -3
  77. package/dist/{task-runner-CWi8j7Z6.js → task-runner-CJF7zIJL.js} +15 -18
  78. package/dist/{thread-context-D3-yYUd0.js → thread-context-Cg0jt0aE.js} +12 -12
  79. package/dist/{turn-session-routing-BFMS9ATF.js → turn-session-routing-CaY3Tp8m.js} +32 -32
  80. package/dist/{turn-user-message-C3-O8Omt.js → turn-user-message-tcom1RYd.js} +3 -3
  81. package/dist/{validation-BSFKUIb4.js → validation-EU91JwIT.js} +2 -2
  82. package/dist/vercel.js +1 -1
  83. package/dist/{version-BHHXNi-0.js → version-BYRPhY5G.js} +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/{viewer-B1SO21Qa.js → viewer-Cf8ISkAc.js} +3 -3
  86. package/dist/{warmup-Bz9bzkzN.js → warmup-TgY4S1vx.js} +202 -577
  87. package/dist/{worker-BspReIIK.js → worker-C6Uq4OKD.js} +9 -12
  88. package/migrations/0109_user_preferences.sql +1 -0
  89. package/migrations/0110_code_change_repository_state_index.sql +1 -0
  90. package/migrations/0111_attachment_kinds.sql +14 -0
  91. package/migrations/0112_attachment_url_fill.sql +51 -0
  92. package/migrations/0113_attachment_url_index.sql +1 -0
  93. package/migrations/meta/0099_snapshot.json +102 -326
  94. package/migrations/meta/0109_snapshot.json +4925 -0
  95. package/migrations/meta/0110_snapshot.json +4952 -0
  96. package/migrations/meta/0111_snapshot.json +5011 -0
  97. package/migrations/meta/0112_snapshot.json +5011 -0
  98. package/migrations/meta/0113_snapshot.json +5033 -0
  99. package/migrations/meta/_journal.json +36 -1
  100. package/package.json +16 -19
@@ -1,39 +1,39 @@
1
- import { h as startSpan } from "./sentry-BRTJqumy.js";
2
- import { $ as loadTurnCheckpoint, $o as isSlackRequestTimeout, A as latestConversationMessageSeq, Ai as getDashboardLinkFilter, Ao as readLatestConversationBrief, Bo as getSlackFileId, Co as conversationIsMemberRoot, Cs as configValueSchema, D as estimateConversationMessagesTokens, Do as viewerMarksFromParticipant, E as buildConversationContext, Eo as conversationViewerMarks, F as turnHasReply, Fr as listReplyActionItems, Go as slackAttachmentsVersionQuery, Gr as canUserReadReviewItem, H as PluginCredentialFailureError, Ho as readAttachmentVisionSummary, Hr as canActOnReviewItem, Ht as releaseInboundMessage, I as upsertConversationMessage, Ii as isDashboardLink, Io as buildSentryConversationUrl, Ir as listWaitingConversations, K as AuthorizationFlowDisabledError, Ko as SlackActionError, Kr as isOnlyAssignee, Li as parseDashboardConversationLink, Ln as trimTrailingAssistantMessages, M as normalizeConversationText, Mi as getDashboardPersonLink, Mo as readConversationEventPageAfter, N as recordDeliveredAssistantMessage, No as readConversationEventPageAround, Nr as getReviewItem, O as getConversationMessageSlackTs, Oa as removeReactionFromMessage, P as trimConversationMessages, Qo as isDmChannel, Ri as parseDashboardPersonLink, S as resolveConversationTitle, So as conversationHasParticipantUser, To as conversationPinnedForUser, Ts as piMessageFromHistoryItem, V as createPluginEgress, Wo as recordSlackAttachment, X as clearPendingAuth, Xo as getSlackClient, Xr as reviewItemNeedsSomeone, Yo as getHeaderString, Zn as createUserTokenStore, _o as createPluginLogger, _s as lookupSlackUser, a as loadProjection, at as failTurnRecord, b as persistConversationMessages, ba as truncateStatusText, bn as persistWithRetry, bo as createConversationAccessReader, ct as listTurnSummaries, d as recordAuthorizationCompleted, di as cancelSubscriptions, es as normalizeSlackConversationId, et as lostWorkerBeforeFirstSave, fa as SLACK_USER_MENTION_RE, ga as normalizeSlackStatusText, h as recordSubscribedReplyRoute, i as loadConversationProjection, it as completeTurnRecord, j as markConversationMessage, jo as readConversationEventPage, k as isHumanConversationMessage, ki as getDashboardConversationLink, kr as closeReviewItem, lt as recordTurnSummary, ms as listConversationAnnotationsById, n as commitMessages, ns as streamPrivateSlackFile, nt as saveTurnCheckpoint, o as loadTurnProjection, ps as listConversationAnnotations, qo as downloadPrivateSlackFile, rs as withSlackRetries, rt as abandonTurnRecord, st as getTurnRecord, t as commitAcceptedReply, tn as buildTurnErrorResponse, tr as applyPluginFormatMarkdown, tt as pauseLostWorkerTurn, ua as resolveBaseUrl, un as getAssistantReplyText, ur as getPlugins, v as hydrateConversationMessages, va as slackMentionedUserIds, vs as lookupSlackUserNames, w as fallbackShortTitle, wo as conversationIsNotUnsubscribedRoot, xa as addReactionToMessage, xo as readConversationAccessFromSql, xs as createPluginCache, y as persistConversationMessageWindow, ya as wrapBareSlackUserIds, yo as canAddConversationMessages, zo as notInheritedByForkChild, zr as takeReviewItem } from "./projection-CIBwgD3s.js";
3
- import { D as resolveGatewayModel, M as textCharsForTokens, R as escapeXml, c as getSlackClientSecret, i as getChatConfig, j as estimateTextTokens, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, q as isProviderRetryError, s as getSlackClientId, y as normalizeSlackEmojiName } from "./config-CzeZiMKs.js";
4
- import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, K as isRecord, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, q as toOptionalNumber, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-C9oDAg4M.js";
5
- import { t as JUNIOR_VERSION } from "./version-BHHXNi-0.js";
1
+ import { $ as loadTurnCheckpoint, $n as applyPluginFormatMarkdown, A as latestConversationMessageSeq, Ai as getDashboardLinkFilter, Ao as readLatestConversationBrief, Bo as getSlackFileId, Co as conversationIsMemberRoot, D as estimateConversationMessagesTokens, Do as viewerMarksFromParticipant, Dr as closeReviewItem, E as buildConversationContext, Eo as conversationViewerMarks, Es as lookupSlackUserNames, F as turnHasReply, Fr as listWaitingConversations, Go as slackAttachmentsVersionQuery, Gr as isOnlyAssignee, H as PluginCredentialFailureError, Ho as readAttachmentVisionSummary, Ht as releaseInboundMessage, I as upsertConversationMessage, Ii as isDashboardLink, In as trimTrailingAssistantMessages, Io as buildSentryConversationUrl, K as AuthorizationFlowDisabledError, Li as parseDashboardConversationLink, M as normalizeConversationText, Mi as getDashboardPersonLink, Mo as readConversationEventPageAfter, Mr as getReviewItem, N as recordDeliveredAssistantMessage, No as readConversationEventPageAround, Ns as piMessageFromHistoryItem, O as getConversationMessageSlackTs, Oa as removeReactionFromMessage, P as trimConversationMessages, Pr as listReplyActionItems, Ri as parseDashboardPersonLink, Rr as takeReviewItem, S as resolveConversationTitle, So as conversationHasParticipantUser, Ss as listConversationAnnotationsById, To as conversationPinnedForUser, Ts as lookupSlackUser, V as createPluginEgress, Vr as canActOnReviewItem, Wo as recordSlackAttachment, Wr as canUserReadReviewItem, X as clearPendingAuth, Xr as reviewItemNeedsSomeone, Yn as createUserTokenStore, Zo as storeAttachment, _o as createPluginLogger, a as loadProjection, at as failTurnRecord, b as persistConversationMessages, ba as truncateStatusText, bn as persistWithRetry, bo as createConversationAccessReader, cr as getPlugins, cs as normalizeSlackConversationId, ct as listTurnSummaries, d as recordAuthorizationCompleted, di as cancelSubscriptions, ds as withSlackRetries, es as SlackActionError, et as lostWorkerBeforeFirstSave, fa as SLACK_USER_MENTION_RE, ga as normalizeSlackStatusText, h as recordSubscribedReplyRoute, i as loadConversationProjection, is as getSlackClient, it as completeTurnRecord, j as markConversationMessage, jo as readConversationEventPage, js as configValueSchema, k as isHumanConversationMessage, ki as getDashboardConversationLink, ks as createPluginCache, lt as recordTurnSummary, n as commitMessages, nt as saveTurnCheckpoint, o as loadTurnProjection, os as isDmChannel, qo as isFileAttachment, rs as getHeaderString, rt as abandonTurnRecord, ss as isSlackRequestTimeout, st as getTurnRecord, t as commitAcceptedReply, tn as buildTurnErrorResponse, ts as downloadPrivateSlackFile, tt as pauseLostWorkerTurn, ua as resolveBaseUrl, un as getAssistantReplyText, us as streamPrivateSlackFile, v as hydrateConversationMessages, va as slackMentionedUserIds, w as fallbackShortTitle, wo as conversationIsNotUnsubscribedRoot, xa as addReactionToMessage, xo as readConversationAccessFromSql, xs as listConversationAnnotations, y as persistConversationMessageWindow, ya as wrapBareSlackUserIds, yo as canAddConversationMessages, zo as notInheritedByForkChild } from "./projection-CNKK7doO.js";
2
+ import { F as textCharsForTokens, P as estimateTextTokens, V as escapeXml, X as isProviderRetryError, c as getSlackClientSecret, i as getChatConfig, k as resolveGatewayModel, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, y as normalizeSlackEmojiName } from "./config-DdO1BNcw.js";
3
+ import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, K as isRecord, S as setTags, T as withLogContext, b as setSpanAttributes, f as logError, h as logWarn, m as logInfo, n as createChatSdkLogger, o as getActiveTraceContext, p as logException, q as toOptionalNumber, s as getActiveTraceId, t as buildTurnFailureResponse, y as setSentryUser } from "./logging-QSZuMcvo.js";
4
+ import { h as startSpan } from "./sentry-CPbZjomA.js";
5
+ import { t as JUNIOR_VERSION } from "./version-BYRPhY5G.js";
6
6
  import { f as parseSlackTeamId, i as isActorUserId, n as createSlackActor, o as isUserActor, r as createSlackResumeActor, s as parseActorUserId, t as createActor, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
7
- import { F as saveActorAvatar, G as createCache, J as getStateAdapter, O as conversationKindFromRow, P as resolveActorIdentityId, Q as acquireActiveLock, S as deliversFinalText, T as postsRunNotices, W as readCachedUserByEmail, X as setStateValues, Y as getStateValues, _ as loadConversationSlackTenantIds, a as getConversationStore, ct as hasAgentTurnUsage, f as withConversationEventLock, ft as nextDetailVersion, g as setArchivedAt, gt as requireSlackDestination, h as readConversationTrees, it as addAgentTurnUsage, k as locationFromRow, lt as resolveRootConversationId, mt as createSlackDestination, o as getDb, p as conversationAncestors, r as getConversationEventStore, rt as parseSessionSource, s as getSqlExecutor, st as agentTurnUsageSchema, v as lastMessageAtSql, w as isTopLevelKind } from "./db-B-gtnNjr.js";
8
- import { D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, O as juniorCodeChanges, P as juniorUsers, T as juniorConversationEvents, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-DZg20EqU.js";
9
- import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-IjdmO_r6.js";
10
- import { d as actorLogContext, f as credentialContextForActor } from "./registry-DdFQHZ_d.js";
11
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
12
- import { M as shouldEmitDevAgentTrace, a as buildAuthPauseResponse, c as createClientMetadata, g as resolveDestinationVisibility, k as RetryableDeliveryError, l as readMcpClientInformation, n as executeAgentRun, s as getMcpOAuthCallbackPath, t as createAgentRunner, u as latestProgressStatus, y as createSlackReviewItemShow } from "./agent-runner-CY9RvsTX.js";
13
- import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-CRQbzp5e.js";
14
- import { f as identityAvatarUrl, g as userAvatarUrlsFromIdentities, h as readUserAvatarUrls } from "./viewer-B1SO21Qa.js";
15
- import { G as MAX_ATTACHMENT_BYTES, Y as readMessageAttachments, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-BNXfq6Lb.js";
16
- import { n as webActorUserIds } from "./legacy-web-actor-id-C-cEeWqL.js";
17
- import { t as readJuniorSecret } from "./secrets-DebYU866.js";
18
- import { G as conversationSubtree, I as maybePostAutomatedTurnLimitNotice, J as isExperimentalFeatureEnabled, K as conversationSubtreeColumns, O as legacyWebMailboxMetadataSchema, R as resolveSlackReplyTarget, T as resolveMailboxTurnWork, U as recordFinishedTurnForAutomatedLimit, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, l as savedInputInstruction, o as skipInputAfterConversationStop, p as instructionActorFor, r as markConversationsStopped, z as sendSlackReply } from "./session-stop-DW63Z3kj.js";
19
- import { $n as renderBlockText, Cr as listThreadReplies, Ct as recordWebConversationActivity, Et as AttachmentUploadError, Fn as wakePausedTurn, Gn as executeTurn, In as getTurnAuthorization, Kt as getChildAgentLabel, Ln as canJoinTurn, Mn as createPausedTurns, Ni as NO_REPLY_GAP_MS, Nn as getPausedTurnRequest, Pi as gapSegment, Pt as storeAttachment, Qn as renderAttachmentText, Rn as canShareTurn, St as createConversationId, Un as getWebAuthorization, Wn as AgentRunError, Xn as throwApiError, _ as connectedState, _n as stopChildAgentsBelow, a as segmentGapsKey, br as isConversationMember, c as listConversationWork, d as firstLiveSavingsDate, dr as resolveSlackChannelIdFromMessage, er as parseSlackMessageReference, f as idlePeriodSavings, fi as readConversationSourceTask, fr as resolveSlackChannelIdFromThreadId, gn as dropOwnUnreadLoopReplies, ht as deliverReviewItemChange, ji as MINUTE_MS, jn as supersedeTurnForInput, kt as verifyAttachmentUploads, lr as parseSlackThreadId, lt as conversationReadPositionQuery, n as GLOBAL_GAPS_MAX, p as replaceHistorySavings, r as GLOBAL_GAPS_TTL_MS, s as isConversationWorkDone, st as readLastUserMessageAtByConversation, t as CONVERSATION_STATE_TTL_MS, u as addHistoryPeriod, ur as readSlackRawMessageContext, v as providerCacheTtlMs, vn as stopChildAgentsOf, vr as getChannelMessage, vt as acceptsWebMessages, wt as webActorFromUser, xr as isPublicSlackChannel, xt as createAndEnqueueConversation, yn as cancelSignInWait, yr as getConversationInfo, yt as appendAndEnqueueWebMessage } from "./warmup-Bz9bzkzN.js";
20
- import { C as markDispatchCompleted, F as readAutomationTitlesByConversationId, S as markDispatchBlocked, T as markDispatchRunning, _ as getDispatchTurnId, a as getPersistedThreadState, c as coerceThreadConversationState, d as confirmDispatchMailboxAppend, g as getDispatchRecord, h as getDispatchInputMessageId, i as getPersistedSandboxState, m as getDispatchIdForConversation, n as resolveTurnSessionRouting, o as persistThreadRuntimeState, p as getDispatchConversationId, r as getLocationConfigurationService, s as persistThreadStateById, t as resolveConversationRouting, u as claimDispatchMailboxAppend, w as markDispatchFailed, x as markDispatchAwaitingResume, y as isTerminalDispatchStatus } from "./turn-session-routing-BFMS9ATF.js";
7
+ import { A as conversationKindFromRow, D as postsRunNotices, E as isTopLevelKind, I as resolveActorIdentityId, K as readCachedUserByEmail, L as saveActorAvatar, Q as setStateValues, X as getStateAdapter, Z as getStateValues, _ as readConversationTrees, a as getConversationStore, at as parseSessionSource, b as lastMessageAtSql, dt as resolveRootConversationId, et as acquireActiveLock, f as copyMessageLinks, gt as createSlackDestination, h as conversationAncestors, j as locationFromRow, k as turnBehavior, lt as agentTurnUsageSchema, m as withConversationEventLock, mt as nextDetailVersion, o as getDb, ot as addAgentTurnUsage, q as createCache, r as getConversationEventStore, s as getSqlExecutor, ut as hasAgentTurnUsage, v as setArchivedAt, vt as requireSlackDestination, w as deliversFinalText, y as loadConversationSlackTenantIds } from "./db-EKJnkrIb.js";
8
+ import { D as juniorConversationAnnotations, F as juniorUsers, I as juniorDestinations, M as juniorMessageAttachments, N as juniorConversations, O as juniorCodeChanges, P as juniorIdentities, T as juniorConversationEvents, g as juniorAgentInvocations, j as juniorAttachments, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-CoIZmFK8.js";
9
+ import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-m2-ceTTX.js";
10
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-DBDNUUmz.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B8ZXvXWm.js";
12
+ import { A as RetryableDeliveryError, N as shouldEmitDevAgentTrace, T as safeLinkUrl, _ as createSlackReviewItemShow, a as buildAuthPauseResponse, c as createClientMetadata, l as readMcpClientInformation, m as resolveDestinationVisibility, n as executeAgentRun, s as getMcpOAuthCallbackPath, t as createAgentRunner, u as latestProgressStatus } from "./agent-runner-CoEeZSRh.js";
13
+ import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-2HmlNPvy.js";
14
+ import { i as webActorUserIds } from "./state-Bveuc4Zh.js";
15
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-DSjhoKu5.js";
16
+ import { f as identityAvatarUrl, g as userAvatarUrlsFromIdentities, h as readUserAvatarUrls } from "./viewer-Cf8ISkAc.js";
17
+ import { J as readMessageAttachments, W as MAX_ATTACHMENT_BYTES, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-BOqdRtUx.js";
18
+ import { t as readJuniorSecret } from "./secrets-DHaJ5TTn.js";
19
+ import { G as conversationSubtree, I as maybePostAutomatedTurnLimitNotice, J as isExperimentalFeatureEnabled, K as conversationSubtreeColumns, O as legacyWebMailboxMetadataSchema, R as resolveSlackReplyTarget, T as resolveMailboxTurnWork, U as recordFinishedTurnForAutomatedLimit, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, l as savedInputInstruction, o as skipInputAfterConversationStop, p as instructionActorFor, r as markConversationsStopped, z as sendSlackReply } from "./session-stop-DEeZKqbX.js";
20
+ import { An as createPausedTurns, Dt as webActorFromUser, Et as recordWebConversationActivity, Fn as canJoinTurn, Hn as AgentRunError, In as canShareTurn, Jn as throwApiError, Mi as gapSegment, Mt as verifyAttachmentUploads, Nn as wakePausedTurn, Pn as getTurnAuthorization, Qn as parseSlackMessageReference, St as appendAndEnqueueWebMessage, Tt as createConversationId, Un as executeTurn, Vn as getWebAuthorization, Wt as getChildAgentLabel, Xn as renderAttachmentText, Zn as renderBlockText, _n as cancelSignInWait, _r as isConversationMember, br as listThreadReplies, c as isConversationWorkDone, cr as readSlackRawMessageContext, d as addHistoryPeriod, f as firstLiveSavingsDate, ft as conversationReadPositionQuery, gn as stopChildAgentsOf, gr as getConversationInfo, hn as stopChildAgentsBelow, hr as getChannelMessage, i as GLOBAL_GAPS_TTL_MS, ji as NO_REPLY_GAP_MS, jn as getPausedTurnRequest, ki as MINUTE_MS, kn as supersedeTurnForInput, kt as AttachmentUploadError, l as listConversationWork, li as readConversationSourceTask, lr as resolveSlackChannelIdFromMessage, m as replaceHistorySavings, mn as dropOwnUnreadLoopReplies, n as CONVERSATION_STATE_TTL_MS, o as segmentGapsKey, p as idlePeriodSavings, r as GLOBAL_GAPS_MAX, sr as parseSlackThreadId, t as ANSWER_TOOL_ENDINGS, ut as readLastUserMessageAtByConversation, v as connectedState, vr as isPublicSlackChannel, vt as deliverReviewItemChange, wt as createAndEnqueueConversation, xt as acceptsWebMessages, y as providerCacheTtlMs } from "./warmup-TgY4S1vx.js";
21
+ import { C as markDispatchCompleted, F as readAutomationTitlesByConversationId, S as markDispatchBlocked, T as markDispatchRunning, _ as getDispatchTurnId, a as getPersistedThreadState, c as coerceThreadConversationState, d as confirmDispatchMailboxAppend, g as getDispatchRecord, h as getDispatchInputMessageId, i as getPersistedSandboxState, m as getDispatchIdForConversation, n as resolveTurnSessionRouting, o as persistThreadRuntimeState, p as getDispatchConversationId, r as getLocationConfigurationService, s as persistThreadStateById, t as resolveConversationRouting, u as claimDispatchMailboxAppend, w as markDispatchFailed, x as markDispatchAwaitingResume, y as isTerminalDispatchStatus } from "./turn-session-routing-CaY3Tp8m.js";
21
22
  import { h as isVisionImageMediaType, l as isEmptyUserInputAnswer, m as detectImageMediaType, t as webMessageId, u as normalizeUserInputAnswer } from "./web-message-id-lNodcCOI.js";
22
- import { L as buildDeterministicAssistantMessageId, R as buildDeterministicTurnId, a as ConversationTurnBoundaryError, c as TurnInputDeferredError, d as isTurnInputCommitLostError, f as isTurnInputDeferredError, g as startActiveTurn, h as markTurnFailed, i as getTurnUserSlackMessageTs, l as getConversationTurnBoundaryError, m as markTurnCompleted, o as CooperativeTurnYieldError, p as markTurnClosed, r as getTurnUserReplyAttachmentContext, s as TurnInputCommitLostError, t as getTurnUserMessage, u as isCooperativeTurnYieldError, v as getTurnLifecycle } from "./turn-user-message-C3-O8Omt.js";
23
- import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-CXFq1_Cz.js";
24
- import { D as stopConversationWork, E as steerWebPendingMessages, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-C28I0CVW.js";
25
- import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-CrZftRTb.js";
26
- import { t as runWithSlackInstallation } from "./adapter-context-Cx9fn9B3.js";
27
- import { D as webPageObjectCard, E as personObjectCard, T as messageObjectCard, l as conversationPendingMessagesReportSchema, n as conversationFeedSchema, p as healthReportSchema, t as conversationFeedBriefSchema, w as conversationObjectCard } from "./conversation-feed-Clf_cv0n.js";
28
- import { c as withTurnSpan, n as createConversationTurnWorker, o as getTurnInputSpanAttributes, r as canPauseConversationDelivery, s as turnInputTelemetry } from "./conversation-turn-D7SEZgTG.js";
29
- import { n as buildStoredAttachmentPromptText } from "./model-input-5jwNC45G.js";
30
- import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-oOMv1t4O.js";
31
- import { t as bindMessageAgent } from "./message-BLUCzJXN.js";
32
- import { t as readConversationLineage } from "./lineage-C79GjoQr.js";
33
- import { t as bindSpawnAgent } from "./spawn-D_RnFYfy.js";
34
- import { a as requireTurnFailureEventId, c as buildDeliveredTurnStatePatch, i as getAgentTurnDiagnosticsAttributes, l as loadPendingMessageCards, n as loadThreadContextTrimFloor, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, s as persistAuthPauseTurnState, t as buildTurnThreadContext } from "./thread-context-D3-yYUd0.js";
35
- import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-CWi8j7Z6.js";
36
- import { r as canContinueInSlack } from "./continue-in-slack-7Uf05ndC.js";
23
+ import { L as buildDeterministicAssistantMessageId, R as buildDeterministicTurnId, a as ConversationTurnBoundaryError, c as TurnInputDeferredError, d as isTurnInputCommitLostError, f as isTurnInputDeferredError, g as startActiveTurn, h as markTurnFailed, i as getTurnUserSlackMessageTs, l as getConversationTurnBoundaryError, m as markTurnCompleted, o as CooperativeTurnYieldError, p as markTurnClosed, r as getTurnUserReplyAttachmentContext, s as TurnInputCommitLostError, t as getTurnUserMessage, u as isCooperativeTurnYieldError, v as getTurnLifecycle } from "./turn-user-message-tcom1RYd.js";
24
+ import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-WLPNSF_b.js";
25
+ import { D as stopConversationWork, E as steerWebPendingMessages, _ as getConversationWorkState, a as cancelHumanFacingPendingMessages, g as getConversation, h as ensureConversationWake, r as appendAndEnqueueInboundMessage, s as claimInboundMessage } from "./store-COeYnPL_.js";
26
+ import { t as runWithSlackInstallation } from "./adapter-context-B1IpoELr.js";
27
+ import { D as personObjectCard, E as messageObjectCard, O as webPageObjectCard, T as conversationObjectCard, m as healthReportSchema, r as conversationFeedSchema, t as conversationFeedBriefSchema, u as conversationPendingMessagesReportSchema } from "./conversation-feed-CgpgP7yi.js";
28
+ import { c as withTurnSpan, n as createConversationTurnWorker, o as getTurnInputSpanAttributes, r as canPauseConversationDelivery, s as turnInputTelemetry } from "./conversation-turn-BptVJylj.js";
29
+ import { n as buildStoredAttachmentPromptText } from "./model-input-BHXfA29g.js";
30
+ import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-B-pauj42.js";
31
+ import { t as bindMessageAgent } from "./message-TtxftRHj.js";
32
+ import { t as readConversationLineage } from "./lineage-C5DGQCS_.js";
33
+ import { t as bindSpawnAgent } from "./spawn-eMho9HDJ.js";
34
+ import { a as requireTurnFailureEventId, c as buildDeliveredTurnStatePatch, i as getAgentTurnDiagnosticsAttributes, l as loadPendingMessageCards, n as loadThreadContextTrimFloor, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, s as persistAuthPauseTurnState, t as buildTurnThreadContext } from "./thread-context-Cg0jt0aE.js";
35
+ import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-CJF7zIJL.js";
36
+ import { r as canContinueInSlack } from "./continue-in-slack-BKEVMBj1.js";
37
37
  import * as z from "zod";
38
38
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
39
39
  import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lte, ne, not, or, sql } from "drizzle-orm";
@@ -334,7 +334,7 @@ function slackChannelTypeFromConversationInfo(info) {
334
334
  function resolveSlackChannelTypeFromMessage(message) {
335
335
  const raw = message.raw;
336
336
  if (!raw || typeof raw !== "object") return;
337
- const channelType = raw.channel_type;
337
+ const channelType = raw["channel_type"];
338
338
  return typeof channelType === "string" ? toSlackEventChannelType(channelType.trim()) : void 0;
339
339
  }
340
340
  /** Build Slack conversation facts available to runtime consumers. */
@@ -619,6 +619,10 @@ async function resolveConversationLink(viewer, url) {
619
619
  });
620
620
  }
621
621
  // src/api/objects/link-types.ts
622
+ /** A link type name for errors, such as `github/task/code_change`. */
623
+ function linkTypeName(linkType) {
624
+ return `${linkType.owner}/${linkType.objectTypes.join("/")}`;
625
+ }
622
626
  function compareSpecificity(left, right) {
623
627
  for (let index = 0; index < left.length; index += 1) {
624
628
  const difference = (left[index] ?? 0) - (right[index] ?? 0);
@@ -645,7 +649,7 @@ function assertNoObjectLinkConflicts(linkTypes) {
645
649
  filter,
646
650
  linkType
647
651
  })));
648
- for (const [index, left] of filters.entries()) for (const right of filters.slice(index + 1)) if (left.linkType !== right.linkType && compareSpecificity(objectLinkFilterSpecificity(left.filter), objectLinkFilterSpecificity(right.filter)) === 0 && filtersOverlap(left.filter, right.filter)) throw new Error(`Link types "${left.linkType.owner}/${left.linkType.objectType}" and "${right.linkType.owner}/${right.linkType.objectType}" claim the same URLs with equal filters.`);
652
+ for (const [index, left] of filters.entries()) for (const right of filters.slice(index + 1)) if (left.linkType !== right.linkType && compareSpecificity(objectLinkFilterSpecificity(left.filter), objectLinkFilterSpecificity(right.filter)) === 0 && filtersOverlap(left.filter, right.filter)) throw new Error(`Link types "${linkTypeName(left.linkType)}" and "${linkTypeName(right.linkType)}" claim the same URLs with equal filters.`);
649
653
  }
650
654
  /** Return the link type whose most specific filter claims the URL. */
651
655
  function findObjectLinkType(linkTypes, url) {
@@ -1051,6 +1055,7 @@ async function decideSubscribedThreadReply(args) {
1051
1055
  questions: buildSubscribedReplyRouterQuestions(args.botUserName),
1052
1056
  metadata: {
1053
1057
  modelId: args.modelId,
1058
+ conversationId: args.input.context.conversationId,
1054
1059
  threadId: args.input.context.threadId ?? "",
1055
1060
  channelId: args.input.context.channelId ?? "",
1056
1061
  actorId: args.input.context.actorId ?? "",
@@ -1167,11 +1172,11 @@ function replaceTopLevelText(content, text) {
1167
1172
  }
1168
1173
  function readRawBlocks(raw) {
1169
1174
  if (!raw || typeof raw !== "object") return void 0;
1170
- return raw.blocks;
1175
+ return raw["blocks"];
1171
1176
  }
1172
1177
  function readRawText(raw) {
1173
1178
  if (!raw || typeof raw !== "object") return "";
1174
- const text = raw.text;
1179
+ const text = raw["text"];
1175
1180
  return typeof text === "string" ? text : "";
1176
1181
  }
1177
1182
  const slackFormat = new SlackFormatConverter();
@@ -1204,7 +1209,7 @@ function renderSlackPlainText(mrkdwn, userNames) {
1204
1209
  function renderTopLevelText(message) {
1205
1210
  const blocks = readRawBlocks(message.raw);
1206
1211
  const blockText = renderBlockText(blocks);
1207
- if (Array.isArray(blocks) && blocks.some((block) => block?.type === "section") && blockText) return blockText;
1212
+ if (Array.isArray(blocks) && blocks.some((block) => isRecord(block) && block["type"] === "section") && blockText) return blockText;
1208
1213
  const rawText = readRawText(message.raw);
1209
1214
  if (rawText.trim()) return renderSlackMrkdwn(rawText);
1210
1215
  if (message.formatted.children.length > 0) return stringifyMarkdown(message.formatted).trim();
@@ -1252,10 +1257,17 @@ function getRunId(thread, message) {
1252
1257
  return readOptionalStringField(thread, "runId") ?? readOptionalStringField(message, "runId");
1253
1258
  }
1254
1259
  function getChannelId(thread, message) {
1255
- return resolveSlackChannelIdFromThreadId(toOptionalString(thread.id)) ?? normalizeSlackConversationId(toOptionalString(thread.channelId)) ?? resolveSlackChannelIdFromMessage(message);
1260
+ return normalizeSlackConversationId(toOptionalString(thread.channelId)) ?? resolveSlackChannelIdFromMessage(message);
1256
1261
  }
1257
- function getThreadTs(threadId) {
1258
- return parseSlackThreadId(threadId)?.threadTs;
1262
+ /**
1263
+ * Read the Slack thread timestamp from the raw Slack event of a message:
1264
+ * `thread_ts`, or `ts` for a thread root. Do not parse `Thread.id` or
1265
+ * `Message.threadId`: a top-level dispatched post has a channel-level id with
1266
+ * no timestamp, and the raw event is the Slack source of truth.
1267
+ */
1268
+ function getThreadTs(message) {
1269
+ const rawContext = readSlackRawMessageContext(message);
1270
+ return rawContext?.threadTs ?? rawContext?.messageTs;
1259
1271
  }
1260
1272
  /**
1261
1273
  * Resolve Slack assistant-thread API context for the current turn.
@@ -1276,9 +1288,6 @@ function getAssistantThreadContext(message) {
1276
1288
  threadTs
1277
1289
  };
1278
1290
  }
1279
- const parsedThreadId = parseSlackThreadId(readOptionalStringField(message, "threadId"));
1280
- if (!parsedThreadId || isDmChannel(parsedThreadId.channelId)) return;
1281
- return parsedThreadId;
1282
1291
  }
1283
1292
  /** Resolve the native Slack timestamp for a message that can target Slack APIs. */
1284
1293
  function getMessageTs(message) {
@@ -1315,7 +1324,7 @@ function logProcessingReactionFailure(error, eventName, attributes) {
1315
1324
  }
1316
1325
  /** Return true when a Slack reaction tool invocation keeps the processing reaction. */
1317
1326
  function shouldKeepProcessingReactionForToolInvocation(input) {
1318
- return input.toolName === "addReaction" && isProcessingReactionEmoji(input.params.emoji);
1327
+ return input.toolName === "addReaction" && isProcessingReactionEmoji(input.params["emoji"]);
1319
1328
  }
1320
1329
  /** Start Junior's automatic Slack processing reaction for one inbound message. */
1321
1330
  async function startProcessingReaction(args) {
@@ -1520,7 +1529,7 @@ function createAcceptedSteeringDrain(hooks, options) {
1520
1529
  }
1521
1530
  function buildLogContext(deps, args) {
1522
1531
  return {
1523
- conversationId: args.threadId ?? args.runId,
1532
+ conversationId: args.conversationId,
1524
1533
  messageConversationId: args.threadId,
1525
1534
  userId: args.actorId,
1526
1535
  userName: args.actorUserName,
@@ -1540,7 +1549,7 @@ function createSlackTurnRuntime(deps) {
1540
1549
  /** Unsubscribe the thread and cancel resource watches for a stop decision. */
1541
1550
  const maybeHandleThreadOptOutDecision = async (args) => {
1542
1551
  if (!args.decision?.shouldUnsubscribe) return false;
1543
- await deps.cancelWatches({ conversationId: args.thread.id });
1552
+ await deps.cancelWatches({ conversationId: args.conversationId });
1544
1553
  await args.thread.unsubscribe();
1545
1554
  await args.beforeFirstResponsePost?.();
1546
1555
  await args.thread.post(THREAD_OPTOUT_ACK);
@@ -1595,7 +1604,7 @@ function createSlackTurnRuntime(deps) {
1595
1604
  try {
1596
1605
  const channelId = getChannelId(args.thread, args.message);
1597
1606
  if (!channelId) throw new Error("Slack fallback error reply requires a channel id");
1598
- const threadTs = getThreadTs(getThreadId(args.thread, args.message));
1607
+ const threadTs = getThreadTs(args.message);
1599
1608
  await sendSlackReply({
1600
1609
  channelId,
1601
1610
  conversationId: args.conversationId,
@@ -1611,9 +1620,10 @@ function createSlackTurnRuntime(deps) {
1611
1620
  throw postError;
1612
1621
  }
1613
1622
  };
1614
- const decideSteeringMessage = async (thread, candidate, conversationContext) => {
1623
+ const decideSteeringMessage = async (thread, candidate, conversationContext, conversationId) => {
1615
1624
  const { message } = candidate;
1616
1625
  const context = {
1626
+ conversationId,
1617
1627
  threadId: getThreadId(thread, message),
1618
1628
  actorId: message.author.userId,
1619
1629
  channelId: getChannelId(thread, message),
@@ -1643,6 +1653,7 @@ function createSlackTurnRuntime(deps) {
1643
1653
  };
1644
1654
  const logSkippedSubscribedDecision = (args) => {
1645
1655
  withLogContext(logContext({
1656
+ conversationId: args.context.conversationId,
1646
1657
  threadId: args.context.threadId,
1647
1658
  actorId: args.context.actorId,
1648
1659
  actorUserName: actorUserName(args.message),
@@ -1675,7 +1686,7 @@ function createSlackTurnRuntime(deps) {
1675
1686
  const selectAcceptedSteeringMessages = async (args) => {
1676
1687
  const selected = [];
1677
1688
  for (const candidate of args.messages) {
1678
- const decision = await decideSteeringMessage(args.thread, candidate, args.conversationContext);
1689
+ const decision = await decideSteeringMessage(args.thread, candidate, args.conversationContext, args.conversationId);
1679
1690
  selected.push({
1680
1691
  context: decision.context,
1681
1692
  decision: decision.decision,
@@ -1706,6 +1717,7 @@ function createSlackTurnRuntime(deps) {
1706
1717
  const handleSkippedSteeringMessages = async (args) => {
1707
1718
  for (const skipped of args.skipped) {
1708
1719
  await maybeHandleThreadOptOutDecision({
1720
+ conversationId: args.conversationId,
1709
1721
  thread: args.thread,
1710
1722
  decision: skipped.decision,
1711
1723
  beforeFirstResponsePost: args.beforeFirstResponsePost
@@ -1740,7 +1752,7 @@ function createSlackTurnRuntime(deps) {
1740
1752
  };
1741
1753
  return {
1742
1754
  async handleNewMention(thread, message, hooks) {
1743
- const conversationId = hooks.conversationId ?? thread.id;
1755
+ const { conversationId } = hooks;
1744
1756
  const processingReactions = createProcessingReactionTracker(thread);
1745
1757
  let processingReaction;
1746
1758
  const skippedSteeringMessages = [];
@@ -1752,6 +1764,7 @@ function createSlackTurnRuntime(deps) {
1752
1764
  conversationId,
1753
1765
  pending: skippedSteeringMessages,
1754
1766
  context: logContext({
1767
+ conversationId,
1755
1768
  threadId: getThreadId(thread, message),
1756
1769
  actorId: message.author.userId,
1757
1770
  actorUserName: actorUserName(message),
@@ -1765,6 +1778,7 @@ function createSlackTurnRuntime(deps) {
1765
1778
  const channelId = getChannelId(thread, message);
1766
1779
  const runId = getRunId(thread, message);
1767
1780
  const context = logContext({
1781
+ conversationId,
1768
1782
  threadId,
1769
1783
  channelId,
1770
1784
  actorId: message.author.userId,
@@ -1807,6 +1821,7 @@ function createSlackTurnRuntime(deps) {
1807
1821
  }),
1808
1822
  selectMessages: (messages, drainContext) => selectAcceptedSteeringMessages({
1809
1823
  conversationContext: drainContext?.conversationContext,
1824
+ conversationId,
1810
1825
  messages,
1811
1826
  thread
1812
1827
  })
@@ -1829,6 +1844,7 @@ function createSlackTurnRuntime(deps) {
1829
1844
  });
1830
1845
  } catch (error) {
1831
1846
  const failureLogContext = logContext({
1847
+ conversationId,
1832
1848
  threadId: getThreadId(thread, message),
1833
1849
  actorId: message.author.userId,
1834
1850
  actorUserName: actorUserName(message),
@@ -1848,7 +1864,7 @@ function createSlackTurnRuntime(deps) {
1848
1864
  }
1849
1865
  const eventId = classifiedFailure?.eventId ?? withLogContext(failureLogContext, () => logException(failureCause, "mention.handler.failed"));
1850
1866
  if (!acked && hooks.isFinalAttempt === false) return;
1851
- if (!eventId) throw new Error("Sentry did not return an event ID for mention.handler.failed");
1867
+ if (!eventId) throw new Error("Sentry did not return an event ID for mention.handler.failed", { cause: error });
1852
1868
  let lifecycleError;
1853
1869
  try {
1854
1870
  await failConversationTurn({
@@ -1877,6 +1893,7 @@ function createSlackTurnRuntime(deps) {
1877
1893
  conversationId,
1878
1894
  pending: skippedSteeringMessages,
1879
1895
  context: logContext({
1896
+ conversationId,
1880
1897
  threadId: getThreadId(thread, message),
1881
1898
  actorId: message.author.userId,
1882
1899
  actorUserName: actorUserName(message),
@@ -1889,7 +1906,7 @@ function createSlackTurnRuntime(deps) {
1889
1906
  }
1890
1907
  },
1891
1908
  async handleSubscribedMessage(thread, message, hooks) {
1892
- const conversationId = hooks.conversationId ?? thread.id;
1909
+ const { conversationId } = hooks;
1893
1910
  const processingReactions = createProcessingReactionTracker(thread);
1894
1911
  let processingReaction;
1895
1912
  const skippedSteeringMessages = [];
@@ -1901,6 +1918,7 @@ function createSlackTurnRuntime(deps) {
1901
1918
  conversationId,
1902
1919
  pending: skippedSteeringMessages,
1903
1920
  context: logContext({
1921
+ conversationId,
1904
1922
  threadId: getThreadId(thread, message),
1905
1923
  actorId: message.author.userId,
1906
1924
  actorUserName: actorUserName(message),
@@ -1915,6 +1933,7 @@ function createSlackTurnRuntime(deps) {
1915
1933
  const runId = getRunId(thread, message);
1916
1934
  const actorId = message.author.userId;
1917
1935
  const turnContext = logContext({
1936
+ conversationId,
1918
1937
  threadId,
1919
1938
  actorId,
1920
1939
  actorUserName: actorUserName(message),
@@ -1962,6 +1981,7 @@ function createSlackTurnRuntime(deps) {
1962
1981
  reason: stopDecision.reasonDetail ? `${stopDecision.reason}:${stopDecision.reasonDetail}` : stopDecision.reason
1963
1982
  };
1964
1983
  await maybeHandleThreadOptOutDecision({
1984
+ conversationId,
1965
1985
  thread,
1966
1986
  decision,
1967
1987
  beforeFirstResponsePost: hooks.beforeFirstResponsePost
@@ -2006,6 +2026,7 @@ function createSlackTurnRuntime(deps) {
2006
2026
  context: threadContext
2007
2027
  });
2008
2028
  await maybeHandleThreadOptOutDecision({
2029
+ conversationId,
2009
2030
  thread,
2010
2031
  decision,
2011
2032
  beforeFirstResponsePost: hooks.beforeFirstResponsePost
@@ -2042,6 +2063,7 @@ function createSlackTurnRuntime(deps) {
2042
2063
  context: threadContext
2043
2064
  });
2044
2065
  if (await maybeHandleThreadOptOutDecision({
2066
+ conversationId,
2045
2067
  thread,
2046
2068
  decision,
2047
2069
  beforeFirstResponsePost: hooks.beforeFirstResponsePost
@@ -2085,6 +2107,7 @@ function createSlackTurnRuntime(deps) {
2085
2107
  }),
2086
2108
  selectMessages: (messages, drainContext) => selectAcceptedSteeringMessages({
2087
2109
  conversationContext: drainContext?.conversationContext ?? conversationContext,
2110
+ conversationId,
2088
2111
  messages,
2089
2112
  thread
2090
2113
  })
@@ -2121,6 +2144,7 @@ function createSlackTurnRuntime(deps) {
2121
2144
  });
2122
2145
  } catch (error) {
2123
2146
  const failureLogContext = logContext({
2147
+ conversationId,
2124
2148
  threadId: getThreadId(thread, message),
2125
2149
  actorId: message.author.userId,
2126
2150
  actorUserName: actorUserName(message),
@@ -2140,7 +2164,7 @@ function createSlackTurnRuntime(deps) {
2140
2164
  }
2141
2165
  const eventId = classifiedFailure?.eventId ?? withLogContext(failureLogContext, () => logException(failureCause, "subscribed_message.handler.failed"));
2142
2166
  if (!acked && hooks.isFinalAttempt === false) return;
2143
- if (!eventId) throw new Error("Sentry did not return an event ID for subscribed_message.handler.failed");
2167
+ if (!eventId) throw new Error("Sentry did not return an event ID for subscribed_message.handler.failed", { cause: error });
2144
2168
  let lifecycleError;
2145
2169
  try {
2146
2170
  await failConversationTurn({
@@ -2169,6 +2193,7 @@ function createSlackTurnRuntime(deps) {
2169
2193
  conversationId,
2170
2194
  pending: skippedSteeringMessages,
2171
2195
  context: logContext({
2196
+ conversationId,
2172
2197
  threadId: getThreadId(thread, message),
2173
2198
  actorId: message.author.userId,
2174
2199
  actorUserName: actorUserName(message),
@@ -2540,6 +2565,7 @@ async function resolveUserAttachmentsWithDeps(attachments, context, deps) {
2540
2565
  "Return plain text only."
2541
2566
  ].join(" "),
2542
2567
  metadata: {
2568
+ conversationId: context.conversationId ?? "",
2543
2569
  threadId: context.threadId ?? "",
2544
2570
  channelId: context.channelId ?? "",
2545
2571
  actorId: context.actorId ?? "",
@@ -2604,6 +2630,7 @@ async function summarizeConversationImage(args, deps) {
2604
2630
  "Return plain text only."
2605
2631
  ].join(" "),
2606
2632
  metadata: {
2633
+ conversationId: args.context.conversationId ?? "",
2607
2634
  threadId: args.context.threadId ?? "",
2608
2635
  channelId: args.context.channelId ?? "",
2609
2636
  actorId: args.context.actorId ?? "",
@@ -2777,7 +2804,7 @@ function createJuniorRuntimeServices(overrides = {}) {
2777
2804
  function getMessageTimestamp(message) {
2778
2805
  const idTs = parseSlackMessageTs(message.id);
2779
2806
  if (idTs) return idTs;
2780
- if (message.raw && typeof message.raw === "object") return parseSlackMessageTs(message.raw.ts);
2807
+ if (message.raw && typeof message.raw === "object") return parseSlackMessageTs(message.raw["ts"]);
2781
2808
  }
2782
2809
  // src/chat/slack/action-token.ts
2783
2810
  const slackActionTokenSchema = z.string().trim().min(1).brand();
@@ -3408,7 +3435,7 @@ function createSlackTurn(deps) {
3408
3435
  });
3409
3436
  const destinationVisibility = conversationVisibilityFromSlackChannelType(slackChannelType);
3410
3437
  const assistantThreadContext = getAssistantThreadContext(message);
3411
- const threadTs = getThreadTs(threadId) ?? assistantThreadContext?.threadTs;
3438
+ const threadTs = getThreadTs(message);
3412
3439
  const messageTs = getMessageTs(message);
3413
3440
  const teamId = destination.teamId;
3414
3441
  const source = options.execution?.source ?? createSlackSource({
@@ -3427,8 +3454,7 @@ function createSlackTurn(deps) {
3427
3454
  });
3428
3455
  const slackActionToken = readSlackActionToken(message);
3429
3456
  const runId = options.execution?.dispatch?.id ?? getRunId(thread, message);
3430
- const conversationId = options.conversationId ?? threadId ?? runId;
3431
- if (!conversationId) throw new Error("Slack reply execution requires a conversation id");
3457
+ const { conversationId } = options;
3432
3458
  await withSpan("chat.reply", "chat.reply", {
3433
3459
  conversationId,
3434
3460
  messageConversationId: threadId,
@@ -3961,7 +3987,7 @@ function createSlackTurn(deps) {
3961
3987
  status.update({ text: event.text });
3962
3988
  return;
3963
3989
  }
3964
- if (event.type === "tool_started") await options.onToolInvocation?.({
3990
+ if (event.type === "tool_started") options.onToolInvocation?.({
3965
3991
  params: event.params,
3966
3992
  toolName: event.toolName
3967
3993
  });
@@ -4296,13 +4322,13 @@ function visionCacheKey(conversationId) {
4296
4322
  return `vision-cache:v${VISION_CACHE_SCHEMA_VERSION}:${conversationId}`;
4297
4323
  }
4298
4324
  function coerceVisionCache(value) {
4299
- if (!isRecord(value) || value.schemaVersion !== VISION_CACHE_SCHEMA_VERSION) return { byFileId: {} };
4300
- const rawByFileId = isRecord(value.byFileId) ? value.byFileId : {};
4325
+ if (!isRecord(value) || value["schemaVersion"] !== VISION_CACHE_SCHEMA_VERSION) return { byFileId: {} };
4326
+ const rawByFileId = isRecord(value["byFileId"]) ? value["byFileId"] : {};
4301
4327
  const byFileId = {};
4302
4328
  for (const [fileId, rawSummary] of Object.entries(rawByFileId)) {
4303
4329
  if (!fileId.trim() || !isRecord(rawSummary)) continue;
4304
- const summary = toOptionalString(rawSummary.summary);
4305
- const analyzedAtMs = toOptionalNumber(rawSummary.analyzedAtMs);
4330
+ const summary = toOptionalString(rawSummary["summary"]);
4331
+ const analyzedAtMs = toOptionalNumber(rawSummary["analyzedAtMs"]);
4306
4332
  if (!summary || analyzedAtMs === void 0) continue;
4307
4333
  byFileId[fileId] = {
4308
4334
  summary,
@@ -4310,7 +4336,7 @@ function coerceVisionCache(value) {
4310
4336
  };
4311
4337
  }
4312
4338
  return {
4313
- backfillCompletedAtMs: toOptionalNumber(value.backfillCompletedAtMs),
4339
+ backfillCompletedAtMs: toOptionalNumber(value["backfillCompletedAtMs"]),
4314
4340
  byFileId
4315
4341
  };
4316
4342
  }
@@ -4391,11 +4417,11 @@ async function seedConversationBackfill(thread, conversation, currentTurn, resol
4391
4417
  /** Build the turn-state preparer from injected conversation services. */
4392
4418
  function createPrepareTurnState(deps) {
4393
4419
  return async function prepareTurnState(args) {
4394
- const conversationId = args.context.conversationId ?? args.context.threadId ?? args.context.runId;
4395
- const existingState = conversationId ? await getPersistedThreadState(conversationId) : await args.thread.state;
4396
- const sandboxRef = getPersistedSandboxState(existingState ?? {});
4420
+ const { conversationId } = args.context;
4421
+ const existingState = await getPersistedThreadState(conversationId);
4422
+ const sandboxRef = getPersistedSandboxState(existingState);
4397
4423
  const conversation = coerceThreadConversationState(existingState);
4398
- if (conversationId && isVisionEnabled()) conversation.vision = await loadConversationVisionCache(conversationId);
4424
+ if (isVisionEnabled()) conversation.vision = await loadConversationVisionCache(conversationId);
4399
4425
  await hydrateConversationMessages({
4400
4426
  conversation,
4401
4427
  conversationId
@@ -4430,19 +4456,19 @@ function createPrepareTurnState(deps) {
4430
4456
  channelId: args.context.channelId,
4431
4457
  actorId: args.context.actorId,
4432
4458
  runId: args.context.runId,
4433
- threadTs: getThreadTs(args.context.threadId)
4459
+ threadTs: getThreadTs(args.message)
4434
4460
  });
4435
- if (conversationId) await persistConversationVisionCache(conversationId, conversation.vision);
4461
+ await persistConversationVisionCache(conversationId, conversation.vision);
4436
4462
  }
4437
4463
  await persistConversationMessages({
4438
4464
  conversation,
4439
4465
  conversationId
4440
4466
  });
4441
- if (conversationId) await hydrateConversationMessages({
4467
+ await hydrateConversationMessages({
4442
4468
  conversation,
4443
4469
  conversationId
4444
4470
  });
4445
- if (await trimConversationMessages(conversation, async () => conversationId ? await loadThreadContextTrimFloor(conversationId) : void 0) && conversationId && conversation.historyFromSeq !== void 0) await persistConversationMessageWindow({
4471
+ if (await trimConversationMessages(conversation, () => loadThreadContextTrimFloor(conversationId)) && conversation.historyFromSeq !== void 0) await persistConversationMessageWindow({
4446
4472
  conversationId,
4447
4473
  historyFromSeq: conversation.historyFromSeq
4448
4474
  });
@@ -4621,7 +4647,10 @@ async function projectDispatchTurnResult(dispatchId, result) {
4621
4647
  case "failed":
4622
4648
  await markDispatchFailed(dispatchId, result.errorMessage ?? "Agent turn failed", result.resultMessageTs);
4623
4649
  break;
4624
- case "completed": await markDispatchCompleted(dispatchId, result.resultMessageTs);
4650
+ case "completed":
4651
+ await markDispatchCompleted(dispatchId, result.resultMessageTs);
4652
+ break;
4653
+ case void 0:
4625
4654
  }
4626
4655
  }
4627
4656
  function getDispatchBlockingError(error) {
@@ -4755,9 +4784,13 @@ function createSlackDispatchTurnRunner(options) {
4755
4784
  await state.connect();
4756
4785
  const conversationId = getDispatchConversationId(dispatch);
4757
4786
  const adapter = options.getSlackAdapter();
4787
+ const slackThreadId = adapter.encodeThreadId({
4788
+ channel: dispatch.destination.channelId,
4789
+ threadTs: dispatch.destination.threadTs ?? ""
4790
+ });
4758
4791
  const message = new Message({
4759
4792
  id: getDispatchInputMessageId(dispatch.id),
4760
- threadId: conversationId,
4793
+ threadId: slackThreadId,
4761
4794
  text: dispatch.input,
4762
4795
  attachments: [],
4763
4796
  formatted: {
@@ -4785,7 +4818,7 @@ function createSlackDispatchTurnRunner(options) {
4785
4818
  const thread = new ThreadImpl({
4786
4819
  adapter,
4787
4820
  stateAdapter: state,
4788
- id: conversationId,
4821
+ id: slackThreadId,
4789
4822
  channelId: dispatch.destination.channelId,
4790
4823
  channelVisibility: dispatch.destinationVisibility === "public" ? "workspace" : "private",
4791
4824
  currentMessage: message,
@@ -4868,8 +4901,8 @@ function createSlackRuntime(options) {
4868
4901
  getPreparedConversationContext: (preparedState) => preparedState.conversationContext,
4869
4902
  decideSubscribedReply: async (args) => {
4870
4903
  const decision = await services.subscribedReplyPolicy(args);
4871
- if (decision.costUsd !== void 0 && args.context.threadId && args.context.runId) await recordSubscribedReplyRoute({
4872
- conversationId: args.context.threadId,
4904
+ if (decision.costUsd !== void 0 && args.context.runId) await recordSubscribedReplyRoute({
4905
+ conversationId: args.context.conversationId,
4873
4906
  costUsd: decision.costUsd,
4874
4907
  reason: decision.reason,
4875
4908
  runId: args.context.runId,
@@ -4968,8 +5001,8 @@ function normalizeIncomingSlackThreadId(threadId, message) {
4968
5001
  if (!message || typeof message !== "object") return threadId;
4969
5002
  const raw = message.raw;
4970
5003
  if (!raw || typeof raw !== "object") return threadId;
4971
- const channelId = nonEmptyString(raw.channel);
4972
- const threadTs = nonEmptyString(raw.thread_ts) ?? nonEmptyString(raw.ts);
5004
+ const channelId = nonEmptyString(raw["channel"]);
5005
+ const threadTs = nonEmptyString(raw["thread_ts"]) ?? nonEmptyString(raw["ts"]);
4973
5006
  if (!channelId || !threadTs) return threadId;
4974
5007
  return `slack:${channelId}:${threadTs}`;
4975
5008
  }
@@ -5013,7 +5046,7 @@ function hasValidMdastBase(node, fields) {
5013
5046
  "type",
5014
5047
  ...fields
5015
5048
  ]);
5016
- return Object.keys(node).every((key) => allowed.has(key)) && (node.data === void 0 || typeof node.data === "object" && node.data !== null && !Array.isArray(node.data)) && (node.position === void 0 || mdastPositionSchema.safeParse(node.position).success);
5049
+ return Object.keys(node).every((key) => allowed.has(key)) && (node["data"] === void 0 || typeof node["data"] === "object" && node["data"] !== null && !Array.isArray(node["data"])) && (node["position"] === void 0 || mdastPositionSchema.safeParse(node["position"]).success);
5017
5050
  }
5018
5051
  const mdastPhrasingTypes = /* @__PURE__ */ new Set([
5019
5052
  "break",
@@ -5045,24 +5078,24 @@ const mdastListItemTypes = /* @__PURE__ */ new Set(["listItem"]);
5045
5078
  const mdastTableCellTypes = /* @__PURE__ */ new Set(["tableCell"]);
5046
5079
  const mdastTableRowTypes = /* @__PURE__ */ new Set(["tableRow"]);
5047
5080
  function hasMdastChildren(node, allowedTypes) {
5048
- return Array.isArray(node.children) && node.children.every((child) => isFormattedContentNode(child) && (!allowedTypes || typeof child === "object" && child !== null && !Array.isArray(child) && allowedTypes.has(String(child.type))));
5081
+ return Array.isArray(node["children"]) && node["children"].every((child) => isFormattedContentNode(child) && (!allowedTypes || typeof child === "object" && child !== null && !Array.isArray(child) && allowedTypes.has(String(child.type))));
5049
5082
  }
5050
5083
  /** Validate every supported mdast node before restoring a serialized message. */
5051
5084
  function isFormattedContentNode(value) {
5052
5085
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
5053
5086
  const node = value;
5054
- switch (node.type) {
5087
+ switch (node["type"]) {
5055
5088
  case "break":
5056
5089
  case "thematicBreak": return hasValidMdastBase(node, []);
5057
5090
  case "html":
5058
5091
  case "inlineCode":
5059
5092
  case "text":
5060
- case "yaml": return hasValidMdastBase(node, ["value"]) && typeof node.value === "string";
5093
+ case "yaml": return hasValidMdastBase(node, ["value"]) && typeof node["value"] === "string";
5061
5094
  case "code": return hasValidMdastBase(node, [
5062
5095
  "lang",
5063
5096
  "meta",
5064
5097
  "value"
5065
- ]) && typeof node.value === "string" && isOptionalNullableString(node.lang) && isOptionalNullableString(node.meta);
5098
+ ]) && typeof node["value"] === "string" && isOptionalNullableString(node["lang"]) && isOptionalNullableString(node["meta"]);
5066
5099
  case "delete":
5067
5100
  case "emphasis":
5068
5101
  case "paragraph":
@@ -5070,60 +5103,60 @@ function isFormattedContentNode(value) {
5070
5103
  case "tableCell": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastPhrasingTypes);
5071
5104
  case "blockquote": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes);
5072
5105
  case "tableRow": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastTableCellTypes);
5073
- case "heading": return hasValidMdastBase(node, ["children", "depth"]) && hasMdastChildren(node, mdastPhrasingTypes) && Number.isInteger(node.depth) && Number(node.depth) >= 1 && Number(node.depth) <= 6;
5106
+ case "heading": return hasValidMdastBase(node, ["children", "depth"]) && hasMdastChildren(node, mdastPhrasingTypes) && Number.isInteger(node["depth"]) && Number(node["depth"]) >= 1 && Number(node["depth"]) <= 6;
5074
5107
  case "list": return hasValidMdastBase(node, [
5075
5108
  "children",
5076
5109
  "ordered",
5077
5110
  "spread",
5078
5111
  "start"
5079
- ]) && hasMdastChildren(node, mdastListItemTypes) && isOptionalNullableBoolean(node.ordered) && isOptionalNullableBoolean(node.spread) && (node.start === void 0 || node.start === null || typeof node.start === "number" && Number.isFinite(node.start));
5112
+ ]) && hasMdastChildren(node, mdastListItemTypes) && isOptionalNullableBoolean(node["ordered"]) && isOptionalNullableBoolean(node["spread"]) && (node["start"] === void 0 || node["start"] === null || typeof node["start"] === "number" && Number.isFinite(node["start"]));
5080
5113
  case "listItem": return hasValidMdastBase(node, [
5081
5114
  "checked",
5082
5115
  "children",
5083
5116
  "spread"
5084
- ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && isOptionalNullableBoolean(node.checked) && isOptionalNullableBoolean(node.spread);
5085
- case "table": return hasValidMdastBase(node, ["align", "children"]) && hasMdastChildren(node, mdastTableRowTypes) && (node.align === void 0 || node.align === null || Array.isArray(node.align) && node.align.every((align) => align === null || align === "center" || align === "left" || align === "right"));
5117
+ ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && isOptionalNullableBoolean(node["checked"]) && isOptionalNullableBoolean(node["spread"]);
5118
+ case "table": return hasValidMdastBase(node, ["align", "children"]) && hasMdastChildren(node, mdastTableRowTypes) && (node["align"] === void 0 || node["align"] === null || Array.isArray(node["align"]) && node["align"].every((align) => align === null || align === "center" || align === "left" || align === "right"));
5086
5119
  case "definition": return hasValidMdastBase(node, [
5087
5120
  "identifier",
5088
5121
  "label",
5089
5122
  "title",
5090
5123
  "url"
5091
- ]) && typeof node.identifier === "string" && typeof node.url === "string" && isOptionalNullableString(node.label) && isOptionalNullableString(node.title);
5124
+ ]) && typeof node["identifier"] === "string" && typeof node["url"] === "string" && isOptionalNullableString(node["label"]) && isOptionalNullableString(node["title"]);
5092
5125
  case "footnoteDefinition": return hasValidMdastBase(node, [
5093
5126
  "children",
5094
5127
  "identifier",
5095
5128
  "label"
5096
- ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && typeof node.identifier === "string" && isOptionalNullableString(node.label);
5097
- case "footnoteReference": return hasValidMdastBase(node, ["identifier", "label"]) && typeof node.identifier === "string" && isOptionalNullableString(node.label);
5129
+ ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]);
5130
+ case "footnoteReference": return hasValidMdastBase(node, ["identifier", "label"]) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]);
5098
5131
  case "image": return hasValidMdastBase(node, [
5099
5132
  "alt",
5100
5133
  "title",
5101
5134
  "url"
5102
- ]) && typeof node.url === "string" && isOptionalNullableString(node.alt) && isOptionalNullableString(node.title);
5135
+ ]) && typeof node["url"] === "string" && isOptionalNullableString(node["alt"]) && isOptionalNullableString(node["title"]);
5103
5136
  case "imageReference": return hasValidMdastBase(node, [
5104
5137
  "alt",
5105
5138
  "identifier",
5106
5139
  "label",
5107
5140
  "referenceType"
5108
- ]) && typeof node.identifier === "string" && isOptionalNullableString(node.alt) && isOptionalNullableString(node.label) && (node.referenceType === "collapsed" || node.referenceType === "full" || node.referenceType === "shortcut");
5141
+ ]) && typeof node["identifier"] === "string" && isOptionalNullableString(node["alt"]) && isOptionalNullableString(node["label"]) && (node["referenceType"] === "collapsed" || node["referenceType"] === "full" || node["referenceType"] === "shortcut");
5109
5142
  case "link": return hasValidMdastBase(node, [
5110
5143
  "children",
5111
5144
  "title",
5112
5145
  "url"
5113
- ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node.url === "string" && isOptionalNullableString(node.title);
5146
+ ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node["url"] === "string" && isOptionalNullableString(node["title"]);
5114
5147
  case "linkReference": return hasValidMdastBase(node, [
5115
5148
  "children",
5116
5149
  "identifier",
5117
5150
  "label",
5118
5151
  "referenceType"
5119
- ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node.identifier === "string" && isOptionalNullableString(node.label) && (node.referenceType === "collapsed" || node.referenceType === "full" || node.referenceType === "shortcut");
5152
+ ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]) && (node["referenceType"] === "collapsed" || node["referenceType"] === "full" || node["referenceType"] === "shortcut");
5120
5153
  default: return false;
5121
5154
  }
5122
5155
  }
5123
5156
  const formattedContentSchema = z.custom((value) => {
5124
5157
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
5125
5158
  const root = value;
5126
- return root.type === "root" && hasValidMdastBase(root, ["children"]) && hasMdastChildren(root);
5159
+ return root["type"] === "root" && hasValidMdastBase(root, ["children"]) && hasMdastChildren(root);
5127
5160
  }, "must be a valid formatted-content root");
5128
5161
  const serializedMessageSchema = z.object({
5129
5162
  _type: z.literal("chat:Message"),
@@ -6569,7 +6602,7 @@ async function runNextPausedTurnInContext(conversationId, options, runOptions) {
6569
6602
  */
6570
6603
  function createSlackSystemTurnDelivery(args) {
6571
6604
  return async ({ conversationId, location, text, cards }) => {
6572
- if (location.provider !== "slack") throw new Error(`Slack system Turn cannot deliver to ${location.provider} Location`);
6605
+ if (location.provider !== "slack") throw new Error(`Slack system Turn cannot deliver to ${String(location.provider)} Location`);
6573
6606
  let messageIds;
6574
6607
  try {
6575
6608
  messageIds = await runWithSlackInstallation({
@@ -7255,9 +7288,9 @@ function children(node) {
7255
7288
  function attribute(element, name) {
7256
7289
  return element.attrs.find((attr) => attr.name === name)?.value;
7257
7290
  }
7258
- function text$1(node) {
7291
+ function text(node) {
7259
7292
  if (node.nodeName === "#text" && "value" in node) return node.value;
7260
- return children(node).map(text$1).join("");
7293
+ return children(node).map(text).join("");
7261
7294
  }
7262
7295
  function clean(value) {
7263
7296
  return value?.replace(/\s+/g, " ").trim() || void 0;
@@ -7269,7 +7302,7 @@ function parsePageMeta(html) {
7269
7302
  const tags = /* @__PURE__ */ new Map();
7270
7303
  let title;
7271
7304
  for (const node of head ? children(head) : []) {
7272
- if (isElement(node, "title")) title ??= clean(text$1(node));
7305
+ if (isElement(node, "title")) title ??= clean(text(node));
7273
7306
  if (!isElement(node, "meta")) continue;
7274
7307
  const name = (attribute(node, "property") ?? attribute(node, "name"))?.toLowerCase();
7275
7308
  const content = clean(attribute(node, "content"));
@@ -7514,7 +7547,7 @@ function webPageLinkType() {
7514
7547
  cacheCards: false,
7515
7548
  canView: async () => true,
7516
7549
  filters: [{ scheme: "https" }],
7517
- objectType: "web_page",
7550
+ objectTypes: ["web_page"],
7518
7551
  owner: "junior",
7519
7552
  resolve: (_viewer, url) => resolveWebPageLink(url)
7520
7553
  };
@@ -7530,7 +7563,7 @@ function coreLinkTypes() {
7530
7563
  const slack = {
7531
7564
  canView: async () => true,
7532
7565
  filters: [SLACK_MESSAGE_LINK_FILTER],
7533
- objectType: "message",
7566
+ objectTypes: ["message"],
7534
7567
  owner: "junior",
7535
7568
  resolve: resolveSlackMessageLink
7536
7569
  };
@@ -7544,7 +7577,7 @@ function coreLinkTypes() {
7544
7577
  {
7545
7578
  canView: canViewConversationLink,
7546
7579
  filters: [conversations],
7547
- objectType: "conversation",
7580
+ objectTypes: ["conversation"],
7548
7581
  owner: "junior",
7549
7582
  resolve: resolveConversationLink
7550
7583
  },
@@ -7552,7 +7585,7 @@ function coreLinkTypes() {
7552
7585
  cacheCards: false,
7553
7586
  canView: async () => true,
7554
7587
  filters: [people, { scheme: "mailto" }],
7555
- objectType: "person",
7588
+ objectTypes: ["person"],
7556
7589
  owner: "junior",
7557
7590
  resolve: (_viewer, url) => resolvePersonLink(url)
7558
7591
  }
@@ -7587,7 +7620,7 @@ function pluginLinkTypes(plugin) {
7587
7620
  return (plugin.objectLinks ?? []).map((link) => ({
7588
7621
  canView: (viewer, url) => link.canView(objectLinkContext(name, viewer), url),
7589
7622
  filters: link.filters,
7590
- objectType: link.objectType,
7623
+ objectTypes: link.objectTypes,
7591
7624
  owner: name,
7592
7625
  readTool: link.readTool,
7593
7626
  resolve: (viewer, url) => link.resolve(objectLinkContext(name, viewer), url),
@@ -7603,12 +7636,24 @@ function readObjectLinkTypes(plugins = getPlugins()) {
7603
7636
  assertNoObjectLinkConflicts(linkTypes);
7604
7637
  return linkTypes;
7605
7638
  }
7639
+ /**
7640
+ * Return the object type of the link type that claims a URL, such as
7641
+ * `code_change` for a pull request link from the GitHub plugin. The plugin
7642
+ * that owns the link type decides; core only reads its filters. A link type
7643
+ * that can open more than one type, such as a GitHub issue URL that can open
7644
+ * a pull request, names no type from the URL alone.
7645
+ */
7646
+ function readLinkObjectType(url, linkTypes = readObjectLinkTypes()) {
7647
+ if (!URL.canParse(url)) return void 0;
7648
+ const objectTypes = findObjectLinkType(linkTypes, new URL(url))?.objectTypes;
7649
+ return objectTypes?.length === 1 ? objectTypes[0] : void 0;
7650
+ }
7606
7651
  async function resolveWithLinkType(linkType, viewer, url) {
7607
7652
  if (!await linkType.canView(viewer, url)) return linkType.webPageFallback ? await resolveWithLinkType(webPageLinkType(), viewer, url) : null;
7608
7653
  const resolved = await linkType.resolve(viewer, url);
7609
7654
  if (!resolved) return null;
7610
7655
  const object = objectAnnotationSchema.parse(resolved);
7611
- if (object.objectType !== linkType.objectType) throw new Error(`Link type "${linkType.owner}/${linkType.objectType}" returned a ${object.objectType} object.`);
7656
+ if (!linkType.objectTypes.includes(object.objectType)) throw new Error(`Link type "${linkTypeName(linkType)}" returned a ${object.objectType} object.`);
7612
7657
  return {
7613
7658
  linkType,
7614
7659
  object: ownedObjectAnnotationSchema.parse({
@@ -7742,8 +7787,9 @@ async function countHistoryConversations(windowStartMs) {
7742
7787
  async function loadEvents(conversationIds) {
7743
7788
  const events = juniorConversationEvents;
7744
7789
  const isUserMessage = sql`${events.type} = 'user_message'`;
7790
+ const isToolResult = sql`${events.type} = 'tool_result'`;
7745
7791
  const message = sql`CASE
7746
- WHEN ${events.type} <> 'assistant_message' THEN NULL
7792
+ WHEN ${events.type} NOT IN ('assistant_message', 'tool_result') THEN NULL
7747
7793
  WHEN ${events.schemaVersion} >= 2 THEN (${events.payload}->>'message')::jsonb
7748
7794
  ELSE ${events.payload}
7749
7795
  END`;
@@ -7752,29 +7798,39 @@ async function loadEvents(conversationIds) {
7752
7798
  type: sql`${events.type}`,
7753
7799
  personInstruction: sql`CASE WHEN ${isUserMessage} THEN (${events.payload}->'provenance'->'actor'->>'userId') IS NOT NULL END`,
7754
7800
  stopReason: sql`(${message})->>'stopReason'`,
7801
+ toolName: sql`(${message})->>'toolName'`,
7755
7802
  startedAtMs: sql`(${message})->>'timestamp'`,
7756
7803
  modelId: sql`(${message})->>'model'`,
7757
7804
  cacheRead: sql`${events.payload}->'usage'->>'cacheRead'`,
7758
7805
  cacheWrite: sql`${events.payload}->'usage'->>'cacheWrite'`
7759
- }).from(events).innerJoin(juniorConversations, eq(juniorConversations.conversationId, events.conversationId)).where(and(inArray(events.conversationId, conversationIds), or(eq(events.type, "assistant_message"), and(isUserMessage, sql`(${events.payload}->'provenance'->>'authority') = 'instruction'`)), gte(events.createdAt, juniorConversations.createdAt))).orderBy(events.conversationId, events.seq);
7806
+ }).from(events).innerJoin(juniorConversations, eq(juniorConversations.conversationId, events.conversationId)).where(and(inArray(events.conversationId, conversationIds), or(eq(events.type, "assistant_message"), and(isToolResult, inArray(sql`(${message})->>'toolName'`, Object.keys(ANSWER_TOOL_ENDINGS)), sql`(${message})->>'isError' IS DISTINCT FROM 'true'`), and(isUserMessage, sql`(${events.payload}->'provenance'->>'authority') = 'instruction'`)), gte(events.createdAt, juniorConversations.createdAt))).orderBy(events.conversationId, events.seq);
7807
+ }
7808
+ async function loadChildAgents(conversationIds) {
7809
+ return await getDb().select({
7810
+ conversationId: juniorAgentInvocations.parentConversationId,
7811
+ createdAt: juniorAgentInvocations.createdAt,
7812
+ terminalAt: juniorAgentInvocations.terminalAt
7813
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, conversationIds));
7760
7814
  }
7761
7815
  /**
7762
7816
  * Replay the model calls of one Conversation the way the recorders in
7763
7817
  * `warmup.ts` and `tool-wait.ts` see them, and return each idle period and
7764
- * tool wait. An idle period starts at a `stop` call and a tool wait at a
7765
- * `toolUse` call, so no pair of calls is in both.
7818
+ * tool wait. An idle period starts at a call that ends the Turn: a `stop`
7819
+ * call or an answer tool call that succeeded. A tool wait starts at any
7820
+ * other `toolUse` call, so no pair of calls is in both.
7766
7821
  *
7767
7822
  * Live recording measures from the start of the request that ended a Turn to
7768
7823
  * the start of the next recorded request. Here both times are the
7769
7824
  * `timestamp` of the stored assistant message, which Pi sets when it starts
7770
7825
  * the request. That is the closest stored time to the recorder's clock.
7771
7826
  */
7772
- function replayConversation(kind, events, nowMs) {
7827
+ function replayConversation(kind, events, children, nowMs) {
7773
7828
  const periods = [];
7774
7829
  const toolWaits = [];
7775
- const close = (idle, untilMs, next) => {
7830
+ const close = ({ waitsOnPendingWork, childRunning, ...idle }, untilMs, next) => {
7776
7831
  const gapMs = untilMs - idle.sinceMs;
7777
7832
  if (gapMs <= 0) return;
7833
+ if (waitsOnPendingWork && !childRunning && !next) return;
7778
7834
  const period = {
7779
7835
  ...idle,
7780
7836
  gapMs
@@ -7788,7 +7844,15 @@ function replayConversation(kind, events, nowMs) {
7788
7844
  let lastCallMs;
7789
7845
  let idle;
7790
7846
  let waiting;
7847
+ const answerEndings = /* @__PURE__ */ new Map();
7848
+ let toolUse;
7849
+ for (const event of events) {
7850
+ if (event.type === "assistant_message") toolUse = event.stopReason === "toolUse" ? event : void 0;
7851
+ const ending = event.type === "tool_result" && event.toolName ? ANSWER_TOOL_ENDINGS[event.toolName] : void 0;
7852
+ if (toolUse && ending) answerEndings.set(toolUse, ending);
7853
+ }
7791
7854
  for (const event of events) {
7855
+ if (event.type === "tool_result") continue;
7792
7856
  if (event.type === "user_message") {
7793
7857
  if (!inTurn) {
7794
7858
  userActor = event.personInstruction === true && kind !== "task";
@@ -7796,7 +7860,9 @@ function replayConversation(kind, events, nowMs) {
7796
7860
  }
7797
7861
  continue;
7798
7862
  }
7799
- if (event.stopReason !== "toolUse") inTurn = false;
7863
+ const answerEnding = answerEndings.get(event);
7864
+ const turnEnding = event.stopReason === "stop" ? "reply" : answerEnding;
7865
+ if (event.stopReason !== "toolUse" || answerEnding) inTurn = false;
7800
7866
  const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
7801
7867
  if (!Number.isFinite(startedAtMs)) continue;
7802
7868
  const next = {
@@ -7809,7 +7875,7 @@ function replayConversation(kind, events, nowMs) {
7809
7875
  gapMs: startedAtMs - waiting.sinceMs,
7810
7876
  next
7811
7877
  });
7812
- waiting = event.stopReason === "toolUse" ? {
7878
+ waiting = event.stopReason === "toolUse" && !answerEnding ? {
7813
7879
  sinceMs: startedAtMs,
7814
7880
  prefixTokens: next.cacheRead + next.cacheWrite
7815
7881
  } : void 0;
@@ -7819,11 +7885,18 @@ function replayConversation(kind, events, nowMs) {
7819
7885
  idle = void 0;
7820
7886
  if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
7821
7887
  lastCallMs = startedAtMs;
7822
- if (event.stopReason === "stop") {
7888
+ if (turnEnding) {
7889
+ const waitsOnPendingWork = turnBehavior({
7890
+ kind,
7891
+ personInput: userActor
7892
+ }).promptMode === "automation";
7823
7893
  idle = {
7824
7894
  sinceMs: startedAtMs,
7825
7895
  segment: historySegment(userActor, endedTurns),
7826
- prefixTokens: cacheRead + cacheWrite
7896
+ turnEnding,
7897
+ prefixTokens: cacheRead + cacheWrite,
7898
+ waitsOnPendingWork,
7899
+ childRunning: waitsOnPendingWork && children.some((child) => child.createdAt.getTime() <= startedAtMs && (child.terminalAt === null || child.terminalAt.getTime() > startedAtMs))
7827
7900
  };
7828
7901
  endedTurns += 1;
7829
7902
  }
@@ -7834,6 +7907,15 @@ function replayConversation(kind, events, nowMs) {
7834
7907
  toolWaits
7835
7908
  };
7836
7909
  }
7910
+ function byConversation(rows) {
7911
+ const grouped = /* @__PURE__ */ new Map();
7912
+ for (const row of rows) {
7913
+ const list = grouped.get(row.conversationId) ?? [];
7914
+ list.push(row);
7915
+ grouped.set(row.conversationId, list);
7916
+ }
7917
+ return grouped;
7918
+ }
7837
7919
  function isQueryCanceled(error) {
7838
7920
  let current = error;
7839
7921
  for (let depth = 0; current && depth < 6; depth += 1) {
@@ -7860,21 +7942,19 @@ async function replayConversations(conversations, args) {
7860
7942
  const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
7861
7943
  lastConversationId = batch.at(-1).conversationId;
7862
7944
  let rows;
7945
+ let children;
7863
7946
  try {
7864
- rows = await loadEvents(batch.map((row) => row.conversationId));
7947
+ const ids = batch.map((row) => row.conversationId);
7948
+ [rows, children] = await Promise.all([loadEvents(ids), loadChildAgents(ids)]);
7865
7949
  } catch (error) {
7866
7950
  if (!isQueryCanceled(error)) throw error;
7867
7951
  canceledBatches += 1;
7868
7952
  continue;
7869
7953
  }
7870
- const events = /* @__PURE__ */ new Map();
7871
- for (const event of rows) {
7872
- const list = events.get(event.conversationId) ?? [];
7873
- list.push(event);
7874
- events.set(event.conversationId, list);
7875
- }
7954
+ const events = byConversation(rows);
7955
+ const childrenByParent = byConversation(children);
7876
7956
  for (const conversation of batch) {
7877
- const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], nowMs);
7957
+ const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], childrenByParent.get(conversation.conversationId) ?? [], nowMs);
7878
7958
  const inScanWindow = (period) => period.sinceMs >= windowStartMs;
7879
7959
  periods.push(...replayed.periods.filter(inScanWindow));
7880
7960
  toolWaits.push(...replayed.toolWaits.filter(inScanWindow));
@@ -8247,15 +8327,49 @@ function treeAwaitsAuthorization(rootConversationId) {
8247
8327
  and ${awaitsAuthorization(tree.conversationId)}
8248
8328
  )`;
8249
8329
  }
8330
+ // src/api/user-settings.ts
8331
+ const userPreferencesSchema = z.object({
8332
+ /** Show the new dashboard UI instead of the current one. */
8333
+ experimentalUi: z.boolean().optional() });
8334
+ /** Settings of a user who has not changed any. */
8335
+ const DEFAULT_USER_SETTINGS = {
8336
+ autoArchiveDefault: false,
8337
+ autoArchiveGraceHours: 24,
8338
+ experimentalUi: false
8339
+ };
8340
+ const userSettingsColumns = {
8341
+ autoArchiveDefault: juniorUsers.autoArchiveDefault,
8342
+ autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours,
8343
+ preferences: juniorUsers.preferences
8344
+ };
8345
+ function toUserSettings(row) {
8346
+ const { preferences, ...columns } = row;
8347
+ const parsed = userPreferencesSchema.parse(preferences);
8348
+ return {
8349
+ ...columns,
8350
+ experimentalUi: parsed.experimentalUi ?? DEFAULT_USER_SETTINGS.experimentalUi
8351
+ };
8352
+ }
8353
+ /** Read the user's dashboard settings. */
8354
+ async function readUserSettings(userId) {
8355
+ const [user] = await getDb().select(userSettingsColumns).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
8356
+ return user && toUserSettings(user);
8357
+ }
8358
+ /** Save changed dashboard settings and return the saved settings. */
8359
+ async function updateUserSettings(userId, settings) {
8360
+ const { experimentalUi, ...columns } = settings;
8361
+ const preferences = experimentalUi === void 0 ? {} : { experimentalUi };
8362
+ const [user] = await getDb().update(juniorUsers).set({
8363
+ ...columns,
8364
+ preferences: sql`${juniorUsers.preferences} || ${JSON.stringify(preferences)}::jsonb`,
8365
+ updatedAt: /* @__PURE__ */ new Date()
8366
+ }).where(eq(juniorUsers.id, userId)).returning(userSettingsColumns);
8367
+ return user && toUserSettings(user);
8368
+ }
8250
8369
  // src/api/conversations/auto-archive.ts
8251
8370
  const HOUR_MS = 36e5;
8252
8371
  /** Participant rows checked per page. A run reads pages until none remain. */
8253
8372
  const AUTO_ARCHIVE_PAGE_SIZE = 500;
8254
- /** Settings of a user who has not changed auto-archive. */
8255
- const DEFAULT_AUTO_ARCHIVE_SETTINGS = {
8256
- autoArchiveDefault: false,
8257
- autoArchiveGraceHours: 24
8258
- };
8259
8373
  function runOptsIn(run) {
8260
8374
  return run.kind === "scheduled" ? sql`coalesce(${juniorConversationParticipants.autoArchive}, ${juniorUsers.autoArchiveDefault}) = true` : sql`${juniorConversationParticipants.autoArchive} is distinct from false`;
8261
8375
  }
@@ -8416,7 +8530,7 @@ async function runAutoArchiveSweep(args) {
8416
8530
  */
8417
8531
  async function archiveViewerDoneConversations(viewer) {
8418
8532
  const { archived } = await archiveUserDoneConversations({
8419
- graceHours: (await readUserAutoArchiveSettings(viewer.id))?.autoArchiveGraceHours ?? DEFAULT_AUTO_ARCHIVE_SETTINGS.autoArchiveGraceHours,
8533
+ graceHours: (await readUserSettings(viewer.id))?.autoArchiveGraceHours ?? 24,
8420
8534
  kind: "manual",
8421
8535
  now: /* @__PURE__ */ new Date(),
8422
8536
  userId: viewer.id
@@ -8440,25 +8554,6 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
8440
8554
  });
8441
8555
  return { autoArchive };
8442
8556
  }
8443
- /** Read the user's auto-archive settings. */
8444
- async function readUserAutoArchiveSettings(userId) {
8445
- const [user] = await getDb().select({
8446
- autoArchiveDefault: juniorUsers.autoArchiveDefault,
8447
- autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours
8448
- }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
8449
- return user;
8450
- }
8451
- /** Save changed auto-archive settings and return the saved settings. */
8452
- async function updateUserAutoArchiveSettings(userId, settings) {
8453
- const [user] = await getDb().update(juniorUsers).set({
8454
- ...settings,
8455
- updatedAt: /* @__PURE__ */ new Date()
8456
- }).where(eq(juniorUsers.id, userId)).returning({
8457
- autoArchiveDefault: juniorUsers.autoArchiveDefault,
8458
- autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours
8459
- });
8460
- return user;
8461
- }
8462
8557
  // src/chat/review-items/reply-match.ts
8463
8558
  const MATCH_CONFIDENCE_THRESHOLD = .7;
8464
8559
  /** A slow decision keeps the items open instead of delaying the close. */
@@ -8839,7 +8934,7 @@ function resolveAllowedDomains(allowedDomains) {
8839
8934
  */
8840
8935
  function assertNoLegacyAllowedDomains(dashboardOptionKeys) {
8841
8936
  if (dashboardOptionKeys.includes("allowedGoogleDomains")) throw new Error("dashboard.allowedGoogleDomains was removed; set createApp({ allowedDomains }) instead");
8842
- if (process.env.JUNIOR_DASHBOARD_GOOGLE_DOMAINS?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
8937
+ if (process.env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
8843
8938
  }
8844
8939
  /** Return whether a verified domain may use Junior. An empty list allows all. */
8845
8940
  function isAllowedDomain(domain, allowedDomains) {
@@ -9522,6 +9617,11 @@ async function copyForkEvents(args) {
9522
9617
  actorIdentityId: e.actorIdentityId,
9523
9618
  createdAt: e.createdAt
9524
9619
  }).from(e).where(and(eq(e.conversationId, args.sourceConversationId), inArray(e.seq, seqs))));
9620
+ await copyMessageLinks(getSqlExecutor(), {
9621
+ conversationId: args.conversationId,
9622
+ seqs,
9623
+ sourceConversationId: args.sourceConversationId
9624
+ });
9525
9625
  }
9526
9626
  function hasUnfinishedToolCalls(messages) {
9527
9627
  const pending = /* @__PURE__ */ new Set();
@@ -9846,8 +9946,9 @@ function format(text, provider) {
9846
9946
  * as GitHub reference and `@login` links that show as object cards. A reply
9847
9947
  * posted to a provider, and the summary of an Event from one, is that
9848
9948
  * provider's text. In a chat reply, a bare `@U123` is a Slack user, as in
9849
- * Slack, and not an account of a plugin's provider. Raw Event text and user
9850
- * text show as written.
9949
+ * Slack, and not an account of a plugin's provider. A person's message gets
9950
+ * the same links, so a typed `owner/repo#12` shows the card that a pasted
9951
+ * URL shows. Raw Event text shows as written.
9851
9952
  */
9852
9953
  function formatConversationEventText(event) {
9853
9954
  const { data } = event;
@@ -9871,13 +9972,15 @@ function formatConversationEventText(event) {
9871
9972
  } : item) } : void 0
9872
9973
  }
9873
9974
  };
9874
- return data.role === "assistant" && data.text !== void 0 ? {
9975
+ if (data.text === void 0 || data.role === "system") return event;
9976
+ const text = data.role === "assistant" ? wrapBareSlackUserIds(data.text) : data.text;
9977
+ return {
9875
9978
  ...event,
9876
9979
  data: {
9877
9980
  ...data,
9878
- text: format(wrapBareSlackUserIds(data.text))
9981
+ text: format(text)
9879
9982
  }
9880
- } : event;
9983
+ };
9881
9984
  }
9882
9985
  // src/api/conversations/mentions.ts
9883
9986
  /** Text in one event that the dashboard renders with mentions. */
@@ -11082,6 +11185,89 @@ async function readConversationFeedBriefs(db, conversationIds) {
11082
11185
  }).from(juniorConversations).innerJoinLateral(latest, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
11083
11186
  return new Map(rows.map(({ conversationId, ...brief }) => [conversationId, conversationFeedBriefSchema.parse(brief)]));
11084
11187
  }
11188
+ // src/api/conversations/feed-links.ts
11189
+ const RECENT_USE_LIMIT = 20;
11190
+ const CANDIDATE_LINK_LIMIT = 6;
11191
+ /** The URLs that a row's Annotations already show, as links compare them. */
11192
+ function annotationUrls(annotations) {
11193
+ return new Set((annotations ?? []).flatMap(({ url }) => {
11194
+ const href = safeLinkUrl(url);
11195
+ return href ? [href] : [];
11196
+ }));
11197
+ }
11198
+ /** The links a feed row shows, from its `feedLinksSql` candidates. */
11199
+ function pickFeedLinks(conversationId, urls, shown) {
11200
+ const links = [];
11201
+ for (const link of urls) {
11202
+ const href = safeLinkUrl(link);
11203
+ if (!href || links.includes(href) || shown.has(href) || parseDashboardConversationLink(href) === conversationId) continue;
11204
+ links.push(href);
11205
+ if (links.length >= 3) break;
11206
+ }
11207
+ return links;
11208
+ }
11209
+ /**
11210
+ * A feed row column with the newest distinct links of its Conversation,
11211
+ * newest message first and in text order within a message, or null. It is
11212
+ * a scalar subquery on the row read, so links cost no round trip of their
11213
+ * own. Links are private content: show them only where the viewer sees
11214
+ * private content. Only URLs leave the database, never message text.
11215
+ */
11216
+ function feedLinksSql(db) {
11217
+ const m = juniorMessageAttachments;
11218
+ const recentUses = db.select({
11219
+ attachmentId: m.attachmentId,
11220
+ position: m.position,
11221
+ seq: m.seq
11222
+ }).from(m).where(eq(m.conversationId, juniorConversations.conversationId)).orderBy(desc(m.seq), asc(m.position)).limit(RECENT_USE_LIMIT).as("recent_uses");
11223
+ const distinctUses = db.selectDistinctOn([recentUses.attachmentId], {
11224
+ attachmentId: recentUses.attachmentId,
11225
+ position: recentUses.position,
11226
+ seq: recentUses.seq
11227
+ }).from(recentUses).orderBy(recentUses.attachmentId, desc(recentUses.seq), asc(recentUses.position)).as("distinct_uses");
11228
+ const candidates = db.select({
11229
+ attachmentId: distinctUses.attachmentId,
11230
+ position: distinctUses.position,
11231
+ seq: distinctUses.seq
11232
+ }).from(distinctUses).orderBy(desc(distinctUses.seq), asc(distinctUses.position)).limit(CANDIDATE_LINK_LIMIT).as("candidate_uses");
11233
+ const urls = db.select({ urls: sql`array_agg(${juniorAttachments.url} order by ${candidates.seq} desc, ${candidates.position})` }).from(candidates).innerJoin(juniorAttachments, and(eq(juniorAttachments.id, candidates.attachmentId), isNotNull(juniorAttachments.url), isNull(juniorAttachments.deleteRequestedAt)));
11234
+ return sql`(${urls})`;
11235
+ }
11236
+ // src/api/conversations/feed-media.ts
11237
+ /**
11238
+ * A feed row column with the newest stored files of its Conversation, or
11239
+ * null when it has none. It is a scalar subquery on the row read, so media
11240
+ * costs no round trip of its own. Files are private content: show them
11241
+ * only where the viewer sees private content. Only file metadata leaves the
11242
+ * database.
11243
+ */
11244
+ function feedMediaSql(db) {
11245
+ const recentFiles = db.select({
11246
+ contentType: juniorAttachments.contentType,
11247
+ createdAt: juniorAttachments.createdAt,
11248
+ filename: juniorAttachments.title,
11249
+ id: juniorAttachments.id
11250
+ }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, juniorConversations.conversationId), isFileAttachment, isNull(juniorAttachments.deleteRequestedAt))).orderBy(desc(juniorAttachments.createdAt), desc(juniorAttachments.id)).limit(3).as("recent_files");
11251
+ const files = db.select({ files: sql`jsonb_agg(jsonb_build_object('contentType', ${recentFiles.contentType}, 'filename', ${recentFiles.filename}, 'id', ${recentFiles.id}) order by ${recentFiles.createdAt} desc, ${recentFiles.id} desc)` }).from(recentFiles);
11252
+ return sql`(${files})`;
11253
+ }
11254
+ // src/api/page-cursor.ts
11255
+ /**
11256
+ * Encode the position after the last row of a page as an opaque `cursor`
11257
+ * value. The cursor only moves a position inside a list that access already
11258
+ * scopes, so it carries no signature.
11259
+ */
11260
+ function encodePageCursor(schema, position) {
11261
+ return Buffer.from(JSON.stringify(schema.parse(position)), "utf8").toString("base64url");
11262
+ }
11263
+ /** Decode a `cursor` query value with its schema, or answer 400. */
11264
+ function decodePageCursor(schema, value, message) {
11265
+ try {
11266
+ return schema.parse(JSON.parse(Buffer.from(value, "base64url").toString("utf8")));
11267
+ } catch (error) {
11268
+ throwApiError(400, message, error);
11269
+ }
11270
+ }
11085
11271
  // src/api/conversations/feed-cursor.ts
11086
11272
  /**
11087
11273
  * Position after the last row of one feed page. `at` keeps the microseconds
@@ -11094,18 +11280,11 @@ const conversationFeedCursorSchema = z.object({
11094
11280
  }).strict();
11095
11281
  /** Encode the feed position after one row for `nextCursor`. */
11096
11282
  function encodeConversationFeedCursor(cursor) {
11097
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
11283
+ return encodePageCursor(conversationFeedCursorSchema, cursor);
11098
11284
  }
11099
- /**
11100
- * Decode a `cursor` query value. The cursor only moves the position inside a
11101
- * feed that membership already scopes, so it carries no signature.
11102
- */
11285
+ /** Decode a feed `cursor` query value. */
11103
11286
  function decodeConversationFeedCursor(value) {
11104
- try {
11105
- return conversationFeedCursorSchema.parse(JSON.parse(Buffer.from(value, "base64url").toString("utf8")));
11106
- } catch (error) {
11107
- throwApiError(400, "Invalid conversation feed cursor.", error);
11108
- }
11287
+ return decodePageCursor(conversationFeedCursorSchema, value, "Invalid conversation feed cursor.");
11109
11288
  }
11110
11289
  // src/api/conversations/list.ts
11111
11290
  const CONVERSATION_FEED_LIMIT = 50;
@@ -11133,12 +11312,14 @@ function conversationCodeRepositoryFilter(repositoryId, viewerUserId) {
11133
11312
  )
11134
11313
  )`, or(eq(juniorDestinations.visibility, "public"), viewerUserId ? conversationHasParticipantUser(viewerUserId) : void 0));
11135
11314
  }
11136
- async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, includePrivateBriefs = false, limit, pinnedForUserId, query, status }) {
11315
+ async function conversationRows(db, { codeRepository, conversationIds, cursor, filter, include = [], includePrivateBriefs = false, limit, pinnedForUserId, query, status }) {
11137
11316
  const rows = db.select({
11138
11317
  ...conversationRecordColumns,
11139
11318
  activityCursor: sql`to_char(${juniorConversations.lastActivityAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
11140
11319
  lastMessageAt: sql`coalesce(${juniorConversations.lastMessageAt}, ${lastMessageAtSql(db)})`.mapWith(juniorConversations.lastMessageAt),
11141
- awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId)
11320
+ awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId),
11321
+ links: include.includes("links") ? feedLinksSql(db) : sql`null`,
11322
+ media: include.includes("media") ? feedMediaSql(db) : sql`null`
11142
11323
  }).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).where(and(listedConversation(), conversationFeedMembershipFilter(status, filter), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, pinnedForUserId ? pinnedForUserId.pinned ? conversationPinnedForUser(pinnedForUserId.userId) : not(conversationPinnedForUser(pinnedForUserId.userId)) : void 0, cursor ? sql`(${juniorConversations.lastActivityAt} < ${cursor.at}::timestamptz or (${juniorConversations.lastActivityAt} = ${cursor.at}::timestamptz and ${juniorConversations.conversationId} > ${cursor.conversationId}))` : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, sql`exists (
11143
11324
  select 1
11144
11325
  from ${juniorConversationBriefs}
@@ -11159,13 +11340,14 @@ async function conversationRows(db, { codeRepository, conversationIds, cursor, f
11159
11340
  * the first page. Needs you shows every conversation that waits on the
11160
11341
  * viewer, so an old one must come back to the feed.
11161
11342
  */
11162
- async function waitingRowsOutsidePage(db, filter, page) {
11343
+ async function waitingRowsOutsidePage(db, filter, page, include) {
11163
11344
  const loaded = new Set(page.map((row) => row.conversation.conversationId));
11164
11345
  const missing = (await listWaitingConversations(db, filter.userId)).map((waiting) => waiting.conversationId).filter((conversationId) => !loaded.has(conversationId));
11165
11346
  if (missing.length === 0) return [];
11166
11347
  return await conversationRows(db, {
11167
11348
  conversationIds: missing,
11168
11349
  filter,
11350
+ include,
11169
11351
  includePrivateBriefs: true,
11170
11352
  limit: missing.length,
11171
11353
  status: "active"
@@ -11280,12 +11462,14 @@ async function readConversationFeedFromSql(options = {}) {
11280
11462
  const cursor = options.cursor ? decodeConversationFeedCursor(options.cursor) : void 0;
11281
11463
  const limit = options.limit ?? CONVERSATION_FEED_LIMIT;
11282
11464
  const pinsFirst = filter?.kind === "viewer" && status === "active";
11465
+ const include = options.include ?? [];
11283
11466
  const feedQuery = {
11284
11467
  ...options.codeRepositoryId ? { codeRepository: {
11285
11468
  id: options.codeRepositoryId,
11286
11469
  ...options.viewer ? { viewerUserId: options.viewer.id } : void 0
11287
11470
  } } : void 0,
11288
11471
  filter,
11472
+ include,
11289
11473
  includePrivateBriefs: filter?.kind === "viewer",
11290
11474
  query,
11291
11475
  status
@@ -11308,7 +11492,7 @@ async function readConversationFeedFromSql(options = {}) {
11308
11492
  const page = pageRows.slice(0, limit);
11309
11493
  const lastRow = pageRows.length > limit ? page.at(-1) : void 0;
11310
11494
  const rows = [...pinnedRows, ...page];
11311
- if (pinsFirst && !cursor) rows.push(...await waitingRowsOutsidePage(db, filter, rows));
11495
+ if (pinsFirst && !cursor) rows.push(...await waitingRowsOutsidePage(db, filter, rows, include));
11312
11496
  const conversations = rows.map((row) => conversationFromRecordRow(row));
11313
11497
  const conversationIds = conversations.map((conversation) => conversation.conversationId);
11314
11498
  const [accessByConversation, viewerMarksByConversation, annotationsByConversation, auxiliaryCostsByRoot, metricsByRoot, participantsByConversation, teamDomainByTeamId, { work: conversationWork, lastUserMessageAt: lastUserMessageAtByConversation }, activityPreviewByConversation, briefByConversation, automationTitleByConversation, firstHumanMessageTextByConversation] = await Promise.all([
@@ -11366,6 +11550,8 @@ async function readConversationFeedFromSql(options = {}) {
11366
11550
  const brief = access?.canViewPrivateContent ? briefByConversation.get(conversation.conversationId) : void 0;
11367
11551
  const participants = access?.canViewPrivateContent ? participantsByConversation.get(conversation.conversationId) : void 0;
11368
11552
  const threads = threadsByRoot.get(conversation.conversationId);
11553
+ const media = access?.canViewPrivateContent ? row.media : null;
11554
+ const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(annotations)) : [];
11369
11555
  const lastMessageAt = row.lastMessageAt?.toISOString();
11370
11556
  return {
11371
11557
  ...summary,
@@ -11376,6 +11562,8 @@ async function readConversationFeedFromSql(options = {}) {
11376
11562
  ...participants && participants.length > 0 ? { participants } : void 0,
11377
11563
  ...activityPreview ? { activityPreview } : void 0,
11378
11564
  ...brief ? { brief } : void 0,
11565
+ ...media?.length ? { media } : void 0,
11566
+ ...links.length > 0 ? { links } : void 0,
11379
11567
  ...annotations.length > 0 ? { annotations } : void 0,
11380
11568
  ...sidebarAnnotationsByConversation[conversation.conversationId] ? { sidebarAnnotations: sidebarAnnotationsByConversation[conversation.conversationId] } : void 0,
11381
11569
  isPriority: isConversationPriority({
@@ -11476,4 +11664,4 @@ function viewerWebMessages(messages, viewer) {
11476
11664
  }] : [];
11477
11665
  });
11478
11666
  }
11479
- export { guardedFetch as $, resolveAllowedDomains as A, runAutoArchiveSweep as B, readConversationPendingMessages as C, createViewerMcp as Ct, isAllowedDomain as D, assertNoLegacyAllowedDomains as E, readReviewItemForUser as F, startSavingsRefill as G, updateUserAutoArchiveSettings as H, reviewItemChange as I, readHealthReport as J, backfillCacheWarmingGaps as K, DEFAULT_AUTO_ARCHIVE_SETTINGS as L, ReviewItemActionError as M, actOnReviewItem as N, isAllowedSignInEmail as O, closeReviewItemsAnsweredByReply as P, resolveObjectLinks as Q, archiveViewerDoneConversations as R, cancelConversationPendingMessagesForViewer as S, readFirstHumanMessageTexts as St, resolveMentions as T, decodeImageId as Tt, readSavingsRefill as U, setConversationAutoArchive as V, runSavingsRefillSlice as W, readObjectLinkTypes as X, OBJECT_LINK_TTL_MS as Y, resolveObjectLinkNow as Z, appendConversationMessageForViewer as _, stripLeadingBotMention as _t, pinConversation as a, buildSlackInboundMessage as at, decodeConversationCursor as b, getThreadStopDecision as bt, readConversationAuxiliaryCostsFromSql as c, normalizeIncomingSlackThreadId as ct, conversationVersionQuery as d, enqueueAgentDispatch as dt, isPublicAddress as et, readConversationDetailEtag as f, failStoppedDispatch as ft, readConversationRecordFromSql as g, startProcessingReaction as gt, readConversationEvents as h, bindMessageAuthorIdentityId as ht, readConversationFeed as i, getProductionSlackAdapter as it, stopConversation as j, readEnvList as k, childAgentTotalsReport as l, withNormalizedThreadId as lt, keepQuickQuestionForViewer as m, createSlackWebApiStatusSender as mt, steerConversationPendingMessagesForViewer as n, createProductionConversationWorkOptions as nt, reorderPinnedConversations as o, clearSlackPendingReactions as ot, forkConversationForViewer as p, recordSkippedConversationMessage as pt, GET as q, conversationFeedVersionQuery as r, createProductionSlackWebhookServices as rt, readConversationDetail as s, slackInboundMessageId as st, stopConversationTurnForViewer as t, publicAddressLookup as tt, readConversationTreeMetricsFromSql as u, AGENT_DISPATCH_MAX_AGE_MS as ut, createConversationForViewer as v, parseContent as vt, requireConversationPendingMessages as w, IMAGE_WIDTHS as wt, encodeConversationCursor as x, conversationSummaryFromStoredConversation as xt, requireWebMessageConversation as y, SubscribedReplyReason as yt, readUserAutoArchiveSettings as z };
11667
+ export { readObjectLinkTypes as $, isAllowedSignInEmail as A, runAutoArchiveSweep as B, encodeConversationCursor as C, getThreadStopDecision as Ct, resolveMentions as D, IMAGE_WIDTHS as Dt, requireConversationPendingMessages as E, createViewerMcp as Et, actOnReviewItem as F, readSavingsRefill as G, DEFAULT_USER_SETTINGS as H, closeReviewItemsAnsweredByReply as I, backfillCacheWarmingGaps as J, runSavingsRefillSlice as K, readReviewItemForUser as L, resolveAllowedDomains as M, stopConversation as N, assertNoLegacyAllowedDomains as O, decodeImageId as Ot, ReviewItemActionError as P, readLinkObjectType as Q, reviewItemChange as R, decodeConversationCursor as S, SubscribedReplyReason as St, readConversationPendingMessages as T, readFirstHumanMessageTexts as Tt, readUserSettings as U, setConversationAutoArchive as V, updateUserSettings as W, readHealthReport as X, GET as Y, OBJECT_LINK_TTL_MS as Z, readConversationEvents as _, createSlackWebApiStatusSender as _t, decodePageCursor as a, createProductionConversationWorkOptions as at, createConversationForViewer as b, stripLeadingBotMention as bt, reorderPinnedConversations as c, buildSlackInboundMessage as ct, childAgentTotalsReport as d, normalizeIncomingSlackThreadId as dt, resolveObjectLinkNow as et, readConversationTreeMetricsFromSql as f, withNormalizedThreadId as ft, keepQuickQuestionForViewer as g, recordSkippedConversationMessage as gt, forkConversationForViewer as h, failStoppedDispatch as ht, readConversationFeed as i, publicAddressLookup as it, readEnvList as j, isAllowedDomain as k, readConversationDetail as l, clearSlackPendingReactions as lt, readConversationDetailEtag as m, enqueueAgentDispatch as mt, steerConversationPendingMessagesForViewer as n, guardedFetch as nt, encodePageCursor as o, createProductionSlackWebhookServices as ot, conversationVersionQuery as p, AGENT_DISPATCH_MAX_AGE_MS as pt, startSavingsRefill as q, conversationFeedVersionQuery as r, isPublicAddress as rt, pinConversation as s, getProductionSlackAdapter as st, stopConversationTurnForViewer as t, resolveObjectLinks as tt, readConversationAuxiliaryCostsFromSql as u, slackInboundMessageId as ut, readConversationRecordFromSql as v, bindMessageAuthorIdentityId as vt, cancelConversationPendingMessagesForViewer as w, conversationSummaryFromStoredConversation as wt, requireWebMessageConversation as x, parseContent as xt, appendConversationMessageForViewer as y, startProcessingReaction as yt, archiveViewerDoneConversations as z };