@sentry/junior 0.302.0 → 0.303.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 (93) hide show
  1. package/dist/{adapter-context-Cx9fn9B3.js → adapter-context-BdVnSuY5.js} +2 -2
  2. package/dist/{admin-_poE5NKL.js → admin-AfeAdS3J.js} +2 -2
  3. package/dist/{agent-runner-CY9RvsTX.js → agent-runner-BP8_DLUv.js} +2987 -2948
  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 +207 -80
  8. package/dist/{app-BpY3wtRP.d.ts → app-Dd9v1mNx.d.ts} +15 -15
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +63 -64
  11. package/dist/{automation-Cva5ZOwW.js → automation-D9MvhOWY.js} +3 -1
  12. package/dist/{background-compaction-queue-CXFq1_Cz.js → background-compaction-queue-xaE05jxH.js} +6 -6
  13. package/dist/{briefs-B3NG-pid.js → briefs-D8i-dKTp.js} +4 -4
  14. package/dist/{catalog-runtime-Dss0lSV6.js → catalog-runtime-d1EM6Z0V.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 +8 -8
  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 +5 -5
  26. package/dist/{config-CzeZiMKs.js → config-oGM7KA9M.js} +44 -63
  27. package/dist/{connections-CDYhMfrs.js → connections-BlikzEJv.js} +6 -6
  28. package/dist/{continue-in-slack-7Uf05ndC.js → continue-in-slack-BZnYifiG.js} +5 -5
  29. package/dist/{conversation-BNXfq6Lb.js → conversation-CY1jnBiC.js} +1 -1
  30. package/dist/{conversation-feed-Clf_cv0n.js → conversation-feed-BZJRk6UV.js} +1 -1
  31. package/dist/{conversation-privacy-D9xnM5mK.js → conversation-privacy-Cx515ddM.js} +7 -7
  32. package/dist/{conversation-turn-D7SEZgTG.js → conversation-turn-DAhRdX4m.js} +20 -23
  33. package/dist/{credential-sync-DoD0gW-j.js → credential-sync-DfhmWFeo.js} +18 -18
  34. package/dist/{db-B-gtnNjr.js → db-C-2tFxk3.js} +15 -15
  35. package/dist/{db-BdsCzytP.d.ts → db-DPqcEM9_.d.ts} +25 -25
  36. package/dist/{executor-DZg20EqU.js → executor-NVfS8aQ2.js} +14 -8
  37. package/dist/{history-IjdmO_r6.js → history-UZ3M2M9r.js} +13 -10
  38. package/dist/{install-t1KQyTUs.js → install-CHLrpRZc.js} +3 -3
  39. package/dist/instrumentation.d.ts +4 -4
  40. package/dist/instrumentation.js +10 -10
  41. package/dist/{lineage-C79GjoQr.js → lineage-HGLhd_-N.js} +2 -2
  42. package/dist/{logging-C9oDAg4M.js → logging-DiyqRLBx.js} +19 -19
  43. package/dist/{message-BLUCzJXN.js → message-CkCOcbFH.js} +9 -9
  44. package/dist/{model-input-5jwNC45G.js → model-input-DmoPPtPE.js} +4 -9
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +7 -7
  47. package/dist/{oauth-callback-server-BBl66vCb.js → oauth-callback-server-CIf_6YmA.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-DBq8tsA5.js} +221 -173
  53. package/dist/{prompt-CRQbzp5e.js → prompt-D2KlJopL.js} +4 -4
  54. package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
  55. package/dist/{queue-DtCDaIct.js → queue-DFaOscp5.js} +4 -4
  56. package/dist/{registry-DdFQHZ_d.js → registry-Bu0Z9BEO.js} +37 -37
  57. package/dist/{resolve-CdW4BdrK.js → resolve-DXuA3G0g.js} +3 -3
  58. package/dist/{result-oOMv1t4O.js → result-DpiNseDA.js} +10 -15
  59. package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
  60. package/dist/{runner-DqitLtm-.js → runner-iu1heRFv.js} +10 -10
  61. package/dist/{sandbox-egress-signals-Bw9I0yfJ.js → sandbox-egress-signals-2HFYDcQf.js} +1 -1
  62. package/dist/{schema-BIFM-U1a.d.ts → schema-DHMOaRzC.d.ts} +520 -13
  63. package/dist/{schema-DnVQepWP.js → schema-DvfX3Gq_.js} +77 -13
  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-BcT5LR7V.js} +47 -47
  68. package/dist/{service-account-B6mKAPVo.js → service-account-xYkaQTrw.js} +3 -3
  69. package/dist/{session-stop-DW63Z3kj.js → session-stop-BLLp1IP_.js} +28 -35
  70. package/dist/{skills-C16fz60Z.js → skills-CNAGH4ju.js} +6 -9
  71. package/dist/{slack-conversation-unfurl-BHhefEb7.js → slack-conversation-unfurl-DYnqe5ci.js} +10 -15
  72. package/dist/{spawn-D_RnFYfy.js → spawn-cGasWW33.js} +7 -7
  73. package/dist/{legacy-web-actor-id-C-cEeWqL.js → state-CDS6h_Wv.js} +32 -32
  74. package/dist/{stop-7p1i08CY.js → stop-DMMA67yT.js} +221 -139
  75. package/dist/{store-C28I0CVW.js → store-Dgs7Oe44.js} +5 -5
  76. package/dist/{task-queue-BVUJbQ28.js → task-queue-DcF0nhhz.js} +3 -3
  77. package/dist/{task-runner-CWi8j7Z6.js → task-runner-BGXF7Fo7.js} +15 -18
  78. package/dist/{thread-context-D3-yYUd0.js → thread-context-BPky1KBe.js} +12 -12
  79. package/dist/{turn-session-routing-BFMS9ATF.js → turn-session-routing-DGvn9MSl.js} +32 -32
  80. package/dist/{turn-user-message-C3-O8Omt.js → turn-user-message-19CkuUvM.js} +3 -3
  81. package/dist/{validation-BSFKUIb4.js → validation-lu1DgjNQ.js} +2 -2
  82. package/dist/vercel.js +1 -1
  83. package/dist/{version-BHHXNi-0.js → version-Uo3c94Dx.js} +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/{viewer-B1SO21Qa.js → viewer-BPQHMx3-.js} +3 -3
  86. package/dist/{warmup-Bz9bzkzN.js → warmup-H8uLvW9e.js} +149 -130
  87. package/dist/{worker-BspReIIK.js → worker-B-pM_-3K.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/meta/0109_snapshot.json +4925 -0
  91. package/migrations/meta/0110_snapshot.json +4952 -0
  92. package/migrations/meta/_journal.json +15 -1
  93. 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, A as latestConversationMessageSeq, Aa as removeReactionFromMessage, Bi as parseDashboardPersonLink, Br as takeReviewItem, Ca as addReactionToMessage, Co as readConversationAccessFromSql, Cs as createPluginCache, D as estimateConversationMessagesTokens, Do as conversationPinnedForUser, Ds as piMessageFromHistoryItem, E as buildConversationContext, Eo as conversationIsNotUnsubscribedRoot, F as turnHasReply, Fo as readConversationEventPageAround, H as PluginCredentialFailureError, Ho as getSlackFileId, Ht as releaseInboundMessage, I as upsertConversationMessage, Ir as listReplyActionItems, Jo as SlackActionError, K as AuthorizationFlowDisabledError, Ko as recordSlackAttachment, Kr as canUserReadReviewItem, Ln as trimTrailingAssistantMessages, Lr as listWaitingConversations, M as normalizeConversationText, Mi as getDashboardLinkFilter, Mo as readLatestConversationBrief, N as recordDeliveredAssistantMessage, No as readConversationEventPage, O as getConversationMessageSlackTs, Oo as conversationViewerMarks, P as trimConversationMessages, Pi as getDashboardPersonLink, Po as readConversationEventPageAfter, Pr as getReviewItem, Qo as getSlackClient, Qr as reviewItemNeedsSomeone, Ri as isDashboardLink, Ro as buildSentryConversationUrl, S as resolveConversationTitle, Sa as truncateStatusText, So as createConversationAccessReader, To as conversationIsMemberRoot, Ts as configValueSchema, Ur as canActOnReviewItem, V as createPluginEgress, Vo as notInheritedByForkChild, Wo as readAttachmentVisionSummary, X as clearPendingAuth, Yo as downloadPrivateSlackFile, Zn as createUserTokenStore, Zo as getHeaderString, a as loadProjection, as as withSlackRetries, at as failTurnRecord, b as persistConversationMessages, ba as slackMentionedUserIds, bn as persistWithRetry, bs as lookupSlackUserNames, ct as listTurnSummaries, d as recordAuthorizationCompleted, es as isDmChannel, et as lostWorkerBeforeFirstSave, fa as resolveBaseUrl, gs as listConversationAnnotationsById, h as recordSubscribedReplyRoute, hs as listConversationAnnotations, i as loadConversationProjection, is as streamPrivateSlackFile, it as completeTurnRecord, j as markConversationMessage, ji as getDashboardConversationLink, k as isHumanConversationMessage, ko as viewerMarksFromParticipant, kr as closeReviewItem, lt as recordTurnSummary, ma as SLACK_USER_MENTION_RE, n as commitMessages, ns as normalizeSlackConversationId, nt as saveTurnCheckpoint, o as loadTurnProjection, pi as cancelSubscriptions, qo as slackAttachmentsVersionQuery, qr as isOnlyAssignee, rt as abandonTurnRecord, st as getTurnRecord, t as commitAcceptedReply, tn as buildTurnErrorResponse, tr as applyPluginFormatMarkdown, ts as isSlackRequestTimeout, tt as pauseLostWorkerTurn, un as getAssistantReplyText, ur as getPlugins, v as hydrateConversationMessages, va as normalizeSlackStatusText, w as fallbackShortTitle, wo as conversationHasParticipantUser, xa as wrapBareSlackUserIds, xo as canAddConversationMessages, y as persistConversationMessageWindow, yo as createPluginLogger, ys as lookupSlackUser, zi as parseDashboardConversationLink } from "./projection-DBq8tsA5.js";
