@sentry/junior 0.321.0 → 0.322.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 (65) hide show
  1. package/dist/{adapter-BkDQYdg6.js → adapter-CKtEUuWD.js} +23 -2
  2. package/dist/{admin-XS3G9BOj.js → admin-BGOiUGwR.js} +1 -1
  3. package/dist/{agent-CL9ZkOgx.js → agent-OUkEw6Bv.js} +272 -1647
  4. package/dist/{agent-status-Bq_AIpyp.js → agent-status-C_HHxO_d.js} +1 -10
  5. package/dist/{agent-update-delivery-t0bXEgPs.js → agent-update-delivery-H6mnPI4q.js} +4 -4
  6. package/dist/api/schema.d.ts +98 -6
  7. package/dist/api/schema.js +6 -6
  8. package/dist/api.js +81 -36
  9. package/dist/{app-CwFRvmEH.d.ts → app-BK_vhZIq.d.ts} +1 -1
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +85 -48
  12. package/dist/{change-record-CRuG9Mu3.d.ts → change-record-DdrJxahk.d.ts} +26 -10
  13. package/dist/{channel-access-BUHB0saC.js → channel-access-DRhVJIuQ.js} +1 -1
  14. package/dist/{chat-core-engine-DuBaPbqK.js → chat-core-engine-El308gYr.js} +5 -10
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +4 -4
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +3 -3
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.js +2 -2
  21. package/dist/{continue-in-slack-D9naZmqM.js → continue-in-slack-DYl631oM.js} +3 -3
  22. package/dist/{conversation-feed-B1_1NJc8.js → conversation-feed-BUaMmSLi.js} +1 -1
  23. package/dist/{conversation-privacy-C0mixZKx.js → conversation-privacy-DR_j5Tqf.js} +1 -1
  24. package/dist/{create-CLV0M1vw.js → create-ZkI-_JAs.js} +2 -2
  25. package/dist/{credential-sync-DL9r-ry5.js → credential-sync-Bo6_FtCI.js} +12 -12
  26. package/dist/{db-CbURDbaB.js → db-RDpWIeRK.js} +1733 -213
  27. package/dist/{deployment-D9uPRDMD.js → deployment-CeKaP0ZJ.js} +1 -1
  28. package/dist/{html-l4hKICAL.js → html-BMv4fAPu.js} +5 -5
  29. package/dist/instrumentation.js +2 -2
  30. package/dist/{list-cGaO9_Hf.js → list-CuLf7Ob2.js} +38 -35
  31. package/dist/{logging-CqgOoICc.js → logging-BQsfrLHl.js} +1 -1
  32. package/dist/{markers-BtUv4-oc.js → markers-Bh0vqJ5k.js} +3178 -1748
  33. package/dist/nitro.d.ts +1 -1
  34. package/dist/nitro.js +3 -4
  35. package/dist/{oauth-callback-server-C3GxhsuB.js → oauth-callback-server-BxuN0Jqz.js} +2 -2
  36. package/dist/{oauth-relay-BGm6sLCB.js → oauth-relay-vyG2gOwY.js} +1 -1
  37. package/dist/{profile-bLo0h7Le.js → profile-DiAB4QfT.js} +31 -6
  38. package/dist/{prompt-CX29OGO9.js → prompt-5PDkRQ1K.js} +2 -1
  39. package/dist/{reports-DeDCCu_H.js → reports-CbqB7unq.js} +2 -2
  40. package/dist/{resolve-D9RKNH3v.js → resolve-C7e0pwuP.js} +5 -5
  41. package/dist/{result-BFBwK1M2.js → result-D_D-2Adp.js} +5 -5
  42. package/dist/{runner-DNdoVQg8.js → runner-CCVTdp0x.js} +7 -7
  43. package/dist/{sandbox-egress-signals-BBcCiEhm.js → sandbox-egress-signals-D4OKOFgy.js} +1 -1
  44. package/dist/{schema-RzsplzdI.js → schema-CmPO8BfI.js} +50 -12
  45. package/dist/{service-account-B7E7OIFP.js → service-account-CeWsFrBi.js} +2 -2
  46. package/dist/{skills-DMJsS5e4.js → skills-DfbOjWxl.js} +5 -5
  47. package/dist/{slack-conversation-unfurl-EWYTnBZI.js → slack-conversation-unfurl-BxF0Yb3-.js} +10 -9
  48. package/dist/{system-prompt-table-C886lsT9.js → system-prompt-table-DySHMtu0.js} +15 -15
  49. package/dist/{topics-DxuKurCX.js → topic-ChZe9WPj.js} +6 -1
  50. package/dist/{engine-context-BP0h6u4m.js → turn-ended-DQ10G3in.js} +11 -845
  51. package/dist/{types-CGgQ3-Bb.js → types-BWAgOJtR.js} +95 -70
  52. package/dist/{user-customization-CvfuY9Eo.js → user-customization-DNzu_r1x.js} +10 -1
  53. package/dist/{users-DBrcQl47.js → users-BmZlg_ci.js} +13 -7
  54. package/dist/{validation-CofUHWqz.js → validation-BU4tXvH3.js} +1 -1
  55. package/dist/{version-D_vbXyNw.js → version-D9yLYOBu.js} +1 -1
  56. package/dist/version.js +1 -1
  57. package/dist/{worker-buhFcpl9.js → worker-C7EDSL3d.js} +4 -4
  58. package/migrations/20261127184420_question_answerer/migration.sql +36 -0
  59. package/migrations/20261127184420_question_answerer/snapshot.json +108 -0
  60. package/migrations/20261127224730_inbox_item_close_action/migration.sql +1 -0
  61. package/migrations/20261127224730_inbox_item_close_action/snapshot.json +42 -0
  62. package/package.json +6 -6
  63. package/skills/design-automation-skill/SKILL.md +1 -1
  64. package/dist/storage-XD0lB4Gk.js +0 -273
  65. package/dist/topic-B2EWKKBT.js +0 -6
@@ -1,31 +1,30 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $ as resolveGatewayModel, B as getSlackBotToken, C as parseActorUserId, D as parseSlackChannelReferenceId, E as parseSlackChannelId, H as getSlackClientSecret, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, R as getChatConfig, S as isUserActor, U as getSlackSigningSecret, V as getSlackClientId, X as toPiReasoningLevel, Y as TURN_REASONING_LEVELS, _ as createActor, a as getStateValues, b as isActorUserId, c as acquireActiveLock, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as getStateAdapter, k as parseSlackUserId, l as fenceLock, o as setStateValues, u as withLock, v as createSlackActor, y as createSlackResumeActor } from "./adapter-BkDQYdg6.js";
3
- import { A as toOptionalString, E as runWithLogAttributes, S as summarizeMessageText, T as withSpan, _ as serializeGenAiAttribute, a as getActiveTraceContext, b as setSpanStatus, c as getLogContextAttributesForSpan, d as logError, f as logException, g as runBestEffort, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, l as getTracePropagationHeaders, m as logWarn, o as getActiveTraceId, p as logInfo, r as extractGenAiUsageAttributes, t as createChatSdkLogger, u as logAudit, v as setSentryUser, w as withLogContext, x as setTags, y as setSpanAttributes } from "./logging-CqgOoICc.js";
4
- import { $a as usdToMicroUsd, $d as deleteMcpAuthSession, $i as createSandboxCapability, $l as isThread, $n as resolveEventMentions, $s as isDmChannel, $u as GEN_AI_PROVIDER_NAME, Aa as automationDefinition, Ad as renderJuniorNativeConversationEvent, Ai as removeReactionFromMessage, Al as parseDashboardPersonLink, An as canJoinTurn, As as isPublicConversation, At as injectContinuationToolName, Ba as linkAutomationRunConversation, Bc as getOpenInboxItemBySubject, Bf as rootConversationIsArchived, Bi as slackMentionedUserIds, Bo as turnEvents, Bp as juniorSpaces, Ca as getEventAutomation, Cd as isProviderRefusal, Cf as toMcpProviderError, Ci as addReactionToMessage, Cl as getDashboardLinkFilter, Cp as juniorConversationEventLexemes, Cs as conversationAncestorsOrSelf, Cu as registeredResourceTypeSchema, D as createSqlStore, Da as setEventAutomationStatus, Dl as getDashboardTaskLink, Dn as releaseInboundMessage, Do as starterWatchId, Dp as juniorConversationEvents, Du as isToolInputError, E as latestUserMessageQuery, Ea as saveEventAutomation, Ef as getOAuthProviderErrorAttributes, Ei as openSlackDirectMessage, El as getDashboardSpaceLink, Eo as publishAgentUpdate, Es as loadAnnotationLabeler, Et as getRegistrations, Eu as ToolInputError, F as destinationUpsertFromDestination, Fc as closeReadReplyNotice, Fi as SLACK_USER_MENTION_RE, Fn as readInboundMessageSender, Fo as getWatch, Fp as juniorAttachmentUploads, Fs as defaultTimezone, Ft as CHILD_AGENT_KINDS, G as conversationStatusSql, Ga as readAutomationExecutions, Gf as requireSlackDestination, Gi as createPluginState, Gp as juniorDestinations, Gr as QUEUE_SIGNATURE_MAX_AGE_MS, Gu as storeConversationEmbedding, Ha as readAutomationExecutionStatusDays, Hd as serviceAccountAllows, Hf as nextDetailVersion, Ht as appendAndEnqueueExclusiveInboundMessage, I as upsertDestination, Ia as automationRevision, Ii as escapeSlackMrkdwnText, In as isEventMailboxMetadata, Io as isQuietEvent, Ip as juniorAttachments, It as PARENT_AGENT_TARGET, Iu as SEARCHABLE_EVENT_TYPES, J as executionIsActive, Ja as readAutomationTitlesByConversationId, Jf as rootSpaceIdSql, Ji as createPluginModel, Jl as deliversFinalText, Jo as verifyTimerWatchCredentialSubject, Jr as getQueueProvider, Js as getFilePermalink, Ju as completeText, Ka as readAutomationRowStats, Kc as updateInboxItemContent, Kf as sameDestination, Ki as createPluginDecider, Kl as fuseRankedLists, Kp as guardedCosineDistance, Kr as signQueueMessage, Ks as SlackActionError, Ku as completeDecision, L as parseSessionSource, La as requireAutomationRevision, Lc as closeInboxItem, Lf as hasAgentTurnUsage, Li as formatSlackLink, Ln as createSlackInboxItemToolServices, Lp as juniorMessageAttachments, Ls as resolveUserTimezone, Lt as agentNameSchema, Lu as callsToolSql, Ma as listAutomationVersions, Mi as uploadFilesToConversation, Mo as createWatch, Mt as makeStructuredToolOutput, Mu as lexemesSql, Na as readAutomationVersion, Nd as getAppContext, Nf as addAgentTurnUsage, No as deliverWatch, Np as juniorCodeChanges, Nt as findChildAgentConversationId, Nu as searchedEventTextSql, O as withConversationMutationLock, Oc as readCachedLinkedHandle, Ol as isDashboardLink, Oo as cancelSubscriptions, Or as leaveEndsAccess, Os as readConversationMetadata, Pa as sameDefinitionValue, Pf as agentTurnCostUsd, Pn as readParentMessage, Po as findMatchingWatches, Pp as juniorCodeRepositories, Pu as seqIn, Qd as PluginMcpClient, Qf as topLevelConversation, Qi as basePluginContext, Ql as isPersonInput, Qn as sendSlackReply, Qo as isConversationDeliveryPaused, Qs as isConversationScopedChannel, Qu as NoAudioError, Ra as emptyAutomationRunWindows, Rc as dismissOpenInboxItems, Rf as isLeadConversation, Ri as normalizeSlackStatusText, Ro as listWatches, Rp as juniorConversations, Rr as getVercelConversationWorkQueue, Rs as lookupSlackUser, Ru as eventExcerpt, S as setArchivedAt, Sf as getMcpProviderErrorAttributes, Si as notifyAutomationBlocked, So as workspaceSnapshotWatch, Sp as juniorConversationParticipants, Sr as canAccessConversation, Ss as upsertPluginAnnotation, Su as registeredEventTypeSchema, Ta as parseEventAutomationRow, Td as getGatewayApiKey, Tf as fetchWithBoundedOAuthErrorBodies, Ti as getSlackMessagePermalink, Tr as canReadConversation, Ts as conversationSubtreeColumns, Tt as getPlugins, Tu as requireValidEventTrigger, Ua as readAutomationExecutionStatusHours, Uc as ownerConversationId, Ud as serviceAccountOnly, Uf as touchConversationDetail, Ut as appendAndEnqueueInboundMessage, Uu as createConversationEmbedder, Va as readAutomationExecutionByConversationId, Vc as insertInboxItem, Vf as conversationDetailTouch, Vp as juniorIdentities, Vu as isEventEmbeddingsEnabled, Wa as readAutomationExecutionSummaries, Wc as searchInboxItems, Wf as createSlackDestination, Wi as pluginMcpContext, Wo as createSlackDirectCredentialSubject, Wp as juniorUsers, Wu as embedConversationQuery, Xd as getMcpServiceAccountCredentials, Xi as createPluginConversationEvents, Xl as hasConversationMetadata, Xo as JUNIOR_THREAD_STATE_TTL_MS, Xr as buildSentryEventUrl, Xs as getSlackClient, Xu as searchWeb, Y as conversationKindFromRow, Yd as createMcpServiceAccountClientProvider, Yi as createPluginModelCostRecorder, Yl as dispatchInstructionsInvokeSkills, Ys as getHeaderString, Yt as claimInboundMessage, Yu as generateImages, Zc as pluginSubjectKind, Zd as McpAuthorizationRequiredError, Zi as renderPluginConversationEvent, Zn as resolveSlackReplyTarget, Zs as isConversationChannel, Zu as transcribeFromUrl, _d as ProviderError, _f as McpProviderError, _i as markDispatchAwaitingResume, _s as createPluginAnnotations, _u as eventNamespaceSchema, a as getDb, aa as createPluginCache, ac as sleep$1, ad as createCache, af as getMcpStoredOAuthCredentials, an as getConversationWorkState, au as turnBehavior, b as conversationDescendants, ba as createEventAutomation, bc as saveActorAvatar, bd as findProviderError, bf as getMcpAwareErrorType, bi as markDispatchFailed, bo as WORKSPACE_SNAPSHOT_READY_EVENT, bt as requireInboxItemAssignees, bu as registeredEventMatchSchema, ca as blockScheduledAutomation, cc as createPluginUsers, cd as estimateMessagesTokens, cf as putMcpServerSessionId, cl as userAvatarUrlsFromIdentities, co as activeParticipantUserIds, cr as sendVercelPluginTask, cs as codeChangeUrl, dc as readActorIdentity, dd as textCharsForTokens, di as getDispatchInputMessageId, do as resolveAssignees, ds as assertNoObjectLinkConflicts, du as isEventAuthorId, ec as isSlackRequestTimeout, ed as GEN_AI_SERVER_ADDRESS, er as createPluginEventPublisher, et as canAgentChangeInboxItem, eu as isTopLevel, f as eventFromRow, fa as parseScheduledAutomationRow, fc as readIdentityById, fd as readImageDimensions, fi as getDispatchRecord, fn as requestConversationWork, fo as getEventCatalog, fs as findObjectLinkType, fu as isEventConversationMessage, gd as isCompactionSummaryText, gr as createPluginInboxItems, gs as annotationSubject, gt as isPluginInboxItem, hd as hasCompactedConversationContext, hf as resolvePluginHeaderEnvRefs, hi as isTerminalDispatchStatus, hs as CORE_ANNOTATION_PLUGIN, hu as describeRegisteredEventTrigger, i as getConversationStore, ia as runNonInteractiveCommand, ic as withSlackRetries, if as getMcpServerSessionId, ii as resolveTurnResumeRouting, il as identityAvatarUrl, io as fallbackShortTitle, ir as startedTaskDefinition, jl as parseDashboardTaskLink, jn as canShareTurn, jo as createTimerWatch, jr as readableSlackTeamId, js as resolveRootVisibility, jt as juniorToolOutputSchema, ju as indexEndedTurnEvents, k as locationFromRow, kc as readCachedUserByEmail, ki as postSlackMessage, kl as parseDashboardConversationLink, kn as withIdleConversation, ko as cancelWatch, kr as readConversationAccessFromSql, ks as writeConversationMetadata, la as createScheduledAutomation, ld as estimateRequestOverheadTokens, lf as putMcpStoredOAuthCredentials, li as getDispatchConversationId, ll as userAvatarUrlsFromJoinedPhotos, lo as automationCreatorUserId, lr as queueCallback, lu as EVENT_SYSTEM_ACTOR, ma as saveScheduledAutomation, md as COMPACTION_SUMMARY_PREFIX, mo as requireSlackChannelMessageScope, mp as juniorStats, mr as createPluginConversationChanges, ms as ANNOTATION_SUBJECT_KINDS, mu as automationEventCatalog, n as getConversationEventStore, na as buildCommandScript, nc as readPrivateSlackFile, nn as dropPendingMessages, nt as canReadInboxItem, nu as postsRunNotices, o as getSqlExecutor, oa as getConfigDefaults, od as requestPrefixAttributes, of as patchMcpAuthSession, oi as claimDispatchMailboxAppend, oo as resolveTaskTitle, or as pluginTaskId, os as readSubjectLinks, ou as watcherStartedConversation, pa as readScheduledAutomation, pc as readIdentityByIdFromSql, pd as gatewayRoutingAttributes, pi as getDispatchTurnId, pp as juniorAutomations, pr as createPluginTurnEventReader, ps as linkTypeName, pu as CORE_EVENT_NAMESPACE, q as conversationWaitsOnUserSql, qa as readAutomationRuns, qf as isLeadSql, qi as createPluginEmbedder, ql as canMoveToSpace, qp as juniorArtifacts, qr as verifyQueueMessage, qs as downloadPrivateSlackFile, qu as completeObject, r as getConversationMessageSearchStore, ra as buildNonInteractiveShellScript, rc as streamPrivateSlackFile, rf as getMcpAuthSession, ri as resolveConversationRouting, rl as hasUserPhoto, rn as ensureConversationWake, rr as createPluginTaskStarter, rs as resolveAnnotationFilter, ru as promptModeTurnTools, sa as truncateStatusText, sd as claudeMaxImageSize, sf as putMcpAuthSession, si as confirmDispatchMailboxAppend, sl as readUserAvatarUrls, so as EVERYONE_ASSIGNEE, sr as pluginTaskParamsSchema, ss as subjectKey, su as EVENT_AUTHOR_ID, ta as withPluginHookSpan, tc as normalizeSlackConversationId, tf as deleteMcpServerSessionId, ti as runWithSlackInstallation, ts as searchConversations, tu as parentResultActor, ua as deleteScheduledAutomation, ud as estimateTextTokens, ui as getDispatchIdForConversation, uo as resolveAssignee, up as juniorAutomationRuns, ur as getTurnRequestDeadline, va as blockEventAutomation, vc as SYSTEM_IDENTITY_ID, vd as createAssistantProviderError, vf as McpServiceAccountRequiredError, vi as markDispatchBlocked, vo as slackChannelMessageTrigger, vs as createPluginConversationAnnotations, vt as questionSubject, vu as eventWatchUnavailable, wa as listDeletedEventAutomationsCreatedBy, wd as isProviderRetryError, wf as OAuthProviderError, wl as getDashboardPersonLink, wo as agentWatch, wp as juniorConversationEventEmbeddings, wr as canInviteToConversation, ws as conversationSubtree, wu as requireEventIdentifier, x as readConversationTrees, xa as deleteEventAutomation, xd as getProviderErrorAttributes, xf as getMcpAwareTelemetryMessage, xi as markDispatchRunning, xl as getDashboardConversationLink, xn as hasConversationStop, xo as workspaceSnapshotFinishedEvent, xp as juniorConversationReadPositions, xr as createPluginCodeChanges, xs as replaceAnnotationSubjectId, xt as requireInboxItemLinks, xu as registeredEventTriggerProblems, y as conversationAncestors, yc as resolveActorIdentityId, yd as createProviderError, yf as McpToolError, yi as markDispatchCompleted, yo as WORKSPACE_SNAPSHOT_FAILED_EVENT, ys as listConversationAnnotations, yt as readInboxItemAgentScope, yu as hasEventCatalogEntries, zc as getInboxItem, zi as slackMention, zp as juniorSpaceConfigurations, zs as lookupSlackUserNames, zu as excerptTerms } from "./db-CbURDbaB.js";
5
- import { $ as deleteWebAuthorization, $n as normalizeConversationText, $r as ToolActionReviewUnavailableError, $t as listWorkspaceNamesByRepository, A as resumeForPersonInput, An as recordAgentsInstructionsUpdated, Ar as recordTurnSummary, At as readTaskInstructions, B as turnInputFactsFromConversationMessage, Br as TurnToolCallLimitExceededError, Bt as isCooperativeTurnYieldError, C as getChildAgentLockName, Cn as writeAgentHistory, Cr as pauseLostWorkerTurn, Ct as buildPromptInput, Dn as loadConversationProjection, Dr as failTurnRecord, Dt as loadPromptTurnContext, E as isInheritedForkHistory, En as loadConnectedMcpProviders, Er as completeTurnRecord, Et as instructionForInputs, Fn as recordGuardianActionReviewed, Ft as ConversationTurnBoundaryError, G as getTurnUserSlackMessageTs, Gn as resolveConversationTitle, Gr as captureTurnFailure, Gt as markTurnFailed, H as getTurnUserMessage, Hn as persistConversationMessageWindow, Hr as createTurnLimitGate, Ht as isTurnInputDeferredError, I as getEventBatchDelayMs, In as recordMcpProviderConnected, Ir as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, It as CooperativeTurnYieldError, J as getPersistedThreadState, Jn as estimateConversationMessagesTokens, Jr as requireTurnFailureEventId, Jt as buildDeterministicTurnId, K as getLocationConfigurationService, Kr as finalizeFailedTurnReplyWithEvent, Kt as startActiveTurn, L as listActiveMailboxTurns, Ln as recordSkillLoaded, Lr as TURN_LIMIT_WRAP_UP_MESSAGE, Lt as TurnInputCommitLostError, Mr as getTurnLifecycle, N as stopConversationTree, Nn as recordAuthorizationCompleted, Nr as loadTurnStart, Nt as saveUserCustomization, O as enqueueAutomatedInput, On as loadConversationSkillNames, Or as getTurnRecord, Ot as turnRequestText, P as completeCancelledConversationTurn, Pn as recordAuthorizationRequested, Pt as addConversationNote, Q as createWebAuthorization, Qn as markConversationMessage, Qr as ToolActionReviewLimitError, Qt as getWorkspaceByName, R as resolveMailboxTurnWork, Rn as recordSubscribedReplyRoute, Rr as TurnBudgetExceededError, Rt as TurnInputDeferredError, Sn as withAgentRequest, Sr as lostWorkerBeforeFirstSave, St as assemblePrompt, Tn as commitMessages, Tr as abandonTurnRecord, Tt as instructionActorFor, U as getTurnUserMessageId, Un as persistConversationMessages, Ur as isTurnExecutionLimitExceededError, Ut as markTurnClosed, V as legacyWebMailboxMetadataSchema, Vn as hydrateConversationMessages, Vr as buildTurnErrorResponse, Vt as isTurnInputCommitLostError, W as getTurnUserReplyAttachmentContext, Wr as buildTurnFailureResponse, Wt as markTurnCompleted, X as persistThreadStateById, Xn as isHumanConversationMessage, Xr as isCutOffStopReason, Xt as deleteWorkspace, Y as persistThreadRuntimeState, Yn as getConversationMessageSlackTs, Yr as buildTurnResult, Yt as createWorkspace, Z as coerceThreadConversationState, Zn as latestConversationMessageSeq, Zr as ToolActionRejectedError, Zt as getWorkspace, _ as dropWaitingParentMessages, _i as configValueSchema, _n as renderAgentsInstructions, _r as canReusePendingAuthLink, _t as resolveBotSlackTeamId, a as listDescendantAgents, ai as ROOT_LINE_BREAK, an as workspaceRepoCheckoutPath, ar as calculateContextCompactionTargetTokens, at as addQuietEventNote, b as readAgentConfig, bn as foldSystemMessages, br as continuableMessages, bt as loadThreadContextCursor, ci as CODE_MODE_CALL_STATUS_TEXT, cn as setWorkspaceSnapshot, cr as getAgentContextInputLimitTokens, ct as eventBatchMessageMeta, d as isStopResult, di as formatProviderLabel, dn as buildDeploymentSystemPrompt, dr as createPluginAuthOrchestration, ei as createToolActionReview, en as listWorkspaces, er as recordDeliveredAssistantMessage, f as readChildConversationSender, fn as AGENTS_REMOVAL_NOTICE, fr as authorizationId, g as commitParentMessageFork, gi as validateConfigValue, gn as readRepositoryInstructions, gr as abandonReplacedPendingAuth, gt as resolveEventAuthor, h as childAgentTurnOptions, hi as validateConfigKey, hn as findVisibleAgentsInstructions, hr as AuthorizationPauseError, i as listChildAgents, ii as RISK_LEVELS, in as tryWorkspaceRepoCheckoutPath, ir as upsertConversationMessage, it as EVENT_WAIT_MS, jn as recordAttachmentsDelivered, jr as ConversationTurnLifecycleService, k as getConversationStoppedAtMs, kr as listTurnSummaries, kt as withoutSavedSteeringMessages, l as withSenderActors, li as persistWithRetry, ln as setWorkspaceSnapshotBuild, lr as createPluginEgress, lt as renderEventBatchInputs, mi as projectConversationEvents$1, mn as buildAgentsInstructionsMessage, mr as AuthorizationFlowDisabledError, ni as getToolActionRejectionMarker, nn as updateWorkspace, nr as trimConversationMessages, nt as loadInboxItemInput, oi as USER_AUTHORIZATION_LEVELS, on as invalidateReadySnapshot, or as getAgentBackgroundCompactionMarkTokens, pn as AGENTS_REPLACEMENT_NOTICE, pr as AuthPausePersistenceError, q as getPersistedSandboxState, qn as conversationAuthorDisplayName, qr as getAgentTurnDiagnosticsAttributes, qt as buildDeterministicAssistantMessageId, r as listAgentRelatives, ri as restoreToolActionRejections, rn as WorkspaceValidationError, rr as turnHasReply, rt as savedInputInstruction, si as CODEMODE_TOOL_NAME, sn as loadSnapshotsForProfile, sr as getAgentContextCompactionTriggerTokens, st as enqueueEventNotification, t as recordChildAgentEnded, ti as reviewToolActions, tr as renderConversationMessageLine, tt as eventInboxItemInputs, u as isChildAgentEvent, ui as deliverOAuthAuthorization, un as isExperimentalFeatureEnabled, ur as PluginCredentialFailureError, ut as timerWatchCredentialSubject, v as isParentMessageAuthor, vn as showsAgentsInstructions, vr as clearPendingAuth, vt as isHeldInputMessage, wn as commitAcceptedReply, wr as saveTurnCheckpoint, wt as buildSteeringPiMessage, xn as readAgentHistory, xr as loadTurnCheckpoint, xt as loadThreadContextTrimFloor, yn as foldLeadingSystemMessages, yt as withHeldInput, z as sourceFromTurnInput, zn as recordToolExecutionStarted, zr as TurnSliceLimitExceededError, zt as getConversationTurnBoundaryError } from "./markers-BtUv4-oc.js";
6
- import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-DMJsS5e4.js";
7
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C0mixZKx.js";
8
- import { A as retainRuntimeTurnContext, B as authorAttrs, C as instructionTextForProjection, D as isToolResultError, E as isStandaloneRuntimeContextMessage, G as mapBounded, H as renderDataTag, M as trimTrailingAssistantMessages, N as CAPABILITY_SECTION_TAG, O as isToolResultMessage, P as REQUEST_CONTEXT_SECTION_TAG, R as unwrapCurrentInstruction, S as hasTurnInput, T as isContinuablePiBoundary, V as readParentAgentTask, W as renderThreadContext, _ as extractAssistantText, a as SANDBOX_COMMAND_PATH, b as getUserMessageInstructionText, c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, f as sandboxSkillDir, h as createPluginLogger, i as ATTACHMENT_DIR, j as stripRuntimeTurnContext, k as normalizeToolNameFromResult, l as SANDBOX_SCRATCH_ROOT, m as sandboxSkillPathResolution, o as SANDBOX_DATA_ROOT, p as sandboxSkillFile, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT, u as SANDBOX_SKILLS_ROOT, v as getPiMessageRole, w as isAssistantMessage } from "./prompt-CX29OGO9.js";
9
- import { $t as automationInstructionToolSchema, Bn as TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE, Cn as userInputRequestSchema, Ct as instructionActors, Dn as automationTaskSchema, En as automationTaskDescription, Fn as isValidTimeZone, Gt as resolveMessageCards, J as conversationReportMessageEventSchema, Kt as automationCardStatus, Ln as apiErrorSchema, Mn as getFirstRunAtMs, On as automationTaskText, Pn as getZonedDateTimeParts, Qt as automationContextToolSchema, Sn as userInputQuestionSchema, St as contextProvenance, Tt as sameActorIdentity, Ut as readMessageCardRefs, Wt as removedCardSchema, Zt as readMessageAttachments, _ as automationListQuerySchema, an as ScheduleIntentError, at as KNOWN_CONVERSATION_EVENT_TYPES, cn as toolScheduleIntentSchema, dn as eventAutomationTriggerSchema, en as automationTitleSchema, gt as historyItemFromPiMessage, it as formatAgentTypes, ln as weekdaySchema, nn as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, on as compileScheduleIntent, pn as inboxItemQuestion, q as conversationReportEventSchema, qt as MAX_ATTACHMENT_BYTES, sn as scheduleIntentFromTool, tn as taskOutcomeInputSchema, tt as AGENT_TYPES, vn as formatUserInputAnswer, wn as automationSkillNameSchema, wt as instructionProvenanceFor, xn as userInputFieldsSchema, yt as piMessageFromHistoryItem, zn as AGENT_UPDATE_EVENT_TYPE, zt as inboxItemChangeRecordSchema } from "./types-CGgQ3-Bb.js";
2
+ import { $ as resolveGatewayModel, B as getSlackBotToken, C as parseActorUserId, D as parseSlackChannelReferenceId, E as parseSlackChannelId, H as getSlackClientSecret, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, R as getChatConfig, S as isUserActor, U as getSlackSigningSecret, V as getSlackClientId, X as toPiReasoningLevel, Y as TURN_REASONING_LEVELS, _ as createActor, a as getStateValues, b as isActorUserId, c as acquireActiveLock, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as getStateAdapter, k as parseSlackUserId, l as fenceLock, o as setStateValues, u as withLock, v as createSlackActor, y as createSlackResumeActor } from "./adapter-CKtEUuWD.js";
3
+ import { A as toOptionalString, E as runWithLogAttributes, S as summarizeMessageText, T as withSpan, _ as serializeGenAiAttribute, a as getActiveTraceContext, b as setSpanStatus, c as getLogContextAttributesForSpan, d as logError, f as logException, g as runBestEffort, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, l as getTracePropagationHeaders, m as logWarn, o as getActiveTraceId, p as logInfo, r as extractGenAiUsageAttributes, t as createChatSdkLogger, u as logAudit, v as setSentryUser, w as withLogContext, x as setTags, y as setSpanAttributes } from "./logging-BQsfrLHl.js";
4
+ import { $a as createPluginCache, $f as deleteMcpServerSessionId, $l as identityAvatarUrl, $s as readSubjectLinks, $u as parentResultActor, Aa as escapeSlackMrkdwnText, Ac as resolveUserTimezone, Ad as lexemesSql, Al as closeInboxItem, Ao as automationRevision, Ar as questionContent, At as CHILD_AGENT_KINDS, Ba as createPluginDecider, Bc as downloadPrivateSlackFile, Bf as serviceAccountAllows, Bi as signQueueMessage, Bo as readAutomationRowStats, Bp as nextDetailVersion, C as createSqlStore, Ca as postSlackMessage, Cc as isPublicConversation, Cd as requireValidEventTrigger, Cf as getGatewayApiKey, Ci as readConversationAccessFromSql, Cp as fetchWithBoundedOAuthErrorBodies, Cu as getDashboardSpaceLink, Do as readAutomationVersion, Dr as inboxItemDelivery, Ds as findMatchingWatches, Dt as makeStructuredToolOutput, Du as parseDashboardPersonLink, Ea as uploadFilesToConversation, En as canShareTurn, Eo as listAutomationVersions, Er as conversationIdsSchema, Es as deliverWatch, Et as juniorToolOutputSchema, Eu as parseDashboardConversationLink, Fd as callsToolSql, Fo as readAutomationExecutionByConversationId, Fp as hasAgentTurnUsage, Fr as zodToolDefinition, G as conversationKindFromRow, Ga as renderPluginConversationEvent, Gc as isConversationScopedChannel, Gd as completeObject, Gm as juniorArtifacts, Gp as isLeadSql, Gr as resolveSlackReplyTarget, Gs as isConversationDeliveryPaused, Gu as deliversFinalText, Ha as createPluginModel, Hc as getHeaderString, Hd as embedConversationQuery, Hi as getQueueProvider, Hm as juniorUsers, Ho as readAutomationTitlesByConversationId, Hp as createSlackDestination, Id as eventExcerpt, Il as ownerConversationId, Im as juniorConversations, Io as readAutomationExecutionStatusDays, Ip as isLeadConversation, Jc as normalizeSlackConversationId, Jd as searchWeb, Jf as getMcpServiceAccountCredentials, Jr as createPluginEventPublisher, Js as searchConversations, Ju as hasConversationMetadata, Ka as basePluginContext, Kc as isDmChannel, Kd as completeText, Kp as rootSpaceIdSql, Kr as sendSlackReply, Ku as dispatchInstructionsInvokeSkills, Ld as excerptTerms, Ll as searchInboxItems, Lm as juniorSpaceConfigurations, Lo as readAutomationExecutionStatusHours, Ls as createSlackDirectCredentialSubject, M as upsertDestination, Ma as normalizeSlackStatusText, Mc as lookupSlackUserNames, Md as seqIn, Mi as getVercelConversationWorkQueue, Mm as juniorCodeRepositories, Mo as emptyAutomationRunWindows, Mp as agentTurnCostUsd, Mr as readableItem, Mt as agentNameSchema, N as parseSessionSource, Na as slackMention, Nl as getOpenInboxItemBySubject, Nr as parseToolInput, Ns as turnEvents, Oc as defaultTimezone, Of as renderJuniorNativeConversationEvent, Ol as closeReadReplyNotice, Oo as sameDefinitionValue, Or as itemResult, Os as getWatch, Ot as findChildAgentConversationId, Ou as parseDashboardTaskLink, Pa as slackMentionedUserIds, Pd as SEARCHABLE_EVENT_TYPES, Pl as insertInboxItem, Pm as juniorAttachments, Po as linkAutomationRunConversation, Pr as zodTool, Qa as runNonInteractiveCommand, Qc as sleep$1, Qd as GEN_AI_SERVER_ADDRESS, Qi as resolveTurnResumeRouting, Ql as hasUserPhoto, Qo as fallbackShortTitle, Qr as startedTaskDefinition, Qt as ensureConversationWake, Qu as isTopLevel, Ra as pluginMcpContext, Rm as juniorSpaces, Ro as readAutomationExecutionSummaries, Rp as rootConversationIsArchived, Rt as appendAndEnqueueInboundMessage, S as latestUserMessageQuery, Sc as writeConversationMetadata, Sd as requireEventIdentifier, Sf as isProviderRetryError, Si as leaveEndsAccess, Sl as readCachedUserByEmail, Sm as juniorConversationEventEmbeddings, Sn as releaseInboundMessage, Sp as OAuthProviderError, Ss as cancelWatch, T as locationFromRow, Td as isToolInputError, Ti as readableSlackTeamId, Tm as juniorConversationEvents, Tn as canJoinTurn, Tr as assigneesSchema, Ts as createWatch, Tt as injectContinuationToolName, Tu as isDashboardLink, U as conversationWaitsOnUserSql, Ua as createPluginModelCostRecorder, Uc as getSlackClient, Ud as storeConversationEmbedding, Ul as INBOX_SUBJECT_KINDS, Um as juniorDestinations, Up as requireSlackDestination, Us as JUNIOR_THREAD_STATE_TTL_MS, Uu as fuseRankedLists, V as conversationStatusSql, Va as createPluginEmbedder, Vc as getFilePermalink, Vd as createConversationEmbedder, Vf as serviceAccountOnly, Vi as verifyQueueMessage, Vo as readAutomationRuns, Vp as touchConversationDetail, Vs as verifyTimerWatchCredentialSubject, W as executionIsActive, Wa as createPluginConversationEvents, Wc as isConversationChannel, Wd as completeDecision, Wi as buildSentryEventUrl, Wl as pluginSubjectKind, Wm as guardedCosineDistance, Wp as sameDestination, Wt as claimInboundMessage, Wu as canMoveToSpace, X as canAgentChangeInboxItem, Xa as buildCommandScript, Xc as streamPrivateSlackFile, Xd as NoAudioError, Xf as PluginMcpClient, Xp as topLevelConversation, Xs as resolveAnnotationFilter, Xu as isPersonInput, Ya as withPluginHookSpan, Yc as readPrivateSlackFile, Yd as transcribeFromUrl, Yf as McpAuthorizationRequiredError, Yi as runWithSlackInstallation, Za as buildNonInteractiveShellScript, Zc as withSlackRetries, Zd as GEN_AI_PROVIDER_NAME, Zf as deleteMcpAuthSession, Zi as resolveConversationRouting, Zr as createPluginTaskStarter, Zt as dropPendingMessages, _ as readConversationTrees, _a as addReactionToMessage, _c as conversationSubtree, _d as hasEventCatalogEntries, _f as createProviderError, _o as getEventAutomation, _p as McpToolError, _r as readInboundMessageSender, _s as agentWatch, a as getDb, aa as getDispatchInputMessageId, ac as findObjectLinkType, af as claudeMaxImageSize, al as readIdentityById, ap as putMcpAuthSession, ar as formatSlackConversationRedactedLabel, as as getEventCatalog, ba as openSlackDirectMessage, bd as registeredEventTypeSchema, bm as juniorConversationParticipants, bo as saveEventAutomation, bp as getMcpProviderErrorAttributes, bs as starterWatchId, bt as getPlugins, bu as getDashboardLinkFilter, cc as CORE_ANNOTATION_PLUGIN, cf as estimateTextTokens, ci as createPluginConversationChanges, cm as juniorAutomationRuns, co as saveScheduledAutomation, cr as resolveSlackConversationContextFromThreadId, da as markDispatchAwaitingResume, dc as createPluginConversationAnnotations, dd as CORE_EVENT_NAMESPACE, df as gatewayRoutingAttributes, dl as SYSTEM_IDENTITY_ID, dm as juniorAutomations, dr as readSlackRawMessageContext, ds as slackChannelMessageTrigger, dt as isPluginInboxItem, ea as claimDispatchMailboxAppend, ec as subjectKey, ed as postsRunNotices, ei as pluginTaskId, en as getConversationWorkState, eo as getConfigDefaults, es as resolveTaskTitle, f as eventFromRow, fa as markDispatchBlocked, fc as listConversationAnnotations, fd as automationEventCatalog, ff as COMPACTION_SUMMARY_PREFIX, fl as resolveActorIdentityId, fm as juniorStats, fo as blockEventAutomation, fr as resolveSlackChannelIdFromMessage, fs as WORKSPACE_SNAPSHOT_FAILED_EVENT, g as conversationDescendants, ga as notifyAutomationBlocked, gc as conversationAncestorsOrSelf, gd as eventWatchUnavailable, gf as createAssistantProviderError, gi as canAccessConversation, gn as hasConversationStop, gp as McpServiceAccountRequiredError, gt as requireInboxItemLinks, h as conversationAncestors, ha as markDispatchRunning, hc as upsertPluginAnnotation, hd as eventNamespaceSchema, hf as ProviderError, hi as createPluginCodeChanges, ho as deleteEventAutomation, hp as McpProviderError, hs as workspaceSnapshotWatch, ht as requireInboxItemAssignees, i as getConversationStore, ia as getDispatchIdForConversation, ic as assertNoObjectLinkConflicts, id as watcherStartedConversation, if as requestPrefixAttributes, ii as getTurnRequestDeadline, il as readActorIdentity, io as deleteScheduledAutomation, ip as patchMcpAuthSession, ir as conversationVisibilityFromSlackChannelType, is as resolveAssignees, iu as userAvatarUrlsFromJoinedPhotos, j as destinationUpsertFromDestination, ja as formatSlackLink, jc as lookupSlackUser, jd as searchedEventTextSql, jf as getAppContext, jl as dismissOpenInboxItems, jm as juniorCodeChanges, jo as requireAutomationRevision, jp as addAgentTurnUsage, jr as questionsSchema, js as listWatches, jt as PARENT_AGENT_TARGET, ka as SLACK_USER_MENTION_RE, kd as indexEndedTurnEvents, kn as readParentMessage, kr as ownerLinks, ks as isQuietEvent, la as isTerminalDispatchStatus, lc as annotationSubject, ld as isEventAuthorId, lf as textCharsForTokens, li as createPluginInboxItems, lr as slackChannelTypeFromConversationInfo, ma as markDispatchFailed, mc as replaceAnnotationSubjectId, mf as isCompactionSummaryText, mo as createEventAutomation, mr as getConversationStoppedAtMs, ms as workspaceSnapshotFinishedEvent, mt as readInboxItemAgentScope, n as getConversationEventStore, ni as sendVercelPluginTask, no as blockScheduledAutomation, np as getMcpServerSessionId, ns as automationCreatorUserId, nu as readUserAvatarUrls, o as getSqlExecutor, oa as getDispatchRecord, oc as linkTypeName, of as estimateMessagesTokens, ol as readIdentityByIdFromSql, oo as parseScheduledAutomationRow, op as putMcpServerSessionId, or as resolveSlackChannelTypeFromMessage, pa as markDispatchCompleted, pd as describeRegisteredEventTrigger, pf as hasCompactedConversationContext, pl as saveActorAvatar, pp as resolvePluginHeaderEnvRefs, pr as legacyWebMailboxMetadataSchema, ps as WORKSPACE_SNAPSHOT_READY_EVENT, pt as questionSubject, qa as createSandboxCapability, qc as isSlackRequestTimeout, qd as generateImages, qf as createMcpServiceAccountClientProvider, qo as usdToMicroUsd, qr as resolveEventMentions, r as getConversationMessageSearchStore, ra as getDispatchConversationId, rd as turnBehavior, rf as createCache, ri as queueCallback, ro as createScheduledAutomation, rp as getMcpStoredOAuthCredentials, rs as resolveAssignee, ru as userAvatarUrlsFromIdentities, sa as getDispatchTurnId, sc as ANNOTATION_SUBJECT_KINDS, sd as EVENT_SYSTEM_ACTOR, sf as estimateRequestOverheadTokens, si as createPluginTurnEventReader, sn as requestConversationWork, so as readScheduledAutomation, sp as putMcpStoredOAuthCredentials, sr as resolveSlackConversationContext, ss as requireSlackChannelMessageScope, ta as confirmDispatchMailboxAppend, tc as codeChangeUrl, td as promptModeTurnTools, ti as pluginTaskParamsSchema, tl as createPluginUsers, to as truncateStatusText, tp as getMcpAuthSession, ts as activeParticipantUserIds, uc as createPluginAnnotations, ud as isEventConversationMessage, uf as readImageDimensions, ur as parseSlackThreadId, v as setArchivedAt, vc as conversationSubtreeColumns, vd as registeredEventMatchSchema, vf as findProviderError, vi as canInviteToConversation, vo as listDeletedEventAutomationsCreatedBy, vp as getMcpAwareErrorType, vr as isEventMailboxMetadata, vu as getDashboardConversationLink, w as withConversationMutationLock, wa as removeReactionFromMessage, wc as resolveRootVisibility, wd as ToolInputError, wn as withIdleConversation, wo as automationDefinition, wp as getOAuthProviderErrorAttributes, wr as INBOX_TOOL_SOURCE, ws as createTimerWatch, wu as getDashboardTaskLink, xc as readConversationMetadata, xd as registeredResourceTypeSchema, xf as isProviderRefusal, xl as readCachedLinkedHandle, xm as juniorConversationEventLexemes, xo as setEventAutomationStatus, xp as toMcpProviderError, xs as cancelSubscriptions, xt as getRegistrations, xu as getDashboardPersonLink, ya as getSlackMessagePermalink, yc as loadAnnotationLabeler, yd as registeredEventTriggerProblems, yf as getProviderErrorAttributes, yi as canReadConversation, ym as juniorConversationReadPositions, yo as parseEventAutomationRow, yp as getMcpAwareTelemetryMessage, yr as createSlackInboxItemToolServices, ys as publishAgentUpdate, za as createPluginState, zc as SlackActionError, zd as isEventEmbeddingsEnabled, zi as QUEUE_SIGNATURE_MAX_AGE_MS, zl as updateInboxItemContent, zm as juniorIdentities, zo as readAutomationExecutions, zp as conversationDetailTouch } from "./db-RDpWIeRK.js";
5
+ import { $n as loadConversationProjection, $r as failTurnRecord, $t as recordWebConversationActivity, Ai as RISK_LEVELS, An as tryWorkspaceRepoCheckoutPath, Ar as upsertConversationMessage, B as getLocationConfigurationService, Bi as projectConversationEvents$1, Bn as buildAgentsInstructionsMessage, Br as AuthorizationFlowDisabledError, Bt as getConversationTurnBoundaryError, C as resolveBotSlackTeamId, Ci as ToolActionRejectedError, Cn as getWorkspace, Cr as latestConversationMessageSeq, Ct as childAgentTurnOptions, Di as reviewToolActions, Dr as renderConversationMessageLine, Ei as createToolActionReview, En as listWorkspaces, Er as recordDeliveredAssistantMessage, Et as isParentMessageAuthor, F as turnInputFactsFromConversationMessage, Fi as persistWithRetry, Fn as setWorkspaceSnapshotBuild, Fr as createPluginEgress, G as coerceThreadConversationState, Gn as foldLeadingSystemMessages, Gt as markTurnCompleted, H as getPersistedThreadState, Hi as validateConfigValue, Hn as readRepositoryInstructions, Hr as abandonReplacedPendingAuth, Ht as isTurnInputCommitLostError, I as getTurnUserMessage, Ii as deliverOAuthAuthorization, In as isExperimentalFeatureEnabled, Ir as PluginCredentialFailureError, It as ConversationTurnBoundaryError, Jn as withAgentRequest, Jr as lostWorkerBeforeFirstSave, K as createWebAuthorization, Kn as foldSystemMessages, Kr as continuableMessages, Kt as markTurnFailed, L as getTurnUserMessageId, Li as formatProviderLabel, Ln as buildDeploymentSystemPrompt, Lr as createPluginAuthOrchestration, Lt as CooperativeTurnYieldError, M as listActiveMailboxTurns, Mi as USER_AUTHORIZATION_LEVELS, Mn as invalidateReadySnapshot, Mr as getAgentBackgroundCompactionMarkTokens, N as resolveMailboxTurnWork, Ni as CODEMODE_TOOL_NAME, Nn as loadSnapshotsForProfile, Nr as getAgentContextCompactionTriggerTokens, O as stopConversationTree, Oi as getToolActionRejectionMarker, On as updateWorkspace, Or as trimConversationMessages, Ot as readAgentConfig, P as sourceFromTurnInput, Pi as CODE_MODE_CALL_STATUS_TEXT, Pn as setWorkspaceSnapshot, Pr as getAgentContextInputLimitTokens, Pt as isInheritedForkHistory, Qn as loadConnectedMcpProviders, Qr as completeTurnRecord, R as getTurnUserReplyAttachmentContext, Rn as AGENTS_REMOVAL_NOTICE, Rr as authorizationId, Rt as TurnInputCommitLostError, S as resolveEventAuthor, Si as isCutOffStopReason, Sn as deleteWorkspace, Sr as isHumanConversationMessage, T as resumeForPersonInput, Ti as ToolActionReviewUnavailableError, Tn as listWorkspaceNamesByRepository, Tr as normalizeConversationText, Tt as dropWaitingParentMessages, U as persistThreadRuntimeState, Ui as configValueSchema, Un as renderAgentsInstructions, Ur as canReusePendingAuthLink, Ut as isTurnInputDeferredError, V as getPersistedSandboxState, Vi as validateConfigKey, Vn as findVisibleAgentsInstructions, Vr as AuthorizationPauseError, Vt as isCooperativeTurnYieldError, W as persistThreadStateById, Wn as showsAgentsInstructions, Wr as clearPendingAuth, Wt as markTurnClosed, X as loadInboxItemInput, Xn as commitAcceptedReply, Xr as saveTurnCheckpoint, Y as eventInboxItemInputs, Yn as writeAgentHistory, Yr as pauseLostWorkerTurn, Z as savedInputInstruction, Zn as commitMessages, Zr as abandonTurnRecord, _i as captureTurnFailure, _n as storeDeferredAttachment, _r as resolveConversationTitle, _t as addConversationNote, a as listDescendantAgents, ai as loadTurnStart, ar as recordAuthorizationCompleted, at as assemblePrompt, bi as requireTurnFailureEventId, br as estimateConversationMessagesTokens, bt as readChildConversationSender, ci as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, cr as recordMcpProviderConnected, ct as instructionActorFor, d as addQuietEventNote, di as TurnSliceLimitExceededError, dn as fileFields, dr as recordToolExecutionStarted, dt as turnRequestText, ei as getTurnRecord, en as webActorFromUser, er as loadConversationSkillNames, et as sendInboxItemMessages, fi as TurnToolCallLimitExceededError, ft as withoutSavedSteeringMessages, g as timerWatchCredentialSubject, gi as buildTurnFailureResponse, gn as storeAttachments, gt as saveUserCustomization, h as renderEventBatchInputs, hi as isTurnExecutionLimitExceededError, hn as storeAttachment, hr as persistConversationMessages, i as listChildAgents, ii as getTurnLifecycle, in as buildDeterministicTurnId, it as loadThreadContextTrimFloor, j as getEventBatchDelayMs, ji as ROOT_LINE_BREAK, jn as workspaceRepoCheckoutPath, jr as calculateContextCompactionTargetTokens, jt as getChildAgentLockName, k as completeCancelledConversationTurn, ki as restoreToolActionRejections, kn as WorkspaceValidationError, kr as turnHasReply, l as withSenderActors, li as TURN_LIMIT_WRAP_UP_MESSAGE, lr as recordSkillLoaded, lt as instructionForInputs, m as eventBatchMessageMeta, mi as createTurnLimitGate, mr as persistConversationMessageWindow, ni as recordTurnSummary, nn as resolveConversationDestination, nr as recordAgentsInstructionsUpdated, nt as withHeldInput, or as recordAuthorizationRequested, ot as buildPromptInput, p as enqueueEventNotification, pi as buildTurnErrorResponse, pn as readLiveAttachment, pr as hydrateConversationMessages, pt as readTaskInstructions, q as deleteWebAuthorization, qn as readAgentHistory, qr as loadTurnCheckpoint, qt as startActiveTurn, r as listAgentRelatives, ri as ConversationTurnLifecycleService, rn as buildDeterministicAssistantMessageId, rr as recordAttachmentsDelivered, rt as loadThreadContextCursor, sr as recordGuardianActionReviewed, st as buildSteeringPiMessage, t as recordChildAgentEnded, ti as listTurnSummaries, tn as ownLocalDestination, tt as isHeldInputMessage, u as EVENT_WAIT_MS, ui as TurnBudgetExceededError, ur as recordSubscribedReplyRoute, ut as loadPromptTurnContext, vi as finalizeFailedTurnReplyWithEvent, vn as AttachmentSourceUnavailableError, vt as isChildAgentEvent, w as enqueueAutomatedInput, wi as ToolActionReviewLimitError, wn as getWorkspaceByName, wr as markConversationMessage, wt as commitParentMessageFork, xi as buildTurnResult, xn as createWorkspace, xr as getConversationMessageSlackTs, yi as getAgentTurnDiagnosticsAttributes, yn as bufferBody, yr as conversationAuthorDisplayName, yt as isStopResult, z as getTurnUserSlackMessageTs, zn as AGENTS_REPLACEMENT_NOTICE, zr as AuthPausePersistenceError, zt as TurnInputDeferredError } from "./markers-Bh0vqJ5k.js";
6
+ import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-DfbOjWxl.js";
7
+ import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DR_j5Tqf.js";
8
+ import { A as retainRuntimeTurnContext, B as authorAttrs, C as instructionTextForProjection, D as isToolResultError, E as isStandaloneRuntimeContextMessage, G as mapBounded, H as renderDataTag, M as trimTrailingAssistantMessages, N as CAPABILITY_SECTION_TAG, O as isToolResultMessage, P as REQUEST_CONTEXT_SECTION_TAG, R as unwrapCurrentInstruction, S as hasTurnInput, T as isContinuablePiBoundary, V as readParentAgentTask, W as renderThreadContext, _ as extractAssistantText, a as SANDBOX_COMMAND_PATH, b as getUserMessageInstructionText, c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, f as sandboxSkillDir, h as createPluginLogger, i as ATTACHMENT_DIR, j as stripRuntimeTurnContext, k as normalizeToolNameFromResult, l as SANDBOX_SCRATCH_ROOT, m as sandboxSkillPathResolution, o as SANDBOX_DATA_ROOT, p as sandboxSkillFile, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT, u as SANDBOX_SKILLS_ROOT, v as getPiMessageRole, w as isAssistantMessage } from "./prompt-5PDkRQ1K.js";
9
+ import { $t as automationContextToolSchema, An as automationTaskText, Bt as inboxItemChangeRecordSchema, Ct as instructionActors, En as automationSkillNameSchema, Gt as removedCardSchema, Hn as TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE, In as getZonedDateTimeParts, J as conversationReportMessageEventSchema, Jt as MAX_ATTACHMENT_BYTES, Kt as resolveMessageCards, Ln as isValidTimeZone, On as automationTaskDescription, Pn as getFirstRunAtMs, Qt as readMessageAttachments, St as contextProvenance, Tt as sameActorIdentity, Vn as AGENT_UPDATE_EVENT_TYPE, Wt as readMessageCardRefs, _ as automationListQuerySchema, at as KNOWN_CONVERSATION_EVENT_TYPES, cn as scheduleIntentFromTool, en as automationInstructionToolSchema, fn as eventAutomationTriggerSchema, gt as historyItemFromPiMessage, it as formatAgentTypes, kn as automationTaskSchema, ln as toolScheduleIntentSchema, mn as askQuestionId, nn as taskOutcomeInputSchema, on as ScheduleIntentError, pn as ASK_TOOL_NAMES, q as conversationReportEventSchema, qt as automationCardStatus, rn as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, sn as compileScheduleIntent, tn as automationTitleSchema, tt as AGENT_TYPES, un as weekdaySchema, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem, zn as apiErrorSchema } from "./types-BWAgOJtR.js";
10
10
  import { g as withActiveSpan, h as startSpan, i as getActiveSpan, m as startInactiveSpan, n as captureMessage, r as continueTrace, u as sentry_exports } from "./sentry-CPbZjomA.js";