2
+ 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-oGM7KA9M.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-DiyqRLBx.js";
4
+ import { h as startSpan } from "./sentry-CPbZjomA.js";
5
+ import { t as JUNIOR_VERSION } from "./version-Uo3c94Dx.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 { D as turnBehavior, 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-C-2tFxk3.js";
8
+ import { D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, O as juniorCodeChanges, P as juniorUsers, T as juniorConversationEvents, g as juniorAgentInvocations, l as juniorReviewItems, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-NVfS8aQ2.js";
9
+ import { d as contextProvenance, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-UZ3M2M9r.js";
10
+ import { d as actorLogContext, f as credentialContextForActor } from "./registry-Bu0Z9BEO.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-d1EM6Z0V.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-BP8_DLUv.js";
13
+ import { d as PluginMcpClient, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials } from "./service-account-BcT5LR7V.js";
14
+ import { i as webActorUserIds } from "./state-CDS6h_Wv.js";
15
+ import { a as EVENT_SYSTEM_ACTOR, c as completeDecision, o as isEventConversationMessage, u as completeText } from "./prompt-D2KlJopL.js";
16
+ import { f as identityAvatarUrl, g as userAvatarUrlsFromIdentities, h as readUserAvatarUrls } from "./viewer-BPQHMx3-.js";
17
+ import { G as MAX_ATTACHMENT_BYTES, Y as readMessageAttachments, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-CY1jnBiC.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-BLLp1IP_.js";
20
+ import { $n as renderAttachmentText, At as verifyAttachmentUploads, Ct as createConversationId, Dt as AttachmentUploadError, Fi as NO_REPLY_GAP_MS, Ft as storeAttachment, Gn as AgentRunError, Ii as gapSegment, In as wakePausedTurn, Kn as executeTurn, Ln as getTurnAuthorization, Mn as supersedeTurnForInput, Ni as MINUTE_MS, Nn as createPausedTurns, Pn as getPausedTurnRequest, Rn as canJoinTurn, Sr as isPublicSlackChannel, St as createAndEnqueueConversation, Tt as webActorFromUser, Wn as getWebAuthorization, Zn as throwApiError, _n as dropOwnUnreadLoopReplies, bn as cancelSignInWait, br as getConversationInfo, bt as appendAndEnqueueWebMessage, c as isConversationWorkDone, ct as readLastUserMessageAtByConversation, d as addHistoryPeriod, dr as readSlackRawMessageContext, er as renderBlockText, f as firstLiveSavingsDate, fr as resolveSlackChannelIdFromMessage, gt as deliverReviewItemChange, i as GLOBAL_GAPS_TTL_MS, l as listConversationWork, m as replaceHistorySavings, n as CONVERSATION_STATE_TTL_MS, o as segmentGapsKey, p as idlePeriodSavings, pi as readConversationSourceTask, pr as resolveSlackChannelIdFromThreadId, qt as getChildAgentLabel, r as GLOBAL_GAPS_MAX, t as ANSWER_TOOL_ENDINGS, tr as parseSlackMessageReference, ur as parseSlackThreadId, ut as conversationReadPositionQuery, v as connectedState, vn as stopChildAgentsBelow, wr as listThreadReplies, wt as recordWebConversationActivity, xr as isConversationMember, y as providerCacheTtlMs, yn as stopChildAgentsOf, yr as getChannelMessage, yt as acceptsWebMessages, zn as canShareTurn } from "./warmup-H8uLvW9e.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-DGvn9MSl.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-19CkuUvM.js";
24
+ import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-xaE05jxH.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-Dgs7Oe44.js";
26
+ import { t as runWithSlackInstallation } from "./adapter-context-BdVnSuY5.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-BZJRk6UV.js";
28
+ import { c as withTurnSpan, n as createConversationTurnWorker, o as getTurnInputSpanAttributes, r as canPauseConversationDelivery, s as turnInputTelemetry } from "./conversation-turn-DAhRdX4m.js";
29
+ import { n as buildStoredAttachmentPromptText } from "./model-input-DmoPPtPE.js";
30
+ import { i as enqueueAgentInvocationResult, n as createDeliverToParent, s as withAgentInvocationResultActors, t as createChildConversationWorker } from "./result-DpiNseDA.js";
31
+ import { t as bindMessageAgent } from "./message-CkCOcbFH.js";
32
+ import { t as readConversationLineage } from "./lineage-HGLhd_-N.js";
33
+ import { t as bindSpawnAgent } from "./spawn-cGasWW33.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-BPky1KBe.js";
35
+ import { n as scheduleSessionCompletedPluginTasks } from "./task-runner-BGXF7Fo7.js";
36
+ import { r as canContinueInSlack } from "./continue-in-slack-BZnYifiG.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) {
@@ -1167,11 +1171,11 @@ function replaceTopLevelText(content, text) {
1167
1171
  }
1168
1172
  function readRawBlocks(raw) {
1169
1173
  if (!raw || typeof raw !== "object") return void 0;
1170
- return raw.blocks;
1174
+ return raw["blocks"];
1171
1175
  }
1172
1176
  function readRawText(raw) {
1173
1177
  if (!raw || typeof raw !== "object") return "";
1174
- const text = raw.text;
1178
+ const text = raw["text"];
1175
1179
  return typeof text === "string" ? text : "";
1176
1180
  }
1177
1181
  const slackFormat = new SlackFormatConverter();
@@ -1204,7 +1208,7 @@ function renderSlackPlainText(mrkdwn, userNames) {
1204
1208
  function renderTopLevelText(message) {
1205
1209
  const blocks = readRawBlocks(message.raw);
1206
1210
  const blockText = renderBlockText(blocks);
1207
- if (Array.isArray(blocks) && blocks.some((block) => block?.type === "section") && blockText) return blockText;
1211
+ if (Array.isArray(blocks) && blocks.some((block) => isRecord(block) && block["type"] === "section") && blockText) return blockText;
1208
1212
  const rawText = readRawText(message.raw);
1209
1213
  if (rawText.trim()) return renderSlackMrkdwn(rawText);
1210
1214
  if (message.formatted.children.length > 0) return stringifyMarkdown(message.formatted).trim();
@@ -1315,7 +1319,7 @@ function logProcessingReactionFailure(error, eventName, attributes) {
1315
1319
  }
1316
1320
  /** Return true when a Slack reaction tool invocation keeps the processing reaction. */
1317
1321
  function shouldKeepProcessingReactionForToolInvocation(input) {
1318
- return input.toolName === "addReaction" && isProcessingReactionEmoji(input.params.emoji);
1322
+ return input.toolName === "addReaction" && isProcessingReactionEmoji(input.params["emoji"]);
1319
1323
  }
1320
1324
  /** Start Junior's automatic Slack processing reaction for one inbound message. */
1321
1325
  async function startProcessingReaction(args) {
@@ -1848,7 +1852,7 @@ function createSlackTurnRuntime(deps) {
1848
1852
  }
1849
1853
  const eventId = classifiedFailure?.eventId ?? withLogContext(failureLogContext, () => logException(failureCause, "mention.handler.failed"));
1850
1854
  if (!acked && hooks.isFinalAttempt === false) return;
1851
- if (!eventId) throw new Error("Sentry did not return an event ID for mention.handler.failed");
1855
+ if (!eventId) throw new Error("Sentry did not return an event ID for mention.handler.failed", { cause: error });
1852
1856
  let lifecycleError;
1853
1857
  try {
1854
1858
  await failConversationTurn({
@@ -2140,7 +2144,7 @@ function createSlackTurnRuntime(deps) {
2140
2144
  }
2141
2145
  const eventId = classifiedFailure?.eventId ?? withLogContext(failureLogContext, () => logException(failureCause, "subscribed_message.handler.failed"));
2142
2146
  if (!acked && hooks.isFinalAttempt === false) return;
2143
- if (!eventId) throw new Error("Sentry did not return an event ID for subscribed_message.handler.failed");
2147
+ if (!eventId) throw new Error("Sentry did not return an event ID for subscribed_message.handler.failed", { cause: error });
2144
2148
  let lifecycleError;
2145
2149
  try {
2146
2150
  await failConversationTurn({
@@ -2777,7 +2781,7 @@ function createJuniorRuntimeServices(overrides = {}) {
2777
2781
  function getMessageTimestamp(message) {
2778
2782
  const idTs = parseSlackMessageTs(message.id);
2779
2783
  if (idTs) return idTs;
2780
- if (message.raw && typeof message.raw === "object") return parseSlackMessageTs(message.raw.ts);
2784
+ if (message.raw && typeof message.raw === "object") return parseSlackMessageTs(message.raw["ts"]);
2781
2785
  }
2782
2786
  // src/chat/slack/action-token.ts
2783
2787
  const slackActionTokenSchema = z.string().trim().min(1).brand();
@@ -3961,7 +3965,7 @@ function createSlackTurn(deps) {
3961
3965
  status.update({ text: event.text });
3962
3966
  return;
3963
3967
  }
3964
- if (event.type === "tool_started") await options.onToolInvocation?.({
3968
+ if (event.type === "tool_started") options.onToolInvocation?.({
3965
3969
  params: event.params,
3966
3970
  toolName: event.toolName
3967
3971
  });
@@ -4296,13 +4300,13 @@ function visionCacheKey(conversationId) {
4296
4300
  return `vision-cache:v${VISION_CACHE_SCHEMA_VERSION}:${conversationId}`;
4297
4301
  }
4298
4302
  function coerceVisionCache(value) {
4299
- if (!isRecord(value) || value.schemaVersion !== VISION_CACHE_SCHEMA_VERSION) return { byFileId: {} };
4300
- const rawByFileId = isRecord(value.byFileId) ? value.byFileId : {};
4303
+ if (!isRecord(value) || value["schemaVersion"] !== VISION_CACHE_SCHEMA_VERSION) return { byFileId: {} };
4304
+ const rawByFileId = isRecord(value["byFileId"]) ? value["byFileId"] : {};
4301
4305
  const byFileId = {};
4302
4306
  for (const [fileId, rawSummary] of Object.entries(rawByFileId)) {
4303
4307
  if (!fileId.trim() || !isRecord(rawSummary)) continue;
4304
- const summary = toOptionalString(rawSummary.summary);
4305
- const analyzedAtMs = toOptionalNumber(rawSummary.analyzedAtMs);
4308
+ const summary = toOptionalString(rawSummary["summary"]);
4309
+ const analyzedAtMs = toOptionalNumber(rawSummary["analyzedAtMs"]);
4306
4310
  if (!summary || analyzedAtMs === void 0) continue;
4307
4311
  byFileId[fileId] = {
4308
4312
  summary,
@@ -4310,7 +4314,7 @@ function coerceVisionCache(value) {
4310
4314
  };
4311
4315
  }
4312
4316
  return {
4313
- backfillCompletedAtMs: toOptionalNumber(value.backfillCompletedAtMs),
4317
+ backfillCompletedAtMs: toOptionalNumber(value["backfillCompletedAtMs"]),
4314
4318
  byFileId
4315
4319
  };
4316
4320
  }
@@ -4621,7 +4625,10 @@ async function projectDispatchTurnResult(dispatchId, result) {
4621
4625
  case "failed":
4622
4626
  await markDispatchFailed(dispatchId, result.errorMessage ?? "Agent turn failed", result.resultMessageTs);
4623
4627
  break;
4624
- case "completed": await markDispatchCompleted(dispatchId, result.resultMessageTs);
4628
+ case "completed":
4629
+ await markDispatchCompleted(dispatchId, result.resultMessageTs);
4630
+ break;
4631
+ case void 0:
4625
4632
  }
4626
4633
  }
4627
4634
  function getDispatchBlockingError(error) {
@@ -4968,8 +4975,8 @@ function normalizeIncomingSlackThreadId(threadId, message) {
4968
4975
  if (!message || typeof message !== "object") return threadId;
4969
4976
  const raw = message.raw;
4970
4977
  if (!raw || typeof raw !== "object") return threadId;
4971
- const channelId = nonEmptyString(raw.channel);
4972
- const threadTs = nonEmptyString(raw.thread_ts) ?? nonEmptyString(raw.ts);
4978
+ const channelId = nonEmptyString(raw["channel"]);
4979
+ const threadTs = nonEmptyString(raw["thread_ts"]) ?? nonEmptyString(raw["ts"]);
4973
4980
  if (!channelId || !threadTs) return threadId;
4974
4981
  return `slack:${channelId}:${threadTs}`;
4975
4982
  }
@@ -5013,7 +5020,7 @@ function hasValidMdastBase(node, fields) {
5013
5020
  "type",
5014
5021
  ...fields
5015
5022
  ]);
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);
5023
+ 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
5024
  }
5018
5025
  const mdastPhrasingTypes = /* @__PURE__ */ new Set([
5019
5026
  "break",
@@ -5045,24 +5052,24 @@ const mdastListItemTypes = /* @__PURE__ */ new Set(["listItem"]);
5045
5052
  const mdastTableCellTypes = /* @__PURE__ */ new Set(["tableCell"]);
5046
5053
  const mdastTableRowTypes = /* @__PURE__ */ new Set(["tableRow"]);
5047
5054
  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))));
5055
+ 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
5056
  }
5050
5057
  /** Validate every supported mdast node before restoring a serialized message. */
5051
5058
  function isFormattedContentNode(value) {
5052
5059
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
5053
5060
  const node = value;
5054
- switch (node.type) {
5061
+ switch (node["type"]) {
5055
5062
  case "break":
5056
5063
  case "thematicBreak": return hasValidMdastBase(node, []);
5057
5064
  case "html":
5058
5065
  case "inlineCode":
5059
5066
  case "text":
5060
- case "yaml": return hasValidMdastBase(node, ["value"]) && typeof node.value === "string";
5067
+ case "yaml": return hasValidMdastBase(node, ["value"]) && typeof node["value"] === "string";
5061
5068
  case "code": return hasValidMdastBase(node, [
5062
5069
  "lang",
5063
5070
  "meta",
5064
5071
  "value"
5065
- ]) && typeof node.value === "string" && isOptionalNullableString(node.lang) && isOptionalNullableString(node.meta);
5072
+ ]) && typeof node["value"] === "string" && isOptionalNullableString(node["lang"]) && isOptionalNullableString(node["meta"]);
5066
5073
  case "delete":
5067
5074
  case "emphasis":
5068
5075
  case "paragraph":
@@ -5070,60 +5077,60 @@ function isFormattedContentNode(value) {
5070
5077
  case "tableCell": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastPhrasingTypes);
5071
5078
  case "blockquote": return hasValidMdastBase(node, ["children"]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes);
5072
5079
  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;
5080
+ case "heading": return hasValidMdastBase(node, ["children", "depth"]) && hasMdastChildren(node, mdastPhrasingTypes) && Number.isInteger(node["depth"]) && Number(node["depth"]) >= 1 && Number(node["depth"]) <= 6;
5074
5081
  case "list": return hasValidMdastBase(node, [
5075
5082
  "children",
5076
5083
  "ordered",
5077
5084
  "spread",
5078
5085
  "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));
5086
+ ]) && 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
5087
  case "listItem": return hasValidMdastBase(node, [
5081
5088
  "checked",
5082
5089
  "children",
5083
5090
  "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"));
5091
+ ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && isOptionalNullableBoolean(node["checked"]) && isOptionalNullableBoolean(node["spread"]);
5092
+ 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
5093
  case "definition": return hasValidMdastBase(node, [
5087
5094
  "identifier",
5088
5095
  "label",
5089
5096
  "title",
5090
5097
  "url"
5091
- ]) && typeof node.identifier === "string" && typeof node.url === "string" && isOptionalNullableString(node.label) && isOptionalNullableString(node.title);
5098
+ ]) && typeof node["identifier"] === "string" && typeof node["url"] === "string" && isOptionalNullableString(node["label"]) && isOptionalNullableString(node["title"]);
5092
5099
  case "footnoteDefinition": return hasValidMdastBase(node, [
5093
5100
  "children",
5094
5101
  "identifier",
5095
5102
  "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);
5103
+ ]) && hasMdastChildren(node, mdastBlockOrDefinitionTypes) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]);
5104
+ case "footnoteReference": return hasValidMdastBase(node, ["identifier", "label"]) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]);
5098
5105
  case "image": return hasValidMdastBase(node, [
5099
5106
  "alt",
5100
5107
  "title",
5101
5108
  "url"
5102
- ]) && typeof node.url === "string" && isOptionalNullableString(node.alt) && isOptionalNullableString(node.title);
5109
+ ]) && typeof node["url"] === "string" && isOptionalNullableString(node["alt"]) && isOptionalNullableString(node["title"]);
5103
5110
  case "imageReference": return hasValidMdastBase(node, [
5104
5111
  "alt",
5105
5112
  "identifier",
5106
5113
  "label",
5107
5114
  "referenceType"
5108
- ]) && typeof node.identifier === "string" && isOptionalNullableString(node.alt) && isOptionalNullableString(node.label) && (node.referenceType === "collapsed" || node.referenceType === "full" || node.referenceType === "shortcut");
5115
+ ]) && typeof node["identifier"] === "string" && isOptionalNullableString(node["alt"]) && isOptionalNullableString(node["label"]) && (node["referenceType"] === "collapsed" || node["referenceType"] === "full" || node["referenceType"] === "shortcut");
5109
5116
  case "link": return hasValidMdastBase(node, [
5110
5117
  "children",
5111
5118
  "title",
5112
5119
  "url"
5113
- ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node.url === "string" && isOptionalNullableString(node.title);
5120
+ ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node["url"] === "string" && isOptionalNullableString(node["title"]);
5114
5121
  case "linkReference": return hasValidMdastBase(node, [
5115
5122
  "children",
5116
5123
  "identifier",
5117
5124
  "label",
5118
5125
  "referenceType"
5119
- ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node.identifier === "string" && isOptionalNullableString(node.label) && (node.referenceType === "collapsed" || node.referenceType === "full" || node.referenceType === "shortcut");
5126
+ ]) && hasMdastChildren(node, mdastPhrasingTypes) && typeof node["identifier"] === "string" && isOptionalNullableString(node["label"]) && (node["referenceType"] === "collapsed" || node["referenceType"] === "full" || node["referenceType"] === "shortcut");
5120
5127
  default: return false;
5121
5128
  }
5122
5129
  }
5123
5130
  const formattedContentSchema = z.custom((value) => {
5124
5131
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
5125
5132
  const root = value;
5126
- return root.type === "root" && hasValidMdastBase(root, ["children"]) && hasMdastChildren(root);
5133
+ return root["type"] === "root" && hasValidMdastBase(root, ["children"]) && hasMdastChildren(root);
5127
5134
  }, "must be a valid formatted-content root");
5128
5135
  const serializedMessageSchema = z.object({
5129
5136
  _type: z.literal("chat:Message"),
@@ -6569,7 +6576,7 @@ async function runNextPausedTurnInContext(conversationId, options, runOptions) {
6569
6576
  */
6570
6577
  function createSlackSystemTurnDelivery(args) {
6571
6578
  return async ({ conversationId, location, text, cards }) => {
6572
- if (location.provider !== "slack") throw new Error(`Slack system Turn cannot deliver to ${location.provider} Location`);
6579
+ if (location.provider !== "slack") throw new Error(`Slack system Turn cannot deliver to ${String(location.provider)} Location`);
6573
6580
  let messageIds;
6574
6581
  try {
6575
6582
  messageIds = await runWithSlackInstallation({
@@ -7255,9 +7262,9 @@ function children(node) {
7255
7262
  function attribute(element, name) {
7256
7263
  return element.attrs.find((attr) => attr.name === name)?.value;
7257
7264
  }
7258
- function text$1(node) {
7265
+ function text(node) {
7259
7266
  if (node.nodeName === "#text" && "value" in node) return node.value;
7260
- return children(node).map(text$1).join("");
7267
+ return children(node).map(text).join("");
7261
7268
  }
7262
7269
  function clean(value) {
7263
7270
  return value?.replace(/\s+/g, " ").trim() || void 0;
@@ -7269,7 +7276,7 @@ function parsePageMeta(html) {
7269
7276
  const tags = /* @__PURE__ */ new Map();
7270
7277
  let title;
7271
7278
  for (const node of head ? children(head) : []) {
7272
- if (isElement(node, "title")) title ??= clean(text$1(node));
7279
+ if (isElement(node, "title")) title ??= clean(text(node));
7273
7280
  if (!isElement(node, "meta")) continue;
7274
7281
  const name = (attribute(node, "property") ?? attribute(node, "name"))?.toLowerCase();
7275
7282
  const content = clean(attribute(node, "content"));
@@ -7514,7 +7521,7 @@ function webPageLinkType() {
7514
7521
  cacheCards: false,
7515
7522
  canView: async () => true,
7516
7523
  filters: [{ scheme: "https" }],
7517
- objectType: "web_page",
7524
+ objectTypes: ["web_page"],
7518
7525
  owner: "junior",
7519
7526
  resolve: (_viewer, url) => resolveWebPageLink(url)
7520
7527
  };
@@ -7530,7 +7537,7 @@ function coreLinkTypes() {
7530
7537
  const slack = {
7531
7538
  canView: async () => true,
7532
7539
  filters: [SLACK_MESSAGE_LINK_FILTER],
7533
- objectType: "message",
7540
+ objectTypes: ["message"],
7534
7541
  owner: "junior",
7535
7542
  resolve: resolveSlackMessageLink
7536
7543
  };
@@ -7544,7 +7551,7 @@ function coreLinkTypes() {
7544
7551
  {
7545
7552
  canView: canViewConversationLink,
7546
7553
  filters: [conversations],
7547
- objectType: "conversation",
7554
+ objectTypes: ["conversation"],
7548
7555
  owner: "junior",
7549
7556
  resolve: resolveConversationLink
7550
7557
  },
@@ -7552,7 +7559,7 @@ function coreLinkTypes() {
7552
7559
  cacheCards: false,
7553
7560
  canView: async () => true,
7554
7561
  filters: [people, { scheme: "mailto" }],
7555
- objectType: "person",
7562
+ objectTypes: ["person"],
7556
7563
  owner: "junior",
7557
7564
  resolve: (_viewer, url) => resolvePersonLink(url)
7558
7565
  }
@@ -7587,7 +7594,7 @@ function pluginLinkTypes(plugin) {
7587
7594
  return (plugin.objectLinks ?? []).map((link) => ({
7588
7595
  canView: (viewer, url) => link.canView(objectLinkContext(name, viewer), url),
7589
7596
  filters: link.filters,
7590
- objectType: link.objectType,
7597
+ objectTypes: link.objectTypes,
7591
7598
  owner: name,
7592
7599
  readTool: link.readTool,
7593
7600
  resolve: (viewer, url) => link.resolve(objectLinkContext(name, viewer), url),
@@ -7603,12 +7610,24 @@ function readObjectLinkTypes(plugins = getPlugins()) {
7603
7610
  assertNoObjectLinkConflicts(linkTypes);
7604
7611
  return linkTypes;
7605
7612
  }
7613
+ /**
7614
+ * Return the object type of the link type that claims a URL, such as
7615
+ * `code_change` for a pull request link from the GitHub plugin. The plugin
7616
+ * that owns the link type decides; core only reads its filters. A link type
7617
+ * that can open more than one type, such as a GitHub issue URL that can open
7618
+ * a pull request, names no type from the URL alone.
7619
+ */
7620
+ function readLinkObjectType(url, linkTypes = readObjectLinkTypes()) {
7621
+ if (!URL.canParse(url)) return void 0;
7622
+ const objectTypes = findObjectLinkType(linkTypes, new URL(url))?.objectTypes;
7623
+ return objectTypes?.length === 1 ? objectTypes[0] : void 0;
7624
+ }
7606
7625
  async function resolveWithLinkType(linkType, viewer, url) {
7607
7626
  if (!await linkType.canView(viewer, url)) return linkType.webPageFallback ? await resolveWithLinkType(webPageLinkType(), viewer, url) : null;
7608
7627
  const resolved = await linkType.resolve(viewer, url);
7609
7628
  if (!resolved) return null;
7610
7629
  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.`);
7630
+ if (!linkType.objectTypes.includes(object.objectType)) throw new Error(`Link type "${linkTypeName(linkType)}" returned a ${object.objectType} object.`);
7612
7631
  return {
7613
7632
  linkType,
7614
7633
  object: ownedObjectAnnotationSchema.parse({
@@ -7742,8 +7761,9 @@ async function countHistoryConversations(windowStartMs) {
7742
7761
  async function loadEvents(conversationIds) {
7743
7762
  const events = juniorConversationEvents;
7744
7763
  const isUserMessage = sql`${events.type} = 'user_message'`;
7764
+ const isToolResult = sql`${events.type} = 'tool_result'`;
7745
7765
  const message = sql`CASE
7746
- WHEN ${events.type} <> 'assistant_message' THEN NULL
7766
+ WHEN ${events.type} NOT IN ('assistant_message', 'tool_result') THEN NULL
7747
7767
  WHEN ${events.schemaVersion} >= 2 THEN (${events.payload}->>'message')::jsonb
7748
7768
  ELSE ${events.payload}
7749
7769
  END`;
@@ -7752,29 +7772,39 @@ async function loadEvents(conversationIds) {
7752
7772
  type: sql`${events.type}`,
7753
7773
  personInstruction: sql`CASE WHEN ${isUserMessage} THEN (${events.payload}->'provenance'->'actor'->>'userId') IS NOT NULL END`,
7754
7774
  stopReason: sql`(${message})->>'stopReason'`,
7775
+ toolName: sql`(${message})->>'toolName'`,
7755
7776
  startedAtMs: sql`(${message})->>'timestamp'`,
7756
7777
  modelId: sql`(${message})->>'model'`,
7757
7778
  cacheRead: sql`${events.payload}->'usage'->>'cacheRead'`,
7758
7779
  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);
7780
+ }).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);
7781
+ }
7782
+ async function loadChildAgents(conversationIds) {
7783
+ return await getDb().select({
7784
+ conversationId: juniorAgentInvocations.parentConversationId,
7785
+ createdAt: juniorAgentInvocations.createdAt,
7786
+ terminalAt: juniorAgentInvocations.terminalAt
7787
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, conversationIds));
7760
7788
  }
7761
7789
  /**
7762
7790
  * Replay the model calls of one Conversation the way the recorders in
7763
7791
  * `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.
7792
+ * tool wait. An idle period starts at a call that ends the Turn: a `stop`
7793
+ * call or an answer tool call that succeeded. A tool wait starts at any
7794
+ * other `toolUse` call, so no pair of calls is in both.
7766
7795
  *
7767
7796
  * Live recording measures from the start of the request that ended a Turn to
7768
7797
  * the start of the next recorded request. Here both times are the
7769
7798
  * `timestamp` of the stored assistant message, which Pi sets when it starts
7770
7799
  * the request. That is the closest stored time to the recorder's clock.
7771
7800
  */
7772
- function replayConversation(kind, events, nowMs) {
7801
+ function replayConversation(kind, events, children, nowMs) {
7773
7802
  const periods = [];
7774
7803
  const toolWaits = [];
7775
- const close = (idle, untilMs, next) => {
7804
+ const close = ({ waitsOnPendingWork, childRunning, ...idle }, untilMs, next) => {
7776
7805
  const gapMs = untilMs - idle.sinceMs;
7777
7806
  if (gapMs <= 0) return;
7807
+ if (waitsOnPendingWork && !childRunning && !next) return;
7778
7808
  const period = {
7779
7809
  ...idle,
7780
7810
  gapMs
@@ -7788,7 +7818,15 @@ function replayConversation(kind, events, nowMs) {
7788
7818
  let lastCallMs;
7789
7819
  let idle;
7790
7820
  let waiting;
7821
+ const answerEndings = /* @__PURE__ */ new Map();
7822
+ let toolUse;
7823
+ for (const event of events) {
7824
+ if (event.type === "assistant_message") toolUse = event.stopReason === "toolUse" ? event : void 0;
7825
+ const ending = event.type === "tool_result" && event.toolName ? ANSWER_TOOL_ENDINGS[event.toolName] : void 0;
7826
+ if (toolUse && ending) answerEndings.set(toolUse, ending);
7827
+ }
7791
7828
  for (const event of events) {
7829
+ if (event.type === "tool_result") continue;
7792
7830
  if (event.type === "user_message") {
7793
7831
  if (!inTurn) {
7794
7832
  userActor = event.personInstruction === true && kind !== "task";
@@ -7796,7 +7834,9 @@ function replayConversation(kind, events, nowMs) {
7796
7834
  }
7797
7835
  continue;
7798
7836
  }
7799
- if (event.stopReason !== "toolUse") inTurn = false;
7837
+ const answerEnding = answerEndings.get(event);
7838
+ const turnEnding = event.stopReason === "stop" ? "reply" : answerEnding;
7839
+ if (event.stopReason !== "toolUse" || answerEnding) inTurn = false;
7800
7840
  const startedAtMs = event.startedAtMs === null ? NaN : Number(event.startedAtMs);
7801
7841
  if (!Number.isFinite(startedAtMs)) continue;
7802
7842
  const next = {
@@ -7809,7 +7849,7 @@ function replayConversation(kind, events, nowMs) {
7809
7849
  gapMs: startedAtMs - waiting.sinceMs,
7810
7850
  next
7811
7851
  });
7812
- waiting = event.stopReason === "toolUse" ? {
7852
+ waiting = event.stopReason === "toolUse" && !answerEnding ? {
7813
7853
  sinceMs: startedAtMs,
7814
7854
  prefixTokens: next.cacheRead + next.cacheWrite
7815
7855
  } : void 0;
@@ -7819,11 +7859,18 @@ function replayConversation(kind, events, nowMs) {
7819
7859
  idle = void 0;
7820
7860
  if (lastCallMs !== void 0 && startedAtMs - lastCallMs > CONVERSATION_STATE_TTL_MS) endedTurns = 0;
7821
7861
  lastCallMs = startedAtMs;
7822
- if (event.stopReason === "stop") {
7862
+ if (turnEnding) {
7863
+ const waitsOnPendingWork = turnBehavior({
7864
+ kind,
7865
+ personInput: userActor
7866
+ }).promptMode === "automation";
7823
7867
  idle = {
7824
7868
  sinceMs: startedAtMs,
7825
7869
  segment: historySegment(userActor, endedTurns),
7826
- prefixTokens: cacheRead + cacheWrite
7870
+ turnEnding,
7871
+ prefixTokens: cacheRead + cacheWrite,
7872
+ waitsOnPendingWork,
7873
+ childRunning: waitsOnPendingWork && children.some((child) => child.createdAt.getTime() <= startedAtMs && (child.terminalAt === null || child.terminalAt.getTime() > startedAtMs))
7827
7874
  };
7828
7875
  endedTurns += 1;
7829
7876
  }
@@ -7834,6 +7881,15 @@ function replayConversation(kind, events, nowMs) {
7834
7881
  toolWaits
7835
7882
  };
7836
7883
  }
7884
+ function byConversation(rows) {
7885
+ const grouped = /* @__PURE__ */ new Map();
7886
+ for (const row of rows) {
7887
+ const list = grouped.get(row.conversationId) ?? [];
7888
+ list.push(row);
7889
+ grouped.set(row.conversationId, list);
7890
+ }
7891
+ return grouped;
7892
+ }
7837
7893
  function isQueryCanceled(error) {
7838
7894
  let current = error;
7839
7895
  for (let depth = 0; current && depth < 6; depth += 1) {
@@ -7860,21 +7916,19 @@ async function replayConversations(conversations, args) {
7860
7916
  const batch = conversations.slice(i, i + CONVERSATION_BATCH_SIZE);
7861
7917
  lastConversationId = batch.at(-1).conversationId;
7862
7918
  let rows;
7919
+ let children;
7863
7920
  try {
7864
- rows = await loadEvents(batch.map((row) => row.conversationId));
7921
+ const ids = batch.map((row) => row.conversationId);
7922
+ [rows, children] = await Promise.all([loadEvents(ids), loadChildAgents(ids)]);
7865
7923
  } catch (error) {
7866
7924
  if (!isQueryCanceled(error)) throw error;
7867
7925
  canceledBatches += 1;
7868
7926
  continue;
7869
7927
  }
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
- }
7928
+ const events = byConversation(rows);
7929
+ const childrenByParent = byConversation(children);
7876
7930
  for (const conversation of batch) {
7877
- const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], nowMs);
7931
+ const replayed = replayConversation(conversationKindFromRow(conversation), events.get(conversation.conversationId) ?? [], childrenByParent.get(conversation.conversationId) ?? [], nowMs);
7878
7932
  const inScanWindow = (period) => period.sinceMs >= windowStartMs;
7879
7933
  periods.push(...replayed.periods.filter(inScanWindow));
7880
7934
  toolWaits.push(...replayed.toolWaits.filter(inScanWindow));
@@ -8247,15 +8301,49 @@ function treeAwaitsAuthorization(rootConversationId) {
8247
8301
  and ${awaitsAuthorization(tree.conversationId)}
8248
8302
  )`;
8249
8303
  }
8304
+ // src/api/user-settings.ts
8305
+ const userPreferencesSchema = z.object({
8306
+ /** Show the new dashboard UI instead of the current one. */
8307
+ experimentalUi: z.boolean().optional() });
8308
+ /** Settings of a user who has not changed any. */
8309
+ const DEFAULT_USER_SETTINGS = {
8310
+ autoArchiveDefault: false,
8311
+ autoArchiveGraceHours: 24,
8312
+ experimentalUi: false
8313
+ };
8314
+ const userSettingsColumns = {
8315
+ autoArchiveDefault: juniorUsers.autoArchiveDefault,
8316
+ autoArchiveGraceHours: juniorUsers.autoArchiveGraceHours,
8317
+ preferences: juniorUsers.preferences
8318
+ };
8319
+ function toUserSettings(row) {
8320
+ const { preferences, ...columns } = row;
8321
+ const parsed = userPreferencesSchema.parse(preferences);
8322
+ return {
8323
+ ...columns,
8324
+ experimentalUi: parsed.experimentalUi ?? DEFAULT_USER_SETTINGS.experimentalUi
8325
+ };
8326
+ }
8327
+ /** Read the user's dashboard settings. */
8328
+ async function readUserSettings(userId) {
8329
+ const [user] = await getDb().select(userSettingsColumns).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
8330
+ return user && toUserSettings(user);
8331
+ }
8332
+ /** Save changed dashboard settings and return the saved settings. */
8333
+ async function updateUserSettings(userId, settings) {
8334
+ const { experimentalUi, ...columns } = settings;
8335
+ const preferences = experimentalUi === void 0 ? {} : { experimentalUi };
8336
+ const [user] = await getDb().update(juniorUsers).set({
8337
+ ...columns,
8338
+ preferences: sql`${juniorUsers.preferences} || ${JSON.stringify(preferences)}::jsonb`,
8339
+ updatedAt: /* @__PURE__ */ new Date()
8340
+ }).where(eq(juniorUsers.id, userId)).returning(userSettingsColumns);
8341
+ return user && toUserSettings(user);
8342
+ }
8250
8343
  // src/api/conversations/auto-archive.ts
8251
8344
  const HOUR_MS = 36e5;
8252
8345
  /** Participant rows checked per page. A run reads pages until none remain. */
8253
8346
  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
8347
  function runOptsIn(run) {
8260
8348
  return run.kind === "scheduled" ? sql`coalesce(${juniorConversationParticipants.autoArchive}, ${juniorUsers.autoArchiveDefault}) = true` : sql`${juniorConversationParticipants.autoArchive} is distinct from false`;
8261
8349
  }
@@ -8416,7 +8504,7 @@ async function runAutoArchiveSweep(args) {
8416
8504
  */
8417
8505
  async function archiveViewerDoneConversations(viewer) {
8418
8506
  const { archived } = await archiveUserDoneConversations({
8419
- graceHours: (await readUserAutoArchiveSettings(viewer.id))?.autoArchiveGraceHours ?? DEFAULT_AUTO_ARCHIVE_SETTINGS.autoArchiveGraceHours,
8507
+ graceHours: (await readUserSettings(viewer.id))?.autoArchiveGraceHours ?? 24,
8420
8508
  kind: "manual",
8421
8509
  now: /* @__PURE__ */ new Date(),
8422
8510
  userId: viewer.id
@@ -8440,25 +8528,6 @@ async function setConversationAutoArchive(viewer, conversationId, autoArchive) {
8440
8528
  });
8441
8529
  return { autoArchive };
8442
8530
  }
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
8531
  // src/chat/review-items/reply-match.ts
8463
8532
  const MATCH_CONFIDENCE_THRESHOLD = .7;
8464
8533
  /** A slow decision keeps the items open instead of delaying the close. */
@@ -8839,7 +8908,7 @@ function resolveAllowedDomains(allowedDomains) {
8839
8908
  */
8840
8909
  function assertNoLegacyAllowedDomains(dashboardOptionKeys) {
8841
8910
  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");
8911
+ if (process.env["JUNIOR_DASHBOARD_GOOGLE_DOMAINS"]?.trim()) throw new Error("JUNIOR_DASHBOARD_GOOGLE_DOMAINS was removed; set JUNIOR_ALLOWED_DOMAINS instead");
8843
8912
  }
8844
8913
  /** Return whether a verified domain may use Junior. An empty list allows all. */
8845
8914
  function isAllowedDomain(domain, allowedDomains) {
@@ -9846,8 +9915,9 @@ function format(text, provider) {
9846
9915
  * as GitHub reference and `@login` links that show as object cards. A reply
9847
9916
  * posted to a provider, and the summary of an Event from one, is that
9848
9917
  * 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.
9918
+ * Slack, and not an account of a plugin's provider. A person's message gets
9919
+ * the same links, so a typed `owner/repo#12` shows the card that a pasted
9920
+ * URL shows. Raw Event text shows as written.
9851
9921
  */
9852
9922
  function formatConversationEventText(event) {
9853
9923
  const { data } = event;
@@ -9871,13 +9941,15 @@ function formatConversationEventText(event) {
9871
9941
  } : item) } : void 0
9872
9942
  }
9873
9943
  };
9874
- return data.role === "assistant" && data.text !== void 0 ? {
9944
+ if (data.text === void 0 || data.role === "system") return event;
9945
+ const text = data.role === "assistant" ? wrapBareSlackUserIds(data.text) : data.text;
9946
+ return {
9875
9947
  ...event,
9876
9948
  data: {
9877
9949
  ...data,
9878
- text: format(wrapBareSlackUserIds(data.text))
9950
+ text: format(text)
9879
9951
  }
9880
- } : event;
9952
+ };
9881
9953
  }
9882
9954
  // src/api/conversations/mentions.ts
9883
9955
  /** Text in one event that the dashboard renders with mentions. */
@@ -11082,6 +11154,23 @@ async function readConversationFeedBriefs(db, conversationIds) {
11082
11154
  }).from(juniorConversations).innerJoinLateral(latest, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
11083
11155
  return new Map(rows.map(({ conversationId, ...brief }) => [conversationId, conversationFeedBriefSchema.parse(brief)]));
11084
11156
  }
11157
+ // src/api/page-cursor.ts
11158
+ /**
11159
+ * Encode the position after the last row of a page as an opaque `cursor`
11160
+ * value. The cursor only moves a position inside a list that access already
11161
+ * scopes, so it carries no signature.
11162
+ */
11163
+ function encodePageCursor(schema, position) {
11164
+ return Buffer.from(JSON.stringify(schema.parse(position)), "utf8").toString("base64url");
11165
+ }
11166
+ /** Decode a `cursor` query value with its schema, or answer 400. */
11167
+ function decodePageCursor(schema, value, message) {
11168
+ try {
11169
+ return schema.parse(JSON.parse(Buffer.from(value, "base64url").toString("utf8")));
11170
+ } catch (error) {
11171
+ throwApiError(400, message, error);
11172
+ }
11173
+ }
11085
11174
  // src/api/conversations/feed-cursor.ts
11086
11175
  /**
11087
11176
  * Position after the last row of one feed page. `at` keeps the microseconds
@@ -11094,18 +11183,11 @@ const conversationFeedCursorSchema = z.object({
11094
11183
  }).strict();
11095
11184
  /** Encode the feed position after one row for `nextCursor`. */
11096
11185
  function encodeConversationFeedCursor(cursor) {
11097
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
11186
+ return encodePageCursor(conversationFeedCursorSchema, cursor);
11098
11187
  }
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
- */
11188
+ /** Decode a feed `cursor` query value. */
11103
11189
  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
- }
11190
+ return decodePageCursor(conversationFeedCursorSchema, value, "Invalid conversation feed cursor.");
11109
11191
  }
11110
11192
  // src/api/conversations/list.ts
11111
11193
  const CONVERSATION_FEED_LIMIT = 50;
@@ -11476,4 +11558,4 @@ function viewerWebMessages(messages, viewer) {
11476
11558
  }] : [];
11477
11559
  });
11478
11560
  }
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 };
11561
+ 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 };