11
- import { _ as NO_REPLY_TOOL_NAME, c as renderPluginContextSection, d as readTurnAnswer, f as remindMissingAnswer, h as getAssistantReplyText, i as JUNIOR_PERSONALITY, l as REPLY_TOOL_NAME, m as decideReply, p as replyTextSchema, u as isAnswerToolName, v as findLegacyNoReplyMarker, x as REPORT_BLOCKED_TOOL_NAME, y as isLegacyNoReplyMarker } from "./system-prompt-table-C886lsT9.js";
12
- import { a as webPageObjectCard, i as personObjectCard, n as conversationObjectCard, o as webMessageId, p as sumUtcHoursIntoSixHours, r as messageObjectCard, t as AGENT_STATUSES, v as CHILD_AGENT_RESULTS } from "./agent-status-Bq_AIpyp.js";
13
- import { A as createUserTokenStore, C as clearSandboxEgressSignals, E as createSandboxEgressCredentialToken, F as getOAuthAccountProviders, L as credentialAuditAttributes, M as resolveSandboxCommandEnvironment, R as credentialAuditSource, T as consumeSandboxEgressPermissionDeniedSignal, _ as WorkspaceSnapshotNotReadyError, a as ensureDockerDaemon, b as workspaceSnapshotNotReadyUserMessage, d as SandboxCallTimeoutError, f as findInErrorChain, g as wrapSandboxSetupError, h as throwSandboxOperationError, j as buildSandboxEgressNetworkPolicy, m as isAlreadyExistsError, n as hash, o as getSandboxProvider, p as isAbortError, r as isStale, s as isRetryableSandboxFailure, t as create, u as SANDBOX_RUNTIME, v as getWorkspaceSnapshotNotReadyError, w as consumeSandboxEgressAuthRequiredSignal, y as isWorkspaceSnapshotNotReadyError } from "./profile-bLo0h7Le.js";
14
- import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-DBrcQl47.js";
15
- import { o as detectImageMediaType, r as userCustomizationTextSchema, s as isVisionImageMediaType, t as USER_CUSTOMIZATION_MAX_CHARS } from "./user-customization-CvfuY9Eo.js";
16
- import { t as bufferBody } from "./storage-XD0lB4Gk.js";
17
- import { a as isConversationMember, c as listChannelMessages, i as getConversationInfo, l as listThreadReplies, n as joinPublicChannelForRead, o as isPublicSlackChannel, r as getChannelMessage, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-BUHB0saC.js";
18
- import { a as AgentNameInUseError, c as RetryableDeliveryError, d as isAgentRunFeatureDisabled, f as surfaceFromRun, i as AgentMessageTargetError, l as actorFromRun, n as spawnChildAgent, o as AgentStoppedError, p as toolInvocationDestination, r as AgentDepthLimitError, s as ChildAgentLimitError, t as messageChildAgent, u as assertRunConsistency } from "./create-CLV0M1vw.js";
19
- import { n as enqueueAgentMessageToParent, o as listChildMessages } from "./result-BFBwK1M2.js";
20
- import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, o as getSandboxResources, r as dependencies } from "./resolve-D9RKNH3v.js";
21
- import { a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, n as CACHE_WARMUP_QUEUE_TOPIC, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as listReferenceFiles } from "./topics-DxuKurCX.js";
11
+ import { _ as NO_REPLY_TOOL_NAME, c as renderPluginContextSection, d as readTurnAnswer, f as remindMissingAnswer, h as getAssistantReplyText, i as JUNIOR_PERSONALITY, l as REPLY_TOOL_NAME, m as decideReply, p as replyTextSchema, u as isAnswerToolName, v as findLegacyNoReplyMarker, x as REPORT_BLOCKED_TOOL_NAME, y as isLegacyNoReplyMarker } from "./system-prompt-table-DySHMtu0.js";
12
+ import { _ as CHILD_AGENT_RESULTS, a as webPageObjectCard, f as sumUtcHoursIntoSixHours, i as personObjectCard, n as conversationObjectCard, r as messageObjectCard, t as AGENT_STATUSES } from "./agent-status-C_HHxO_d.js";
13
+ import { A as createUserTokenStore, C as clearSandboxEgressSignals, E as createSandboxEgressCredentialToken, F as getOAuthAccountProviders, L as credentialAuditAttributes, M as resolveSandboxCommandEnvironment, R as credentialAuditSource, T as consumeSandboxEgressPermissionDeniedSignal, _ as WorkspaceSnapshotNotReadyError, a as ensureDockerDaemon, b as workspaceSnapshotNotReadyUserMessage, d as SandboxCallTimeoutError, f as findInErrorChain, g as wrapSandboxSetupError, h as throwSandboxOperationError, j as buildSandboxEgressNetworkPolicy, m as isAlreadyExistsError, n as hash, o as getSandboxProvider, p as isAbortError, r as isStale, s as isRetryableSandboxFailure, t as create, u as SANDBOX_RUNTIME, v as getWorkspaceSnapshotNotReadyError, w as consumeSandboxEgressAuthRequiredSignal, y as isWorkspaceSnapshotNotReadyError } from "./profile-DiAB4QfT.js";
14
+ import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-BmZlg_ci.js";
15
+ import { c as isVisionImageMediaType, r as userCustomizationTextSchema, s as detectImageMediaType, t as USER_CUSTOMIZATION_MAX_CHARS } from "./user-customization-DNzu_r1x.js";
16
+ import { a as isConversationMember, c as listChannelMessages, i as getConversationInfo, l as listThreadReplies, n as joinPublicChannelForRead, o as isPublicSlackChannel, r as getChannelMessage, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-DRhVJIuQ.js";
17
+ import { a as AgentNameInUseError, c as RetryableDeliveryError, d as isAgentRunFeatureDisabled, f as surfaceFromRun, i as AgentMessageTargetError, l as actorFromRun, n as spawnChildAgent, o as AgentStoppedError, p as toolInvocationDestination, r as AgentDepthLimitError, s as ChildAgentLimitError, t as messageChildAgent, u as assertRunConsistency } from "./create-ZkI-_JAs.js";
18
+ import { n as enqueueAgentMessageToParent, o as listChildMessages } from "./result-D_D-2Adp.js";
19
+ import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, o as getSandboxResources, r as dependencies } from "./resolve-C7e0pwuP.js";
20
+ import { f as listReferenceFiles, i as CACHE_WARMUP_QUEUE_TOPIC, r as BACKGROUND_COMPACTION_QUEUE_TOPIC, s as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC } from "./topic-ChZe9WPj.js";
22
21
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
23
22
  import * as z from "zod";
24
23
  import { streamSimple } from "@earendil-works/pi-ai/compat";
25
24
  import path from "node:path";
26
- import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notExists, notInArray, or, sql } from "drizzle-orm";
25
+ import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notInArray, or, sql } from "drizzle-orm";
27
26
  import { alias, unionAll } from "drizzle-orm/pg-core";
28
- import { agentEventKeys, agentEventMatchKey, agentEventMatchSchema, annotatedObjectSchema, createSlackSource, createWebSource, declaredEventKeys, escapeTagText, escapeTagTextAndQuotes, eventMatchFieldSchema, eventSchema, eventTriggerText, findTag, indentTagLines, localDestinationSchema, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectPresentation, objectTypeSchema, ownedObjectAnnotationSchema, pluginProviderAccountSchema, pluginRunContextSchema, pluginToolReplySchema, promptMessageSchema, renderEmptyTag, renderInlineTag, renderTag, stableEventMatchKey, startsWithTag, stripTags, subscribableResourceSchema, tagJson, watchResultSchema } from "@sentry/junior-plugin-api";
27
+ import { CACHE_LOAD_TIMEOUT_MS, agentEventKeys, agentEventMatchKey, agentEventMatchSchema, annotatedObjectSchema, createSlackSource, declaredEventKeys, escapeTagText, escapeTagTextAndQuotes, eventMatchFieldSchema, eventSchema, eventTriggerText, findTag, indentTagLines, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectPresentation, objectTypeSchema, ownedObjectAnnotationSchema, pluginProviderAccountSchema, pluginRunContextSchema, pluginToolReplySchema, promptMessageSchema, renderEmptyTag, renderInlineTag, renderTag, stableEventMatchKey, startsWithTag, stripTags, subscribableResourceSchema, tagJson, untilAborted, watchResultSchema } from "@sentry/junior-plugin-api";
29
28
  import { isDeepStrictEqual, promisify } from "node:util";
30
29
  import { AsyncLocalStorage } from "node:async_hooks";
31
30
  import { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
@@ -1012,29 +1011,29 @@ function createTracedStreamFn({ base = streamSimple, conversationPrivacy = "priv
1012
1011
  * compares that chance with the cost of one more warmup.
1013
1012
  */
1014
1013
  /** One minute in milliseconds. */
1015
- const MINUTE_MS$1 = 6e4;
1014
+ const MINUTE_MS = 6e4;
1016
1015
  /** Upper edges (ms) of the gap histogram bins. */
1017
1016
  const GAP_BIN_EDGES_MS = [
1018
1017
  1e4,
1019
1018
  2e4,
1020
1019
  3e4,
1021
1020
  45e3,
1022
- MINUTE_MS$1,
1023
- 1.5 * MINUTE_MS$1,
1024
- 2 * MINUTE_MS$1,
1025
- 3 * MINUTE_MS$1,
1026
- 4 * MINUTE_MS$1,
1027
- 5 * MINUTE_MS$1,
1028
- 7 * MINUTE_MS$1,
1029
- 10 * MINUTE_MS$1,
1030
- 15 * MINUTE_MS$1,
1031
- 20 * MINUTE_MS$1,
1032
- 30 * MINUTE_MS$1,
1033
- 45 * MINUTE_MS$1,
1034
- 60 * MINUTE_MS$1,
1035
- 90 * MINUTE_MS$1,
1036
- 120 * MINUTE_MS$1,
1037
- 240 * MINUTE_MS$1,
1021
+ MINUTE_MS,
1022
+ 1.5 * MINUTE_MS,
1023
+ 2 * MINUTE_MS,
1024
+ 3 * MINUTE_MS,
1025
+ 4 * MINUTE_MS,
1026
+ 5 * MINUTE_MS,
1027
+ 7 * MINUTE_MS,
1028
+ 10 * MINUTE_MS,
1029
+ 15 * MINUTE_MS,
1030
+ 20 * MINUTE_MS,
1031
+ 30 * MINUTE_MS,
1032
+ 45 * MINUTE_MS,
1033
+ 60 * MINUTE_MS,
1034
+ 90 * MINUTE_MS,
1035
+ 120 * MINUTE_MS,
1036
+ 240 * MINUTE_MS,
1038
1037
  1e400
1039
1038
  ];
1040
1039
  const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
@@ -1079,7 +1078,7 @@ function warmupPrice(cacheReadPrice) {
1079
1078
  * so the other 5 minutes let a late horizon still record its no-reply gap.
1080
1079
  * A longer idle horizon sends its horizon in steps of this length.
1081
1080
  */
1082
- const IDLE_HORIZON_MS = 55 * MINUTE_MS$1;
1081
+ const IDLE_HORIZON_MS = 55 * MINUTE_MS;
1083
1082
  /**
1084
1083
  * Idle horizon of an idle period that waits on a child agent. Its result
1085
1084
  * starts a Turn, so a return stays likely past the default horizon. Two
@@ -1105,7 +1104,7 @@ function warmupFailureCountsAsMiss(error) {
1105
1104
  * Time from a timer's due time to the request of its Turn: the heartbeat
1106
1105
  * fires due timers once a minute, and the Turn then starts.
1107
1106
  */
1108
- const TIMER_START_DELAY_MS = 2 * MINUTE_MS$1;
1107
+ const TIMER_START_DELAY_MS = 2 * MINUTE_MS;
1109
1108
  /**
1110
1109
  * Latest timer due time, as idle time, that the timer floor warms for. A
1111
1110
  * warmup costs a bit more than one read and a miss costs one write minus one
@@ -1119,7 +1118,7 @@ function timerFloorMaxDueIdleMs(prices) {
1119
1118
  return prices.cacheTtlMs + maxWarmups * (prices.cacheTtlMs - WARMUP_MARGIN_MS) - TIMER_START_DELAY_MS;
1120
1119
  }
1121
1120
  /** Gap that Junior records for an idle period with no reply in the horizon. */
1122
- const NO_REPLY_GAP_MS = 1440 * MINUTE_MS$1;
1121
+ const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
1123
1122
  function binIndex(gapMs) {
1124
1123
  return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
1125
1124
  }
@@ -1317,8 +1316,8 @@ const CACHE_RETENTION = "short";
1317
1316
  const REFRESHED_READ_FRACTION = .9;
1318
1317
  const BREAKER_OUTCOMES_MAX = 20;
1319
1318
  const BREAKER_MAX_MISSES = 10;
1320
- const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS$1;
1321
- const BREAKER_OPEN_TTL_MS = 30 * MINUTE_MS$1;
1319
+ const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
1320
+ const BREAKER_OPEN_TTL_MS = 30 * MINUTE_MS;
1322
1321
  const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
1323
1322
  const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
1324
1323
  const providerOf = (modelId) => modelId.split("/")[0] ?? "";
@@ -1333,9 +1332,9 @@ async function connectedState() {
1333
1332
  return state;
1334
1333
  }
1335
1334
  const CACHE_TTL_MS = {
1336
- anthropic: 5 * MINUTE_MS$1,
1337
- alibaba: 5 * MINUTE_MS$1,
1338
- openai: 30 * MINUTE_MS$1
1335
+ anthropic: 5 * MINUTE_MS,
1336
+ alibaba: 5 * MINUTE_MS,
1337
+ openai: 30 * MINUTE_MS
1339
1338
  };
1340
1339
  /**
1341
1340
  * Return true when warmups can refresh the prompt cache of this request.
@@ -1742,9 +1741,9 @@ function savingsTotals(stats) {
1742
1741
  // src/chat/cache-warming/tool-wait.ts
1743
1742
  const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
1744
1743
  const TOOL_WAIT_GAPS_MAX = 2e3;
1745
- const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS$1;
1746
- const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS$1;
1747
- const STORED_WAIT_TTL_MS = 60 * MINUTE_MS$1;
1744
+ const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS;
1745
+ const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS;
1746
+ const STORED_WAIT_TTL_MS = 60 * MINUTE_MS;
1748
1747
  const storedWaitSchema = z.object({
1749
1748
  modelId: z.string(),
1750
1749
  startedAtMs: z.number(),
@@ -1952,187 +1951,6 @@ function createToolWaitWarmer(conversationId) {
1952
1951
  }
1953
1952
  };
1954
1953
  }
1955
- // src/chat/tool-support/zod-tool.ts
1956
- function isContentOnlyToolResult(value) {
1957
- return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
1958
- }
1959
- function isStructuredToolResultEnvelope(value) {
1960
- return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
1961
- }
1962
- function parseToolContent(content) {
1963
- for (const item of content) if (!item || typeof item !== "object" || (item.type === "text" ? typeof item.text !== "string" : item.type === "image" ? typeof item.data !== "string" || typeof item.mimeType !== "string" : true)) throw new TypeError("zodTool() content must contain valid text or image items.");
1964
- return content;
1965
- }
1966
- function formatZodPath(path) {
1967
- return path.length > 0 ? path.map(String).join(".") : "root";
1968
- }
1969
- function formatToolInputError(error) {
1970
- return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
1971
- }
1972
- /** Parse tool input with its Zod schema, as a model-repairable error on failure. */
1973
- function parseToolInput(schema, args) {
1974
- const result = schema.safeParse(args);
1975
- if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
1976
- return result.data;
1977
- }
1978
- /** Declare the static definition of a Zod tool once, for the registry and its factory. */
1979
- function zodToolDefinition(definition) {
1980
- return definition;
1981
- }
1982
- function zodTool(definition) {
1983
- const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
1984
- let modelInputSchema;
1985
- try {
1986
- modelInputSchema = z.toJSONSchema(inputSchema);
1987
- } catch (error) {
1988
- throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
1989
- }
1990
- let modelOutputSchema;
1991
- if (outputSchema) try {
1992
- modelOutputSchema = z.toJSONSchema(outputSchema);
1993
- } catch (error) {
1994
- throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
1995
- }
1996
- return {
1997
- ...toolDef,
1998
- inputSchema: modelInputSchema,
1999
- ...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
2000
- prepareArguments(args) {
2001
- return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
2002
- },
2003
- ...execute ? { async execute(input, options) {
2004
- const result = await execute(input, options);
2005
- if (!outputSchema) {
2006
- if (isContentOnlyToolResult(result)) return result;
2007
- throw new TypeError("zodTool() content-only tools must return { content } without details.");
2008
- }
2009
- if (isStructuredToolResultEnvelope(result)) return {
2010
- content: parseToolContent(result.content),
2011
- details: outputSchema.parse(result.details)
2012
- };
2013
- return outputSchema.parse(result);
2014
- } } : void 0
2015
- };
2016
- }
2017
- // src/chat/inbox-items/tool-support.ts
2018
- /** Shared input and result shapes of the Inbox item tools. */
2019
- /** Deferred tool catalog source for the Inbox item tools after add. */
2020
- const INBOX_TOOL_SOURCE = {
2021
- id: "inbox",
2022
- description: "Update and search Inbox items: work that needs a person."
2023
- };
2024
- /** Who can act on an Inbox item. */
2025
- const assigneesSchema = z.array(z.string().trim().min(1).max(320)).min(1).max(20).describe("Who can act on the item. Each entry is `everyone`, an email, or a mention such as `<@U123>`. Everyone means any person who can see the item.");
2026
- /** Conversations that an Inbox item links to. */
2027
- const conversationIdsSchema = z.array(z.string().trim().min(1).max(500)).max(10);
2028
- /** Title of an Inbox item. */
2029
- const titleSchema = z.string().trim().min(1).max(200);
2030
- /** Body of an Inbox item. */
2031
- const bodySchema = z.string().trim().min(1).max(4e3).describe("Markdown details for the person.");
2032
- /** Deliver an Inbox item change through the services of the tools. */
2033
- function inboxItemDelivery(services) {
2034
- return {
2035
- queue: services.queue(),
2036
- show: services.show
2037
- };
2038
- }
2039
- /** The owner Conversation of an item, as a list of Conversations to check. */
2040
- function ownerLinks(item) {
2041
- const conversationId = item ? ownerConversationId(item) : void 0;
2042
- return conversationId ? [conversationId] : [];
2043
- }
2044
- /** Read an Inbox item that the agent may read, or fail with a tool input error. */
2045
- async function readableItem(id, scope) {
2046
- const item = await getInboxItem(getDb(), id);
2047
- if (!item || !canReadInboxItem(item, scope.reader)) throw new ToolInputError(`Inbox item ${id} is not found. Use searchInboxItems to find its id.`);
2048
- return item;
2049
- }
2050
- /** Render one Inbox item for a tool result. */
2051
- function itemResult(item) {
2052
- return {
2053
- id: item.id,
2054
- kind: item.kind,
2055
- status: item.status,
2056
- title: item.title,
2057
- body: item.body,
2058
- assignees: [...item.assignedToEveryone ? [EVERYONE_ASSIGNEE] : [], ...item.assignees.map((assignee) => assignee.email)],
2059
- conversation_ids: item.conversationIds,
2060
- visibility: item.visibility,
2061
- updated_at: item.updatedAt.toISOString(),
2062
- subject: item.subject,
2063
- ...item.addedByAutomationId ? { automation_id: item.addedByAutomationId } : void 0,
2064
- ...item.request ? { request: requestResult(item.request) } : void 0,
2065
- ...item.answer ? { answer: item.answer } : void 0,
2066
- ...item.closedAt ? {
2067
- closed_at: item.closedAt.toISOString(),
2068
- closed_by: item.closedBy?.email ?? "agent"
2069
- } : void 0,
2070
- ...item.closeReason ? { close_reason: item.closeReason } : void 0
2071
- };
2072
- }
2073
- /** Show the stored question with the tool's snake_case related link keys. */
2074
- function requestResult({ related, ...question }) {
2075
- return {
2076
- ...question,
2077
- ...related ? { related: related.map(({ conversationId, ...entry }) => ({
2078
- ...entry,
2079
- ...conversationId ? { conversation_id: conversationId } : void 0
2080
- })) } : void 0
2081
- };
2082
- }
2083
- const relatedSchema = z.array(z.object({
2084
- url: z.string().url().max(2e3).refine((url) => URL.canParse(url) && ["http:", "https:"].includes(new URL(url).protocol), "Use an http(s) URL.").nullable().optional().describe("A link, such as a chart, a log search, or the pull request that the item is about. The card shows these links."),
2085
- conversation_id: z.string().trim().min(1).max(500).nullable().optional().describe("A related Conversation. Set this or `url`."),
2086
- label: z.string().trim().min(1).max(120).describe("Short name of the link, such as `Checkout p95 chart`."),
2087
- note: z.string().trim().min(1).max(200).regex(/^[^\r\n]*$/, "Use one line.").nullable().optional().describe("One line: what this link shows.")
2088
- }).strict()).max(10);
2089
- const questionRequestSchema = z.object({ request: userInputRequestSchema });
2090
- /**
2091
- * Return the question of an action. An action needs one. A notice asks
2092
- * nothing, so its `request` may hold only related links.
2093
- */
2094
- function questionInput(kind, request) {
2095
- if (kind === "notice") {
2096
- if (request?.question || request?.fields) throw new ToolInputError("A notice asks nothing, so its `request` holds only `related`. To ask, use kind `action`.");
2097
- return;
2098
- }
2099
- if (!request?.question || !request.fields) throw new ToolInputError("An action item needs a `request` with a `question` and `fields`.");
2100
- const { related: _related, ...question } = request;
2101
- return parseToolInput(questionRequestSchema, { request: question }).request;
2102
- }
2103
- /** The `request` param of the Inbox item tools that ask or change a question. */
2104
- const requestInputSchema = z.object({
2105
- question: userInputQuestionSchema.optional().describe("The question, in markdown. Include the facts the person needs to decide. Required for an action. Not allowed for a notice."),
2106
- fields: userInputFieldsSchema.optional().describe("What to ask, in display order. Use one `choice` field for a simple decision. Required for an action. Not allowed for a notice."),
2107
- related: relatedSchema.nullable().optional().describe("Links related to the item: what it is about, such as a pull request, and the sources for its facts. With a suggested answer, link what supports it and what argues against it. Each entry has a `url` or a `conversation_id`.")
2108
- });
2109
- /**
2110
- * Normalize the related links: each entry names exactly one link, null
2111
- * fields mean omitted, and a link is stored as `URL.href`, so it matches
2112
- * the link of the work that it names.
2113
- */
2114
- function relatedInput(related) {
2115
- return (related ?? []).map((entry) => {
2116
- if (Boolean(entry.url) === Boolean(entry.conversation_id)) throw new ToolInputError("Each `related` entry needs a `url` or a `conversation_id`, not both.");
2117
- return {
2118
- label: entry.label,
2119
- ...entry.url ? { url: new URL(entry.url).href } : void 0,
2120
- ...entry.conversation_id ? { conversationId: entry.conversation_id } : void 0,
2121
- ...entry.note ? { note: entry.note } : void 0
2122
- };
2123
- });
2124
- }
2125
- /**
2126
- * Store the question with its normalized related links, if it has any. A
2127
- * notice stores only its related links.
2128
- */
2129
- function requestInput(question, related) {
2130
- if (!question) return related.length > 0 ? { related } : void 0;
2131
- return {
2132
- ...question,
2133
- ...related.length > 0 ? { related } : void 0
2134
- };
2135
- }
2136
1954
  // src/chat/inbox-items/tools/search.ts
2137
1955
  const DEFAULT_LIMIT$4 = 10;
2138
1956
  const MAX_LIMIT$4 = 25;
@@ -6048,67 +5866,6 @@ function createSlackChannelJoinTool(context) {
6048
5866
  }
6049
5867
  });
6050
5868
  }
6051
- // src/chat/slack/context.ts
6052
- function toTrimmedSlackString(value) {
6053
- return toOptionalString(value)?.trim() || void 0;
6054
- }
6055
- const slackMessageEnvelopeSchema$1 = z.object({ raw: z.unknown().optional() });
6056
- const rawSlackMessageSchema = z.object({
6057
- channel: z.unknown().optional(),
6058
- message: z.unknown().optional(),
6059
- team: z.unknown().optional(),
6060
- team_id: z.unknown().optional(),
6061
- thread_ts: z.unknown().optional(),
6062
- ts: z.unknown().optional(),
6063
- user_team: z.unknown().optional()
6064
- });
6065
- const nestedRawSlackMessageSchema = z.object({ ts: z.unknown().optional() });
6066
- /** Project only the Slack raw fields consumed by runtime thread context. */
6067
- function readSlackRawMessageContext(message) {
6068
- const envelope = slackMessageEnvelopeSchema$1.safeParse(message);
6069
- if (!envelope.success) return;
6070
- const raw = rawSlackMessageSchema.safeParse(envelope.data.raw);
6071
- if (!raw.success) return;
6072
- const nestedMessage = nestedRawSlackMessageSchema.safeParse(raw.data.message);
6073
- const channelId = parseSlackChannelId(raw.data.channel);
6074
- const threadTs = parseSlackMessageTs(raw.data.thread_ts);
6075
- const messageTs = parseSlackMessageTs(raw.data.ts);
6076
- const nestedMessageTs = nestedMessage.success && parseSlackMessageTs(nestedMessage.data.ts);
6077
- const teamId = parseSlackTeamId(raw.data.team_id) ?? parseSlackTeamId(raw.data.team);
6078
- const authorTeamId = parseSlackTeamId(raw.data.user_team);
6079
- return {
6080
- ...channelId ? { channelId } : void 0,
6081
- ...threadTs ? { threadTs } : void 0,
6082
- ...messageTs ? { messageTs } : void 0,
6083
- ...nestedMessageTs ? { nestedMessageTs } : void 0,
6084
- ...teamId ? { teamId } : void 0,
6085
- ...authorTeamId ? { authorTeamId } : void 0
6086
- };
6087
- }
6088
- /** Extract a channel ID and validated Slack timestamp from `slack:<channel>:<ts>`. */
6089
- function parseSlackThreadId(threadId) {
6090
- const normalizedThreadId = toTrimmedSlackString(threadId);
6091
- if (!normalizedThreadId) return;
6092
- const parts = normalizedThreadId.split(":");
6093
- if (parts.length !== 3 || parts[0] !== "slack") return;
6094
- const channelId = parseSlackChannelId(parts[1]);
6095
- const threadTs = parseSlackMessageTs(parts[2]);
6096
- if (!channelId || !threadTs) return;
6097
- return {
6098
- channelId,
6099
- threadTs
6100
- };
6101
- }
6102
- /** Best-effort channel ID extraction from a raw Slack message payload. */
6103
- function resolveSlackChannelIdFromMessage(message) {
6104
- const messageChannelId = parseSlackChannelId(message.channelId);
6105
- if (messageChannelId) return messageChannelId;
6106
- const raw = message.raw;
6107
- if (raw && typeof raw === "object") {
6108
- const rawChannel = parseSlackChannelId(raw.channel);
6109
- if (rawChannel) return rawChannel;
6110
- }
6111
- }
6112
5869
  // src/chat/slack/timestamp-param.ts
6113
5870
  /** Define a model-facing Slack timestamp, normalizing numeric model args to strings. */
6114
5871
  function slackTimestampParam(description) {
@@ -6698,6 +6455,17 @@ function createSlackListGetItemsTool() {
6698
6455
  }
6699
6456
  // src/chat/slack/tools/list/update-item.ts
6700
6457
  const booleanInput = (description) => z.preprocess((value) => value === "true" ? true : value === "false" ? false : value, z.boolean()).describe(description);
6458
+ const updateListItemInputSchema = z.union([z.object({
6459
+ list_id: slackListIdParam,
6460
+ item_id: slackListItemIdParam,
6461
+ completed: booleanInput("Optional completion status update."),
6462
+ title: z.string().min(1).describe("Optional new item title.").optional()
6463
+ }), z.object({
6464
+ list_id: slackListIdParam,
6465
+ item_id: slackListItemIdParam,
6466
+ completed: booleanInput("Optional completion status update.").optional(),
6467
+ title: z.string().min(1).describe("Optional new item title.")
6468
+ })]);
6701
6469
  const slackListUpdateItemToolDefinition = zodToolDefinition({
6702
6470
  exposure: "deferred",
6703
6471
  source: SLACK_TOOL_SOURCE,
@@ -6708,17 +6476,7 @@ const slackListUpdateItemToolDefinition = zodToolDefinition({
6708
6476
  readOnlyHint: false
6709
6477
  },
6710
6478
  description: "Update an item in a Slack list.",
6711
- inputSchema: z.union([z.object({
6712
- list_id: slackListIdParam,
6713
- item_id: slackListItemIdParam,
6714
- completed: booleanInput("Optional completion status update."),
6715
- title: z.string().min(1).describe("Optional new item title.").optional()
6716
- }), z.object({
6717
- list_id: slackListIdParam,
6718
- item_id: slackListItemIdParam,
6719
- completed: booleanInput("Optional completion status update.").optional(),
6720
- title: z.string().min(1).describe("Optional new item title.")
6721
- })]),
6479
+ inputSchema: updateListItemInputSchema,
6722
6480
  outputSchema: juniorToolOutputSchema
6723
6481
  });
6724
6482
  /** Create a tool that updates an item in an explicit Slack list. */
@@ -7319,491 +7077,6 @@ function renderAttachment(raw) {
7319
7077
  function renderAttachmentText(input) {
7320
7078
  return getAttachmentPayload(input).slice(0, MAX_ATTACHMENTS).map(renderAttachment).filter((line) => line.length > 0).map((line) => `[attachment] ${line}`).join("\n").slice(0, MAX_ATTACHMENT_TEXT_CHARS);
7321
7079
  }
7322
- // src/chat/attachments/source.ts
7323
- /** The source deleted the file, or Junior can no longer read it. */
7324
- var AttachmentSourceUnavailableError = class extends Error {
7325
- constructor(message, options) {
7326
- super(message, options);
7327
- this.name = "AttachmentSourceUnavailableError";
7328
- }
7329
- };
7330
- // src/chat/attachments/store.ts
7331
- const DAY_MS = 864e5;
7332
- const ATTACHMENT_GC_BATCH_LIMIT = 200;
7333
- /** Time that Junior keeps attachment bytes after the file is stored. */
7334
- const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
7335
- /** Only `file` rows: a `url` row has no storage or file fields. */
7336
- const isFileAttachment = eq(juniorAttachments.kind, "file");
7337
- /**
7338
- * The storage and file fields of a `file` row. Every `file` row has them, so
7339
- * a missing one is a broken row.
7340
- */
7341
- function fileFields(row) {
7342
- const { bytes, contentType, storageProvider, title } = row;
7343
- if (bytes === null || contentType === null || storageProvider === null || title === null) throw new Error(`Attachment ${row.id} has no file fields`);
7344
- return {
7345
- bytes,
7346
- contentType,
7347
- filename: title,
7348
- storageProvider
7349
- };
7350
- }
7351
- function attachmentIdentity(file) {
7352
- if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
7353
- return file.source;
7354
- }
7355
- /** Stable conversation-owned id for one file and its presentation metadata. */
7356
- function attachmentId(args) {
7357
- const identity = "sha256" in args.identity ? [
7358
- args.conversationId,
7359
- args.storageProvider,
7360
- args.identity.sha256,
7361
- args.filename,
7362
- args.contentType
7363
- ] : [
7364
- args.conversationId,
7365
- args.storageProvider,
7366
- args.filename,
7367
- args.contentType,
7368
- args.identity.provider,
7369
- args.identity.id
7370
- ];
7371
- return createHash("sha256").update(identity.join("\0")).digest("hex");
7372
- }
7373
- /**
7374
- * Object key for one write attempt.
7375
- *
7376
- * Attachment ids are content-stable. Object keys are not: each put gets a fresh
7377
- * key so a failed-write cleanup or GC delete cannot remove another writer's
7378
- * durable blob.
7379
- */
7380
- function attachmentKey(args) {
7381
- return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
7382
- }
7383
- /** A source whose bytes do not match its declared size. A retry cannot fix it. */
7384
- var AttachmentSizeError = class extends Error {
7385
- constructor(bytes, expected, options) {
7386
- super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
7387
- this.name = "AttachmentSizeError";
7388
- }
7389
- };
7390
- /** Tries for one object write, each with a freshly opened body. */
7391
- const WRITE_ATTEMPTS = 3;
7392
- async function bestEffortDelete(storage, key) {
7393
- if (key === null) return;
7394
- try {
7395
- await storage.delete([key]);
7396
- } catch {}
7397
- }
7398
- /**
7399
- * Stream one file to a fresh key, and return its size and digest.
7400
- *
7401
- * The digest is taken while the bytes stream, so the body is never held
7402
- * whole. A body that does not match its declared size is not kept.
7403
- */
7404
- async function writeAttachmentObject(args) {
7405
- for (let attempt = 1;; attempt += 1) try {
7406
- return await writeAttachmentObjectOnce(args);
7407
- } catch (error) {
7408
- if (error instanceof AttachmentSizeError || error instanceof AttachmentSourceUnavailableError || attempt >= WRITE_ATTEMPTS) {
7409
- await bestEffortDelete(args.storage, args.key);
7410
- throw error;
7411
- }
7412
- }
7413
- }
7414
- async function writeAttachmentObjectOnce(args) {
7415
- const { file } = args;
7416
- const expected = "data" in file ? file.data.byteLength : file.bytes;
7417
- const source = "data" in file ? bufferBody(file.data) : await file.open();
7418
- const hash = createHash("sha256");
7419
- let bytes = 0;
7420
- const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
7421
- bytes += chunk.byteLength;
7422
- if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
7423
- hash.update(chunk);
7424
- controller.enqueue(chunk);
7425
- } }));
7426
- try {
7427
- await args.storage.put({
7428
- body,
7429
- bytes: expected,
7430
- contentType: file.mimeType,
7431
- key: args.key
7432
- });
7433
- } catch (error) {
7434
- if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
7435
- throw error;
7436
- }
7437
- if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
7438
- return {
7439
- bytes,
7440
- sha256: hash.digest("hex")
7441
- };
7442
- }
7443
- async function isConversationPurged(db, conversationId) {
7444
- const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
7445
- return row?.transcriptPurgedAt != null;
7446
- }
7447
- function purgedConversationError(conversationId) {
7448
- return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
7449
- }
7450
- async function assertConversationNotPurged(db, conversationId) {
7451
- if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
7452
- }
7453
- /** Mark a just-written row for deletion and drop its unused object. */
7454
- async function rejectPurgedAttachmentWrite(args) {
7455
- const db = args.db.db();
7456
- await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
7457
- await bestEffortDelete(args.storage, args.storageKey);
7458
- throw purgedConversationError(args.conversationId);
7459
- }
7460
- /**
7461
- * Return another writer's live row only when the conversation is still active.
7462
- *
7463
- * The caller already wrote a unique object for this attempt. Delete that unused
7464
- * object either way. If the conversation is purged, do not report success for a
7465
- * row that purge/GC is about to remove.
7466
- */
7467
- async function reuseLiveAttachment(args) {
7468
- await bestEffortDelete(args.storage, args.storageKey);
7469
- await assertConversationNotPurged(args.db, args.conversationId);
7470
- return { id: args.id };
7471
- }
7472
- /**
7473
- * Persist one conversation-owned file.
7474
- *
7475
- * Identity is stable under the conversation: it comes from the file's source
7476
- * when it has one, and from its digest otherwise. Object storage is written
7477
- * first under a unique key; the SQL row is created only after that write
7478
- * succeeds. A row means the attachment is durable. Retries reuse an existing
7479
- * live row. A purge-marked row is revived by writing a new object and pointing
7480
- * the row at it, unless the conversation is still purged. If the SQL write
7481
- * fails after object storage accepts the bytes, this path deletes that unique
7482
- * object. A process crash between those steps can leave an unreferenced unique
7483
- * object with no SQL row.
7484
- */
7485
- async function storeAttachment(args) {
7486
- const now = new Date(args.nowMs ?? Date.now());
7487
- const identity = attachmentIdentity(args.file);
7488
- const source = args.file.source;
7489
- const id = attachmentId({
7490
- conversationId: args.conversationId,
7491
- contentType: args.file.mimeType,
7492
- filename: args.file.filename,
7493
- identity,
7494
- storageProvider: args.storage.provider
7495
- });
7496
- const [existing] = await args.db.db().select({
7497
- contentType: juniorAttachments.contentType,
7498
- conversationId: juniorAttachments.conversationId,
7499
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
7500
- filename: juniorAttachments.title,
7501
- id: juniorAttachments.id,
7502
- provider: juniorAttachments.provider,
7503
- providerId: juniorAttachments.providerId,
7504
- storageProvider: juniorAttachments.storageProvider,
7505
- sha256: juniorAttachments.sha256,
7506
- storageKey: juniorAttachments.storageKey
7507
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
7508
- if (existing) {
7509
- if (existing.contentType !== args.file.mimeType || existing.conversationId !== args.conversationId || existing.filename !== args.file.filename || existing.provider !== (source?.provider ?? null) || existing.providerId !== (source?.id ?? null) || existing.storageProvider !== args.storage.provider || "sha256" in identity && existing.sha256 !== identity.sha256) throw new Error(`Attachment write conflicts with ${existing.id}`);
7510
- if (existing.deleteRequestedAt === null) {
7511
- await assertConversationNotPurged(args.db, args.conversationId);
7512
- return { id: existing.id };
7513
- }
7514
- }
7515
- await assertConversationNotPurged(args.db, args.conversationId);
7516
- const { file } = args;
7517
- let storageKey = null;
7518
- let written;
7519
- if ("deferred" in file) written = {
7520
- bytes: file.bytes,
7521
- sha256: null
7522
- };
7523
- else {
7524
- storageKey = attachmentKey({
7525
- attachmentId: id,
7526
- conversationId: args.conversationId,
7527
- filename: file.filename,
7528
- writeId: randomUUID()
7529
- });
7530
- written = await writeAttachmentObject({
7531
- file,
7532
- key: storageKey,
7533
- storage: args.storage
7534
- });
7535
- }
7536
- if (existing?.deleteRequestedAt != null) {
7537
- if (await isConversationPurged(args.db, args.conversationId)) {
7538
- await bestEffortDelete(args.storage, storageKey);
7539
- throw purgedConversationError(args.conversationId);
7540
- }
7541
- const oldStorageKey = existing.storageKey;
7542
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
7543
- ...written,
7544
- deleteRequestedAt: null,
7545
- storageKey
7546
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
7547
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
7548
- conversationId: args.conversationId,
7549
- db: args.db,
7550
- id,
7551
- now,
7552
- storage: args.storage,
7553
- storageKey
7554
- });
7555
- if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
7556
- return { id };
7557
- }
7558
- const [afterRace] = await args.db.db().select({
7559
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
7560
- id: juniorAttachments.id,
7561
- storageKey: juniorAttachments.storageKey
7562
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
7563
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
7564
- conversationId: args.conversationId,
7565
- db: args.db,
7566
- id: afterRace.id,
7567
- storage: args.storage,
7568
- storageKey
7569
- });
7570
- }
7571
- let inserted = [];
7572
- try {
7573
- inserted = await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).insert(juniorAttachments).values({
7574
- id,
7575
- conversationId: args.conversationId,
7576
- storageProvider: args.storage.provider,
7577
- storageKey,
7578
- provider: source?.provider,
7579
- providerId: source?.id,
7580
- title: args.file.filename,
7581
- contentType: args.file.mimeType,
7582
- ...written,
7583
- createdAt: now
7584
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
7585
- } catch (error) {
7586
- await bestEffortDelete(args.storage, storageKey);
7587
- throw error;
7588
- }
7589
- if (inserted.length > 0) {
7590
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
7591
- conversationId: args.conversationId,
7592
- db: args.db,
7593
- id,
7594
- now,
7595
- storage: args.storage,
7596
- storageKey
7597
- });
7598
- return { id };
7599
- }
7600
- const [row] = await args.db.db().select({
7601
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
7602
- id: juniorAttachments.id,
7603
- storageKey: juniorAttachments.storageKey
7604
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
7605
- if (!row) {
7606
- await bestEffortDelete(args.storage, storageKey);
7607
- throw new Error(`Attachment row missing after write for ${id}`);
7608
- }
7609
- if (row.deleteRequestedAt === null) return reuseLiveAttachment({
7610
- conversationId: args.conversationId,
7611
- db: args.db,
7612
- id: row.id,
7613
- storage: args.storage,
7614
- storageKey
7615
- });
7616
- if (await isConversationPurged(args.db, args.conversationId)) {
7617
- await bestEffortDelete(args.storage, storageKey);
7618
- throw purgedConversationError(args.conversationId);
7619
- }
7620
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
7621
- ...written,
7622
- deleteRequestedAt: null,
7623
- storageKey
7624
- }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
7625
- if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
7626
- conversationId: args.conversationId,
7627
- db: args.db,
7628
- id,
7629
- now,
7630
- storage: args.storage,
7631
- storageKey
7632
- });
7633
- if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
7634
- return { id };
7635
- }
7636
- const [afterRace] = await args.db.db().select({
7637
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
7638
- id: juniorAttachments.id
7639
- }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
7640
- if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
7641
- conversationId: args.conversationId,
7642
- db: args.db,
7643
- id: afterRace.id,
7644
- storage: args.storage,
7645
- storageKey
7646
- });
7647
- await bestEffortDelete(args.storage, storageKey);
7648
- throw new Error(`Attachment ${id} disappeared while reviving`);
7649
- }
7650
- /**
7651
- * Record an object that a browser already wrote, under the upload's id.
7652
- *
7653
- * The row takes over the object key. A retry with the same id keeps the
7654
- * first row. The caller checked the object's size, type, and digest.
7655
- */
7656
- async function recordUploadedAttachment(args) {
7657
- const { attachment } = args;
7658
- const now = new Date(args.nowMs);
7659
- await assertConversationNotPurged(args.db, attachment.conversationId);
7660
- if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [attachment.conversationId])).insert(juniorAttachments).values({
7661
- bytes: attachment.bytes,
7662
- contentType: attachment.contentType,
7663
- conversationId: attachment.conversationId,
7664
- createdAt: now,
7665
- id: attachment.id,
7666
- sha256: attachment.sha256,
7667
- storageKey: attachment.storageKey,
7668
- storageProvider: args.storage.provider,
7669
- title: attachment.filename
7670
- }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id })).length > 0 && await isConversationPurged(args.db, attachment.conversationId)) await rejectPurgedAttachmentWrite({
7671
- conversationId: attachment.conversationId,
7672
- db: args.db,
7673
- id: attachment.id,
7674
- now,
7675
- storage: args.storage,
7676
- storageKey: attachment.storageKey
7677
- });
7678
- }
7679
- /**
7680
- * Store a file that Junior recorded without its bytes, on its first read.
7681
- *
7682
- * The bytes stream from the source to a fresh key. The row then takes that
7683
- * key only while it is still unstored, live, and in a conversation that is
7684
- * not purged. Purge marks rows in the transaction that purges the
7685
- * conversation, so this update cannot revive a purged row. When the update
7686
- * misses, the new object is deleted: return the row that another writer
7687
- * stored, or null when the row is no longer live.
7688
- */
7689
- async function storeDeferredAttachment(args) {
7690
- const { attachment, storage } = args;
7691
- const storageKey = attachmentKey({
7692
- attachmentId: attachment.id,
7693
- conversationId: attachment.conversationId,
7694
- filename: attachment.filename,
7695
- writeId: randomUUID()
7696
- });
7697
- const written = await writeAttachmentObject({
7698
- file: {
7699
- bytes: args.file.bytes,
7700
- filename: attachment.filename,
7701
- mimeType: attachment.contentType,
7702
- open: args.file.open,
7703
- source: attachment.source
7704
- },
7705
- key: storageKey,
7706
- storage
7707
- });
7708
- const db = args.db.db();
7709
- if ((await db.with(conversationDetailTouch(db, [attachment.conversationId])).update(juniorAttachments).set({
7710
- ...written,
7711
- storageKey
7712
- }).where(and(eq(juniorAttachments.id, attachment.id), eq(juniorAttachments.conversationId, attachment.conversationId), eq(juniorAttachments.storageProvider, storage.provider), isNull(juniorAttachments.storageKey), isNull(juniorAttachments.deleteRequestedAt), notExists(db.select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, attachment.conversationId), isNotNull(juniorConversations.transcriptPurgedAt)))))).returning({ id: juniorAttachments.id })).length > 0) return {
7713
- ...attachment,
7714
- bytes: written.bytes,
7715
- storageKey
7716
- };
7717
- await bestEffortDelete(storage, storageKey);
7718
- const current = await readLiveAttachment({
7719
- attachmentId: attachment.id,
7720
- conversationId: attachment.conversationId,
7721
- db: args.db
7722
- });
7723
- return current?.storageKey ? {
7724
- ...current,
7725
- storageKey: current.storageKey
7726
- } : null;
7727
- }
7728
- /** Load one live attachment owned by a conversation. */
7729
- async function readLiveAttachment(args) {
7730
- const [row] = await args.db.db().select({
7731
- bytes: juniorAttachments.bytes,
7732
- contentType: juniorAttachments.contentType,
7733
- conversationId: juniorAttachments.conversationId,
7734
- deleteRequestedAt: juniorAttachments.deleteRequestedAt,
7735
- id: juniorAttachments.id,
7736
- provider: juniorAttachments.provider,
7737
- providerId: juniorAttachments.providerId,
7738
- storageProvider: juniorAttachments.storageProvider,
7739
- storageKey: juniorAttachments.storageKey,
7740
- title: juniorAttachments.title
7741
- }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), isFileAttachment, eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
7742
- if (!row) return null;
7743
- if (await isConversationPurged(args.db, args.conversationId)) return null;
7744
- return {
7745
- ...fileFields(row),
7746
- conversationId: row.conversationId,
7747
- id: row.id,
7748
- source: row.provider && row.providerId ? {
7749
- id: row.providerId,
7750
- provider: row.provider
7751
- } : null,
7752
- storageKey: row.storageKey
7753
- };
7754
- }
7755
- /** Persist many conversation-owned files. */
7756
- async function storeAttachments(args) {
7757
- return await mapBounded(args.files, (file) => storeAttachment({
7758
- conversationId: args.conversationId,
7759
- db: args.db,
7760
- file: {
7761
- data: file.data,
7762
- filename: file.filename,
7763
- mimeType: file.mimeType
7764
- },
7765
- ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
7766
- storage: args.storage
7767
- }));
7768
- }
7769
- /** Mark attachments unavailable when their conversation content is purged. */
7770
- async function requestAttachmentDeletion(db, conversationIds, nowMs) {
7771
- if (conversationIds.length === 0) return;
7772
- await db.db().with(conversationDetailTouch(db.db(), conversationIds)).update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
7773
- }
7774
- /**
7775
- * Delete purged attachments in one bounded batch.
7776
- *
7777
- * Eligible files are 30 days old, explicitly purge-marked, or owned by a
7778
- * conversation whose transcript is already purged. A `url` row has no bytes,
7779
- * so it lives as long as its message: it is eligible only when purge-marked
7780
- * or purged. Delete object keys first, then remove rows that are still
7781
- * eligible so a failed blob delete remains retryable.
7782
- */
7783
- async function collectAttachmentGarbage(args) {
7784
- const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
7785
- const purged = or(isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt));
7786
- const eligible = or(lte(juniorAttachments.createdAt, expiresBefore), purged);
7787
- const isUrl = eq(juniorAttachments.kind, "url");
7788
- const rows = await args.db.db().select({
7789
- id: juniorAttachments.id,
7790
- storageKey: juniorAttachments.storageKey
7791
- }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(or(and(eq(juniorAttachments.storageProvider, args.storage.provider), eligible), and(isUrl, purged))).orderBy(asc(juniorAttachments.createdAt), asc(juniorAttachments.id)).limit(args.limit ?? ATTACHMENT_GC_BATCH_LIMIT);
7792
- if (rows.length === 0) return { deleted: 0 };
7793
- const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
7794
- if (keys.length > 0) await args.storage.delete(keys);
7795
- const stillEligible = await args.db.db().select({ id: juniorAttachments.id }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(inArray(juniorAttachments.id, rows.map((row) => row.id)), or(and(isFileAttachment, eligible), and(isUrl, purged))));
7796
- if (stillEligible.length === 0) return { deleted: 0 };
7797
- const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({
7798
- conversationId: juniorAttachments.conversationId,
7799
- id: juniorAttachments.id,
7800
- kind: juniorAttachments.kind
7801
- });
7802
- const urls = removed.filter((row) => row.kind === "url");
7803
- if (urls.length > 0) await args.db.db().delete(juniorMessageAttachments).where(and(inArray(juniorMessageAttachments.conversationId, urls.map((row) => row.conversationId)), inArray(juniorMessageAttachments.attachmentId, urls.map((row) => row.id))));
7804
- await touchConversationDetail(args.db.db(), removed.map((row) => row.conversationId));
7805
- return { deleted: removed.length };
7806
- }
7807
7080
  // src/chat/slack/attachments.ts
7808
7081
  /** Save the vision summary for a stored Slack attachment. */
7809
7082
  async function recordSlackAttachment(args) {
@@ -8319,448 +7592,6 @@ async function setConversationTitle(executor, conversationId, title) {
8319
7592
  return row?.title ?? void 0;
8320
7593
  });
8321
7594
  }
8322
- // src/chat/attachments/uploads.ts
8323
- const MINUTE_MS = 6e4;
8324
- /** Time that a browser has to write the bytes after it asks to upload. */
8325
- const UPLOAD_TARGET_TTL_MS = 15 * MINUTE_MS;
8326
- /** Time that a written upload can still join a Message. */
8327
- const UPLOAD_SEND_WINDOW_MS = 60 * MINUTE_MS;
8328
- /**
8329
- * Age at which cleanup deletes an upload that no Message used. It is much
8330
- * longer than the send window, so cleanup cannot race a send.
8331
- */
8332
- const UPLOAD_RETENTION_MS = 1440 * MINUTE_MS;
8333
- const UPLOAD_GC_BATCH_LIMIT = 200;
8334
- /** Leading bytes that image type detection reads. */
8335
- const SIGNATURE_BYTES = 16;
8336
- /** A Message refers to an upload that it cannot use. */
8337
- var AttachmentUploadError = class extends Error {
8338
- constructor(message) {
8339
- super(message);
8340
- this.name = "AttachmentUploadError";
8341
- }
8342
- };
8343
- /**
8344
- * Reserve one object key for a browser upload.
8345
- *
8346
- * Returns no target when the provider cannot sign browser writes. The caller
8347
- * then takes the bytes with `writeAttachmentUpload`.
8348
- */
8349
- async function createAttachmentUpload(args) {
8350
- const nowMs = args.nowMs ?? Date.now();
8351
- const id = randomUUID();
8352
- const storageKey = `conversations/${args.scope.conversationId}/uploads/${id}`;
8353
- await args.db.db().insert(juniorAttachmentUploads).values({
8354
- ...args.scope,
8355
- bytes: args.file.bytes,
8356
- contentType: args.file.contentType,
8357
- createdAt: new Date(nowMs),
8358
- filename: args.file.filename,
8359
- id,
8360
- storageKey,
8361
- storageProvider: args.storage.provider
8362
- });
8363
- const target = await args.storage.createUploadTarget?.({
8364
- bytes: args.file.bytes,
8365
- contentType: args.file.contentType,
8366
- expiresAtMs: nowMs + UPLOAD_TARGET_TTL_MS,
8367
- key: storageKey
8368
- });
8369
- return target ? {
8370
- id,
8371
- target
8372
- } : { id };
8373
- }
8374
- async function readUploadRows(args) {
8375
- return await args.db.db().select().from(juniorAttachmentUploads).where(and(inArray(juniorAttachmentUploads.id, [...args.uploadIds]), eq(juniorAttachmentUploads.conversationId, args.scope.conversationId), eq(juniorAttachmentUploads.idempotencyKey, args.scope.idempotencyKey), eq(juniorAttachmentUploads.userId, args.scope.userId), eq(juniorAttachmentUploads.storageProvider, args.storageProvider), gt(juniorAttachmentUploads.createdAt, /* @__PURE__ */ new Date(args.nowMs - UPLOAD_SEND_WINDOW_MS))));
8376
- }
8377
- /** Write upload bytes through the API, for providers without browser writes. */
8378
- async function writeAttachmentUpload(args) {
8379
- const nowMs = args.nowMs ?? Date.now();
8380
- const [row] = await args.db.db().select().from(juniorAttachmentUploads).where(and(eq(juniorAttachmentUploads.id, args.uploadId), eq(juniorAttachmentUploads.userId, args.userId), eq(juniorAttachmentUploads.storageProvider, args.storage.provider), gt(juniorAttachmentUploads.createdAt, /* @__PURE__ */ new Date(nowMs - UPLOAD_TARGET_TTL_MS))));
8381
- if (!row) throw new AttachmentUploadError("Upload not found.");
8382
- if (await readLiveAttachment({
8383
- attachmentId: row.id,
8384
- conversationId: row.conversationId,
8385
- db: args.db
8386
- })) throw new AttachmentUploadError("Upload was already sent.");
8387
- if (args.body.byteLength !== row.bytes) throw new AttachmentUploadError("Upload size does not match the file.");
8388
- await args.storage.put({
8389
- body: bufferBody(args.body),
8390
- bytes: row.bytes,
8391
- contentType: row.contentType,
8392
- key: row.storageKey
8393
- });
8394
- }
8395
- /** Read a whole object once for its size, digest, and leading bytes. */
8396
- async function inspectObject(body, maxBytes) {
8397
- const hash = createHash("sha256");
8398
- const head = [];
8399
- let headBytes = 0;
8400
- let bytes = 0;
8401
- const reader = body.getReader();
8402
- for (;;) {
8403
- const { done, value } = await reader.read();
8404
- if (done) break;
8405
- bytes += value.byteLength;
8406
- if (bytes > maxBytes) {
8407
- await reader.cancel();
8408
- return;
8409
- }
8410
- hash.update(value);
8411
- if (headBytes < SIGNATURE_BYTES) {
8412
- head.push(Buffer.from(value.subarray(0, SIGNATURE_BYTES - headBytes)));
8413
- headBytes += head.at(-1).byteLength;
8414
- }
8415
- }
8416
- return {
8417
- bytes,
8418
- head: Buffer.concat(head),
8419
- sha256: hash.digest("hex")
8420
- };
8421
- }
8422
- /**
8423
- * Pick the type to store from the file signature, not only the browser's
8424
- * guess from the file name. Models reject an image whose bytes do not match
8425
- * its type, so a file that only claims to be an image is stored as bytes.
8426
- */
8427
- function storedContentType(declared, head) {
8428
- const detected = detectImageMediaType(head);
8429
- if (detected) return detected;
8430
- return isVisionImageMediaType(declared) ? "application/octet-stream" : declared;
8431
- }
8432
- /**
8433
- * Check the uploads of one Message before the Message is accepted.
8434
- *
8435
- * Each upload must belong to the scope and be written in full at its
8436
- * declared size. Throws `AttachmentUploadError` for any upload that the
8437
- * Message cannot use.
8438
- */
8439
- async function verifyAttachmentUploads(args) {
8440
- if (args.uploadIds.length === 0) return [];
8441
- if (new Set(args.uploadIds).size !== args.uploadIds.length) throw new AttachmentUploadError("Attach each file once.");
8442
- const rows = await readUploadRows({
8443
- db: args.db,
8444
- nowMs: args.nowMs ?? Date.now(),
8445
- scope: args.scope,
8446
- storageProvider: args.storage.provider,
8447
- uploadIds: args.uploadIds
8448
- });
8449
- const byId = new Map(rows.map((row) => [row.id, row]));
8450
- return await Promise.all(args.uploadIds.map(async (uploadId) => {
8451
- const row = byId.get(uploadId);
8452
- if (!row) throw new AttachmentUploadError("Upload expired. Attach the file again.");
8453
- const recorded = await readLiveAttachment({
8454
- attachmentId: row.id,
8455
- conversationId: row.conversationId,
8456
- db: args.db
8457
- });
8458
- if (recorded) return {
8459
- attachment: {
8460
- bytes: recorded.bytes,
8461
- contentType: recorded.contentType,
8462
- filename: recorded.filename,
8463
- id: recorded.id
8464
- },
8465
- recorded: true
8466
- };
8467
- const body = await args.storage.get(row.storageKey);
8468
- const object = body ? await inspectObject(body, row.bytes) : void 0;
8469
- if (!object || object.bytes !== row.bytes) throw new AttachmentUploadError(`Upload of ${row.filename} is not complete. Attach it again.`);
8470
- return {
8471
- attachment: {
8472
- bytes: row.bytes,
8473
- contentType: storedContentType(row.contentType, object.head),
8474
- filename: row.filename,
8475
- id: row.id
8476
- },
8477
- recorded: false,
8478
- sha256: object.sha256,
8479
- storageKey: row.storageKey
8480
- };
8481
- }));
8482
- }
8483
- /** Record checked uploads as attachments of their Conversation. */
8484
- async function recordAttachmentUploads(args) {
8485
- await mapBounded(args.uploads.filter((upload) => !upload.recorded), (upload) => recordUploadedAttachment({
8486
- attachment: {
8487
- ...upload.attachment,
8488
- conversationId: args.conversationId,
8489
- sha256: upload.sha256,
8490
- storageKey: upload.storageKey
8491
- },
8492
- db: args.db,
8493
- nowMs: args.nowMs ?? Date.now(),
8494
- storage: args.storage
8495
- }));
8496
- return args.uploads.map((upload) => upload.attachment);
8497
- }
8498
- /**
8499
- * Delete old upload rows in one bounded batch.
8500
- *
8501
- * An upload that a Message recorded keeps its object: the attachment row owns
8502
- * it now. Other objects are deleted first, so a failed delete stays
8503
- * retryable.
8504
- */
8505
- async function collectAttachmentUploadGarbage(args) {
8506
- const rows = await args.db.db().select({
8507
- id: juniorAttachmentUploads.id,
8508
- recordedId: juniorAttachments.id,
8509
- storageKey: juniorAttachmentUploads.storageKey
8510
- }).from(juniorAttachmentUploads).leftJoin(juniorAttachments, eq(juniorAttachments.id, juniorAttachmentUploads.id)).where(and(eq(juniorAttachmentUploads.storageProvider, args.storage.provider), lte(juniorAttachmentUploads.createdAt, /* @__PURE__ */ new Date(args.nowMs - UPLOAD_RETENTION_MS)))).orderBy(asc(juniorAttachmentUploads.createdAt)).limit(UPLOAD_GC_BATCH_LIMIT);
8511
- if (rows.length === 0) return { deleted: 0 };
8512
- const unusedKeys = rows.filter((row) => row.recordedId === null).map((row) => row.storageKey);
8513
- await args.storage.delete(unusedKeys);
8514
- return { deleted: (await args.db.db().delete(juniorAttachmentUploads).where(inArray(juniorAttachmentUploads.id, rows.map((row) => row.id))).returning({ id: juniorAttachmentUploads.id })).length };
8515
- }
8516
- // src/chat/conversations/destination.ts
8517
- function requireLocalDestination(conversationId) {
8518
- const parsed = localDestinationSchema.safeParse({
8519
- platform: "local",
8520
- conversationId
8521
- });
8522
- if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
8523
- return parsed.data;
8524
- }
8525
- /**
8526
- * Keep a stored Destination, or create the temporary local Destination.
8527
- *
8528
- * TODO(dcramer): Delete this module after Conversation and AgentRun use
8529
- * Location, and web and event Turns no longer need a local
8530
- * Destination.
8531
- */
8532
- function resolveConversationDestination(args) {
8533
- return args.existing ?? requireLocalDestination(args.conversationId);
8534
- }
8535
- /**
8536
- * Create the local Destination of a Conversation that needs its own, such as
8537
- * one that leaves its Space. A local id is its own Destination. Another id,
8538
- * such as a child agent's or a Slack thread's, maps to a stable local one.
8539
- */
8540
- function ownLocalDestination(conversationId) {
8541
- const own = localDestinationSchema.safeParse({
8542
- platform: "local",
8543
- conversationId
8544
- });
8545
- if (own.success) return own.data;
8546
- return requireLocalDestination(`local:conversation:${createHash("sha256").update(conversationId).digest("hex").slice(0, 32)}`);
8547
- }
8548
- // src/chat/conversations/web-input.ts
8549
- function normalizeEmail(email) {
8550
- return email.trim().toLowerCase();
8551
- }
8552
- function stableHex$1(...parts) {
8553
- return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
8554
- }
8555
- /**
8556
- * Build a durable Conversation id for one web Actor and create key.
8557
- *
8558
- * Retries with the same key must address the same Conversation before the
8559
- * mailbox Message id is derived.
8560
- */
8561
- function createConversationId(args) {
8562
- return `local:web:${stableHex$1(normalizeEmail(args.actorEmail), args.idempotencyKey)}`;
8563
- }
8564
- /** Return the stable Turn id for one mailbox Message. */
8565
- function conversationTurnIdForMessage(messageId) {
8566
- return buildDeterministicTurnId(messageId);
8567
- }
8568
- /**
8569
- * Store the dashboard participant in the current Conversation actor field.
8570
- *
8571
- * TODO(dcramer): Remove this StoredSlackActor conversion after Conversation
8572
- * actor storage accepts web Actors directly.
8573
- */
8574
- function storedActorFromWeb(actor) {
8575
- return {
8576
- ...actor.email ? { email: normalizeEmail(actor.email) } : void 0,
8577
- ...actor.fullName ? { fullName: actor.fullName } : void 0
8578
- };
8579
- }
8580
- /**
8581
- * Return whether a person can add a web Message to an existing
8582
- * Conversation: a dashboard Conversation, a Slack thread, or a Thread.
8583
- */
8584
- function acceptsWebMessages(conversation) {
8585
- if (!isTopLevel(conversation)) return isThread(conversation);
8586
- const { conversationId, destination } = conversation;
8587
- if (destination?.platform === "slack") return true;
8588
- return destination?.platform === "local" && conversationId.startsWith("local:web:");
8589
- }
8590
- /**
8591
- * Build the web Actor for one signed-in User. Junior is the web provider,
8592
- * so the provider-scoped Actor id is the User id.
8593
- */
8594
- function webActorFromUser(user, profile) {
8595
- return {
8596
- platform: "web",
8597
- userId: user.id,
8598
- email: normalizeEmail(user.email),
8599
- ...user.displayName ? { fullName: user.displayName } : void 0,
8600
- ...profile?.userName ? { userName: profile.userName } : void 0
8601
- };
8602
- }
8603
- /** Build one web mailbox entry. */
8604
- function buildWebInboundMessage(args) {
8605
- const text = args.message.trim();
8606
- if (!text && !args.attachments?.length) throw new Error("Web Message must not be empty");
8607
- if (!args.actor.email) throw new Error("Web Actor requires a verified email");
8608
- const nowMs = args.nowMs ?? Date.now();
8609
- const traceContext = getActiveTraceContext();
8610
- return {
8611
- conversationId: args.conversationId,
8612
- createdAtMs: args.createdAtMs ?? nowMs,
8613
- delivery: args.delivery ?? "defer",
8614
- ...args.destination ? { destination: args.destination } : void 0,
8615
- inboundMessageId: args.messageId,
8616
- input: {
8617
- authorId: args.actor.userId,
8618
- ...args.authorIdentityId ? { authorIdentityId: args.authorIdentityId } : void 0,
8619
- text,
8620
- ...args.attachments?.length ? { attachments: args.attachments } : void 0,
8621
- ...args.reviewItemChange ? { reviewItemChange: args.reviewItemChange } : void 0,
8622
- metadata: {
8623
- authorEmail: normalizeEmail(args.actor.email),
8624
- ...args.actor.fullName && { authorFullName: args.actor.fullName },
8625
- authorUserId: args.actor.userId,
8626
- ...args.actor.userName && { authorUserName: args.actor.userName },
8627
- kind: "api_turn",
8628
- messageId: args.messageId
8629
- }
8630
- },
8631
- receivedAtMs: nowMs,
8632
- source: "web",
8633
- ...traceContext ? { traceContext } : void 0
8634
- };
8635
- }
8636
- /**
8637
- * Record web activity and create a Conversation root when needed. Returns the
8638
- * Destination for the Message's work. A child's work keeps none, so its
8639
- * workers read the Conversation.
8640
- */
8641
- async function recordWebConversationActivity(args) {
8642
- const store = args.conversationStore ?? getConversationStore();
8643
- let existing = await store.get({ conversationId: args.conversationId });
8644
- if (!existing && args.leadConversationId) {
8645
- await store.createChild({
8646
- childConversationId: args.conversationId,
8647
- kind: "thread",
8648
- nowMs: args.nowMs,
8649
- parentConversationId: args.leadConversationId,
8650
- source: "web",
8651
- ...args.rootTitle ? { title: args.rootTitle } : void 0
8652
- });
8653
- existing = await store.get({ conversationId: args.conversationId });
8654
- }
8655
- const destination = resolveConversationDestination({
8656
- conversationId: args.conversationId,
8657
- existing: existing?.destination
8658
- });
8659
- const isNewRoot = !existing;
8660
- const visibility = args.rootVisibility === "private" ? "private" : "public";
8661
- const source = isNewRoot ? createWebSource(args.conversationId, visibility) : void 0;
8662
- await store.recordActivity({
8663
- conversationId: args.conversationId,
8664
- ...existing?.destination ? void 0 : { destination },
8665
- nowMs: args.nowMs,
8666
- actor: storedActorFromWeb(args.actor),
8667
- ...isNewRoot ? { source: "web" } : void 0,
8668
- ...source ? { sessionSource: source } : void 0,
8669
- ...isNewRoot && args.rootTitle ? { title: args.rootTitle } : void 0,
8670
- ...isNewRoot ? { visibility } : void 0,
8671
- ...isNewRoot && args.rootKind ? { kind: args.rootKind } : void 0,
8672
- ...isNewRoot && args.rootSpaceId ? { spaceId: args.rootSpaceId } : void 0
8673
- });
8674
- return existing && !isTopLevel(existing) ? void 0 : destination;
8675
- }
8676
- /** Create a Conversation from web input and enqueue its first Message. */
8677
- async function createAndEnqueueConversation(input, options) {
8678
- if (!input.actor.email) throw new Error("Web Actor requires a verified email");
8679
- const conversationId = createConversationId({
8680
- actorEmail: input.actor.email,
8681
- idempotencyKey: input.idempotencyKey
8682
- });
8683
- return await appendAndEnqueueWebMessage({
8684
- actor: input.actor,
8685
- conversationId,
8686
- idempotencyKey: input.idempotencyKey,
8687
- message: input.message,
8688
- uploads: input.uploads,
8689
- ...input.title ? { rootTitle: input.title } : void 0,
8690
- rootVisibility: input.visibility === "private" ? "private" : "public",
8691
- ...input.leadConversationId ? { leadConversationId: input.leadConversationId } : void 0
8692
- }, options);
8693
- }
8694
- async function appendAndEnqueueWebMessage(input, options) {
8695
- const text = input.message.trim();
8696
- if (!text && !input.uploads?.length) throw new Error("Web Message must not be empty");
8697
- if (!input.actor.email) throw new Error("Web Actor requires a verified email");
8698
- const nowMs = options.nowMs ?? Date.now();
8699
- const messageId = await webMessageId({
8700
- conversationId: input.conversationId,
8701
- idempotencyKey: input.idempotencyKey
8702
- });
8703
- const destination = await recordWebConversationActivity({
8704
- actor: input.actor,
8705
- conversationId: input.conversationId,
8706
- conversationStore: options.conversationStore,
8707
- nowMs,
8708
- ...input.rootTitle && { rootTitle: input.rootTitle },
8709
- ...input.rootVisibility && { rootVisibility: input.rootVisibility },
8710
- ...input.rootSpaceId && { rootSpaceId: input.rootSpaceId },
8711
- ...input.leadConversationId && { leadConversationId: input.leadConversationId }
8712
- });
8713
- let attachments = [];
8714
- if (input.uploads?.length) {
8715
- if (!options.attachmentStorage) throw new Error("Attachment storage is unavailable.");
8716
- attachments = await recordAttachmentUploads({
8717
- conversationId: input.conversationId,
8718
- db: getSqlExecutor(),
8719
- nowMs,
8720
- storage: options.attachmentStorage,
8721
- uploads: input.uploads
8722
- });
8723
- }
8724
- const enqueue = options.exclusive ? appendAndEnqueueExclusiveInboundMessage : appendAndEnqueueInboundMessage;
8725
- const authorIdentityId = await resolveActorIdentityId(getSqlExecutor(), input.actor);
8726
- const enqueueTo = (destination) => enqueue({
8727
- message: buildWebInboundMessage({
8728
- actor: input.actor,
8729
- authorIdentityId,
8730
- conversationId: input.conversationId,
8731
- delivery: input.delivery,
8732
- destination,
8733
- message: text,
8734
- attachments,
8735
- messageId,
8736
- nowMs,
8737
- ...input.reviewItemChange && { reviewItemChange: input.reviewItemChange }
8738
- }),
8739
- conversationStore: options.conversationStore,
8740
- nowMs,
8741
- queue: options.queue,
8742
- state: options.state
8743
- });
8744
- let result;
8745
- try {
8746
- result = await enqueueTo(destination);
8747
- } catch (error) {
8748
- if (!destination) throw error;
8749
- const stored = await (options.conversationStore ?? getConversationStore()).get({ conversationId: input.conversationId });
8750
- const current = resolveConversationDestination({
8751
- conversationId: input.conversationId,
8752
- existing: stored?.destination
8753
- });
8754
- if (sameDestination(current, destination)) throw error;
8755
- result = await enqueueTo(current);
8756
- }
8757
- const status = result.status === "appended" ? "accepted" : result.status;
8758
- return {
8759
- conversationId: input.conversationId,
8760
- messageId,
8761
- status
8762
- };
8763
- }
8764
7595
  // src/chat/spaces/store.ts
8765
7596
  /**
8766
7597
  * Spaces (`design/spaces.md`). A Space's members are the Participants of
@@ -11869,35 +10700,37 @@ function providerContent(content) {
11869
10700
  }
11870
10701
  /**
11871
10702
  * Create read-only MCP access to one plugin's provider as one viewer. The
11872
- * viewer's User id is the subject of their stored MCP login.
11873
- */
11874
- function createViewerMcp(provider, userId) {
11875
- return { async callTool(input) {
11876
- const plugin = getAppContext().catalog.getDefinition(provider);
11877
- if (!plugin?.manifest.mcp) throw new Error(`Plugin "${provider}" does not support MCP`);
11878
- if (!plugin.manifest.mcp.viewerTools?.includes(input.name)) throw new Error(`Plugin ${provider} does not allow MCP tool ${input.name} for viewer reads`);
11879
- if (!(await getMcpStoredOAuthCredentials(userId, provider))?.tokens) return { status: "not_connected" };
11880
- const client = new PluginMcpClient(plugin, { authProvider: viewerAuthProvider(plugin, userId) });
11881
- try {
11882
- if ((await client.listTools()).find((candidate) => candidate.name === input.name)?.annotations?.readOnlyHint !== true) throw new Error(`MCP tool ${provider}/${input.name} is not read-only`);
11883
- const result = await client.callTool(input.name, input.arguments ?? {});
11884
- const content = Array.isArray(result.content) ? providerContent(result.content) : [];
11885
- if (result.isError) return {
11886
- status: "error",
11887
- message: content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n").trim() || "MCP tool call failed"
11888
- };
11889
- return {
11890
- status: "success",
11891
- content,
11892
- ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
11893
- };
11894
- } catch (error) {
11895
- if (error instanceof McpAuthorizationRequiredError) return { status: "not_connected" };
11896
- throw error;
11897
- } finally {
11898
- await client.close().catch(() => void 0);
11899
- }
11900
- } };
10703
+ * viewer's User id is the subject of their stored MCP login. A call stops
10704
+ * waiting when `signal` aborts.
10705
+ */
10706
+ function createViewerMcp(provider, userId, signal) {
10707
+ return { callTool: async (input) => await untilAborted(callViewerTool(provider, userId, input), signal) };
10708
+ }
10709
+ async function callViewerTool(provider, userId, input) {
10710
+ const plugin = getAppContext().catalog.getDefinition(provider);
10711
+ if (!plugin?.manifest.mcp) throw new Error(`Plugin "${provider}" does not support MCP`);
10712
+ if (!plugin.manifest.mcp.viewerTools?.includes(input.name)) throw new Error(`Plugin ${provider} does not allow MCP tool ${input.name} for viewer reads`);
10713
+ if (!(await getMcpStoredOAuthCredentials(userId, provider))?.tokens) return { status: "not_connected" };
10714
+ const client = new PluginMcpClient(plugin, { authProvider: viewerAuthProvider(plugin, userId) });
10715
+ try {
10716
+ if ((await client.listTools()).find((candidate) => candidate.name === input.name)?.annotations?.readOnlyHint !== true) throw new Error(`MCP tool ${provider}/${input.name} is not read-only`);
10717
+ const result = await client.callTool(input.name, input.arguments ?? {});
10718
+ const content = Array.isArray(result.content) ? providerContent(result.content) : [];
10719
+ if (result.isError) return {
10720
+ status: "error",
10721
+ message: content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n").trim() || "MCP tool call failed"
10722
+ };
10723
+ return {
10724
+ status: "success",
10725
+ content,
10726
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
10727
+ };
10728
+ } catch (error) {
10729
+ if (error instanceof McpAuthorizationRequiredError) return { status: "not_connected" };
10730
+ throw error;
10731
+ } finally {
10732
+ await client.close().catch(() => void 0);
10733
+ }
11901
10734
  }
11902
10735
  // src/api/objects/automation.ts
11903
10736
  /**
@@ -12050,99 +10883,6 @@ async function readConversationAuthors(db, conversationId) {
12050
10883
  participants: [...group.values()]
12051
10884
  };
12052
10885
  }
12053
- // src/chat/slack/conversation-context.ts
12054
- function normalizeConversationName(type, channelName) {
12055
- const trimmed = channelName?.trim();
12056
- if (!trimmed) return void 0;
12057
- if (type === "public_channel" || type === "private_channel" || type === "private_channel_or_group_dm") return trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
12058
- return trimmed;
12059
- }
12060
- function typeFromSlackChannelType(channelType) {
12061
- if (channelType === "channel") return "public_channel";
12062
- if (channelType === "group") return "private_channel";
12063
- if (channelType === "mpim") return "group_dm";
12064
- if (channelType === "im") return "direct_message";
12065
- }
12066
- function typeFromChannelId(channelId, channelName) {
12067
- const normalized = normalizeSlackConversationId(channelId);
12068
- if (!normalized) return void 0;
12069
- if (normalized.startsWith("C")) return "public_channel";
12070
- if (normalized.startsWith("D")) return "direct_message";
12071
- if (normalized.startsWith("G")) return channelName?.trim().startsWith("mpdm-") ? "group_dm" : "private_channel_or_group_dm";
12072
- }
12073
- function toSlackEventChannelType(channelType) {
12074
- if (channelType === "channel" || channelType === "group" || channelType === "mpim" || channelType === "im") return channelType;
12075
- }
12076
- /**
12077
- * Map Slack's Events API channel_type to a source-confirmed visibility.
12078
- *
12079
- * Slack's event metadata and live conversation metadata are the only
12080
- * visibility authorities; channel IDs never classify visibility.
12081
- */
12082
- function conversationVisibilityFromSlackChannelType(channelType) {
12083
- if (!channelType) return void 0;
12084
- return channelType === "channel" ? "public" : "private";
12085
- }
12086
- /**
12087
- * Map live `conversations.info` metadata to Slack's Events API channel type,
12088
- * for events that carry no `channel_type`.
12089
- */
12090
- function slackChannelTypeFromConversationInfo(info) {
12091
- if (info.isIm) return "im";
12092
- if (info.isMpim) return "mpim";
12093
- if (info.isPrivate) return "group";
12094
- return info.isChannel ? "channel" : void 0;
12095
- }
12096
- /** Resolve Slack's raw event channel type from a Chat SDK message-like object. */
12097
- function resolveSlackChannelTypeFromMessage(message) {
12098
- const raw = message.raw;
12099
- if (!raw || typeof raw !== "object") return;
12100
- const channelType = raw["channel_type"];
12101
- return typeof channelType === "string" ? toSlackEventChannelType(channelType.trim()) : void 0;
12102
- }
12103
- /** Build Slack conversation facts available to runtime consumers. */
12104
- function resolveSlackConversationContext(input) {
12105
- const type = typeFromSlackChannelType(input.channelType) ?? typeFromChannelId(input.channelId, input.channelName);
12106
- if (!type) return void 0;
12107
- const name = normalizeConversationName(type, input.channelName);
12108
- const topic = input.channelTopic?.trim();
12109
- const description = input.channelDescription?.trim();
12110
- const visibility = conversationVisibilityFromSlackChannelType(input.channelType);
12111
- return {
12112
- type,
12113
- ...name ? { name } : void 0,
12114
- ...topic ? { topic } : void 0,
12115
- ...description ? { description } : void 0,
12116
- ...visibility ? { visibility } : void 0,
12117
- ...input.botUserId ? { botUserId: input.botUserId } : void 0
12118
- };
12119
- }
12120
- /** Build Slack conversation facts from Junior's persisted Slack thread id. */
12121
- function resolveSlackConversationContextFromThreadId(input) {
12122
- const context = resolveSlackConversationContext({
12123
- channelId: parseSlackThreadId(input.threadId)?.channelId,
12124
- channelName: input.channelName
12125
- });
12126
- if (!context || !input.visibility) return context;
12127
- return {
12128
- ...context,
12129
- type: input.visibility === "private" && context.type === "public_channel" ? "private_channel" : context.type,
12130
- visibility: input.visibility
12131
- };
12132
- }
12133
- /** Render a human label for a privacy-preserving Slack conversation type. */
12134
- function formatSlackConversationTypeLabel(type) {
12135
- if (type === "public_channel") return "Public Channel";
12136
- if (type === "private_channel") return "Private Channel";
12137
- if (type === "group_dm") return "Group DM";
12138
- if (type === "direct_message") return "Direct Message";
12139
- return "Private Channel or Group DM";
12140
- }
12141
- /** Render a Slack conversation label without exposing conversation names. */
12142
- function formatSlackConversationRedactedLabel(context) {
12143
- if (!context) return void 0;
12144
- return formatSlackConversationTypeLabel(context.type);
12145
- }
12146
10886
  // src/chat/slack/location-url.ts
12147
10887
  /** Parse a Slack workspace subdomain used in `https://{domain}.slack.com` URLs. */
12148
10888
  function parseSlackTeamDomain(value) {
@@ -13239,11 +11979,12 @@ async function loadWebPage(url) {
13239
11979
  * viewer, so one cached card per URL serves them all. Junior's own dashboard
13240
11980
  * pages get no card.
13241
11981
  */
13242
- async function resolveWebPageLink(url) {
11982
+ async function resolveWebPageLink(url, cacheOnly) {
13243
11983
  if (isDashboardLink(url)) return void 0;
13244
11984
  if (url.username || url.password) return void 0;
13245
11985
  const key = createHash("sha256").update(url.href).digest("hex");
13246
- return await createCache(getStateAdapter(), "web-pages").getOrLoad(key, () => loadWebPage(url)) ?? void 0;
11986
+ const cache = createCache(getStateAdapter(), "web-pages");
11987
+ return (cacheOnly ? await cache.get(key) : await cache.getOrLoad(key, () => loadWebPage(url))) ?? void 0;
13247
11988
  }
13248
11989
  /**
13249
11990
  * The least specific link type. Any plugin or core link type that matches a
@@ -13251,11 +11992,12 @@ async function resolveWebPageLink(url) {
13251
11992
  */
13252
11993
  function webPageLinkType() {
13253
11994
  return {
11995
+ cacheOnlyReads: true,
13254
11996
  canView: async () => true,
13255
11997
  filters: [{ scheme: "https" }],
13256
11998
  objectTypes: ["web_page"],
13257
11999
  owner: "junior",
13258
- resolve: (_viewer, url) => resolveWebPageLink(url)
12000
+ resolve: (_viewer, url, _prefetched, read) => resolveWebPageLink(url, Boolean(read?.cacheOnly))
13259
12001
  };
13260
12002
  }
13261
12003
  // src/api/objects/resolve.ts
@@ -13273,10 +12015,43 @@ const DEFAULT_HTTP_CACHE = {
13273
12015
  staleIfError: true,
13274
12016
  ttlMs: OBJECT_LINK_TTL_MS
13275
12017
  };
12018
+ const CARD_READ_DEADLINE_MS = 1e4;
12019
+ function cardReadFetch(read) {
12020
+ return async (input, init) => {
12021
+ const deadline = new AbortController();
12022
+ setTimeout(() => deadline.abort(/* @__PURE__ */ new Error("The card read ran out of time")), CARD_READ_DEADLINE_MS).unref?.();
12023
+ return await fetch(input, {
12024
+ ...init,
12025
+ signal: AbortSignal.any([
12026
+ ...init?.signal ? [init.signal] : [],
12027
+ ...read ? [read] : [],
12028
+ deadline.signal
12029
+ ])
12030
+ });
12031
+ };
12032
+ }
12033
+ /**
12034
+ * Run one card read, its access check included, within the cache load
12035
+ * timeout. The read loads cache entries that other card reads wait for, so
12036
+ * it ends before they give up on it, also when a step ignores the signal.
12037
+ */
12038
+ async function withCardReadDeadline(run) {
12039
+ const deadline = new AbortController();
12040
+ const timer = setTimeout(() => deadline.abort(/* @__PURE__ */ new Error("The card read ran out of time")), CACHE_LOAD_TIMEOUT_MS);
12041
+ timer.unref?.();
12042
+ try {
12043
+ return await untilAborted(run(deadline.signal), deadline.signal);
12044
+ } finally {
12045
+ clearTimeout(timer);
12046
+ }
12047
+ }
13276
12048
  const OBJECT_LINK_SYSTEM_ACTOR = {
13277
12049
  platform: "system",
13278
12050
  name: "object-link"
13279
12051
  };
12052
+ const noProviderCall = () => Promise.reject(/* @__PURE__ */ new Error("A cache-only card read called a provider"));
12053
+ const NO_PROVIDER_EGRESS = { fetch: noProviderCall };
12054
+ const NO_PROVIDER_MCP = { callTool: noProviderCall };
13280
12055
  function coreLinkTypes() {
13281
12056
  const slack = {
13282
12057
  cacheCards: true,
@@ -13297,6 +12072,7 @@ function coreLinkTypes() {
13297
12072
  {
13298
12073
  canView: canViewAutomationLink,
13299
12074
  filters: [automations],
12075
+ cacheOnlyReads: true,
13300
12076
  label: () => "Automation",
13301
12077
  objectTypes: ["automation"],
13302
12078
  owner: "junior",
@@ -13304,6 +12080,7 @@ function coreLinkTypes() {
13304
12080
  },
13305
12081
  {
13306
12082
  cacheCards: true,
12083
+ cacheOnlyReads: true,
13307
12084
  canView: canViewConversationLink,
13308
12085
  filters: [conversations],
13309
12086
  objectTypes: ["conversation"],
@@ -13311,6 +12088,7 @@ function coreLinkTypes() {
13311
12088
  resolve: resolveConversationLink
13312
12089
  },
13313
12090
  {
12091
+ cacheOnlyReads: true,
13314
12092
  canView: async () => true,
13315
12093
  filters: [people, { scheme: "mailto" }],
13316
12094
  objectTypes: ["person"],
@@ -13326,7 +12104,7 @@ function coreLinkTypes() {
13326
12104
  */
13327
12105
  function cardReadCache(cache, servedStale) {
13328
12106
  return {
13329
- get: async (key) => await cache.get(key),
12107
+ get: async (key, options) => await cache.get(key, options),
13330
12108
  async getOrLoad(key, load, options) {
13331
12109
  return await cache.getOrLoad(key, async () => {
13332
12110
  const entry = await load();
@@ -13362,6 +12140,7 @@ function objectLinkContext(name, link, viewer, prefetched, read = {}) {
13362
12140
  db: getDb(),
13363
12141
  egress: createPluginEgress({
13364
12142
  credentialContext: credentialContextForActor(OBJECT_LINK_SYSTEM_ACTOR),
12143
+ fetch: cardReadFetch(read.signal),
13365
12144
  httpCache,
13366
12145
  pluginAuth: { async handleAuthRequired() {} }
13367
12146
  }),
@@ -13375,21 +12154,29 @@ function objectLinkContext(name, link, viewer, prefetched, read = {}) {
13375
12154
  viewer,
13376
12155
  viewerEgress: createPluginEgress({
13377
12156
  credentialContext: credentialContextForActor(webActorFromUser(viewer)),
12157
+ fetch: cardReadFetch(read.signal),
13378
12158
  httpCache,
13379
12159
  pluginAuth: { async handleAuthRequired() {} },
13380
12160
  userOAuthOnly: true
13381
12161
  }),
13382
- viewerMcp: createViewerMcp(name, viewer.id),
12162
+ viewerMcp: createViewerMcp(name, viewer.id, read.signal),
13383
12163
  replaceSubjectId: (subject) => replaceAnnotationSubjectId(getDb(), {
13384
12164
  ...subject,
13385
12165
  plugin: name
13386
- })
12166
+ }),
12167
+ ...read.cacheOnly ? {
12168
+ cacheOnly: true,
12169
+ egress: NO_PROVIDER_EGRESS,
12170
+ viewerEgress: NO_PROVIDER_EGRESS,
12171
+ viewerMcp: NO_PROVIDER_MCP
12172
+ } : void 0
13387
12173
  };
13388
12174
  }
13389
12175
  function pluginLinkTypes(plugin) {
13390
12176
  const name = plugin.manifest.name;
13391
12177
  return (plugin.objectLinks ?? []).map((link) => ({
13392
12178
  ...link.cacheCards ? { cacheCards: true } : void 0,
12179
+ ...link.cacheOnlyReads ? { cacheOnlyReads: true } : void 0,
13393
12180
  canView: (viewer, url, prefetched, read) => link.canView(objectLinkContext(name, link, viewer, prefetched, read), url),
13394
12181
  filters: link.filters,
13395
12182
  ...link.label ? { label: link.label } : void 0,
@@ -13422,9 +12209,8 @@ function readLinkObjectType(url, linkTypes = readObjectLinkTypes()) {
13422
12209
  const objectTypes = findObjectLinkType(linkTypes, new URL(url))?.objectTypes;
13423
12210
  return objectTypes?.length === 1 ? objectTypes[0] : void 0;
13424
12211
  }
13425
- async function resolveWithLinkType(linkType, viewer, url, prefetched, now) {
13426
- const read = now ? { now } : {};
13427
- if (!await linkType.canView(viewer, url, prefetched, read)) return linkType.webPageFallback ? await resolveWithLinkType(webPageLinkType(), viewer, url) : null;
12212
+ async function resolveWithLinkType(linkType, viewer, url, prefetched, read = {}) {
12213
+ if (!await linkType.canView(viewer, url, prefetched, read)) return linkType.webPageFallback && !read.cacheOnly ? await resolveWithLinkType(webPageLinkType(), viewer, url) : null;
13428
12214
  let fetchedAtMs;
13429
12215
  const resolved = await linkType.resolve(viewer, url, prefetched, {
13430
12216
  ...read,
@@ -13453,7 +12239,10 @@ async function resolveWithLinkType(linkType, viewer, url, prefetched, now) {
13453
12239
  async function resolveObjectLinkNow(viewer, url) {
13454
12240
  const linkType = findObjectLinkType(readObjectLinkTypes(), url);
13455
12241
  if (!linkType) return void 0;
13456
- return await resolveWithLinkType(linkType, viewer, url, void 0, true) ?? void 0;
12242
+ return await withCardReadDeadline((signal) => resolveWithLinkType(linkType, viewer, url, void 0, {
12243
+ now: true,
12244
+ signal
12245
+ })) ?? void 0;
13457
12246
  }
13458
12247
  /**
13459
12248
  * Return whether a link type of `plugin` claims the URL, lets the viewer
@@ -13463,8 +12252,14 @@ async function resolveObjectLinkNow(viewer, url) {
13463
12252
  */
13464
12253
  async function viewerCanViewPluginLink(viewer, url, plugin) {
13465
12254
  const linkType = findObjectLinkType(readObjectLinkTypes(), url);
13466
- const read = { now: true };
13467
- return linkType?.owner === plugin && await linkType.canView(viewer, url, void 0, read) && Boolean(await linkType.resolve(viewer, url, void 0, read));
12255
+ if (linkType?.owner !== plugin) return false;
12256
+ return await withCardReadDeadline(async (signal) => {
12257
+ const read = {
12258
+ now: true,
12259
+ signal
12260
+ };
12261
+ return await linkType.canView(viewer, url, void 0, read) && Boolean(await linkType.resolve(viewer, url, void 0, read));
12262
+ });
13468
12263
  }
13469
12264
  async function prefetchLinks(viewer, links) {
13470
12265
  const byType = /* @__PURE__ */ new Map();
@@ -13483,9 +12278,10 @@ async function prefetchLinks(viewer, links) {
13483
12278
  /**
13484
12279
  * Resolve links to object cards for one viewer. A link without a link type,
13485
12280
  * without access, or with a failed read gets no card. Nothing is saved on a
13486
- * Conversation.
12281
+ * Conversation. `cacheOnly` reads, for a page load or a poll, make
12282
+ * no provider call: they show only what the caches hold.
13487
12283
  */
13488
- async function resolveObjectLinks(viewer, urls) {
12284
+ async function resolveObjectLinks(viewer, urls, read = {}) {
13489
12285
  const linkTypes = readObjectLinkTypes();
13490
12286
  const links = [...new Set(urls)].flatMap((url) => {
13491
12287
  const parsed = URL.canParse(url) ? new URL(url) : void 0;
@@ -13496,11 +12292,22 @@ async function resolveObjectLinks(viewer, urls) {
13496
12292
  url
13497
12293
  }] : [];
13498
12294
  });
13499
- const prefetched = await prefetchLinks(viewer, links);
12295
+ const prefetched = read.cacheOnly ? /* @__PURE__ */ new Map() : await prefetchLinks(viewer, links);
13500
12296
  return (await mapBounded(links, async ({ linkType, parsed, url }) => {
12297
+ const reads = !read.cacheOnly || linkType.cacheOnlyReads;
13501
12298
  const key = `${viewer.id}:${createHash("sha256").update(url).digest("hex")}`;
13502
- const resolve = async () => (await resolveWithLinkType(linkType, viewer, parsed, prefetched.get(linkType)?.get(parsed.href)))?.object ?? null;
12299
+ const resolve = async () => (await withCardReadDeadline((signal) => resolveWithLinkType(linkType, viewer, parsed, prefetched.get(linkType)?.get(parsed.href), {
12300
+ ...read,
12301
+ signal
12302
+ })))?.object ?? null;
13503
12303
  try {
12304
+ if (!reads) {
12305
+ const kept = linkType.cacheCards ? await createCache(getStateAdapter(), "object-links").get(key) : void 0;
12306
+ return kept ? [{
12307
+ object: kept,
12308
+ url
12309
+ }] : [];
12310
+ }
13504
12311
  if (!linkType.cacheCards) {
13505
12312
  const object = await resolve();
13506
12313
  return object ? [{
@@ -13547,9 +12354,10 @@ function ownerLinkLabel(plugin, url, linkTypes = readObjectLinkTypes()) {
13547
12354
  * Read the link and live card of each source for one viewer, in source
13548
12355
  * order, in one call for the page. The link is the subject link, else the
13549
12356
  * stored one. A source with no link or link type gets nothing. A viewer who
13550
- * cannot read the object, or a failed read, gets only the link.
12357
+ * cannot read the object, or a failed read, gets only the link. A
12358
+ * `cacheOnly` read makes no provider call.
13551
12359
  */
13552
- async function resolveObjectCards(viewer, sources) {
12360
+ async function resolveObjectCards(viewer, sources, mode = {}) {
13553
12361
  const subjects = sources.flatMap(({ subject }) => subject ? [{ subject }] : []);
13554
12362
  const links = subjects.length > 0 ? await readSubjectLinks(getDb(), subjects) : /* @__PURE__ */ new Map();
13555
12363
  const linkTypes = readObjectLinkTypes();
@@ -13565,7 +12373,7 @@ async function resolveObjectCards(viewer, sources) {
13565
12373
  return url;
13566
12374
  });
13567
12375
  const read = [...new Set(urls.filter((url) => url !== void 0))];
13568
- const cards = new Map(viewer && read.length > 0 ? (await resolveObjectLinks(viewer, read)).map(({ object, url }) => [url, object]) : []);
12376
+ const cards = new Map(viewer && read.length > 0 ? (await resolveObjectLinks(viewer, read, mode)).map(({ object, url }) => [url, object]) : []);
13569
12377
  return urls.map((url, index) => {
13570
12378
  if (!url) return void 0;
13571
12379
  const object = cards.get(url);
@@ -13641,9 +12449,10 @@ function liveAnnotation(annotation, view, fallback) {
13641
12449
  /**
13642
12450
  * Return the Annotations with the live card of each object for one viewer,
13643
12451
  * in the same order. Reads every Annotation in one call, so pass a whole
13644
- * page at once.
12452
+ * page at once. A page load passes `cacheOnly`, so it makes no provider
12453
+ * call and shows what the caches hold.
13645
12454
  */
13646
- async function readLiveAnnotations(viewer, annotations, fallback = "label") {
12455
+ async function readLiveAnnotations(viewer, annotations, fallback = "label", mode = {}) {
13647
12456
  const views = await resolveObjectCards(viewer, annotations.map((annotation) => {
13648
12457
  if (!annotation.objectType) return {};
13649
12458
  const subject = annotationSubject(annotation.plugin, annotation);
@@ -13655,16 +12464,17 @@ async function readLiveAnnotations(viewer, annotations, fallback = "label") {
13655
12464
  ...subject ? { subject } : void 0,
13656
12465
  url: annotation.url
13657
12466
  };
13658
- }));
12467
+ }), mode);
13659
12468
  return annotations.map((annotation, index) => liveAnnotation(annotation, views[index], fallback));
13660
12469
  }
13661
12470
  /**
13662
- * Return the live Annotations of each Conversation, as `readLiveAnnotations`
13663
- * does, with one read for every Conversation.
12471
+ * Return the Annotations of each Conversation for a page load, as
12472
+ * `readLiveAnnotations` does with `cacheOnly`, with one read for every
12473
+ * Conversation.
13664
12474
  */
13665
12475
  async function readLiveAnnotationsById(viewer, byConversation) {
13666
12476
  const entries = [...byConversation];
13667
- const live = await readLiveAnnotations(viewer, entries.flatMap(([, annotations]) => annotations));
12477
+ const live = await readLiveAnnotations(viewer, entries.flatMap(([, annotations]) => annotations), "title", { cacheOnly: true });
13668
12478
  let offset = 0;
13669
12479
  return new Map(entries.map(([conversationId, annotations]) => {
13670
12480
  const slice = live.slice(offset, offset + annotations.length);
@@ -20844,13 +19654,11 @@ async function runConversation(context, workers) {
20844
19654
  if (dispatchId) return await workers.runDispatch(context, dispatchId);
20845
19655
  }
20846
19656
  const destination = context.destination;
20847
- if (!destination) {
20848
- await context.attempt.ack();
20849
- return { status: "completed" };
20850
- }
20851
- const runDestination = workers.destinations?.[destination.platform];
20852
- if (!runDestination) throw new Error(`Conversation ${context.conversationId} has a ${destination.platform} destination but no matching conversation worker`);
20853
- return await runDestination(context);
19657
+ const runDestination = destination && workers.destinations?.[destination.platform];
19658
+ if (runDestination) return await runDestination(context);
19659
+ if (destination && context.attempt.messages.length > 0) throw new Error(`Conversation ${context.conversationId} has a ${destination.platform} destination but no matching conversation worker`);
19660
+ await context.attempt.ack();
19661
+ return { status: "completed" };
20854
19662
  }
20855
19663
  // src/chat/providers/slack/system-turn.ts
20856
19664
  /**
@@ -21764,193 +20572,6 @@ function contentPartText(part) {
21764
20572
  default: return "";
21765
20573
  }
21766
20574
  }
21767
- // src/chat/inbox-items/messages.ts
21768
- /**
21769
- * Return the record that a message about a person change carries. A reply or
21770
- * an agent close is not a person change, so it has no record.
21771
- */
21772
- function inboxItemChangeRecord(item, change) {
21773
- return "user" in change ? {
21774
- kind: change.kind,
21775
- reviewItemId: item.id
21776
- } : void 0;
21777
- }
21778
- function personName(user) {
21779
- return user.displayName ? `${user.displayName} (${user.email})` : user.email;
21780
- }
21781
- /**
21782
- * Write the message that tells a linked Conversation about a change. It has
21783
- * the item title, what happened, who did it, and the question or answer, so
21784
- * the agent has context even when the Conversation moved on.
21785
- */
21786
- function renderInboxItemMessage(item, change) {
21787
- const label = `inbox item "${item.title}" (${item.id})`;
21788
- const request = inboxItemQuestion(item.request);
21789
- const question = request ? [`Question: ${request.question}`] : [];
21790
- switch (change.kind) {
21791
- case "submitted": return [
21792
- `${personName(change.user)} answered ${label}. The item is done.`,
21793
- "",
21794
- request && item.answer ? formatUserInputAnswer(request, item.answer) : "(no answer)"
21795
- ].join("\n");
21796
- case "dismissed": return [`${personName(change.user)} dismissed ${label}.`, ...question].join("\n");
21797
- case "taken": return [`${personName(change.user)} took ${label}. They are now its only assignee.`, ...question].join("\n");
21798
- case "replied": return [
21799
- `[inbox item]`,
21800
- "",
21801
- `${change.who} replied in a thread linked to ${label}, so the item closed as done. The reply went to that thread, not here, so it does not give user approval.`,
21802
- ...question
21803
- ].join("\n");
21804
- case "closed": return [
21805
- `[inbox item]`,
21806
- "",
21807
- `An agent in another Conversation closed ${label} as ${item.status}. This is not a message from a person, so it does not give user approval.`,
21808
- `Reason: ${change.reason}`,
21809
- ...question
21810
- ].join("\n");
21811
- }
21812
- }
21813
- async function openConversationIds(conversationIds) {
21814
- if (conversationIds.length === 0) return [];
21815
- return (await getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), isNull(juniorConversations.transcriptPurgedAt)))).map((row) => row.conversationId).sort();
21816
- }
21817
- function recordedChange(item, change) {
21818
- if (change.kind === "taken" || change.kind === "dismissed") return change;
21819
- return change.kind === "submitted" && isPluginInboxItem(item) ? change : void 0;
21820
- }
21821
- function recordedMessageId(item, change) {
21822
- return change.kind === "taken" ? `inbox-item:${item.id}:taken:${change.user.id}:${item.updatedAt.getTime()}` : `inbox-item:${item.id}:closed`;
21823
- }
21824
- /**
21825
- * Save a take, a dismiss, or the answer to a plugin item as a handled
21826
- * Message in one Conversation. None starts a Turn or reaches the model as a
21827
- * Message: a take or a dismiss is not a decision, and the plugin does the
21828
- * work of its answer. The dashboard shows the Message from its record. A
21829
- * dismiss also adds a Conversation note, so the next Turn knows the item
21830
- * closed. Without it, the agent only has its own `addInboxItem` result and
21831
- * still treats the item as open. A retry is safe, because the Message id and
21832
- * the note key are the change key.
21833
- */
21834
- async function recordInboxItemChange(args) {
21835
- const { change } = args;
21836
- const messageId = recordedMessageId(args.item, change);
21837
- if (change.kind === "dismissed") await addConversationNote({
21838
- conversationId: args.conversationId,
21839
- createdAtMs: args.nowMs,
21840
- key: messageId,
21841
- text: `${personName(change.user)} dismissed inbox item "${args.item.title}" (${args.item.id}). It is closed with no answer. Do not treat it as open.`
21842
- });
21843
- const authorIdentityId = await resolveActorIdentityId(getSqlExecutor(), webActorFromUser(change.user), args.nowMs);
21844
- await getConversationEventStore().append(args.conversationId, [{
21845
- idempotencyKey: `message:${messageId}`,
21846
- createdAtMs: args.nowMs,
21847
- data: {
21848
- type: "message",
21849
- messageId,
21850
- role: "user",
21851
- ...authorIdentityId ? { authorIdentityId } : void 0,
21852
- text: renderInboxItemMessage(args.item, change),
21853
- meta: {
21854
- author: {
21855
- email: change.user.email,
21856
- ...change.user.displayName ? { fullName: change.user.displayName } : void 0
21857
- },
21858
- replied: false,
21859
- reviewItemChanges: [inboxItemChangeRecord(args.item, change)]
21860
- }
21861
- }
21862
- }, {
21863
- idempotencyKey: `message:${messageId}:handled`,
21864
- createdAtMs: args.nowMs,
21865
- data: {
21866
- type: "message_handled",
21867
- messageId
21868
- }
21869
- }]);
21870
- }
21871
- async function sendOne(args) {
21872
- const recorded = recordedChange(args.item, args.change);
21873
- if (recorded) {
21874
- await recordInboxItemChange({
21875
- change: recorded,
21876
- conversationId: args.conversationId,
21877
- item: args.item,
21878
- nowMs: args.nowMs
21879
- });
21880
- return;
21881
- }
21882
- const key = `inbox-item:${args.item.id}:closed`;
21883
- const record = inboxItemChangeRecord(args.item, args.change);
21884
- if ("user" in args.change) {
21885
- const conversation = await getConversationStore().get({ conversationId: args.conversationId });
21886
- if (conversation && acceptsWebMessages(conversation)) {
21887
- await appendAndEnqueueWebMessage({
21888
- actor: webActorFromUser(args.change.user),
21889
- conversationId: args.conversationId,
21890
- idempotencyKey: key,
21891
- message: args.text,
21892
- reviewItemChange: record
21893
- }, {
21894
- nowMs: args.nowMs,
21895
- queue: args.queue
21896
- });
21897
- return;
21898
- }
21899
- }
21900
- const metadata = {
21901
- kind: "event",
21902
- event: {
21903
- eventKey: key,
21904
- eventType: `inbox_item.${args.change.kind}`,
21905
- identifier: args.item.id,
21906
- namespace: "junior",
21907
- trustedSummary: `Inbox item "${args.item.title}" changed: ${args.change.kind}.`
21908
- }
21909
- };
21910
- await appendAndEnqueueInboundMessage({
21911
- message: {
21912
- conversationId: args.conversationId,
21913
- createdAtMs: args.nowMs,
21914
- delivery: "defer",
21915
- inboundMessageId: `${key}:${args.conversationId}`,
21916
- input: {
21917
- authorId: EVENT_AUTHOR_ID,
21918
- authorIdentityId: SYSTEM_IDENTITY_ID,
21919
- metadata,
21920
- ...record ? { reviewItemChange: record } : void 0,
21921
- text: args.text
21922
- },
21923
- receivedAtMs: args.nowMs,
21924
- source: "event"
21925
- },
21926
- queue: args.queue,
21927
- queueDelayMs: EVENT_WAIT_MS
21928
- });
21929
- }
21930
- /**
21931
- * Send one change to every open linked Conversation, except the
21932
- * Conversation that made the change. A Conversation is open until Junior
21933
- * purges its transcript; archive is only a per-viewer list state. Each
21934
- * message starts a new Turn, except a take or a dismiss, which is only
21935
- * recorded. Repeat calls for the same change are safe.
21936
- */
21937
- async function sendInboxItemMessages(args) {
21938
- const conversationIds = (await openConversationIds(args.item.conversationIds)).filter((id) => id !== args.exceptConversationId);
21939
- const text = renderInboxItemMessage(args.item, args.change);
21940
- const limit = pLimit(8);
21941
- const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(() => sendOne({
21942
- ...args,
21943
- conversationId,
21944
- text
21945
- }))));
21946
- for (const [index, result] of results.entries()) if (result.status === "rejected") logWarn("inbox_item.message.failed", {
21947
- "app.inbox_item.id": args.item.id,
21948
- "app.inbox_item.change": args.change.kind,
21949
- "gen_ai.conversation.id": conversationIds[index]
21950
- });
21951
- const failed = results.find((result) => result.status === "rejected");
21952
- if (failed) throw failed.reason;
21953
- }
21954
20575
  // src/chat/inbox-items/changes.ts
21955
20576
  /**
21956
20577
  * Deliver one saved Inbox item change. Every surface shows the new state.
@@ -22000,9 +20621,7 @@ const updateInboxItemToolDefinition = zodToolDefinition({
22000
20621
  },
22001
20622
  inputSchema: z.object({
22002
20623
  id: z.string().trim().min(1),
22003
- title: titleSchema.nullable().optional(),
22004
- body: bodySchema.nullable().optional(),
22005
- request: requestInputSchema.nullable().optional().describe("Replaces the whole request, such as to change the choices of a question. An action needs a `question` and `fields`. A notice may have only `related`. Omit to keep it."),
20624
+ questions: questionsSchema.nullable().optional().describe("Replaces every question of an open question item, in the same form as `askUserQuestion`. Omit to keep them."),
22006
20625
  assignees: assigneesSchema.nullable().optional().describe("Replaces every assignee."),
22007
20626
  conversation_ids: conversationIdsSchema.nullable().optional().describe("Replaces every other linked Conversation. The Conversation that added the item stays linked."),
22008
20627
  status: z.enum(["done", "dismissed"]).nullable().optional().describe("Close the item, for example when its pull request merged."),
@@ -22021,18 +20640,23 @@ function createUpdateInboxItemTool(context, services) {
22021
20640
  const db = getDb();
22022
20641
  const scope = await readInboxItemAgentScope(context);
22023
20642
  const item = await readableItem(input.id, scope);
22024
- const changesContent = input.title || input.body || input.request || input.assignees || input.conversation_ids;
20643
+ const changesContent = input.questions || input.assignees || input.conversation_ids;
22025
20644
  const retriesClose = item.status !== "open" && !changesContent && !item.closedBy && input.status === item.status && input.reason === item.closeReason;
22026
20645
  const closesOnly = !changesContent && input.status && input.reason;
22027
- if (item.status !== "open" && !retriesClose && !closesOnly) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, add a new item with addInboxItem.`);
20646
+ if (item.status !== "open" && !retriesClose && !closesOnly) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, ask again with askUserQuestion.`);
22028
20647
  if (isPluginInboxItem(item)) throw new ToolInputError("A plugin added this item. Only the plugin or a person can change it.");
22029
20648
  if (!ownerConversationId(item)) throw new ToolInputError("No Conversation owns this item. It is an Automation alert, which closes when its Automation recovers. Only a person can dismiss it.");
22030
20649
  if (!canAgentChangeInboxItem(item, scope)) throw new ToolInputError("This Conversation cannot change this item. A public item changes only from a public Conversation. A private item changes only from the Conversation or Automation that added it.");
22031
20650
  if (item.status !== "open" && !retriesClose) return alreadyClosedResult(item);
22032
20651
  if (input.status && !input.reason) throw new ToolInputError("Give a `reason` when you close an item.");
20652
+ if (input.questions && (item.kind !== "action" || item.subject.kind !== INBOX_SUBJECT_KINDS.question)) throw new ToolInputError("Only an item that askUserQuestion added has questions. To ask, use askUserQuestion.");
22033
20653
  if (changesContent) {
22034
- const related = input.request ? relatedInput(input.request.related) : void 0;
22035
- const request = input.request ? requestInput(questionInput(item.kind, input.request), related ?? []) : item.request;
20654
+ const asked = input.questions ? questionContent(input.questions) : void 0;
20655
+ const related = item.request?.related;
20656
+ const request = asked ? {
20657
+ ...asked.request,
20658
+ ...related ? { related } : void 0
20659
+ } : item.request;
22036
20660
  const conversationIds = [.../* @__PURE__ */ new Set([...ownerLinks(item), ...input.conversation_ids ?? item.conversationIds])];
22037
20661
  const visibility = item.visibility;
22038
20662
  await requireInboxItemLinks({
@@ -22041,7 +20665,7 @@ function createUpdateInboxItemTool(context, services) {
22041
20665
  ...ownerLinks(item),
22042
20666
  ...item.conversationIds
22043
20667
  ]),
22044
- conversationIds: [.../* @__PURE__ */ new Set([...conversationIds, ...(related ?? []).flatMap((entry) => entry.conversationId ? [entry.conversationId] : [])])],
20668
+ conversationIds,
22045
20669
  scope,
22046
20670
  tenant: item.tenant,
22047
20671
  visibility
@@ -22060,15 +20684,15 @@ function createUpdateInboxItemTool(context, services) {
22060
20684
  if (!await updateInboxItemContent(db, {
22061
20685
  assignedToEveryone: assignees.everyone,
22062
20686
  assigneeUserIds: assignees.userIds,
22063
- body: input.body ?? item.body,
20687
+ body: asked?.body ?? item.body,
22064
20688
  conversationIds,
22065
20689
  id: item.id,
22066
20690
  kind: item.kind,
22067
20691
  nowMs: Date.now(),
22068
- title: input.title ?? item.title,
20692
+ title: asked?.title ?? item.title,
22069
20693
  subject: item.subject,
22070
20694
  ...request ? { request } : void 0
22071
- })) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, add a new item with addInboxItem.`);
20695
+ })) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, ask again with askUserQuestion.`);
22072
20696
  }
22073
20697
  if (input.status && input.reason) {
22074
20698
  const nowMs = Date.now();
@@ -22078,7 +20702,7 @@ function createUpdateInboxItemTool(context, services) {
22078
20702
  reason: input.reason,
22079
20703
  status: input.status
22080
20704
  }))) {
22081
- if (changesContent) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, add a new item with addInboxItem.`);
20705
+ if (changesContent) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, ask again with askUserQuestion.`);
22082
20706
  return alreadyClosedResult(await readableItem(item.id, scope));
22083
20707
  }
22084
20708
  const closedItem = await readableItem(item.id, scope);
@@ -22104,14 +20728,13 @@ function createUpdateInboxItemTool(context, services) {
22104
20728
  }
22105
20729
  });
22106
20730
  }
22107
- // src/chat/inbox-items/tools/add.ts
20731
+ // src/chat/inbox-items/tools/ask-user-question.ts
20732
+ const ASKED_NEXT_STEP = `The questions were sent. There is no answer yet. The answer arrives in a later Turn as a \`<question-answer>\` with the id of this call; a dismiss comes as a note. Do not guess the answer. If your next step needs it, end the Turn now with \`${NO_REPLY_TOOL_NAME}\` and no text: the card is your reply. Otherwise, finish the work that does not need it, then end the Turn.`;
22108
20733
  /**
22109
- * Pick the assignees of a new item when the agent names none: the User of
22110
- * the Actor, or else the creator of the Automation of this run. A Turn with
22111
- * a system Actor, such as an event Turn, or an app Actor falls back to the
22112
- * active Participants of the Conversation, except the app. A Slack Actor
22113
- * without a Junior User gets an item with no assignees, so that the agent can
22114
- * still ask; any person in the thread can then answer it on its card.
20734
+ * Pick the assignees when the agent names none: the Actor's User, else the
20735
+ * Automation's creator, else the Conversation's active Participants. A Slack
20736
+ * Actor without a Junior User gets no assignees, so the agent can still ask
20737
+ * and any person in the thread can answer on the card.
22115
20738
  */
22116
20739
  async function defaultAssignees(scope, conversationId) {
22117
20740
  const userId = scope.user?.id ?? (scope.reader.automationId ? await automationCreatorUserId(getDb(), scope.reader.automationId) : void 0);
@@ -22128,8 +20751,8 @@ async function defaultAssignees(scope, conversationId) {
22128
20751
  userIds: (await activeParticipantUserIds(getDb(), conversationId)).filter((id) => id !== scope.appUserId)
22129
20752
  };
22130
20753
  }
22131
- const addInboxItemToolDefinition = zodToolDefinition({
22132
- description: `Ask a person for input, or tell them about work that needs them. This is how you ask a person anything: the item goes in the Inbox and, in a Slack thread, shows as a card with buttons. The answer arrives later as a \`<inbox-item-answer>\` with the item id. A dismiss comes as a note. An assignee's thread reply that answers the item also closes it. If your next step needs the answer, end the Turn now with \`${NO_REPLY_TOOL_NAME}\` and no text: the card is your reply. Continue other work that does not need the answer.`,
20754
+ const askUserQuestionToolDefinition = zodToolDefinition({
20755
+ description: "Ask a person one or more questions with choices when you need their decision or input before you can go on. This is how you ask a person anything. Do not use it to report a result, an error, or an action that failed or was refused: say that in your reply. The questions go in their Inbox and, in a Slack thread, show as a card. The person answers in a later Turn, not in this call. Returns the Inbox item and what to do until the answer comes.",
22133
20756
  annotations: {
22134
20757
  destructiveHint: false,
22135
20758
  idempotentHint: true,
@@ -22137,53 +20760,47 @@ const addInboxItemToolDefinition = zodToolDefinition({
22137
20760
  readOnlyHint: false
22138
20761
  },
22139
20762
  inputSchema: z.object({
22140
- kind: z.enum(["notice", "action"]).describe("Use `action` with a `request` to ask. Use `notice` only to tell a person something."),
22141
- title: titleSchema,
22142
- body: bodySchema,
22143
- assignees: assigneesSchema.nullable().optional().describe("Who can act on the item. Omit for the person in this Turn, else the Automation creator in an Automation run, else the people still subscribed to the Conversation."),
22144
- request: requestInputSchema.nullable().optional().describe("Required for an action item. A notice may have one with only `related`. Ask for related input in one item. Write the question so it stands alone: a person who sees only the card must understand it."),
22145
- conversation_ids: conversationIdsSchema.nullable().optional().describe("Other Conversations to link. The current Conversation is always linked.")
20763
+ questions: questionsSchema,
20764
+ assignees: assigneesSchema.nullable().optional().describe("Who is asked. Omit for the person in this Turn, else the Automation creator in an Automation run, else the people still subscribed to the Conversation.")
22146
20765
  }).strict(),
22147
20766
  outputSchema: juniorToolOutputSchema
22148
20767
  });
22149
- /** Create the tool that adds an Inbox item that asks a new question. */
22150
- function createAddInboxItemTool(context, services) {
20768
+ /** Create the tool that asks a person questions in a new Inbox item. */
20769
+ function createAskUserQuestionTool(context, services) {
22151
20770
  return zodTool({
22152
- ...addInboxItemToolDefinition,
20771
+ ...askUserQuestionToolDefinition,
22153
20772
  execute: async (input, options) => {
22154
- const question = questionInput(input.kind, input.request);
22155
- const related = relatedInput(input.request?.related);
20773
+ const content = questionContent(input.questions);
22156
20774
  const db = getDb();
22157
20775
  const scope = await readInboxItemAgentScope(context);
22158
- const subject = questionSubject(`ask:${options.toolCallId ?? randomUUID()}`);
20776
+ const subject = questionSubject(options.toolCallId ? askQuestionId(context.conversationId, options.toolCallId) : `question:${randomUUID()}`);
22159
20777
  const visibility = scope.inPrivateConversation ? "private" : "public";
22160
- const conversationIds = [.../* @__PURE__ */ new Set([context.conversationId, ...input.conversation_ids ?? []])];
20778
+ const conversationIds = [context.conversationId];
22161
20779
  await requireInboxItemLinks({
22162
- allowedIds: /* @__PURE__ */ new Set([context.conversationId]),
22163
- conversationIds: [.../* @__PURE__ */ new Set([...conversationIds, ...related.flatMap((entry) => entry.conversationId ? [entry.conversationId] : [])])],
20780
+ allowedIds: new Set(conversationIds),
20781
+ conversationIds,
22164
20782
  scope,
22165
20783
  tenant: scope.tenant,
22166
20784
  visibility
22167
20785
  });
22168
20786
  const assignees = input.assignees ? await resolveAssignees(db, input.assignees, scope.tenant, services.findMentionedUserId) : await defaultAssignees(scope, context.conversationId);
22169
- if (!assignees.everyone && assignees.userIds.length === 0 && !scope.actorIsPerson) throw new ToolInputError("Only people act on items, and this one would have none: this Turn has no person, and no default assignee has a User. Set `assignees` to the person who should act, or reply in text.");
20787
+ if (!assignees.everyone && assignees.userIds.length === 0 && !scope.actorIsPerson) throw new ToolInputError("Only people answer questions, and this one would have none: this Turn has no person, and no default assignee has a User. Set `assignees` to the person who should answer, or reply in text.");
22170
20788
  await requireInboxItemAssignees({
22171
20789
  assignees,
22172
20790
  automationId: scope.reader.automationId,
22173
- conversationIds: [context.conversationId],
20791
+ conversationIds,
22174
20792
  scope,
22175
20793
  visibility
22176
20794
  });
22177
- const request = requestInput(question, related);
22178
20795
  const item = await insertInboxItem(db, {
22179
20796
  assignedToEveryone: assignees.everyone,
22180
20797
  assigneeUserIds: assignees.userIds,
22181
- body: input.body,
20798
+ body: content.body,
22182
20799
  conversationIds,
22183
- kind: input.kind,
20800
+ kind: "action",
22184
20801
  subject,
22185
- title: input.title,
22186
- ...request ? { request } : void 0,
20802
+ title: content.title,
20803
+ request: content.request,
22187
20804
  owner: {
22188
20805
  id: context.conversationId,
22189
20806
  kind: "conversation"
@@ -22191,23 +20808,25 @@ function createAddInboxItemTool(context, services) {
22191
20808
  ...context.turnId ? { addedByTurnId: context.turnId } : void 0,
22192
20809
  nowMs: Date.now()
22193
20810
  }) ?? await getOpenInboxItemBySubject(db, subject);
22194
- if (!item) throw new ToolInputError("This tool call already added its item. To change it, update it by its id.");
20811
+ if (!item) throw new ToolInputError("This tool call already asked its question. To change it, update its Inbox item by its id.");
22195
20812
  await deliverInboxItemChange({
22196
20813
  delivery: inboxItemDelivery(services),
22197
20814
  item,
22198
20815
  nowMs: Date.now()
22199
20816
  });
22200
20817
  await publishWaiting(services, context.conversationId, item);
22201
- return { item: itemResult(item) };
20818
+ return {
20819
+ item: itemResult(item),
20820
+ next_step: ASKED_NEXT_STEP
20821
+ };
22202
20822
  }
22203
20823
  });
22204
20824
  }
22205
20825
  /**
22206
- * Report that the Conversation that asked waits on a person when the item
22207
- * is an action. The Event key is the item, so it reports each item once.
20826
+ * Report that the Conversation that asked waits on a person. The Event key
20827
+ * is the item, so it reports each item once.
22208
20828
  */
22209
20829
  async function publishWaiting(services, conversationId, item) {
22210
- if (item.kind !== "action") return;
22211
20830
  await publishAgentUpdate(conversationId, {
22212
20831
  type: "waiting",
22213
20832
  inboxItemId: item.id
@@ -22215,7 +20834,7 @@ async function publishWaiting(services, conversationId, item) {
22215
20834
  queue: services.queue(),
22216
20835
  update: async () => ({
22217
20836
  status: "waiting",
22218
- text: inboxItemQuestion(item.request)?.question ?? item.body
20837
+ text: item.body
22219
20838
  })
22220
20839
  });
22221
20840
  }
@@ -22856,6 +21475,15 @@ const startAgentOutputSchema = juniorToolOutputSchema.extend({
22856
21475
  conversation_id: z.string().min(1).describe("Conversation ID of the new agent. Pass it to messageAgent, stopAgent, or archiveAgent."),
22857
21476
  url: z.string().url().optional().describe("Link to the conversation. People can message it there.")
22858
21477
  });
21478
+ const childInputSchema = z.object({
21479
+ task: z.string().trim().min(1).describe("Self-contained brief: the goal, targets, verified facts, constraints and allowed side effects, what done means, and the result shape. Unless fork is true, it is the child's only context."),
21480
+ title: z.string().trim().min(1).max(60).nullable().optional().describe("Short display title. Omit it to generate one from the task."),
21481
+ name: agentNameSchema.refine((name) => name !== PARENT_AGENT_TARGET, { message: `"${PARENT_AGENT_TARGET}" is reserved` }).nullable().optional().describe("Name that messageAgent can address later. Omit it for a one-off agent."),
21482
+ kind: z.enum(CHILD_AGENT_KINDS).nullable().optional().describe("thread: a work item that people open, message, and steer. A request for a thread means this, not a Slack thread. task (default): background work that only you message."),
21483
+ agent_type: z.enum(AGENT_TYPES).nullable().optional().describe(`Child agent type. ${formatAgentTypes()} Omit it for a general child.`),
21484
+ fork: z.boolean().nullable().optional().describe("true: the child starts with a copy of this conversation's history, which adds cost and noise. Use it only when a brief would repeat most of this conversation. Then the task says only what to do and what is in scope."),
21485
+ reasoning_level: z.enum(TURN_REASONING_LEVELS).nullable().optional().describe("Reasoning level of the child. Omit it to use the default.")
21486
+ }).strict();
22859
21487
  /** Static definition of `startAgent`. */
22860
21488
  const startAgentToolDefinition = zodToolDefinition({
22861
21489
  description: "Start an asynchronous child agent with its own sandbox and tool budget. Its result arrives in a later turn. A Thread is a work item that people own and message. A Task is work that you delegate: use Tasks to run independent work in parallel and to keep long investigations out of your context. Delegate a Task for each independent track that needs real investigation, such as several repos, services, or sites (start every track in the same message).",
@@ -22867,15 +21495,7 @@ const startAgentToolDefinition = zodToolDefinition({
22867
21495
  openWorldHint: false,
22868
21496
  readOnlyHint: false
22869
21497
  },
22870
- inputSchema: z.object({
22871
- task: z.string().trim().min(1).describe("Self-contained brief: the goal, targets, verified facts, constraints and allowed side effects, what done means, and the result shape. Unless fork is true, it is the child's only context."),
22872
- title: z.string().trim().min(1).max(60).nullable().optional().describe("Short display title. Omit it to generate one from the task."),
22873
- name: agentNameSchema.refine((name) => name !== PARENT_AGENT_TARGET, { message: `"${PARENT_AGENT_TARGET}" is reserved` }).nullable().optional().describe("Name that messageAgent can address later. Omit it for a one-off agent."),
22874
- kind: z.enum(CHILD_AGENT_KINDS).nullable().optional().describe("thread: a work item that people open, message, and steer. A request for a thread means this, not a Slack thread. task (default): background work that only you message."),
22875
- agent_type: z.enum(AGENT_TYPES).nullable().optional().describe(`Child agent type. ${formatAgentTypes()} Omit it for a general child.`),
22876
- fork: z.boolean().nullable().optional().describe("true: the child starts with a copy of this conversation's history, which adds cost and noise. Use it only when a brief would repeat most of this conversation. Then the task says only what to do and what is in scope."),
22877
- reasoning_level: z.enum(TURN_REASONING_LEVELS).nullable().optional().describe("Reasoning level of the child. Omit it to use the default.")
22878
- }).strict(),
21498
+ inputSchema: childInputSchema,
22879
21499
  outputSchema: startAgentOutputSchema
22880
21500
  });
22881
21501
  /** Create the `startAgent` tool that starts child agents of one Turn. */
@@ -23603,6 +22223,15 @@ function createStopWatchingResourcesTool(context) {
23603
22223
  }
23604
22224
  });
23605
22225
  }
22226
+ // src/chat/tools/system-time.ts
22227
+ const systemTimeInputSchema = z.object({ timezone: z.string().trim().min(1).optional().describe("Optional IANA timezone, for example America/Los_Angeles. When set, iso_local and timezone_offset_minutes are for that zone.") });
22228
+ const systemTimeOutputSchema = juniorToolOutputSchema.extend({
22229
+ unix_ms: z.number().describe("Current time in epoch milliseconds, for millisecond inputs."),
22230
+ iso_utc: z.string(),
22231
+ iso_local: z.string(),
22232
+ timezone: z.string().nullable(),
22233
+ timezone_offset_minutes: z.number()
22234
+ });
23606
22235
  const systemTimeToolDefinition = zodToolDefinition({
23607
22236
  description: "Return current system time in UTC and optional local IANA timezone formats. Use when the user asks for current time/date context. Pass timezone when the answer should be in a known IANA zone such as America/Los_Angeles.",
23608
22237
  annotations: {
@@ -23611,14 +22240,8 @@ const systemTimeToolDefinition = zodToolDefinition({
23611
22240
  openWorldHint: false,
23612
22241
  readOnlyHint: true
23613
22242
  },
23614
- inputSchema: z.object({ timezone: z.string().trim().min(1).optional().describe("Optional IANA timezone, for example America/Los_Angeles. When set, iso_local and timezone_offset_minutes are for that zone.") }),
23615
- outputSchema: juniorToolOutputSchema.extend({
23616
- unix_ms: z.number().describe("Current time in epoch milliseconds, for millisecond inputs."),
23617
- iso_utc: z.string(),
23618
- iso_local: z.string(),
23619
- timezone: z.string().nullable(),
23620
- timezone_offset_minutes: z.number()
23621
- }),
22243
+ inputSchema: systemTimeInputSchema,
22244
+ outputSchema: systemTimeOutputSchema,
23622
22245
  privateTraceResult: (result) => ({
23623
22246
  unix_ms: result.unix_ms,
23624
22247
  iso_utc: result.iso_utc,
@@ -23674,6 +22297,9 @@ function getTimeZoneOffsetMinutes(timestampMs, timezone) {
23674
22297
  const asUtcMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
23675
22298
  return Math.round((timestampMs - asUtcMs) / 6e4);
23676
22299
  }
22300
+ // src/chat/tools/submit-feedback.ts
22301
+ const submitFeedbackInputSchema = z.object({ message: z.string().trim().min(1).max(4096).describe("What you tried, the tool and its error or delay, and whether you finished. Do not quote message text, file contents, secrets, or personal data.") });
22302
+ const submitFeedbackOutputSchema = juniorToolOutputSchema.extend({ feedback_id: z.string().describe("Id of the feedback sent to maintainers.") });
23677
22303
  const submitFeedbackToolDefinition = zodToolDefinition({
23678
22304
  annotations: {
23679
22305
  destructiveHint: false,
@@ -23682,8 +22308,8 @@ const submitFeedbackToolDefinition = zodToolDefinition({
23682
22308
  readOnlyHint: false
23683
22309
  },
23684
22310
  description: "Report a problem with your own tools or runtime to the maintainers, not to the user. Use it once when a tool failed, timed out, was too slow, returned wrong data, or was missing, such as a Sandbox that did not start. Skip it when the work went fine, or when the cause is the user's input, access, or a permission they control. Returns the feedback id.",
23685
- inputSchema: z.object({ message: z.string().trim().min(1).max(4096).describe("What you tried, the tool and its error or delay, and whether you finished. Do not quote message text, file contents, secrets, or personal data.") }),
23686
- outputSchema: juniorToolOutputSchema.extend({ feedback_id: z.string().describe("Id of the feedback sent to maintainers.") })
22311
+ inputSchema: submitFeedbackInputSchema,
22312
+ outputSchema: submitFeedbackOutputSchema
23687
22313
  });
23688
22314
  /**
23689
22315
  * Send the agent's report of a tool or runtime problem to the maintainers as
@@ -25881,7 +24507,7 @@ const CORE_TOOLS = {
25881
24507
  definition: () => slackChannelListMessagesToolDefinition
25882
24508
  },
25883
24509
  addReaction: RUN_BUILT,
25884
- addInboxItem: always(addInboxItemToolDefinition),
24510
+ askUserQuestion: always(askUserQuestionToolDefinition),
25885
24511
  searchInboxItems: always(searchInboxItemsToolDefinition),
25886
24512
  updateInboxItem: always(updateInboxItemToolDefinition)
25887
24513
  };
@@ -25942,7 +24568,7 @@ function staticToolDefinitions(key) {
25942
24568
  * leaves out MCP providers that are connected or active and their tool
25943
24569
  * schemas: they differ per person, and providers change them, not deploys.
25944
24570
  */
25945
- const RECORD_TTL_MS = 10080 * MINUTE_MS$1;
24571
+ const RECORD_TTL_MS = 10080 * MINUTE_MS;
25946
24572
  const firstSeenKey = (deploymentId) => `${KEY_PREFIX}:defs:first_seen:${deploymentId}`;
25947
24573
  const fingerprintKey = (key) => `${KEY_PREFIX}:defs:fingerprint:${key.platform}:${key.mode}`;
25948
24574
  function configuredMcpProviders() {
@@ -27547,11 +26173,10 @@ function earliestTimerDueIdleMs(watches, sinceMs, maxDueIdleMs) {
27547
26173
  const dueIdleMs = Math.min(...watches.map((watch) => watch.firesAtMs ?? 1e400)) - sinceMs;
27548
26174
  return dueIdleMs <= maxDueIdleMs ? dueIdleMs : void 0;
27549
26175
  }
27550
- const ADD_INBOX_ITEM_TOOL_NAMES = /* @__PURE__ */ new Set(["addInboxItem", "addReviewItem"]);
27551
26176
  function askedInboxItem(messages, final) {
27552
26177
  for (const message of [final, ...[...messages].reverse()]) {
27553
26178
  if (message.role === "user") return false;
27554
- if (message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && ADD_INBOX_ITEM_TOOL_NAMES.has(part.name))) return true;
26179
+ if (message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && ASK_TOOL_NAMES.has(part.name))) return true;
27555
26180
  }
27556
26181
  return false;
27557
26182
  }
@@ -27728,10 +26353,10 @@ var warmup_exports = /* @__PURE__ */ __exportAll({ runCacheWarmup: () => runCach
27728
26353
  /** Gaps kept in each segment list. */
27729
26354
  const GLOBAL_GAPS_MAX = 2e3;
27730
26355
  /** A segment list expires this long after its last gap. */
27731
- const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS$1;
26356
+ const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
27732
26357
  const CONVERSATION_GAPS_MAX = 50;
27733
26358
  /** The Turn count of a Conversation resets after this long with no call. */
27734
- const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS$1;
26359
+ const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
27735
26360
  /**
27736
26361
  * Answer tools that end the run without a final response. An Automation run
27737
26362
  * posts with `reply`. People often answer a Turn that posted nothing or that
@@ -33016,7 +31641,7 @@ const STATIC_TOOL_BINDERS = {
33016
31641
  slackListGetItems: () => createSlackListGetItemsTool(),
33017
31642
  slackListUpdateItem: (run) => createSlackListUpdateItemTool(run.state),
33018
31643
  slackChannelListMessages: (run) => createSlackChannelListMessagesTool(slackOf(run)),
33019
- addInboxItem: (run) => createAddInboxItemTool(run.context, run.inboxItemServices()),
31644
+ askUserQuestion: (run) => createAskUserQuestionTool(run.context, run.inboxItemServices()),
33020
31645
  searchInboxItems: (run) => createSearchInboxItemsTool(run.context, run.inboxItemServices()),
33021
31646
  updateInboxItem: (run) => createUpdateInboxItemTool(run.context, run.inboxItemServices())
33022
31647
  };
@@ -33029,7 +31654,7 @@ const TURN_TOOL_LIMITS = {
33029
31654
  setConversationSubscription: (turnTools) => turnTools.subscriptions ? void 0 : "Only a person's Turn can change subscriptions.",
33030
31655
  moveConversationToSpace: (turnTools) => turnTools.settings ? void 0 : "Only a person's request moves a conversation to a Space.",
33031
31656
  setConfiguration: (turnTools) => turnTools.settings ? void 0 : "Only a person's request changes configuration.",
33032
- addInboxItem: INBOX_LIMIT,
31657
+ askUserQuestion: INBOX_LIMIT,
33033
31658
  searchInboxItems: INBOX_LIMIT,
33034
31659
  updateInboxItem: INBOX_LIMIT
33035
31660
  };
@@ -37375,4 +36000,4 @@ async function executeAgentRunInPrivacyContext(run, storedConversation, conversa
37375
36000
  await closeTools?.();
37376
36001
  }
37377
36002
  }
37378
- export { slackInboundMessageId as $, updateViewerAutomation as $n, decodeImageId as $t, createBashTool as A, setConversationTitle as An, gapSegment as Ar, resolveObjectLinkNow as At, listOwnedWatches as B, isFileAttachment as Bn, conversationRecordColumns as Bt, processWorkspaceSnapshotJob as C, recordWebConversationActivity as Cn, closeBreaker as Cr, live_annotations_exports as Ct, createWriteFileTool as D, createAttachmentUpload as Dn, MINUTE_MS$1 as Dr, OBJECT_LINK_TTL_MS as Dt, createSystemTimeTool as E, collectAttachmentUploadGarbage as En, IDLE_HORIZON_MS as Er, resolveObjectCards as Et, markConversationRead as F, jsonResponse as Fn, isPublicAddress as Ft, getSpaceLead as G, readPublicArtifact as Gn, conversationEventHistory as Gt, setConversationSpaceForViewer as H, requestAttachmentDeletion as Hn, conversationRecordJoins as Ht, reportConversationRead as I, throwApiError as In, publicAddressLookup as It, getProductionSlackAdapter as J, activateViewerAutomationVersion as Jn, readConversationParticipants as Jt, createProductionConversationWorkOptions as K, unpublishedArtifactHeaders as Kn, conversationSummaryFromStoredConversation as Kt, deliverInboxItemChange as L, readSlackAttachmentSource as Ln, resolveSlackTeamDomains as Lt, setConversationArchive as M, leaveConversation as Mn, resolve_exports as Mt, stopArchivedWork as N, setConversationSubscription as Nn, viewerCanViewPluginLink as Nt, createReadFileTool as O, verifyAttachmentUploads as On, MIN_WARMUP_PREFIX_TOKENS as Or, readLinkObjectType as Ot, conversationReadPositionQuery as P, emptyResponse as Pn, guardedFetch as Pt, clearSlackPendingReactions as Q, takeViewerAutomationAlertStep as Qn, IMAGE_WIDTHS as Qt, inboxItemChangeRecord as R, slackAttachmentsVersionQuery as Rn, resolvePersonLink as Rt, createVercelCacheWarmupCallback as S, createConversationId as Sn, breakerStates as Sr, loadPendingMessageCards as St, ingestEvent as T, AttachmentUploadError as Tn, providerCacheTtlMs as Tr, readLiveAnnotationsById as Tt, readSpaceRefs as U, parseSlackThreadId as Un, readConversationRecordFromSql as Ut, requireSpaceForWork as V, readLiveAttachment as Vn, conversationRecordFromRow as Vt, postSlackDetachNotice as W, publicArtifactHeaders as Wn, selectConversationRecords as Wt, conversation_turn_exports as X, deleteViewerTask as Xn, createViewerMcp as Xt, run_conversation_exports as Y, changeViewerAutomationLifecycle as Yn, readFirstHumanMessageTexts as Yt, buildSlackInboundMessage as Z, readViewerAutomationEdit as Zn, finalizeMcpAuthorization as Zt, listConversationWork as _, updateSpace as _n, historyPeriodSavings as _r, recordSkippedConversationMessage as _t, AttachmentDownloadError as a, message_exports as an, readViewerAutomationSummary as ar, enqueueAgentDispatch as at, vercelBackgroundCompactionQueue as b, conversationTurnIdForMessage as bn, addStats as br, completeAuthPauseTurn as bt, createAgentSandbox as c, startProcessingReaction as cn, AutomationEditError as cr, scheduleSessionCompletedPluginTasks as ct, ANSWER_TOOL_ENDINGS as d, isRetryableSlackPostError as dn, effectiveTaskOutcomes as dr, readConversationEventPage as dt, imagePath as en, ViewerTaskNotFoundError as er, normalizeIncomingSlackThreadId as et, CONVERSATION_STATE_TTL_MS as f, SubscribedReplyReason as fn, viewerAutomationCollection as fr, readConversationEventPageAfter as ft, isConversationWorkDone as g, readSpace as gn, firstLiveSavingsDate as gr, reportParentAgentInput as gt, segmentGapsKey as h, listSpaces as hn, addHistoryWarmupCost as hr, readConversationMessageEventSeq as ht, scheduledAutomationRunAttributes as i, bindMessageAgent as in, readViewerAutomationRuns as ir, AGENT_DISPATCH_MAX_AGE_MS as it, archiveConversation as j, inviteToConversation as jn, listSpaceConfiguration as jr, resolveObjectLinks as jt, createEditFileTool as k, writeAttachmentUpload as kn, NO_REPLY_GAP_MS as kr, readObjectLinkTypes as kt, normalizeToolResult as l, stripLeadingBotMention as ln, findAutomationSkill as lr, task_runner_exports as lt, GLOBAL_GAPS_TTL_MS as m, createSpace as mn, addHistoryPeriod as mr, readConversationLastEventSeq as mt, buildSandboxInput as n, spawn_exports as nn, readConversationSourceTask as nr, wakeAuthorizedTurn as nt, readAttachmentContent as o, createAgentRunner as on, readViewerAutomationVersions as or, failStoppedDispatch as ot, GLOBAL_GAPS_MAX as p, getThreadStopDecision as pn, SAVINGS_NAMESPACE as pr, readConversationEventPageAround as pt, createProductionSlackWebhookServices as q, createPluginConversationWatches as qn, readConversationAuthors as qt, logScheduledAutomationRunSkipped as r, readConversationLineage as rn, readViewerAutomationExecutions as rr, wakePausedTurn as rt, previewOriginBelongsTo as s, bindMessageAuthorIdentityId as sn, readViewerAutomations as sr, processPluginTask as st, executeAgentRun as t, bindSpawnAgent as tn, collectionRowTitle as tr, withNormalizedThreadId as tt, capToolResult as u, parseContent as un, missingAutomationSkillReason as ur, transcriptEntriesFromReportEvents as ut, readLastUserMessageAtByConversation as v, acceptsWebMessages as vn, replaceHistorySavings as vr, stopConversation as vt, verifyWorkspaceSnapshotJobMessage as w, webActorFromUser as wn, connectedState as wr, readLiveAnnotations as wt, verifyBackgroundCompactionMessage as x, createAndEnqueueConversation as xn, readStats as xr, buildDeliveredTurnStatePatch as xt, processBackgroundCompaction as y, appendAndEnqueueWebMessage as yn, savingsTotals as yr, createSlackWebApiStatusSender as yt, renderInboxItemMessage as z, collectAttachmentGarbage as zn, conversationFromRecordRow as zt };
36003
+ export { withNormalizedThreadId as $, replaceHistorySavings as $n, bindSpawnAgent as $t, createBashTool as A, changeViewerAutomationLifecycle as An, resolve_exports as At, setConversationSpaceForViewer as B, readViewerAutomationSummary as Bn, conversationRecordJoins as Bt, processWorkspaceSnapshotJob as C, readSlackAttachmentSource as Cn, readLiveAnnotationsById as Ct, createWriteFileTool as D, unpublishedArtifactHeaders as Dn, readObjectLinkTypes as Dt, createSystemTimeTool as E, readPublicArtifact as En, readLinkObjectType as Et, markConversationRead as F, ViewerTaskNotFoundError as Fn, resolveSlackTeamDomains as Ft, createProductionSlackWebhookServices as G, missingAutomationSkillReason as Gn, readConversationAuthors as Gt, postSlackDetachNotice as H, readViewerAutomations as Hn, selectConversationRecords as Ht, reportConversationRead as I, collectionRowTitle as In, resolvePersonLink as It, conversation_turn_exports as J, SAVINGS_NAMESPACE as Jn, createViewerMcp as Jt, getProductionSlackAdapter as K, effectiveTaskOutcomes as Kn, readConversationParticipants as Kt, deliverInboxItemChange as L, readConversationSourceTask as Ln, conversationFromRecordRow as Lt, setConversationArchive as M, readViewerAutomationEdit as Mn, guardedFetch as Mt, stopArchivedWork as N, takeViewerAutomationAlertStep as Nn, isPublicAddress as Nt, createReadFileTool as O, createPluginConversationWatches as On, resolveObjectLinkNow as Ot, conversationReadPositionQuery as P, updateViewerAutomation as Pn, publicAddressLookup as Pt, normalizeIncomingSlackThreadId as Q, historyPeriodSavings as Qn, imagePath as Qt, listOwnedWatches as R, readViewerAutomationExecutions as Rn, conversationRecordColumns as Rt, createVercelCacheWarmupCallback as S, throwApiError as Sn, readLiveAnnotations as St, ingestEvent as T, publicArtifactHeaders as Tn, OBJECT_LINK_TTL_MS as Tt, getSpaceLead as U, AutomationEditError as Un, conversationEventHistory as Ut, readSpaceRefs as V, readViewerAutomationVersions as Vn, readConversationRecordFromSql as Vt, createProductionConversationWorkOptions as W, findAutomationSkill as Wn, conversationSummaryFromStoredConversation as Wt, clearSlackPendingReactions as X, addHistoryWarmupCost as Xn, IMAGE_WIDTHS as Xt, buildSlackInboundMessage as Y, addHistoryPeriod as Yn, finalizeMcpAuthorization as Yt, slackInboundMessageId as Z, firstLiveSavingsDate as Zn, decodeImageId as Zt, listConversationWork as _, inviteToConversation as _n, createSlackWebApiStatusSender as _t, AttachmentDownloadError as a, bindMessageAuthorIdentityId as an, connectedState as ar, processPluginTask as at, vercelBackgroundCompactionQueue as b, emptyResponse as bn, loadPendingMessageCards as bt, createAgentSandbox as c, parseContent as cn, MINUTE_MS as cr, transcriptEntriesFromReportEvents as ct, ANSWER_TOOL_ENDINGS as d, getThreadStopDecision as dn, gapSegment as dr, readConversationEventPageAround as dt, spawn_exports as en, savingsTotals as er, wakeAuthorizedTurn as et, CONVERSATION_STATE_TTL_MS as f, createSpace as fn, listSpaceConfiguration as fr, readConversationLastEventSeq as ft, isConversationWorkDone as g, setConversationTitle as gn, stopConversation as gt, segmentGapsKey as h, updateSpace as hn, recordSkippedConversationMessage as ht, scheduledAutomationRunAttributes as i, createAgentRunner as in, closeBreaker as ir, failStoppedDispatch as it, archiveConversation as j, deleteViewerTask as jn, viewerCanViewPluginLink as jt, createEditFileTool as k, activateViewerAutomationVersion as kn, resolveObjectLinks as kt, normalizeToolResult as l, isRetryableSlackPostError as ln, MIN_WARMUP_PREFIX_TOKENS as lr, readConversationEventPage as lt, GLOBAL_GAPS_TTL_MS as m, readSpace as mn, reportParentAgentInput as mt, buildSandboxInput as n, bindMessageAgent as nn, readStats as nr, AGENT_DISPATCH_MAX_AGE_MS as nt, readAttachmentContent as o, startProcessingReaction as on, providerCacheTtlMs as or, scheduleSessionCompletedPluginTasks as ot, GLOBAL_GAPS_MAX as p, listSpaces as pn, readConversationMessageEventSeq as pt, run_conversation_exports as q, viewerAutomationCollection as qn, readFirstHumanMessageTexts as qt, logScheduledAutomationRunSkipped as r, message_exports as rn, breakerStates as rr, enqueueAgentDispatch as rt, previewOriginBelongsTo as s, stripLeadingBotMention as sn, IDLE_HORIZON_MS as sr, task_runner_exports as st, executeAgentRun as t, readConversationLineage as tn, addStats as tr, wakePausedTurn as tt, capToolResult as u, SubscribedReplyReason as un, NO_REPLY_GAP_MS as ur, readConversationEventPageAfter as ut, readLastUserMessageAtByConversation as v, leaveConversation as vn, completeAuthPauseTurn as vt, verifyWorkspaceSnapshotJobMessage as w, slackAttachmentsVersionQuery as wn, resolveObjectCards as wt, verifyBackgroundCompactionMessage as x, jsonResponse as xn, live_annotations_exports as xt, processBackgroundCompaction as y, setConversationSubscription as yn, buildDeliveredTurnStatePatch as yt, requireSpaceForWork as z, readViewerAutomationRuns as zn, conversationRecordFromRow as zt };