@sentry/junior 0.320.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.
- package/dist/{adapter-DlLLoJKj.js → adapter-CKtEUuWD.js} +23 -2
- package/dist/{admin-BzRXDVfh.js → admin-BGOiUGwR.js} +1 -1
- package/dist/{agent-DxZ7nHfD.js → agent-OUkEw6Bv.js} +276 -1648
- package/dist/{agent-status-Bq_AIpyp.js → agent-status-C_HHxO_d.js} +1 -10
- package/dist/{agent-update-delivery-CO4FU5Gg.js → agent-update-delivery-H6mnPI4q.js} +4 -4
- package/dist/api/schema.d.ts +98 -16
- package/dist/api/schema.js +6 -6
- package/dist/api.js +81 -36
- package/dist/{app-CHCFIIDu.d.ts → app-BK_vhZIq.d.ts} +1 -1
- package/dist/app.d.ts +1 -1
- package/dist/app.js +85 -48
- package/dist/{change-record-K-KsqNhT.d.ts → change-record-DdrJxahk.d.ts} +26 -15
- package/dist/{channel-access-BghWqlXx.js → channel-access-DRhVJIuQ.js} +1 -1
- package/dist/{chat-core-engine-BgfSLrDu.js → chat-core-engine-El308gYr.js} +5 -10
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +4 -4
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +3 -3
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.js +2 -2
- package/dist/{continue-in-slack-DBlQP4PC.js → continue-in-slack-DYl631oM.js} +3 -3
- package/dist/{conversation-feed-DEUdD7mb.js → conversation-feed-BUaMmSLi.js} +2 -12
- package/dist/{conversation-privacy-qoh95v90.js → conversation-privacy-DR_j5Tqf.js} +1 -1
- package/dist/{create-jZSaDrCR.js → create-ZkI-_JAs.js} +2 -2
- package/dist/{credential-sync-Bj9-UlNE.js → credential-sync-Bo6_FtCI.js} +12 -12
- package/dist/{db-BacvswT0.js → db-RDpWIeRK.js} +1744 -216
- package/dist/{deployment-BoJkRPDt.js → deployment-CeKaP0ZJ.js} +1 -1
- package/dist/{html-DW0pw5Pr.js → html-BMv4fAPu.js} +5 -5
- package/dist/instrumentation.js +2 -2
- package/dist/{list-Dz3CdP3g.js → list-CuLf7Ob2.js} +39 -70
- package/dist/{logging-DsTnMqyi.js → logging-BQsfrLHl.js} +1 -1
- package/dist/{markers-C33gNYNE.js → markers-Bh0vqJ5k.js} +3186 -1754
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -4
- package/dist/{oauth-callback-server-C-pEhAQK.js → oauth-callback-server-BxuN0Jqz.js} +2 -2
- package/dist/{oauth-relay-DIXdH-io.js → oauth-relay-vyG2gOwY.js} +1 -1
- package/dist/{profile-v9vA3RvH.js → profile-DiAB4QfT.js} +39 -8
- package/dist/{prompt-C5CW2wKO.js → prompt-5PDkRQ1K.js} +2 -1
- package/dist/{reports-eBgrhPXS.js → reports-CbqB7unq.js} +2 -2
- package/dist/{resolve-HVXmbeCr.js → resolve-C7e0pwuP.js} +5 -5
- package/dist/{result-BPNzgeTl.js → result-D_D-2Adp.js} +7 -7
- package/dist/{runner-aNSDTST6.js → runner-CCVTdp0x.js} +7 -7
- package/dist/{sandbox-egress-signals-nzp9Ykf7.js → sandbox-egress-signals-D4OKOFgy.js} +1 -1
- package/dist/{schema-BlTO5M1d.js → schema-CmPO8BfI.js} +50 -12
- package/dist/{service-account-DWIf1t6p.js → service-account-CeWsFrBi.js} +2 -2
- package/dist/{skills-50izzzdK.js → skills-DfbOjWxl.js} +5 -5
- package/dist/{slack-conversation-unfurl-C6jXhVYg.js → slack-conversation-unfurl-BxF0Yb3-.js} +10 -9
- package/dist/{system-prompt-table-CIR1B44Z.js → system-prompt-table-DySHMtu0.js} +17 -17
- package/dist/{topics-DxuKurCX.js → topic-ChZe9WPj.js} +6 -1
- package/dist/{engine-context-Bi3Ync5t.js → turn-ended-DQ10G3in.js} +11 -845
- package/dist/{types-BNHkJrOP.js → types-BWAgOJtR.js} +95 -78
- package/dist/{user-customization-CvfuY9Eo.js → user-customization-DNzu_r1x.js} +10 -1
- package/dist/{users-DOVo9sdU.js → users-BmZlg_ci.js} +13 -7
- package/dist/{validation-CK0vuEHB.js → validation-BU4tXvH3.js} +1 -1
- package/dist/{version-BuLVNlxB.js → version-D9yLYOBu.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-C82kHU1R.js → worker-C7EDSL3d.js} +4 -4
- package/migrations/20261127184420_question_answerer/migration.sql +36 -0
- package/migrations/20261127184420_question_answerer/snapshot.json +108 -0
- package/migrations/20261127224730_inbox_item_close_action/migration.sql +1 -0
- package/migrations/20261127224730_inbox_item_close_action/snapshot.json +42 -0
- package/package.json +6 -6
- package/skills/design-automation-skill/SKILL.md +1 -1
- package/dist/storage-BtCxXiNt.js +0 -273
- 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-
|
|
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-
|
|
4
|
-
import { $a as usdToMicroUsd, $d as PluginMcpClient, $f as topLevelConversation, $i as createSandboxCapability, $l as isPersonInput, $n as resolveEventMentions, $s as isDmChannel, $u as NoAudioError, Aa as automationDefinition, Ai as removeReactionFromMessage, Al as parseDashboardConversationLink, An as canJoinTurn, As as isPublicConversation, At as injectContinuationToolName, Ba as linkAutomationRunConversation, Bc as getOpenInboxItemBySubject, Bi as slackMentionedUserIds, Bo as turnEvents, Bp as juniorSpaceConfigurations, Bu as excerptTerms, Ca as getEventAutomation, Cf as getMcpProviderErrorAttributes, Ci as addReactionToMessage, Cp as juniorConversationParticipants, Cs as conversationAncestorsOrSelf, Cu as registeredEventTypeSchema, D as createSqlStore, Da as setEventAutomationStatus, Df as getOAuthProviderErrorAttributes, Dl as getDashboardSpaceLink, Dn as releaseInboundMessage, Do as starterWatchId, Du as ToolInputError, E as latestUserMessageQuery, Ea as saveEventAutomation, Ed as getGatewayApiKey, Ef as fetchWithBoundedOAuthErrorBodies, Ei as openSlackDirectMessage, Eo as publishAgentUpdate, Es as loadAnnotationLabeler, Et as getRegistrations, Eu as requireValidEventTrigger, F as destinationUpsertFromDestination, Fc as closeReadReplyNotice, Ff as agentTurnCostUsd, Fi as SLACK_USER_MENTION_RE, Fn as readInboundMessageSender, Fo as getWatch, Fp as juniorCodeRepositories, Fs as defaultTimezone, Ft as CHILD_AGENT_KINDS, Fu as seqIn, G as conversationStatusSql, Ga as readAutomationExecutions, Gf as createSlackDestination, Gi as createPluginState, Gp as juniorUsers, Gr as QUEUE_SIGNATURE_MAX_AGE_MS, Gu as embedConversationQuery, Ha as readAutomationExecutionStatusDays, Hf as conversationDetailTouch, Hp as juniorIdentities, Ht as appendAndEnqueueExclusiveInboundMessage, Hu as isEventEmbeddingsEnabled, I as upsertDestination, Ia as automationRevision, Ii as escapeSlackMrkdwnText, In as isEventMailboxMetadata, Io as isQuietEvent, Ip as juniorAttachmentUploads, It as PARENT_AGENT_TARGET, J as executionIsActive, Ja as readAutomationTitlesByConversationId, Jf as isLeadSql, Ji as createPluginModel, Jl as canMoveToSpace, Jo as verifyTimerWatchCredentialSubject, Jp as juniorArtifacts, Jr as getQueueProvider, Js as getFilePermalink, Ju as completeObject, Ka as readAutomationRowStats, Kc as updateInboxItemContent, Kf as requireSlackDestination, Ki as createPluginDecider, Kp as juniorDestinations, Kr as signQueueMessage, Ks as SlackActionError, Ku as storeConversationEmbedding, L as parseSessionSource, La as requireAutomationRevision, Lc as closeInboxItem, Li as formatSlackLink, Ln as createSlackInboxItemToolServices, Lp as juniorAttachments, Ls as resolveUserTimezone, Lt as agentNameSchema, Lu as SEARCHABLE_EVENT_TYPES, Ma as listAutomationVersions, Mi as uploadFilesToConversation, Ml as parseDashboardTaskLink, Mo as createWatch, Mt as makeStructuredToolOutput, Mu as indexEndedTurnEvents, Na as readAutomationVersion, No as deliverWatch, Nt as findChildAgentConversationId, Nu as lexemesSql, O as withConversationMutationLock, Oc as readCachedLinkedHandle, Ol as getDashboardTaskLink, Oo as cancelSubscriptions, Op as juniorConversationEvents, Or as leaveEndsAccess, Os as readConversationMetadata, Ou as isToolInputError, Pa as sameDefinitionValue, Pd as getAppContext, Pf as addAgentTurnUsage, Pn as readParentMessage, Po as findMatchingWatches, Pp as juniorCodeChanges, Pu as searchedEventTextSql, Qc as pluginSubjectKind, Qd as McpAuthorizationRequiredError, Qi as basePluginContext, Qn as sendSlackReply, Qo as isConversationDeliveryPaused, Qs as isConversationScopedChannel, Qu as transcribeFromUrl, Ra as emptyAutomationRunWindows, Rc as dismissOpenInboxItems, Rf as hasAgentTurnUsage, Ri as normalizeSlackStatusText, Ro as listWatches, Rp as juniorMessageAttachments, Rr as getVercelConversationWorkQueue, Rs as lookupSlackUser, Ru as callsToolSql, S as setArchivedAt, Sd as getProviderErrorAttributes, Sf as getMcpAwareTelemetryMessage, Si as notifyAutomationBlocked, Sl as getDashboardConversationLink, So as workspaceSnapshotWatch, Sp as juniorConversationReadPositions, Sr as canAccessConversation, Ss as upsertPluginAnnotation, Su as registeredEventTriggerProblems, Ta as parseEventAutomationRow, Td as isProviderRetryError, Tf as OAuthProviderError, Ti as getSlackMessagePermalink, Tl as getDashboardPersonLink, Tp as juniorConversationEventEmbeddings, Tr as canReadConversation, Ts as conversationSubtreeColumns, Tt as getPlugins, Tu as requireEventIdentifier, Ua as readAutomationExecutionStatusHours, Uc as ownerConversationId, Ud as serviceAccountAllows, Uf as nextDetailVersion, Ut as appendAndEnqueueInboundMessage, Va as readAutomationExecutionByConversationId, Vc as insertInboxItem, Vf as rootConversationIsArchived, Vp as juniorSpaces, Wa as readAutomationExecutionSummaries, Wc as searchInboxItems, Wd as serviceAccountOnly, Wf as touchConversationDetail, Wi as pluginMcpContext, Wo as createSlackDirectCredentialSubject, Wu as createConversationEmbedder, Xd as createMcpServiceAccountClientProvider, Xi as createPluginConversationEvents, Xl as dispatchInstructionsInvokeSkills, Xo as JUNIOR_THREAD_STATE_TTL_MS, Xr as buildSentryEventUrl, Xs as getSlackClient, Xu as generateImages, Y as conversationKindFromRow, Yf as rootSpaceIdSql, Yi as createPluginModelCostRecorder, Yl as deliversFinalText, Ys as getHeaderString, Yt as claimInboundMessage, Yu as completeText, Zd as getMcpServiceAccountCredentials, Zi as renderPluginConversationEvent, Zl as hasConversationMetadata, Zn as resolveSlackReplyTarget, Zs as isConversationChannel, Zu as searchWeb, _d as isCompactionSummaryText, _i as markDispatchAwaitingResume, _s as createPluginAnnotations, a as getDb, aa as createPluginCache, ac as sleep$1, af as getMcpServerSessionId, al as identityAvatarUrl, an as getConversationWorkState, b as conversationDescendants, ba as createEventAutomation, bc as saveActorAvatar, bd as createProviderError, bf as McpToolError, bi as markDispatchFailed, bo as WORKSPACE_SNAPSHOT_READY_EVENT, bt as requireInboxItemAssignees, bu as hasEventCatalogEntries, ca as blockScheduledAutomation, cc as createPluginUsers, cd as claudeMaxImageSize, cf as putMcpAuthSession, cl as readUserAvatarUrls, co as activeParticipantUserIds, cr as sendVercelPluginTask, cs as codeChangeUrl, cu as EVENT_AUTHOR_ID, dc as readActorIdentity, dd as estimateTextTokens, di as getDispatchInputMessageId, do as resolveAssignees, dp as juniorAutomationRuns, ds as assertNoObjectLinkConflicts, ec as isSlackRequestTimeout, ed as GEN_AI_PROVIDER_NAME, ef as deleteMcpAuthSession, er as createPluginEventPublisher, et as canAgentChangeInboxItem, eu as isThread, f as eventFromRow, fa as parseScheduledAutomationRow, fc as readIdentityById, fd as textCharsForTokens, fi as getDispatchRecord, fn as requestConversationWork, fo as getEventCatalog, fs as findObjectLinkType, fu as isEventAuthorId, gd as hasCompactedConversationContext, gf as resolvePluginHeaderEnvRefs, gr as createPluginInboxItems, gs as annotationSubject, gt as isPluginInboxItem, gu as describeRegisteredEventTrigger, hd as COMPACTION_SUMMARY_PREFIX, hi as isTerminalDispatchStatus, hp as juniorStats, hs as CORE_ANNOTATION_PLUGIN, hu as automationEventCatalog, i as getConversationStore, ia as runNonInteractiveCommand, ic as withSlackRetries, if as getMcpAuthSession, ii as resolveTurnResumeRouting, il as hasUserPhoto, io as fallbackShortTitle, ir as startedTaskDefinition, iu as promptModeTurnTools, jd as renderJuniorNativeConversationEvent, jl as parseDashboardPersonLink, jn as canShareTurn, jo as createTimerWatch, jr as readableSlackTeamId, js as resolveRootVisibility, jt as juniorToolOutputSchema, k as locationFromRow, kc as readCachedUserByEmail, ki as postSlackMessage, kl as isDashboardLink, kn as withIdleConversation, ko as cancelWatch, kr as readConversationAccessFromSql, ks as writeConversationMetadata, la as createScheduledAutomation, ld as estimateMessagesTokens, lf as putMcpServerSessionId, li as getDispatchConversationId, ll as userAvatarUrlsFromIdentities, lo as automationCreatorUserId, lr as queueCallback, ma as saveScheduledAutomation, md as gatewayRoutingAttributes, mo as requireSlackChannelMessageScope, mp as juniorAutomations, mr as createPluginConversationChanges, ms as ANNOTATION_SUBJECT_KINDS, mu as CORE_EVENT_NAMESPACE, n as getConversationEventStore, na as buildCommandScript, nc as readPrivateSlackFile, nf as deleteMcpServerSessionId, nn as dropPendingMessages, nt as canReadInboxItem, nu as parentResultActor, o as getSqlExecutor, oa as getConfigDefaults, od as createCache, of as getMcpStoredOAuthCredentials, oi as claimDispatchMailboxAppend, oo as resolveTaskTitle, or as pluginTaskId, os as readSubjectLinks, ou as turnBehavior, pa as readScheduledAutomation, pc as readIdentityByIdFromSql, pd as readImageDimensions, pi as getDispatchTurnId, pr as createPluginTurnEventReader, ps as linkTypeName, pu as isEventConversationMessage, q as conversationWaitsOnUserSql, qa as readAutomationRuns, qf as sameDestination, qi as createPluginEmbedder, ql as fuseRankedLists, qp as guardedCosineDistance, qr as verifyQueueMessage, qs as downloadPrivateSlackFile, qu as completeDecision, r as getConversationMessageSearchStore, ra as buildNonInteractiveShellScript, rc as streamPrivateSlackFile, ri as resolveConversationRouting, rn as ensureConversationWake, rr as createPluginTaskStarter, rs as resolveAnnotationFilter, ru as postsRunNotices, sa as truncateStatusText, sd as requestPrefixAttributes, sf as patchMcpAuthSession, si as confirmDispatchMailboxAppend, so as EVERYONE_ASSIGNEE, sr as pluginTaskParamsSchema, ss as subjectKey, su as watcherStartedConversation, ta as withPluginHookSpan, tc as normalizeSlackConversationId, td as GEN_AI_SERVER_ADDRESS, ti as runWithSlackInstallation, ts as searchConversations, tu as isTopLevel, ua as deleteScheduledAutomation, ud as estimateRequestOverheadTokens, uf as putMcpStoredOAuthCredentials, ui as getDispatchIdForConversation, ul as userAvatarUrlsFromJoinedPhotos, uo as resolveAssignee, ur as getTurnRequestDeadline, uu as EVENT_SYSTEM_ACTOR, va as blockEventAutomation, vc as SYSTEM_IDENTITY_ID, vd as ProviderError, vf as McpProviderError, vi as markDispatchBlocked, vo as slackChannelMessageTrigger, vs as createPluginConversationAnnotations, vt as questionSubject, vu as eventNamespaceSchema, wa as listDeletedEventAutomationsCreatedBy, wd as isProviderRefusal, wf as toMcpProviderError, wl as getDashboardLinkFilter, wo as agentWatch, wp as juniorConversationEventLexemes, wr as canInviteToConversation, ws as conversationSubtree, wu as registeredResourceTypeSchema, x as readConversationTrees, xa as deleteEventAutomation, xd as findProviderError, xf as getMcpAwareErrorType, xi as markDispatchRunning, xn as hasConversationStop, xo as workspaceSnapshotFinishedEvent, xr as createPluginCodeChanges, xs as replaceAnnotationSubjectId, xt as requireInboxItemLinks, xu as registeredEventMatchSchema, y as conversationAncestors, yc as resolveActorIdentityId, yd as createAssistantProviderError, yf as McpServiceAccountRequiredError, yi as markDispatchCompleted, yo as WORKSPACE_SNAPSHOT_FAILED_EVENT, ys as listConversationAnnotations, yt as readInboxItemAgentScope, yu as eventWatchUnavailable, zc as getInboxItem, zf as isLeadConversation, zi as slackMention, zp as juniorConversations, zs as lookupSlackUserNames, zu as eventExcerpt } from "./db-BacvswT0.js";
|
|
5
|
-
import { $
|
|
6
|
-
import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
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-
|
|
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-
|
|
9
|
-
import { $t as
|
|
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-
|
|
12
|
-
import {
|
|
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-
|
|
14
|
-
import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-
|
|
15
|
-
import {
|
|
16
|
-
import { t as
|
|
17
|
-
import { a as
|
|
18
|
-
import {
|
|
19
|
-
import { n as
|
|
20
|
-
import {
|
|
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,
|
|
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,
|
|
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";
|
|
@@ -570,6 +569,7 @@ var McpToolManager = class {
|
|
|
570
569
|
...tool.title?.trim() ? { title: tool.title.trim() } : void 0,
|
|
571
570
|
...outputSchema ? { outputSchema } : void 0,
|
|
572
571
|
...annotations ? { annotations } : void 0,
|
|
572
|
+
...plugin.manifest.mcp?.guardian?.skipReview?.includes(tool.name) ? { skipReview: true } : void 0,
|
|
573
573
|
execute: async (args, options) => {
|
|
574
574
|
const resolvedArgs = typeof args === "object" && args !== null ? args : {};
|
|
575
575
|
const conversationPrivacy = options?.conversationPrivacy ?? "private";
|
|
@@ -714,7 +714,8 @@ var McpToolManager = class {
|
|
|
714
714
|
parameters: tool.parameters,
|
|
715
715
|
...tool.outputSchema ? { outputSchema: tool.outputSchema } : void 0,
|
|
716
716
|
...tool.annotations ? { annotations: tool.annotations } : void 0,
|
|
717
|
-
provider: tool.provider
|
|
717
|
+
provider: tool.provider,
|
|
718
|
+
...tool.skipReview ? { skipReview: true } : void 0
|
|
718
719
|
};
|
|
719
720
|
}
|
|
720
721
|
};
|
|
@@ -1010,29 +1011,29 @@ function createTracedStreamFn({ base = streamSimple, conversationPrivacy = "priv
|
|
|
1010
1011
|
* compares that chance with the cost of one more warmup.
|
|
1011
1012
|
*/
|
|
1012
1013
|
/** One minute in milliseconds. */
|
|
1013
|
-
const MINUTE_MS
|
|
1014
|
+
const MINUTE_MS = 6e4;
|
|
1014
1015
|
/** Upper edges (ms) of the gap histogram bins. */
|
|
1015
1016
|
const GAP_BIN_EDGES_MS = [
|
|
1016
1017
|
1e4,
|
|
1017
1018
|
2e4,
|
|
1018
1019
|
3e4,
|
|
1019
1020
|
45e3,
|
|
1020
|
-
MINUTE_MS
|
|
1021
|
-
1.5 * MINUTE_MS
|
|
1022
|
-
2 * MINUTE_MS
|
|
1023
|
-
3 * MINUTE_MS
|
|
1024
|
-
4 * MINUTE_MS
|
|
1025
|
-
5 * MINUTE_MS
|
|
1026
|
-
7 * MINUTE_MS
|
|
1027
|
-
10 * MINUTE_MS
|
|
1028
|
-
15 * MINUTE_MS
|
|
1029
|
-
20 * MINUTE_MS
|
|
1030
|
-
30 * MINUTE_MS
|
|
1031
|
-
45 * MINUTE_MS
|
|
1032
|
-
60 * MINUTE_MS
|
|
1033
|
-
90 * MINUTE_MS
|
|
1034
|
-
120 * MINUTE_MS
|
|
1035
|
-
240 * MINUTE_MS
|
|
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,
|
|
1036
1037
|
1e400
|
|
1037
1038
|
];
|
|
1038
1039
|
const GAP_BIN_COUNT = GAP_BIN_EDGES_MS.length;
|
|
@@ -1077,7 +1078,7 @@ function warmupPrice(cacheReadPrice) {
|
|
|
1077
1078
|
* so the other 5 minutes let a late horizon still record its no-reply gap.
|
|
1078
1079
|
* A longer idle horizon sends its horizon in steps of this length.
|
|
1079
1080
|
*/
|
|
1080
|
-
const IDLE_HORIZON_MS = 55 * MINUTE_MS
|
|
1081
|
+
const IDLE_HORIZON_MS = 55 * MINUTE_MS;
|
|
1081
1082
|
/**
|
|
1082
1083
|
* Idle horizon of an idle period that waits on a child agent. Its result
|
|
1083
1084
|
* starts a Turn, so a return stays likely past the default horizon. Two
|
|
@@ -1103,7 +1104,7 @@ function warmupFailureCountsAsMiss(error) {
|
|
|
1103
1104
|
* Time from a timer's due time to the request of its Turn: the heartbeat
|
|
1104
1105
|
* fires due timers once a minute, and the Turn then starts.
|
|
1105
1106
|
*/
|
|
1106
|
-
const TIMER_START_DELAY_MS = 2 * MINUTE_MS
|
|
1107
|
+
const TIMER_START_DELAY_MS = 2 * MINUTE_MS;
|
|
1107
1108
|
/**
|
|
1108
1109
|
* Latest timer due time, as idle time, that the timer floor warms for. A
|
|
1109
1110
|
* warmup costs a bit more than one read and a miss costs one write minus one
|
|
@@ -1117,7 +1118,7 @@ function timerFloorMaxDueIdleMs(prices) {
|
|
|
1117
1118
|
return prices.cacheTtlMs + maxWarmups * (prices.cacheTtlMs - WARMUP_MARGIN_MS) - TIMER_START_DELAY_MS;
|
|
1118
1119
|
}
|
|
1119
1120
|
/** Gap that Junior records for an idle period with no reply in the horizon. */
|
|
1120
|
-
const NO_REPLY_GAP_MS = 1440 * MINUTE_MS
|
|
1121
|
+
const NO_REPLY_GAP_MS = 1440 * MINUTE_MS;
|
|
1121
1122
|
function binIndex(gapMs) {
|
|
1122
1123
|
return GAP_BIN_EDGES_MS.findIndex((edge) => gapMs < edge);
|
|
1123
1124
|
}
|
|
@@ -1315,8 +1316,8 @@ const CACHE_RETENTION = "short";
|
|
|
1315
1316
|
const REFRESHED_READ_FRACTION = .9;
|
|
1316
1317
|
const BREAKER_OUTCOMES_MAX = 20;
|
|
1317
1318
|
const BREAKER_MAX_MISSES = 10;
|
|
1318
|
-
const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS
|
|
1319
|
-
const BREAKER_OPEN_TTL_MS = 30 * MINUTE_MS
|
|
1319
|
+
const BREAKER_OUTCOMES_TTL_MS = 360 * MINUTE_MS;
|
|
1320
|
+
const BREAKER_OPEN_TTL_MS = 30 * MINUTE_MS;
|
|
1320
1321
|
const breakerOutcomesKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:outcomes`;
|
|
1321
1322
|
const breakerOpenKey = (provider) => `${KEY_PREFIX}:breaker:${provider}:open`;
|
|
1322
1323
|
const providerOf = (modelId) => modelId.split("/")[0] ?? "";
|
|
@@ -1331,9 +1332,9 @@ async function connectedState() {
|
|
|
1331
1332
|
return state;
|
|
1332
1333
|
}
|
|
1333
1334
|
const CACHE_TTL_MS = {
|
|
1334
|
-
anthropic: 5 * MINUTE_MS
|
|
1335
|
-
alibaba: 5 * MINUTE_MS
|
|
1336
|
-
openai: 30 * MINUTE_MS
|
|
1335
|
+
anthropic: 5 * MINUTE_MS,
|
|
1336
|
+
alibaba: 5 * MINUTE_MS,
|
|
1337
|
+
openai: 30 * MINUTE_MS
|
|
1337
1338
|
};
|
|
1338
1339
|
/**
|
|
1339
1340
|
* Return true when warmups can refresh the prompt cache of this request.
|
|
@@ -1740,9 +1741,9 @@ function savingsTotals(stats) {
|
|
|
1740
1741
|
// src/chat/cache-warming/tool-wait.ts
|
|
1741
1742
|
const TOOL_WAIT_GAPS_KEY = `${KEY_PREFIX}:gaps:tool_wait`;
|
|
1742
1743
|
const TOOL_WAIT_GAPS_MAX = 2e3;
|
|
1743
|
-
const TOOL_WAIT_GAPS_TTL_MS = 43200 * MINUTE_MS
|
|
1744
|
-
const MIN_RECORDED_TOOL_WAIT_MS = 2 * MINUTE_MS
|
|
1745
|
-
const STORED_WAIT_TTL_MS = 60 * MINUTE_MS
|
|
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;
|
|
1746
1747
|
const storedWaitSchema = z.object({
|
|
1747
1748
|
modelId: z.string(),
|
|
1748
1749
|
startedAtMs: z.number(),
|
|
@@ -1950,187 +1951,6 @@ function createToolWaitWarmer(conversationId) {
|
|
|
1950
1951
|
}
|
|
1951
1952
|
};
|
|
1952
1953
|
}
|
|
1953
|
-
// src/chat/tool-support/zod-tool.ts
|
|
1954
|
-
function isContentOnlyToolResult(value) {
|
|
1955
|
-
return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
|
|
1956
|
-
}
|
|
1957
|
-
function isStructuredToolResultEnvelope(value) {
|
|
1958
|
-
return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
|
|
1959
|
-
}
|
|
1960
|
-
function parseToolContent(content) {
|
|
1961
|
-
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.");
|
|
1962
|
-
return content;
|
|
1963
|
-
}
|
|
1964
|
-
function formatZodPath(path) {
|
|
1965
|
-
return path.length > 0 ? path.map(String).join(".") : "root";
|
|
1966
|
-
}
|
|
1967
|
-
function formatToolInputError(error) {
|
|
1968
|
-
return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
|
|
1969
|
-
}
|
|
1970
|
-
/** Parse tool input with its Zod schema, as a model-repairable error on failure. */
|
|
1971
|
-
function parseToolInput(schema, args) {
|
|
1972
|
-
const result = schema.safeParse(args);
|
|
1973
|
-
if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
|
|
1974
|
-
return result.data;
|
|
1975
|
-
}
|
|
1976
|
-
/** Declare the static definition of a Zod tool once, for the registry and its factory. */
|
|
1977
|
-
function zodToolDefinition(definition) {
|
|
1978
|
-
return definition;
|
|
1979
|
-
}
|
|
1980
|
-
function zodTool(definition) {
|
|
1981
|
-
const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
|
|
1982
|
-
let modelInputSchema;
|
|
1983
|
-
try {
|
|
1984
|
-
modelInputSchema = z.toJSONSchema(inputSchema);
|
|
1985
|
-
} catch (error) {
|
|
1986
|
-
throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
|
|
1987
|
-
}
|
|
1988
|
-
let modelOutputSchema;
|
|
1989
|
-
if (outputSchema) try {
|
|
1990
|
-
modelOutputSchema = z.toJSONSchema(outputSchema);
|
|
1991
|
-
} catch (error) {
|
|
1992
|
-
throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
|
|
1993
|
-
}
|
|
1994
|
-
return {
|
|
1995
|
-
...toolDef,
|
|
1996
|
-
inputSchema: modelInputSchema,
|
|
1997
|
-
...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
|
|
1998
|
-
prepareArguments(args) {
|
|
1999
|
-
return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
|
|
2000
|
-
},
|
|
2001
|
-
...execute ? { async execute(input, options) {
|
|
2002
|
-
const result = await execute(input, options);
|
|
2003
|
-
if (!outputSchema) {
|
|
2004
|
-
if (isContentOnlyToolResult(result)) return result;
|
|
2005
|
-
throw new TypeError("zodTool() content-only tools must return { content } without details.");
|
|
2006
|
-
}
|
|
2007
|
-
if (isStructuredToolResultEnvelope(result)) return {
|
|
2008
|
-
content: parseToolContent(result.content),
|
|
2009
|
-
details: outputSchema.parse(result.details)
|
|
2010
|
-
};
|
|
2011
|
-
return outputSchema.parse(result);
|
|
2012
|
-
} } : void 0
|
|
2013
|
-
};
|
|
2014
|
-
}
|
|
2015
|
-
// src/chat/inbox-items/tool-support.ts
|
|
2016
|
-
/** Shared input and result shapes of the Inbox item tools. */
|
|
2017
|
-
/** Deferred tool catalog source for the Inbox item tools after add. */
|
|
2018
|
-
const INBOX_TOOL_SOURCE = {
|
|
2019
|
-
id: "inbox",
|
|
2020
|
-
description: "Update and search Inbox items: work that needs a person."
|
|
2021
|
-
};
|
|
2022
|
-
/** Who can act on an Inbox item. */
|
|
2023
|
-
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.");
|
|
2024
|
-
/** Conversations that an Inbox item links to. */
|
|
2025
|
-
const conversationIdsSchema = z.array(z.string().trim().min(1).max(500)).max(10);
|
|
2026
|
-
/** Title of an Inbox item. */
|
|
2027
|
-
const titleSchema = z.string().trim().min(1).max(200);
|
|
2028
|
-
/** Body of an Inbox item. */
|
|
2029
|
-
const bodySchema = z.string().trim().min(1).max(4e3).describe("Markdown details for the person.");
|
|
2030
|
-
/** Deliver an Inbox item change through the services of the tools. */
|
|
2031
|
-
function inboxItemDelivery(services) {
|
|
2032
|
-
return {
|
|
2033
|
-
queue: services.queue(),
|
|
2034
|
-
show: services.show
|
|
2035
|
-
};
|
|
2036
|
-
}
|
|
2037
|
-
/** The owner Conversation of an item, as a list of Conversations to check. */
|
|
2038
|
-
function ownerLinks(item) {
|
|
2039
|
-
const conversationId = item ? ownerConversationId(item) : void 0;
|
|
2040
|
-
return conversationId ? [conversationId] : [];
|
|
2041
|
-
}
|
|
2042
|
-
/** Read an Inbox item that the agent may read, or fail with a tool input error. */
|
|
2043
|
-
async function readableItem(id, scope) {
|
|
2044
|
-
const item = await getInboxItem(getDb(), id);
|
|
2045
|
-
if (!item || !canReadInboxItem(item, scope.reader)) throw new ToolInputError(`Inbox item ${id} is not found. Use searchInboxItems to find its id.`);
|
|
2046
|
-
return item;
|
|
2047
|
-
}
|
|
2048
|
-
/** Render one Inbox item for a tool result. */
|
|
2049
|
-
function itemResult(item) {
|
|
2050
|
-
return {
|
|
2051
|
-
id: item.id,
|
|
2052
|
-
kind: item.kind,
|
|
2053
|
-
status: item.status,
|
|
2054
|
-
title: item.title,
|
|
2055
|
-
body: item.body,
|
|
2056
|
-
assignees: [...item.assignedToEveryone ? [EVERYONE_ASSIGNEE] : [], ...item.assignees.map((assignee) => assignee.email)],
|
|
2057
|
-
conversation_ids: item.conversationIds,
|
|
2058
|
-
visibility: item.visibility,
|
|
2059
|
-
updated_at: item.updatedAt.toISOString(),
|
|
2060
|
-
subject: item.subject,
|
|
2061
|
-
...item.addedByAutomationId ? { automation_id: item.addedByAutomationId } : void 0,
|
|
2062
|
-
...item.request ? { request: requestResult(item.request) } : void 0,
|
|
2063
|
-
...item.answer ? { answer: item.answer } : void 0,
|
|
2064
|
-
...item.closedAt ? {
|
|
2065
|
-
closed_at: item.closedAt.toISOString(),
|
|
2066
|
-
closed_by: item.closedBy?.email ?? "agent"
|
|
2067
|
-
} : void 0,
|
|
2068
|
-
...item.closeReason ? { close_reason: item.closeReason } : void 0
|
|
2069
|
-
};
|
|
2070
|
-
}
|
|
2071
|
-
/** Show the stored question with the tool's snake_case related link keys. */
|
|
2072
|
-
function requestResult({ related, ...question }) {
|
|
2073
|
-
return {
|
|
2074
|
-
...question,
|
|
2075
|
-
...related ? { related: related.map(({ conversationId, ...entry }) => ({
|
|
2076
|
-
...entry,
|
|
2077
|
-
...conversationId ? { conversation_id: conversationId } : void 0
|
|
2078
|
-
})) } : void 0
|
|
2079
|
-
};
|
|
2080
|
-
}
|
|
2081
|
-
const relatedSchema = z.array(z.object({
|
|
2082
|
-
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."),
|
|
2083
|
-
conversation_id: z.string().trim().min(1).max(500).nullable().optional().describe("A related Conversation. Set this or `url`."),
|
|
2084
|
-
label: z.string().trim().min(1).max(120).describe("Short name of the link, such as `Checkout p95 chart`."),
|
|
2085
|
-
note: z.string().trim().min(1).max(200).regex(/^[^\r\n]*$/, "Use one line.").nullable().optional().describe("One line: what this link shows.")
|
|
2086
|
-
}).strict()).max(10);
|
|
2087
|
-
const questionRequestSchema = z.object({ request: userInputRequestSchema });
|
|
2088
|
-
/**
|
|
2089
|
-
* Return the question of an action. An action needs one. A notice asks
|
|
2090
|
-
* nothing, so its `request` may hold only related links.
|
|
2091
|
-
*/
|
|
2092
|
-
function questionInput(kind, request) {
|
|
2093
|
-
if (kind === "notice") {
|
|
2094
|
-
if (request?.question || request?.fields) throw new ToolInputError("A notice asks nothing, so its `request` holds only `related`. To ask, use kind `action`.");
|
|
2095
|
-
return;
|
|
2096
|
-
}
|
|
2097
|
-
if (!request?.question || !request.fields) throw new ToolInputError("An action item needs a `request` with a `question` and `fields`.");
|
|
2098
|
-
const { related: _related, ...question } = request;
|
|
2099
|
-
return parseToolInput(questionRequestSchema, { request: question }).request;
|
|
2100
|
-
}
|
|
2101
|
-
/** The `request` param of the Inbox item tools that ask or change a question. */
|
|
2102
|
-
const requestInputSchema = z.object({
|
|
2103
|
-
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."),
|
|
2104
|
-
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."),
|
|
2105
|
-
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`.")
|
|
2106
|
-
});
|
|
2107
|
-
/**
|
|
2108
|
-
* Normalize the related links: each entry names exactly one link, null
|
|
2109
|
-
* fields mean omitted, and a link is stored as `URL.href`, so it matches
|
|
2110
|
-
* the link of the work that it names.
|
|
2111
|
-
*/
|
|
2112
|
-
function relatedInput(related) {
|
|
2113
|
-
return (related ?? []).map((entry) => {
|
|
2114
|
-
if (Boolean(entry.url) === Boolean(entry.conversation_id)) throw new ToolInputError("Each `related` entry needs a `url` or a `conversation_id`, not both.");
|
|
2115
|
-
return {
|
|
2116
|
-
label: entry.label,
|
|
2117
|
-
...entry.url ? { url: new URL(entry.url).href } : void 0,
|
|
2118
|
-
...entry.conversation_id ? { conversationId: entry.conversation_id } : void 0,
|
|
2119
|
-
...entry.note ? { note: entry.note } : void 0
|
|
2120
|
-
};
|
|
2121
|
-
});
|
|
2122
|
-
}
|
|
2123
|
-
/**
|
|
2124
|
-
* Store the question with its normalized related links, if it has any. A
|
|
2125
|
-
* notice stores only its related links.
|
|
2126
|
-
*/
|
|
2127
|
-
function requestInput(question, related) {
|
|
2128
|
-
if (!question) return related.length > 0 ? { related } : void 0;
|
|
2129
|
-
return {
|
|
2130
|
-
...question,
|
|
2131
|
-
...related.length > 0 ? { related } : void 0
|
|
2132
|
-
};
|
|
2133
|
-
}
|
|
2134
1954
|
// src/chat/inbox-items/tools/search.ts
|
|
2135
1955
|
const DEFAULT_LIMIT$4 = 10;
|
|
2136
1956
|
const MAX_LIMIT$4 = 25;
|
|
@@ -6046,67 +5866,6 @@ function createSlackChannelJoinTool(context) {
|
|
|
6046
5866
|
}
|
|
6047
5867
|
});
|
|
6048
5868
|
}
|
|
6049
|
-
// src/chat/slack/context.ts
|
|
6050
|
-
function toTrimmedSlackString(value) {
|
|
6051
|
-
return toOptionalString(value)?.trim() || void 0;
|
|
6052
|
-
}
|
|
6053
|
-
const slackMessageEnvelopeSchema$1 = z.object({ raw: z.unknown().optional() });
|
|
6054
|
-
const rawSlackMessageSchema = z.object({
|
|
6055
|
-
channel: z.unknown().optional(),
|
|
6056
|
-
message: z.unknown().optional(),
|
|
6057
|
-
team: z.unknown().optional(),
|
|
6058
|
-
team_id: z.unknown().optional(),
|
|
6059
|
-
thread_ts: z.unknown().optional(),
|
|
6060
|
-
ts: z.unknown().optional(),
|
|
6061
|
-
user_team: z.unknown().optional()
|
|
6062
|
-
});
|
|
6063
|
-
const nestedRawSlackMessageSchema = z.object({ ts: z.unknown().optional() });
|
|
6064
|
-
/** Project only the Slack raw fields consumed by runtime thread context. */
|
|
6065
|
-
function readSlackRawMessageContext(message) {
|
|
6066
|
-
const envelope = slackMessageEnvelopeSchema$1.safeParse(message);
|
|
6067
|
-
if (!envelope.success) return;
|
|
6068
|
-
const raw = rawSlackMessageSchema.safeParse(envelope.data.raw);
|
|
6069
|
-
if (!raw.success) return;
|
|
6070
|
-
const nestedMessage = nestedRawSlackMessageSchema.safeParse(raw.data.message);
|
|
6071
|
-
const channelId = parseSlackChannelId(raw.data.channel);
|
|
6072
|
-
const threadTs = parseSlackMessageTs(raw.data.thread_ts);
|
|
6073
|
-
const messageTs = parseSlackMessageTs(raw.data.ts);
|
|
6074
|
-
const nestedMessageTs = nestedMessage.success && parseSlackMessageTs(nestedMessage.data.ts);
|
|
6075
|
-
const teamId = parseSlackTeamId(raw.data.team_id) ?? parseSlackTeamId(raw.data.team);
|
|
6076
|
-
const authorTeamId = parseSlackTeamId(raw.data.user_team);
|
|
6077
|
-
return {
|
|
6078
|
-
...channelId ? { channelId } : void 0,
|
|
6079
|
-
...threadTs ? { threadTs } : void 0,
|
|
6080
|
-
...messageTs ? { messageTs } : void 0,
|
|
6081
|
-
...nestedMessageTs ? { nestedMessageTs } : void 0,
|
|
6082
|
-
...teamId ? { teamId } : void 0,
|
|
6083
|
-
...authorTeamId ? { authorTeamId } : void 0
|
|
6084
|
-
};
|
|
6085
|
-
}
|
|
6086
|
-
/** Extract a channel ID and validated Slack timestamp from `slack:<channel>:<ts>`. */
|
|
6087
|
-
function parseSlackThreadId(threadId) {
|
|
6088
|
-
const normalizedThreadId = toTrimmedSlackString(threadId);
|
|
6089
|
-
if (!normalizedThreadId) return;
|
|
6090
|
-
const parts = normalizedThreadId.split(":");
|
|
6091
|
-
if (parts.length !== 3 || parts[0] !== "slack") return;
|
|
6092
|
-
const channelId = parseSlackChannelId(parts[1]);
|
|
6093
|
-
const threadTs = parseSlackMessageTs(parts[2]);
|
|
6094
|
-
if (!channelId || !threadTs) return;
|
|
6095
|
-
return {
|
|
6096
|
-
channelId,
|
|
6097
|
-
threadTs
|
|
6098
|
-
};
|
|
6099
|
-
}
|
|
6100
|
-
/** Best-effort channel ID extraction from a raw Slack message payload. */
|
|
6101
|
-
function resolveSlackChannelIdFromMessage(message) {
|
|
6102
|
-
const messageChannelId = parseSlackChannelId(message.channelId);
|
|
6103
|
-
if (messageChannelId) return messageChannelId;
|
|
6104
|
-
const raw = message.raw;
|
|
6105
|
-
if (raw && typeof raw === "object") {
|
|
6106
|
-
const rawChannel = parseSlackChannelId(raw.channel);
|
|
6107
|
-
if (rawChannel) return rawChannel;
|
|
6108
|
-
}
|
|
6109
|
-
}
|
|
6110
5869
|
// src/chat/slack/timestamp-param.ts
|
|
6111
5870
|
/** Define a model-facing Slack timestamp, normalizing numeric model args to strings. */
|
|
6112
5871
|
function slackTimestampParam(description) {
|
|
@@ -6696,6 +6455,17 @@ function createSlackListGetItemsTool() {
|
|
|
6696
6455
|
}
|
|
6697
6456
|
// src/chat/slack/tools/list/update-item.ts
|
|
6698
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
|
+
})]);
|
|
6699
6469
|
const slackListUpdateItemToolDefinition = zodToolDefinition({
|
|
6700
6470
|
exposure: "deferred",
|
|
6701
6471
|
source: SLACK_TOOL_SOURCE,
|
|
@@ -6706,17 +6476,7 @@ const slackListUpdateItemToolDefinition = zodToolDefinition({
|
|
|
6706
6476
|
readOnlyHint: false
|
|
6707
6477
|
},
|
|
6708
6478
|
description: "Update an item in a Slack list.",
|
|
6709
|
-
inputSchema:
|
|
6710
|
-
list_id: slackListIdParam,
|
|
6711
|
-
item_id: slackListItemIdParam,
|
|
6712
|
-
completed: booleanInput("Optional completion status update."),
|
|
6713
|
-
title: z.string().min(1).describe("Optional new item title.").optional()
|
|
6714
|
-
}), z.object({
|
|
6715
|
-
list_id: slackListIdParam,
|
|
6716
|
-
item_id: slackListItemIdParam,
|
|
6717
|
-
completed: booleanInput("Optional completion status update.").optional(),
|
|
6718
|
-
title: z.string().min(1).describe("Optional new item title.")
|
|
6719
|
-
})]),
|
|
6479
|
+
inputSchema: updateListItemInputSchema,
|
|
6720
6480
|
outputSchema: juniorToolOutputSchema
|
|
6721
6481
|
});
|
|
6722
6482
|
/** Create a tool that updates an item in an explicit Slack list. */
|
|
@@ -7317,491 +7077,6 @@ function renderAttachment(raw) {
|
|
|
7317
7077
|
function renderAttachmentText(input) {
|
|
7318
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);
|
|
7319
7079
|
}
|
|
7320
|
-
// src/chat/attachments/source.ts
|
|
7321
|
-
/** The source deleted the file, or Junior can no longer read it. */
|
|
7322
|
-
var AttachmentSourceUnavailableError = class extends Error {
|
|
7323
|
-
constructor(message, options) {
|
|
7324
|
-
super(message, options);
|
|
7325
|
-
this.name = "AttachmentSourceUnavailableError";
|
|
7326
|
-
}
|
|
7327
|
-
};
|
|
7328
|
-
// src/chat/attachments/store.ts
|
|
7329
|
-
const DAY_MS = 864e5;
|
|
7330
|
-
const ATTACHMENT_GC_BATCH_LIMIT = 200;
|
|
7331
|
-
/** Time that Junior keeps attachment bytes after the file is stored. */
|
|
7332
|
-
const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
|
|
7333
|
-
/** Only `file` rows: a `url` row has no storage or file fields. */
|
|
7334
|
-
const isFileAttachment = eq(juniorAttachments.kind, "file");
|
|
7335
|
-
/**
|
|
7336
|
-
* The storage and file fields of a `file` row. Every `file` row has them, so
|
|
7337
|
-
* a missing one is a broken row.
|
|
7338
|
-
*/
|
|
7339
|
-
function fileFields(row) {
|
|
7340
|
-
const { bytes, contentType, storageProvider, title } = row;
|
|
7341
|
-
if (bytes === null || contentType === null || storageProvider === null || title === null) throw new Error(`Attachment ${row.id} has no file fields`);
|
|
7342
|
-
return {
|
|
7343
|
-
bytes,
|
|
7344
|
-
contentType,
|
|
7345
|
-
filename: title,
|
|
7346
|
-
storageProvider
|
|
7347
|
-
};
|
|
7348
|
-
}
|
|
7349
|
-
function attachmentIdentity(file) {
|
|
7350
|
-
if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
|
|
7351
|
-
return file.source;
|
|
7352
|
-
}
|
|
7353
|
-
/** Stable conversation-owned id for one file and its presentation metadata. */
|
|
7354
|
-
function attachmentId(args) {
|
|
7355
|
-
const identity = "sha256" in args.identity ? [
|
|
7356
|
-
args.conversationId,
|
|
7357
|
-
args.storageProvider,
|
|
7358
|
-
args.identity.sha256,
|
|
7359
|
-
args.filename,
|
|
7360
|
-
args.contentType
|
|
7361
|
-
] : [
|
|
7362
|
-
args.conversationId,
|
|
7363
|
-
args.storageProvider,
|
|
7364
|
-
args.filename,
|
|
7365
|
-
args.contentType,
|
|
7366
|
-
args.identity.provider,
|
|
7367
|
-
args.identity.id
|
|
7368
|
-
];
|
|
7369
|
-
return createHash("sha256").update(identity.join("\0")).digest("hex");
|
|
7370
|
-
}
|
|
7371
|
-
/**
|
|
7372
|
-
* Object key for one write attempt.
|
|
7373
|
-
*
|
|
7374
|
-
* Attachment ids are content-stable. Object keys are not: each put gets a fresh
|
|
7375
|
-
* key so a failed-write cleanup or GC delete cannot remove another writer's
|
|
7376
|
-
* durable blob.
|
|
7377
|
-
*/
|
|
7378
|
-
function attachmentKey(args) {
|
|
7379
|
-
return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
|
|
7380
|
-
}
|
|
7381
|
-
/** A source whose bytes do not match its declared size. A retry cannot fix it. */
|
|
7382
|
-
var AttachmentSizeError = class extends Error {
|
|
7383
|
-
constructor(bytes, expected, options) {
|
|
7384
|
-
super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
|
|
7385
|
-
this.name = "AttachmentSizeError";
|
|
7386
|
-
}
|
|
7387
|
-
};
|
|
7388
|
-
/** Tries for one object write, each with a freshly opened body. */
|
|
7389
|
-
const WRITE_ATTEMPTS = 3;
|
|
7390
|
-
async function bestEffortDelete(storage, key) {
|
|
7391
|
-
if (key === null) return;
|
|
7392
|
-
try {
|
|
7393
|
-
await storage.delete([key]);
|
|
7394
|
-
} catch {}
|
|
7395
|
-
}
|
|
7396
|
-
/**
|
|
7397
|
-
* Stream one file to a fresh key, and return its size and digest.
|
|
7398
|
-
*
|
|
7399
|
-
* The digest is taken while the bytes stream, so the body is never held
|
|
7400
|
-
* whole. A body that does not match its declared size is not kept.
|
|
7401
|
-
*/
|
|
7402
|
-
async function writeAttachmentObject(args) {
|
|
7403
|
-
for (let attempt = 1;; attempt += 1) try {
|
|
7404
|
-
return await writeAttachmentObjectOnce(args);
|
|
7405
|
-
} catch (error) {
|
|
7406
|
-
if (error instanceof AttachmentSizeError || error instanceof AttachmentSourceUnavailableError || attempt >= WRITE_ATTEMPTS) {
|
|
7407
|
-
await bestEffortDelete(args.storage, args.key);
|
|
7408
|
-
throw error;
|
|
7409
|
-
}
|
|
7410
|
-
}
|
|
7411
|
-
}
|
|
7412
|
-
async function writeAttachmentObjectOnce(args) {
|
|
7413
|
-
const { file } = args;
|
|
7414
|
-
const expected = "data" in file ? file.data.byteLength : file.bytes;
|
|
7415
|
-
const source = "data" in file ? bufferBody(file.data) : await file.open();
|
|
7416
|
-
const hash = createHash("sha256");
|
|
7417
|
-
let bytes = 0;
|
|
7418
|
-
const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
7419
|
-
bytes += chunk.byteLength;
|
|
7420
|
-
if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
|
|
7421
|
-
hash.update(chunk);
|
|
7422
|
-
controller.enqueue(chunk);
|
|
7423
|
-
} }));
|
|
7424
|
-
try {
|
|
7425
|
-
await args.storage.put({
|
|
7426
|
-
body,
|
|
7427
|
-
bytes: expected,
|
|
7428
|
-
contentType: file.mimeType,
|
|
7429
|
-
key: args.key
|
|
7430
|
-
});
|
|
7431
|
-
} catch (error) {
|
|
7432
|
-
if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
|
|
7433
|
-
throw error;
|
|
7434
|
-
}
|
|
7435
|
-
if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
|
|
7436
|
-
return {
|
|
7437
|
-
bytes,
|
|
7438
|
-
sha256: hash.digest("hex")
|
|
7439
|
-
};
|
|
7440
|
-
}
|
|
7441
|
-
async function isConversationPurged(db, conversationId) {
|
|
7442
|
-
const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
|
|
7443
|
-
return row?.transcriptPurgedAt != null;
|
|
7444
|
-
}
|
|
7445
|
-
function purgedConversationError(conversationId) {
|
|
7446
|
-
return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
|
|
7447
|
-
}
|
|
7448
|
-
async function assertConversationNotPurged(db, conversationId) {
|
|
7449
|
-
if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
|
|
7450
|
-
}
|
|
7451
|
-
/** Mark a just-written row for deletion and drop its unused object. */
|
|
7452
|
-
async function rejectPurgedAttachmentWrite(args) {
|
|
7453
|
-
const db = args.db.db();
|
|
7454
|
-
await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
|
|
7455
|
-
await bestEffortDelete(args.storage, args.storageKey);
|
|
7456
|
-
throw purgedConversationError(args.conversationId);
|
|
7457
|
-
}
|
|
7458
|
-
/**
|
|
7459
|
-
* Return another writer's live row only when the conversation is still active.
|
|
7460
|
-
*
|
|
7461
|
-
* The caller already wrote a unique object for this attempt. Delete that unused
|
|
7462
|
-
* object either way. If the conversation is purged, do not report success for a
|
|
7463
|
-
* row that purge/GC is about to remove.
|
|
7464
|
-
*/
|
|
7465
|
-
async function reuseLiveAttachment(args) {
|
|
7466
|
-
await bestEffortDelete(args.storage, args.storageKey);
|
|
7467
|
-
await assertConversationNotPurged(args.db, args.conversationId);
|
|
7468
|
-
return { id: args.id };
|
|
7469
|
-
}
|
|
7470
|
-
/**
|
|
7471
|
-
* Persist one conversation-owned file.
|
|
7472
|
-
*
|
|
7473
|
-
* Identity is stable under the conversation: it comes from the file's source
|
|
7474
|
-
* when it has one, and from its digest otherwise. Object storage is written
|
|
7475
|
-
* first under a unique key; the SQL row is created only after that write
|
|
7476
|
-
* succeeds. A row means the attachment is durable. Retries reuse an existing
|
|
7477
|
-
* live row. A purge-marked row is revived by writing a new object and pointing
|
|
7478
|
-
* the row at it, unless the conversation is still purged. If the SQL write
|
|
7479
|
-
* fails after object storage accepts the bytes, this path deletes that unique
|
|
7480
|
-
* object. A process crash between those steps can leave an unreferenced unique
|
|
7481
|
-
* object with no SQL row.
|
|
7482
|
-
*/
|
|
7483
|
-
async function storeAttachment(args) {
|
|
7484
|
-
const now = new Date(args.nowMs ?? Date.now());
|
|
7485
|
-
const identity = attachmentIdentity(args.file);
|
|
7486
|
-
const source = args.file.source;
|
|
7487
|
-
const id = attachmentId({
|
|
7488
|
-
conversationId: args.conversationId,
|
|
7489
|
-
contentType: args.file.mimeType,
|
|
7490
|
-
filename: args.file.filename,
|
|
7491
|
-
identity,
|
|
7492
|
-
storageProvider: args.storage.provider
|
|
7493
|
-
});
|
|
7494
|
-
const [existing] = await args.db.db().select({
|
|
7495
|
-
contentType: juniorAttachments.contentType,
|
|
7496
|
-
conversationId: juniorAttachments.conversationId,
|
|
7497
|
-
deleteRequestedAt: juniorAttachments.deleteRequestedAt,
|
|
7498
|
-
filename: juniorAttachments.title,
|
|
7499
|
-
id: juniorAttachments.id,
|
|
7500
|
-
provider: juniorAttachments.provider,
|
|
7501
|
-
providerId: juniorAttachments.providerId,
|
|
7502
|
-
storageProvider: juniorAttachments.storageProvider,
|
|
7503
|
-
sha256: juniorAttachments.sha256,
|
|
7504
|
-
storageKey: juniorAttachments.storageKey
|
|
7505
|
-
}).from(juniorAttachments).where(eq(juniorAttachments.id, id));
|
|
7506
|
-
if (existing) {
|
|
7507
|
-
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}`);
|
|
7508
|
-
if (existing.deleteRequestedAt === null) {
|
|
7509
|
-
await assertConversationNotPurged(args.db, args.conversationId);
|
|
7510
|
-
return { id: existing.id };
|
|
7511
|
-
}
|
|
7512
|
-
}
|
|
7513
|
-
await assertConversationNotPurged(args.db, args.conversationId);
|
|
7514
|
-
const { file } = args;
|
|
7515
|
-
let storageKey = null;
|
|
7516
|
-
let written;
|
|
7517
|
-
if ("deferred" in file) written = {
|
|
7518
|
-
bytes: file.bytes,
|
|
7519
|
-
sha256: null
|
|
7520
|
-
};
|
|
7521
|
-
else {
|
|
7522
|
-
storageKey = attachmentKey({
|
|
7523
|
-
attachmentId: id,
|
|
7524
|
-
conversationId: args.conversationId,
|
|
7525
|
-
filename: file.filename,
|
|
7526
|
-
writeId: randomUUID()
|
|
7527
|
-
});
|
|
7528
|
-
written = await writeAttachmentObject({
|
|
7529
|
-
file,
|
|
7530
|
-
key: storageKey,
|
|
7531
|
-
storage: args.storage
|
|
7532
|
-
});
|
|
7533
|
-
}
|
|
7534
|
-
if (existing?.deleteRequestedAt != null) {
|
|
7535
|
-
if (await isConversationPurged(args.db, args.conversationId)) {
|
|
7536
|
-
await bestEffortDelete(args.storage, storageKey);
|
|
7537
|
-
throw purgedConversationError(args.conversationId);
|
|
7538
|
-
}
|
|
7539
|
-
const oldStorageKey = existing.storageKey;
|
|
7540
|
-
if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
|
|
7541
|
-
...written,
|
|
7542
|
-
deleteRequestedAt: null,
|
|
7543
|
-
storageKey
|
|
7544
|
-
}).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
|
|
7545
|
-
if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
|
|
7546
|
-
conversationId: args.conversationId,
|
|
7547
|
-
db: args.db,
|
|
7548
|
-
id,
|
|
7549
|
-
now,
|
|
7550
|
-
storage: args.storage,
|
|
7551
|
-
storageKey
|
|
7552
|
-
});
|
|
7553
|
-
if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
|
|
7554
|
-
return { id };
|
|
7555
|
-
}
|
|
7556
|
-
const [afterRace] = await args.db.db().select({
|
|
7557
|
-
deleteRequestedAt: juniorAttachments.deleteRequestedAt,
|
|
7558
|
-
id: juniorAttachments.id,
|
|
7559
|
-
storageKey: juniorAttachments.storageKey
|
|
7560
|
-
}).from(juniorAttachments).where(eq(juniorAttachments.id, id));
|
|
7561
|
-
if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
|
|
7562
|
-
conversationId: args.conversationId,
|
|
7563
|
-
db: args.db,
|
|
7564
|
-
id: afterRace.id,
|
|
7565
|
-
storage: args.storage,
|
|
7566
|
-
storageKey
|
|
7567
|
-
});
|
|
7568
|
-
}
|
|
7569
|
-
let inserted = [];
|
|
7570
|
-
try {
|
|
7571
|
-
inserted = await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).insert(juniorAttachments).values({
|
|
7572
|
-
id,
|
|
7573
|
-
conversationId: args.conversationId,
|
|
7574
|
-
storageProvider: args.storage.provider,
|
|
7575
|
-
storageKey,
|
|
7576
|
-
provider: source?.provider,
|
|
7577
|
-
providerId: source?.id,
|
|
7578
|
-
title: args.file.filename,
|
|
7579
|
-
contentType: args.file.mimeType,
|
|
7580
|
-
...written,
|
|
7581
|
-
createdAt: now
|
|
7582
|
-
}).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
|
|
7583
|
-
} catch (error) {
|
|
7584
|
-
await bestEffortDelete(args.storage, storageKey);
|
|
7585
|
-
throw error;
|
|
7586
|
-
}
|
|
7587
|
-
if (inserted.length > 0) {
|
|
7588
|
-
if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
|
|
7589
|
-
conversationId: args.conversationId,
|
|
7590
|
-
db: args.db,
|
|
7591
|
-
id,
|
|
7592
|
-
now,
|
|
7593
|
-
storage: args.storage,
|
|
7594
|
-
storageKey
|
|
7595
|
-
});
|
|
7596
|
-
return { id };
|
|
7597
|
-
}
|
|
7598
|
-
const [row] = await args.db.db().select({
|
|
7599
|
-
deleteRequestedAt: juniorAttachments.deleteRequestedAt,
|
|
7600
|
-
id: juniorAttachments.id,
|
|
7601
|
-
storageKey: juniorAttachments.storageKey
|
|
7602
|
-
}).from(juniorAttachments).where(eq(juniorAttachments.id, id));
|
|
7603
|
-
if (!row) {
|
|
7604
|
-
await bestEffortDelete(args.storage, storageKey);
|
|
7605
|
-
throw new Error(`Attachment row missing after write for ${id}`);
|
|
7606
|
-
}
|
|
7607
|
-
if (row.deleteRequestedAt === null) return reuseLiveAttachment({
|
|
7608
|
-
conversationId: args.conversationId,
|
|
7609
|
-
db: args.db,
|
|
7610
|
-
id: row.id,
|
|
7611
|
-
storage: args.storage,
|
|
7612
|
-
storageKey
|
|
7613
|
-
});
|
|
7614
|
-
if (await isConversationPurged(args.db, args.conversationId)) {
|
|
7615
|
-
await bestEffortDelete(args.storage, storageKey);
|
|
7616
|
-
throw purgedConversationError(args.conversationId);
|
|
7617
|
-
}
|
|
7618
|
-
if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
|
|
7619
|
-
...written,
|
|
7620
|
-
deleteRequestedAt: null,
|
|
7621
|
-
storageKey
|
|
7622
|
-
}).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
|
|
7623
|
-
if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
|
|
7624
|
-
conversationId: args.conversationId,
|
|
7625
|
-
db: args.db,
|
|
7626
|
-
id,
|
|
7627
|
-
now,
|
|
7628
|
-
storage: args.storage,
|
|
7629
|
-
storageKey
|
|
7630
|
-
});
|
|
7631
|
-
if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
|
|
7632
|
-
return { id };
|
|
7633
|
-
}
|
|
7634
|
-
const [afterRace] = await args.db.db().select({
|
|
7635
|
-
deleteRequestedAt: juniorAttachments.deleteRequestedAt,
|
|
7636
|
-
id: juniorAttachments.id
|
|
7637
|
-
}).from(juniorAttachments).where(eq(juniorAttachments.id, id));
|
|
7638
|
-
if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
|
|
7639
|
-
conversationId: args.conversationId,
|
|
7640
|
-
db: args.db,
|
|
7641
|
-
id: afterRace.id,
|
|
7642
|
-
storage: args.storage,
|
|
7643
|
-
storageKey
|
|
7644
|
-
});
|
|
7645
|
-
await bestEffortDelete(args.storage, storageKey);
|
|
7646
|
-
throw new Error(`Attachment ${id} disappeared while reviving`);
|
|
7647
|
-
}
|
|
7648
|
-
/**
|
|
7649
|
-
* Record an object that a browser already wrote, under the upload's id.
|
|
7650
|
-
*
|
|
7651
|
-
* The row takes over the object key. A retry with the same id keeps the
|
|
7652
|
-
* first row. The caller checked the object's size, type, and digest.
|
|
7653
|
-
*/
|
|
7654
|
-
async function recordUploadedAttachment(args) {
|
|
7655
|
-
const { attachment } = args;
|
|
7656
|
-
const now = new Date(args.nowMs);
|
|
7657
|
-
await assertConversationNotPurged(args.db, attachment.conversationId);
|
|
7658
|
-
if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [attachment.conversationId])).insert(juniorAttachments).values({
|
|
7659
|
-
bytes: attachment.bytes,
|
|
7660
|
-
contentType: attachment.contentType,
|
|
7661
|
-
conversationId: attachment.conversationId,
|
|
7662
|
-
createdAt: now,
|
|
7663
|
-
id: attachment.id,
|
|
7664
|
-
sha256: attachment.sha256,
|
|
7665
|
-
storageKey: attachment.storageKey,
|
|
7666
|
-
storageProvider: args.storage.provider,
|
|
7667
|
-
title: attachment.filename
|
|
7668
|
-
}).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id })).length > 0 && await isConversationPurged(args.db, attachment.conversationId)) await rejectPurgedAttachmentWrite({
|
|
7669
|
-
conversationId: attachment.conversationId,
|
|
7670
|
-
db: args.db,
|
|
7671
|
-
id: attachment.id,
|
|
7672
|
-
now,
|
|
7673
|
-
storage: args.storage,
|
|
7674
|
-
storageKey: attachment.storageKey
|
|
7675
|
-
});
|
|
7676
|
-
}
|
|
7677
|
-
/**
|
|
7678
|
-
* Store a file that Junior recorded without its bytes, on its first read.
|
|
7679
|
-
*
|
|
7680
|
-
* The bytes stream from the source to a fresh key. The row then takes that
|
|
7681
|
-
* key only while it is still unstored, live, and in a conversation that is
|
|
7682
|
-
* not purged. Purge marks rows in the transaction that purges the
|
|
7683
|
-
* conversation, so this update cannot revive a purged row. When the update
|
|
7684
|
-
* misses, the new object is deleted: return the row that another writer
|
|
7685
|
-
* stored, or null when the row is no longer live.
|
|
7686
|
-
*/
|
|
7687
|
-
async function storeDeferredAttachment(args) {
|
|
7688
|
-
const { attachment, storage } = args;
|
|
7689
|
-
const storageKey = attachmentKey({
|
|
7690
|
-
attachmentId: attachment.id,
|
|
7691
|
-
conversationId: attachment.conversationId,
|
|
7692
|
-
filename: attachment.filename,
|
|
7693
|
-
writeId: randomUUID()
|
|
7694
|
-
});
|
|
7695
|
-
const written = await writeAttachmentObject({
|
|
7696
|
-
file: {
|
|
7697
|
-
bytes: args.file.bytes,
|
|
7698
|
-
filename: attachment.filename,
|
|
7699
|
-
mimeType: attachment.contentType,
|
|
7700
|
-
open: args.file.open,
|
|
7701
|
-
source: attachment.source
|
|
7702
|
-
},
|
|
7703
|
-
key: storageKey,
|
|
7704
|
-
storage
|
|
7705
|
-
});
|
|
7706
|
-
const db = args.db.db();
|
|
7707
|
-
if ((await db.with(conversationDetailTouch(db, [attachment.conversationId])).update(juniorAttachments).set({
|
|
7708
|
-
...written,
|
|
7709
|
-
storageKey
|
|
7710
|
-
}).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 {
|
|
7711
|
-
...attachment,
|
|
7712
|
-
bytes: written.bytes,
|
|
7713
|
-
storageKey
|
|
7714
|
-
};
|
|
7715
|
-
await bestEffortDelete(storage, storageKey);
|
|
7716
|
-
const current = await readLiveAttachment({
|
|
7717
|
-
attachmentId: attachment.id,
|
|
7718
|
-
conversationId: attachment.conversationId,
|
|
7719
|
-
db: args.db
|
|
7720
|
-
});
|
|
7721
|
-
return current?.storageKey ? {
|
|
7722
|
-
...current,
|
|
7723
|
-
storageKey: current.storageKey
|
|
7724
|
-
} : null;
|
|
7725
|
-
}
|
|
7726
|
-
/** Load one live attachment owned by a conversation. */
|
|
7727
|
-
async function readLiveAttachment(args) {
|
|
7728
|
-
const [row] = await args.db.db().select({
|
|
7729
|
-
bytes: juniorAttachments.bytes,
|
|
7730
|
-
contentType: juniorAttachments.contentType,
|
|
7731
|
-
conversationId: juniorAttachments.conversationId,
|
|
7732
|
-
deleteRequestedAt: juniorAttachments.deleteRequestedAt,
|
|
7733
|
-
id: juniorAttachments.id,
|
|
7734
|
-
provider: juniorAttachments.provider,
|
|
7735
|
-
providerId: juniorAttachments.providerId,
|
|
7736
|
-
storageProvider: juniorAttachments.storageProvider,
|
|
7737
|
-
storageKey: juniorAttachments.storageKey,
|
|
7738
|
-
title: juniorAttachments.title
|
|
7739
|
-
}).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), isFileAttachment, eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
|
|
7740
|
-
if (!row) return null;
|
|
7741
|
-
if (await isConversationPurged(args.db, args.conversationId)) return null;
|
|
7742
|
-
return {
|
|
7743
|
-
...fileFields(row),
|
|
7744
|
-
conversationId: row.conversationId,
|
|
7745
|
-
id: row.id,
|
|
7746
|
-
source: row.provider && row.providerId ? {
|
|
7747
|
-
id: row.providerId,
|
|
7748
|
-
provider: row.provider
|
|
7749
|
-
} : null,
|
|
7750
|
-
storageKey: row.storageKey
|
|
7751
|
-
};
|
|
7752
|
-
}
|
|
7753
|
-
/** Persist many conversation-owned files. */
|
|
7754
|
-
async function storeAttachments(args) {
|
|
7755
|
-
return await mapBounded(args.files, (file) => storeAttachment({
|
|
7756
|
-
conversationId: args.conversationId,
|
|
7757
|
-
db: args.db,
|
|
7758
|
-
file: {
|
|
7759
|
-
data: file.data,
|
|
7760
|
-
filename: file.filename,
|
|
7761
|
-
mimeType: file.mimeType
|
|
7762
|
-
},
|
|
7763
|
-
...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
|
|
7764
|
-
storage: args.storage
|
|
7765
|
-
}));
|
|
7766
|
-
}
|
|
7767
|
-
/** Mark attachments unavailable when their conversation content is purged. */
|
|
7768
|
-
async function requestAttachmentDeletion(db, conversationIds, nowMs) {
|
|
7769
|
-
if (conversationIds.length === 0) return;
|
|
7770
|
-
await db.db().with(conversationDetailTouch(db.db(), conversationIds)).update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
|
|
7771
|
-
}
|
|
7772
|
-
/**
|
|
7773
|
-
* Delete purged attachments in one bounded batch.
|
|
7774
|
-
*
|
|
7775
|
-
* Eligible files are 30 days old, explicitly purge-marked, or owned by a
|
|
7776
|
-
* conversation whose transcript is already purged. A `url` row has no bytes,
|
|
7777
|
-
* so it lives as long as its message: it is eligible only when purge-marked
|
|
7778
|
-
* or purged. Delete object keys first, then remove rows that are still
|
|
7779
|
-
* eligible so a failed blob delete remains retryable.
|
|
7780
|
-
*/
|
|
7781
|
-
async function collectAttachmentGarbage(args) {
|
|
7782
|
-
const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
|
|
7783
|
-
const purged = or(isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt));
|
|
7784
|
-
const eligible = or(lte(juniorAttachments.createdAt, expiresBefore), purged);
|
|
7785
|
-
const isUrl = eq(juniorAttachments.kind, "url");
|
|
7786
|
-
const rows = await args.db.db().select({
|
|
7787
|
-
id: juniorAttachments.id,
|
|
7788
|
-
storageKey: juniorAttachments.storageKey
|
|
7789
|
-
}).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);
|
|
7790
|
-
if (rows.length === 0) return { deleted: 0 };
|
|
7791
|
-
const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
|
|
7792
|
-
if (keys.length > 0) await args.storage.delete(keys);
|
|
7793
|
-
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))));
|
|
7794
|
-
if (stillEligible.length === 0) return { deleted: 0 };
|
|
7795
|
-
const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({
|
|
7796
|
-
conversationId: juniorAttachments.conversationId,
|
|
7797
|
-
id: juniorAttachments.id,
|
|
7798
|
-
kind: juniorAttachments.kind
|
|
7799
|
-
});
|
|
7800
|
-
const urls = removed.filter((row) => row.kind === "url");
|
|
7801
|
-
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))));
|
|
7802
|
-
await touchConversationDetail(args.db.db(), removed.map((row) => row.conversationId));
|
|
7803
|
-
return { deleted: removed.length };
|
|
7804
|
-
}
|
|
7805
7080
|
// src/chat/slack/attachments.ts
|
|
7806
7081
|
/** Save the vision summary for a stored Slack attachment. */
|
|
7807
7082
|
async function recordSlackAttachment(args) {
|
|
@@ -8317,448 +7592,6 @@ async function setConversationTitle(executor, conversationId, title) {
|
|
|
8317
7592
|
return row?.title ?? void 0;
|
|
8318
7593
|
});
|
|
8319
7594
|
}
|
|
8320
|
-
// src/chat/attachments/uploads.ts
|
|
8321
|
-
const MINUTE_MS = 6e4;
|
|
8322
|
-
/** Time that a browser has to write the bytes after it asks to upload. */
|
|
8323
|
-
const UPLOAD_TARGET_TTL_MS = 15 * MINUTE_MS;
|
|
8324
|
-
/** Time that a written upload can still join a Message. */
|
|
8325
|
-
const UPLOAD_SEND_WINDOW_MS = 60 * MINUTE_MS;
|
|
8326
|
-
/**
|
|
8327
|
-
* Age at which cleanup deletes an upload that no Message used. It is much
|
|
8328
|
-
* longer than the send window, so cleanup cannot race a send.
|
|
8329
|
-
*/
|
|
8330
|
-
const UPLOAD_RETENTION_MS = 1440 * MINUTE_MS;
|
|
8331
|
-
const UPLOAD_GC_BATCH_LIMIT = 200;
|
|
8332
|
-
/** Leading bytes that image type detection reads. */
|
|
8333
|
-
const SIGNATURE_BYTES = 16;
|
|
8334
|
-
/** A Message refers to an upload that it cannot use. */
|
|
8335
|
-
var AttachmentUploadError = class extends Error {
|
|
8336
|
-
constructor(message) {
|
|
8337
|
-
super(message);
|
|
8338
|
-
this.name = "AttachmentUploadError";
|
|
8339
|
-
}
|
|
8340
|
-
};
|
|
8341
|
-
/**
|
|
8342
|
-
* Reserve one object key for a browser upload.
|
|
8343
|
-
*
|
|
8344
|
-
* Returns no target when the provider cannot sign browser writes. The caller
|
|
8345
|
-
* then takes the bytes with `writeAttachmentUpload`.
|
|
8346
|
-
*/
|
|
8347
|
-
async function createAttachmentUpload(args) {
|
|
8348
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
8349
|
-
const id = randomUUID();
|
|
8350
|
-
const storageKey = `conversations/${args.scope.conversationId}/uploads/${id}`;
|
|
8351
|
-
await args.db.db().insert(juniorAttachmentUploads).values({
|
|
8352
|
-
...args.scope,
|
|
8353
|
-
bytes: args.file.bytes,
|
|
8354
|
-
contentType: args.file.contentType,
|
|
8355
|
-
createdAt: new Date(nowMs),
|
|
8356
|
-
filename: args.file.filename,
|
|
8357
|
-
id,
|
|
8358
|
-
storageKey,
|
|
8359
|
-
storageProvider: args.storage.provider
|
|
8360
|
-
});
|
|
8361
|
-
const target = await args.storage.createUploadTarget?.({
|
|
8362
|
-
bytes: args.file.bytes,
|
|
8363
|
-
contentType: args.file.contentType,
|
|
8364
|
-
expiresAtMs: nowMs + UPLOAD_TARGET_TTL_MS,
|
|
8365
|
-
key: storageKey
|
|
8366
|
-
});
|
|
8367
|
-
return target ? {
|
|
8368
|
-
id,
|
|
8369
|
-
target
|
|
8370
|
-
} : { id };
|
|
8371
|
-
}
|
|
8372
|
-
async function readUploadRows(args) {
|
|
8373
|
-
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))));
|
|
8374
|
-
}
|
|
8375
|
-
/** Write upload bytes through the API, for providers without browser writes. */
|
|
8376
|
-
async function writeAttachmentUpload(args) {
|
|
8377
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
8378
|
-
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))));
|
|
8379
|
-
if (!row) throw new AttachmentUploadError("Upload not found.");
|
|
8380
|
-
if (await readLiveAttachment({
|
|
8381
|
-
attachmentId: row.id,
|
|
8382
|
-
conversationId: row.conversationId,
|
|
8383
|
-
db: args.db
|
|
8384
|
-
})) throw new AttachmentUploadError("Upload was already sent.");
|
|
8385
|
-
if (args.body.byteLength !== row.bytes) throw new AttachmentUploadError("Upload size does not match the file.");
|
|
8386
|
-
await args.storage.put({
|
|
8387
|
-
body: bufferBody(args.body),
|
|
8388
|
-
bytes: row.bytes,
|
|
8389
|
-
contentType: row.contentType,
|
|
8390
|
-
key: row.storageKey
|
|
8391
|
-
});
|
|
8392
|
-
}
|
|
8393
|
-
/** Read a whole object once for its size, digest, and leading bytes. */
|
|
8394
|
-
async function inspectObject(body, maxBytes) {
|
|
8395
|
-
const hash = createHash("sha256");
|
|
8396
|
-
const head = [];
|
|
8397
|
-
let headBytes = 0;
|
|
8398
|
-
let bytes = 0;
|
|
8399
|
-
const reader = body.getReader();
|
|
8400
|
-
for (;;) {
|
|
8401
|
-
const { done, value } = await reader.read();
|
|
8402
|
-
if (done) break;
|
|
8403
|
-
bytes += value.byteLength;
|
|
8404
|
-
if (bytes > maxBytes) {
|
|
8405
|
-
await reader.cancel();
|
|
8406
|
-
return;
|
|
8407
|
-
}
|
|
8408
|
-
hash.update(value);
|
|
8409
|
-
if (headBytes < SIGNATURE_BYTES) {
|
|
8410
|
-
head.push(Buffer.from(value.subarray(0, SIGNATURE_BYTES - headBytes)));
|
|
8411
|
-
headBytes += head.at(-1).byteLength;
|
|
8412
|
-
}
|
|
8413
|
-
}
|
|
8414
|
-
return {
|
|
8415
|
-
bytes,
|
|
8416
|
-
head: Buffer.concat(head),
|
|
8417
|
-
sha256: hash.digest("hex")
|
|
8418
|
-
};
|
|
8419
|
-
}
|
|
8420
|
-
/**
|
|
8421
|
-
* Pick the type to store from the file signature, not only the browser's
|
|
8422
|
-
* guess from the file name. Models reject an image whose bytes do not match
|
|
8423
|
-
* its type, so a file that only claims to be an image is stored as bytes.
|
|
8424
|
-
*/
|
|
8425
|
-
function storedContentType(declared, head) {
|
|
8426
|
-
const detected = detectImageMediaType(head);
|
|
8427
|
-
if (detected) return detected;
|
|
8428
|
-
return isVisionImageMediaType(declared) ? "application/octet-stream" : declared;
|
|
8429
|
-
}
|
|
8430
|
-
/**
|
|
8431
|
-
* Check the uploads of one Message before the Message is accepted.
|
|
8432
|
-
*
|
|
8433
|
-
* Each upload must belong to the scope and be written in full at its
|
|
8434
|
-
* declared size. Throws `AttachmentUploadError` for any upload that the
|
|
8435
|
-
* Message cannot use.
|
|
8436
|
-
*/
|
|
8437
|
-
async function verifyAttachmentUploads(args) {
|
|
8438
|
-
if (args.uploadIds.length === 0) return [];
|
|
8439
|
-
if (new Set(args.uploadIds).size !== args.uploadIds.length) throw new AttachmentUploadError("Attach each file once.");
|
|
8440
|
-
const rows = await readUploadRows({
|
|
8441
|
-
db: args.db,
|
|
8442
|
-
nowMs: args.nowMs ?? Date.now(),
|
|
8443
|
-
scope: args.scope,
|
|
8444
|
-
storageProvider: args.storage.provider,
|
|
8445
|
-
uploadIds: args.uploadIds
|
|
8446
|
-
});
|
|
8447
|
-
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
8448
|
-
return await Promise.all(args.uploadIds.map(async (uploadId) => {
|
|
8449
|
-
const row = byId.get(uploadId);
|
|
8450
|
-
if (!row) throw new AttachmentUploadError("Upload expired. Attach the file again.");
|
|
8451
|
-
const recorded = await readLiveAttachment({
|
|
8452
|
-
attachmentId: row.id,
|
|
8453
|
-
conversationId: row.conversationId,
|
|
8454
|
-
db: args.db
|
|
8455
|
-
});
|
|
8456
|
-
if (recorded) return {
|
|
8457
|
-
attachment: {
|
|
8458
|
-
bytes: recorded.bytes,
|
|
8459
|
-
contentType: recorded.contentType,
|
|
8460
|
-
filename: recorded.filename,
|
|
8461
|
-
id: recorded.id
|
|
8462
|
-
},
|
|
8463
|
-
recorded: true
|
|
8464
|
-
};
|
|
8465
|
-
const body = await args.storage.get(row.storageKey);
|
|
8466
|
-
const object = body ? await inspectObject(body, row.bytes) : void 0;
|
|
8467
|
-
if (!object || object.bytes !== row.bytes) throw new AttachmentUploadError(`Upload of ${row.filename} is not complete. Attach it again.`);
|
|
8468
|
-
return {
|
|
8469
|
-
attachment: {
|
|
8470
|
-
bytes: row.bytes,
|
|
8471
|
-
contentType: storedContentType(row.contentType, object.head),
|
|
8472
|
-
filename: row.filename,
|
|
8473
|
-
id: row.id
|
|
8474
|
-
},
|
|
8475
|
-
recorded: false,
|
|
8476
|
-
sha256: object.sha256,
|
|
8477
|
-
storageKey: row.storageKey
|
|
8478
|
-
};
|
|
8479
|
-
}));
|
|
8480
|
-
}
|
|
8481
|
-
/** Record checked uploads as attachments of their Conversation. */
|
|
8482
|
-
async function recordAttachmentUploads(args) {
|
|
8483
|
-
await mapBounded(args.uploads.filter((upload) => !upload.recorded), (upload) => recordUploadedAttachment({
|
|
8484
|
-
attachment: {
|
|
8485
|
-
...upload.attachment,
|
|
8486
|
-
conversationId: args.conversationId,
|
|
8487
|
-
sha256: upload.sha256,
|
|
8488
|
-
storageKey: upload.storageKey
|
|
8489
|
-
},
|
|
8490
|
-
db: args.db,
|
|
8491
|
-
nowMs: args.nowMs ?? Date.now(),
|
|
8492
|
-
storage: args.storage
|
|
8493
|
-
}));
|
|
8494
|
-
return args.uploads.map((upload) => upload.attachment);
|
|
8495
|
-
}
|
|
8496
|
-
/**
|
|
8497
|
-
* Delete old upload rows in one bounded batch.
|
|
8498
|
-
*
|
|
8499
|
-
* An upload that a Message recorded keeps its object: the attachment row owns
|
|
8500
|
-
* it now. Other objects are deleted first, so a failed delete stays
|
|
8501
|
-
* retryable.
|
|
8502
|
-
*/
|
|
8503
|
-
async function collectAttachmentUploadGarbage(args) {
|
|
8504
|
-
const rows = await args.db.db().select({
|
|
8505
|
-
id: juniorAttachmentUploads.id,
|
|
8506
|
-
recordedId: juniorAttachments.id,
|
|
8507
|
-
storageKey: juniorAttachmentUploads.storageKey
|
|
8508
|
-
}).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);
|
|
8509
|
-
if (rows.length === 0) return { deleted: 0 };
|
|
8510
|
-
const unusedKeys = rows.filter((row) => row.recordedId === null).map((row) => row.storageKey);
|
|
8511
|
-
await args.storage.delete(unusedKeys);
|
|
8512
|
-
return { deleted: (await args.db.db().delete(juniorAttachmentUploads).where(inArray(juniorAttachmentUploads.id, rows.map((row) => row.id))).returning({ id: juniorAttachmentUploads.id })).length };
|
|
8513
|
-
}
|
|
8514
|
-
// src/chat/conversations/destination.ts
|
|
8515
|
-
function requireLocalDestination(conversationId) {
|
|
8516
|
-
const parsed = localDestinationSchema.safeParse({
|
|
8517
|
-
platform: "local",
|
|
8518
|
-
conversationId
|
|
8519
|
-
});
|
|
8520
|
-
if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
|
|
8521
|
-
return parsed.data;
|
|
8522
|
-
}
|
|
8523
|
-
/**
|
|
8524
|
-
* Keep a stored Destination, or create the temporary local Destination.
|
|
8525
|
-
*
|
|
8526
|
-
* TODO(dcramer): Delete this module after Conversation and AgentRun use
|
|
8527
|
-
* Location, and web and event Turns no longer need a local
|
|
8528
|
-
* Destination.
|
|
8529
|
-
*/
|
|
8530
|
-
function resolveConversationDestination(args) {
|
|
8531
|
-
return args.existing ?? requireLocalDestination(args.conversationId);
|
|
8532
|
-
}
|
|
8533
|
-
/**
|
|
8534
|
-
* Create the local Destination of a Conversation that needs its own, such as
|
|
8535
|
-
* one that leaves its Space. A local id is its own Destination. Another id,
|
|
8536
|
-
* such as a child agent's or a Slack thread's, maps to a stable local one.
|
|
8537
|
-
*/
|
|
8538
|
-
function ownLocalDestination(conversationId) {
|
|
8539
|
-
const own = localDestinationSchema.safeParse({
|
|
8540
|
-
platform: "local",
|
|
8541
|
-
conversationId
|
|
8542
|
-
});
|
|
8543
|
-
if (own.success) return own.data;
|
|
8544
|
-
return requireLocalDestination(`local:conversation:${createHash("sha256").update(conversationId).digest("hex").slice(0, 32)}`);
|
|
8545
|
-
}
|
|
8546
|
-
// src/chat/conversations/web-input.ts
|
|
8547
|
-
function normalizeEmail(email) {
|
|
8548
|
-
return email.trim().toLowerCase();
|
|
8549
|
-
}
|
|
8550
|
-
function stableHex$1(...parts) {
|
|
8551
|
-
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
|
|
8552
|
-
}
|
|
8553
|
-
/**
|
|
8554
|
-
* Build a durable Conversation id for one web Actor and create key.
|
|
8555
|
-
*
|
|
8556
|
-
* Retries with the same key must address the same Conversation before the
|
|
8557
|
-
* mailbox Message id is derived.
|
|
8558
|
-
*/
|
|
8559
|
-
function createConversationId(args) {
|
|
8560
|
-
return `local:web:${stableHex$1(normalizeEmail(args.actorEmail), args.idempotencyKey)}`;
|
|
8561
|
-
}
|
|
8562
|
-
/** Return the stable Turn id for one mailbox Message. */
|
|
8563
|
-
function conversationTurnIdForMessage(messageId) {
|
|
8564
|
-
return buildDeterministicTurnId(messageId);
|
|
8565
|
-
}
|
|
8566
|
-
/**
|
|
8567
|
-
* Store the dashboard participant in the current Conversation actor field.
|
|
8568
|
-
*
|
|
8569
|
-
* TODO(dcramer): Remove this StoredSlackActor conversion after Conversation
|
|
8570
|
-
* actor storage accepts web Actors directly.
|
|
8571
|
-
*/
|
|
8572
|
-
function storedActorFromWeb(actor) {
|
|
8573
|
-
return {
|
|
8574
|
-
...actor.email ? { email: normalizeEmail(actor.email) } : void 0,
|
|
8575
|
-
...actor.fullName ? { fullName: actor.fullName } : void 0
|
|
8576
|
-
};
|
|
8577
|
-
}
|
|
8578
|
-
/**
|
|
8579
|
-
* Return whether a person can add a web Message to an existing
|
|
8580
|
-
* Conversation: a dashboard Conversation, a Slack thread, or a Thread.
|
|
8581
|
-
*/
|
|
8582
|
-
function acceptsWebMessages(conversation) {
|
|
8583
|
-
if (!isTopLevel(conversation)) return isThread(conversation);
|
|
8584
|
-
const { conversationId, destination } = conversation;
|
|
8585
|
-
if (destination?.platform === "slack") return true;
|
|
8586
|
-
return destination?.platform === "local" && conversationId.startsWith("local:web:");
|
|
8587
|
-
}
|
|
8588
|
-
/**
|
|
8589
|
-
* Build the web Actor for one signed-in User. Junior is the web provider,
|
|
8590
|
-
* so the provider-scoped Actor id is the User id.
|
|
8591
|
-
*/
|
|
8592
|
-
function webActorFromUser(user, profile) {
|
|
8593
|
-
return {
|
|
8594
|
-
platform: "web",
|
|
8595
|
-
userId: user.id,
|
|
8596
|
-
email: normalizeEmail(user.email),
|
|
8597
|
-
...user.displayName ? { fullName: user.displayName } : void 0,
|
|
8598
|
-
...profile?.userName ? { userName: profile.userName } : void 0
|
|
8599
|
-
};
|
|
8600
|
-
}
|
|
8601
|
-
/** Build one web mailbox entry. */
|
|
8602
|
-
function buildWebInboundMessage(args) {
|
|
8603
|
-
const text = args.message.trim();
|
|
8604
|
-
if (!text && !args.attachments?.length) throw new Error("Web Message must not be empty");
|
|
8605
|
-
if (!args.actor.email) throw new Error("Web Actor requires a verified email");
|
|
8606
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
8607
|
-
const traceContext = getActiveTraceContext();
|
|
8608
|
-
return {
|
|
8609
|
-
conversationId: args.conversationId,
|
|
8610
|
-
createdAtMs: args.createdAtMs ?? nowMs,
|
|
8611
|
-
delivery: args.delivery ?? "defer",
|
|
8612
|
-
...args.destination ? { destination: args.destination } : void 0,
|
|
8613
|
-
inboundMessageId: args.messageId,
|
|
8614
|
-
input: {
|
|
8615
|
-
authorId: args.actor.userId,
|
|
8616
|
-
...args.authorIdentityId ? { authorIdentityId: args.authorIdentityId } : void 0,
|
|
8617
|
-
text,
|
|
8618
|
-
...args.attachments?.length ? { attachments: args.attachments } : void 0,
|
|
8619
|
-
...args.reviewItemChange ? { reviewItemChange: args.reviewItemChange } : void 0,
|
|
8620
|
-
metadata: {
|
|
8621
|
-
authorEmail: normalizeEmail(args.actor.email),
|
|
8622
|
-
...args.actor.fullName && { authorFullName: args.actor.fullName },
|
|
8623
|
-
authorUserId: args.actor.userId,
|
|
8624
|
-
...args.actor.userName && { authorUserName: args.actor.userName },
|
|
8625
|
-
kind: "api_turn",
|
|
8626
|
-
messageId: args.messageId
|
|
8627
|
-
}
|
|
8628
|
-
},
|
|
8629
|
-
receivedAtMs: nowMs,
|
|
8630
|
-
source: "web",
|
|
8631
|
-
...traceContext ? { traceContext } : void 0
|
|
8632
|
-
};
|
|
8633
|
-
}
|
|
8634
|
-
/**
|
|
8635
|
-
* Record web activity and create a Conversation root when needed. Returns the
|
|
8636
|
-
* Destination for the Message's work. A child's work keeps none, so its
|
|
8637
|
-
* workers read the Conversation.
|
|
8638
|
-
*/
|
|
8639
|
-
async function recordWebConversationActivity(args) {
|
|
8640
|
-
const store = args.conversationStore ?? getConversationStore();
|
|
8641
|
-
let existing = await store.get({ conversationId: args.conversationId });
|
|
8642
|
-
if (!existing && args.leadConversationId) {
|
|
8643
|
-
await store.createChild({
|
|
8644
|
-
childConversationId: args.conversationId,
|
|
8645
|
-
kind: "thread",
|
|
8646
|
-
nowMs: args.nowMs,
|
|
8647
|
-
parentConversationId: args.leadConversationId,
|
|
8648
|
-
source: "web",
|
|
8649
|
-
...args.rootTitle ? { title: args.rootTitle } : void 0
|
|
8650
|
-
});
|
|
8651
|
-
existing = await store.get({ conversationId: args.conversationId });
|
|
8652
|
-
}
|
|
8653
|
-
const destination = resolveConversationDestination({
|
|
8654
|
-
conversationId: args.conversationId,
|
|
8655
|
-
existing: existing?.destination
|
|
8656
|
-
});
|
|
8657
|
-
const isNewRoot = !existing;
|
|
8658
|
-
const visibility = args.rootVisibility === "private" ? "private" : "public";
|
|
8659
|
-
const source = isNewRoot ? createWebSource(args.conversationId, visibility) : void 0;
|
|
8660
|
-
await store.recordActivity({
|
|
8661
|
-
conversationId: args.conversationId,
|
|
8662
|
-
...existing?.destination ? void 0 : { destination },
|
|
8663
|
-
nowMs: args.nowMs,
|
|
8664
|
-
actor: storedActorFromWeb(args.actor),
|
|
8665
|
-
...isNewRoot ? { source: "web" } : void 0,
|
|
8666
|
-
...source ? { sessionSource: source } : void 0,
|
|
8667
|
-
...isNewRoot && args.rootTitle ? { title: args.rootTitle } : void 0,
|
|
8668
|
-
...isNewRoot ? { visibility } : void 0,
|
|
8669
|
-
...isNewRoot && args.rootKind ? { kind: args.rootKind } : void 0,
|
|
8670
|
-
...isNewRoot && args.rootSpaceId ? { spaceId: args.rootSpaceId } : void 0
|
|
8671
|
-
});
|
|
8672
|
-
return existing && !isTopLevel(existing) ? void 0 : destination;
|
|
8673
|
-
}
|
|
8674
|
-
/** Create a Conversation from web input and enqueue its first Message. */
|
|
8675
|
-
async function createAndEnqueueConversation(input, options) {
|
|
8676
|
-
if (!input.actor.email) throw new Error("Web Actor requires a verified email");
|
|
8677
|
-
const conversationId = createConversationId({
|
|
8678
|
-
actorEmail: input.actor.email,
|
|
8679
|
-
idempotencyKey: input.idempotencyKey
|
|
8680
|
-
});
|
|
8681
|
-
return await appendAndEnqueueWebMessage({
|
|
8682
|
-
actor: input.actor,
|
|
8683
|
-
conversationId,
|
|
8684
|
-
idempotencyKey: input.idempotencyKey,
|
|
8685
|
-
message: input.message,
|
|
8686
|
-
uploads: input.uploads,
|
|
8687
|
-
...input.title ? { rootTitle: input.title } : void 0,
|
|
8688
|
-
rootVisibility: input.visibility === "private" ? "private" : "public",
|
|
8689
|
-
...input.leadConversationId ? { leadConversationId: input.leadConversationId } : void 0
|
|
8690
|
-
}, options);
|
|
8691
|
-
}
|
|
8692
|
-
async function appendAndEnqueueWebMessage(input, options) {
|
|
8693
|
-
const text = input.message.trim();
|
|
8694
|
-
if (!text && !input.uploads?.length) throw new Error("Web Message must not be empty");
|
|
8695
|
-
if (!input.actor.email) throw new Error("Web Actor requires a verified email");
|
|
8696
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
8697
|
-
const messageId = await webMessageId({
|
|
8698
|
-
conversationId: input.conversationId,
|
|
8699
|
-
idempotencyKey: input.idempotencyKey
|
|
8700
|
-
});
|
|
8701
|
-
const destination = await recordWebConversationActivity({
|
|
8702
|
-
actor: input.actor,
|
|
8703
|
-
conversationId: input.conversationId,
|
|
8704
|
-
conversationStore: options.conversationStore,
|
|
8705
|
-
nowMs,
|
|
8706
|
-
...input.rootTitle && { rootTitle: input.rootTitle },
|
|
8707
|
-
...input.rootVisibility && { rootVisibility: input.rootVisibility },
|
|
8708
|
-
...input.rootSpaceId && { rootSpaceId: input.rootSpaceId },
|
|
8709
|
-
...input.leadConversationId && { leadConversationId: input.leadConversationId }
|
|
8710
|
-
});
|
|
8711
|
-
let attachments = [];
|
|
8712
|
-
if (input.uploads?.length) {
|
|
8713
|
-
if (!options.attachmentStorage) throw new Error("Attachment storage is unavailable.");
|
|
8714
|
-
attachments = await recordAttachmentUploads({
|
|
8715
|
-
conversationId: input.conversationId,
|
|
8716
|
-
db: getSqlExecutor(),
|
|
8717
|
-
nowMs,
|
|
8718
|
-
storage: options.attachmentStorage,
|
|
8719
|
-
uploads: input.uploads
|
|
8720
|
-
});
|
|
8721
|
-
}
|
|
8722
|
-
const enqueue = options.exclusive ? appendAndEnqueueExclusiveInboundMessage : appendAndEnqueueInboundMessage;
|
|
8723
|
-
const authorIdentityId = await resolveActorIdentityId(getSqlExecutor(), input.actor);
|
|
8724
|
-
const enqueueTo = (destination) => enqueue({
|
|
8725
|
-
message: buildWebInboundMessage({
|
|
8726
|
-
actor: input.actor,
|
|
8727
|
-
authorIdentityId,
|
|
8728
|
-
conversationId: input.conversationId,
|
|
8729
|
-
delivery: input.delivery,
|
|
8730
|
-
destination,
|
|
8731
|
-
message: text,
|
|
8732
|
-
attachments,
|
|
8733
|
-
messageId,
|
|
8734
|
-
nowMs,
|
|
8735
|
-
...input.reviewItemChange && { reviewItemChange: input.reviewItemChange }
|
|
8736
|
-
}),
|
|
8737
|
-
conversationStore: options.conversationStore,
|
|
8738
|
-
nowMs,
|
|
8739
|
-
queue: options.queue,
|
|
8740
|
-
state: options.state
|
|
8741
|
-
});
|
|
8742
|
-
let result;
|
|
8743
|
-
try {
|
|
8744
|
-
result = await enqueueTo(destination);
|
|
8745
|
-
} catch (error) {
|
|
8746
|
-
if (!destination) throw error;
|
|
8747
|
-
const stored = await (options.conversationStore ?? getConversationStore()).get({ conversationId: input.conversationId });
|
|
8748
|
-
const current = resolveConversationDestination({
|
|
8749
|
-
conversationId: input.conversationId,
|
|
8750
|
-
existing: stored?.destination
|
|
8751
|
-
});
|
|
8752
|
-
if (sameDestination(current, destination)) throw error;
|
|
8753
|
-
result = await enqueueTo(current);
|
|
8754
|
-
}
|
|
8755
|
-
const status = result.status === "appended" ? "accepted" : result.status;
|
|
8756
|
-
return {
|
|
8757
|
-
conversationId: input.conversationId,
|
|
8758
|
-
messageId,
|
|
8759
|
-
status
|
|
8760
|
-
};
|
|
8761
|
-
}
|
|
8762
7595
|
// src/chat/spaces/store.ts
|
|
8763
7596
|
/**
|
|
8764
7597
|
* Spaces (`design/spaces.md`). A Space's members are the Participants of
|
|
@@ -11867,35 +10700,37 @@ function providerContent(content) {
|
|
|
11867
10700
|
}
|
|
11868
10701
|
/**
|
|
11869
10702
|
* Create read-only MCP access to one plugin's provider as one viewer. The
|
|
11870
|
-
* viewer's User id is the subject of their stored MCP login.
|
|
11871
|
-
|
|
11872
|
-
|
|
11873
|
-
|
|
11874
|
-
|
|
11875
|
-
|
|
11876
|
-
|
|
11877
|
-
|
|
11878
|
-
|
|
11879
|
-
|
|
11880
|
-
|
|
11881
|
-
|
|
11882
|
-
|
|
11883
|
-
|
|
11884
|
-
|
|
11885
|
-
|
|
11886
|
-
|
|
11887
|
-
|
|
11888
|
-
|
|
11889
|
-
|
|
11890
|
-
|
|
11891
|
-
|
|
11892
|
-
|
|
11893
|
-
|
|
11894
|
-
|
|
11895
|
-
|
|
11896
|
-
|
|
11897
|
-
|
|
11898
|
-
}
|
|
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
|
+
}
|
|
11899
10734
|
}
|
|
11900
10735
|
// src/api/objects/automation.ts
|
|
11901
10736
|
/**
|
|
@@ -12048,99 +10883,6 @@ async function readConversationAuthors(db, conversationId) {
|
|
|
12048
10883
|
participants: [...group.values()]
|
|
12049
10884
|
};
|
|
12050
10885
|
}
|
|
12051
|
-
// src/chat/slack/conversation-context.ts
|
|
12052
|
-
function normalizeConversationName(type, channelName) {
|
|
12053
|
-
const trimmed = channelName?.trim();
|
|
12054
|
-
if (!trimmed) return void 0;
|
|
12055
|
-
if (type === "public_channel" || type === "private_channel" || type === "private_channel_or_group_dm") return trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
|
|
12056
|
-
return trimmed;
|
|
12057
|
-
}
|
|
12058
|
-
function typeFromSlackChannelType(channelType) {
|
|
12059
|
-
if (channelType === "channel") return "public_channel";
|
|
12060
|
-
if (channelType === "group") return "private_channel";
|
|
12061
|
-
if (channelType === "mpim") return "group_dm";
|
|
12062
|
-
if (channelType === "im") return "direct_message";
|
|
12063
|
-
}
|
|
12064
|
-
function typeFromChannelId(channelId, channelName) {
|
|
12065
|
-
const normalized = normalizeSlackConversationId(channelId);
|
|
12066
|
-
if (!normalized) return void 0;
|
|
12067
|
-
if (normalized.startsWith("C")) return "public_channel";
|
|
12068
|
-
if (normalized.startsWith("D")) return "direct_message";
|
|
12069
|
-
if (normalized.startsWith("G")) return channelName?.trim().startsWith("mpdm-") ? "group_dm" : "private_channel_or_group_dm";
|
|
12070
|
-
}
|
|
12071
|
-
function toSlackEventChannelType(channelType) {
|
|
12072
|
-
if (channelType === "channel" || channelType === "group" || channelType === "mpim" || channelType === "im") return channelType;
|
|
12073
|
-
}
|
|
12074
|
-
/**
|
|
12075
|
-
* Map Slack's Events API channel_type to a source-confirmed visibility.
|
|
12076
|
-
*
|
|
12077
|
-
* Slack's event metadata and live conversation metadata are the only
|
|
12078
|
-
* visibility authorities; channel IDs never classify visibility.
|
|
12079
|
-
*/
|
|
12080
|
-
function conversationVisibilityFromSlackChannelType(channelType) {
|
|
12081
|
-
if (!channelType) return void 0;
|
|
12082
|
-
return channelType === "channel" ? "public" : "private";
|
|
12083
|
-
}
|
|
12084
|
-
/**
|
|
12085
|
-
* Map live `conversations.info` metadata to Slack's Events API channel type,
|
|
12086
|
-
* for events that carry no `channel_type`.
|
|
12087
|
-
*/
|
|
12088
|
-
function slackChannelTypeFromConversationInfo(info) {
|
|
12089
|
-
if (info.isIm) return "im";
|
|
12090
|
-
if (info.isMpim) return "mpim";
|
|
12091
|
-
if (info.isPrivate) return "group";
|
|
12092
|
-
return info.isChannel ? "channel" : void 0;
|
|
12093
|
-
}
|
|
12094
|
-
/** Resolve Slack's raw event channel type from a Chat SDK message-like object. */
|
|
12095
|
-
function resolveSlackChannelTypeFromMessage(message) {
|
|
12096
|
-
const raw = message.raw;
|
|
12097
|
-
if (!raw || typeof raw !== "object") return;
|
|
12098
|
-
const channelType = raw["channel_type"];
|
|
12099
|
-
return typeof channelType === "string" ? toSlackEventChannelType(channelType.trim()) : void 0;
|
|
12100
|
-
}
|
|
12101
|
-
/** Build Slack conversation facts available to runtime consumers. */
|
|
12102
|
-
function resolveSlackConversationContext(input) {
|
|
12103
|
-
const type = typeFromSlackChannelType(input.channelType) ?? typeFromChannelId(input.channelId, input.channelName);
|
|
12104
|
-
if (!type) return void 0;
|
|
12105
|
-
const name = normalizeConversationName(type, input.channelName);
|
|
12106
|
-
const topic = input.channelTopic?.trim();
|
|
12107
|
-
const description = input.channelDescription?.trim();
|
|
12108
|
-
const visibility = conversationVisibilityFromSlackChannelType(input.channelType);
|
|
12109
|
-
return {
|
|
12110
|
-
type,
|
|
12111
|
-
...name ? { name } : void 0,
|
|
12112
|
-
...topic ? { topic } : void 0,
|
|
12113
|
-
...description ? { description } : void 0,
|
|
12114
|
-
...visibility ? { visibility } : void 0,
|
|
12115
|
-
...input.botUserId ? { botUserId: input.botUserId } : void 0
|
|
12116
|
-
};
|
|
12117
|
-
}
|
|
12118
|
-
/** Build Slack conversation facts from Junior's persisted Slack thread id. */
|
|
12119
|
-
function resolveSlackConversationContextFromThreadId(input) {
|
|
12120
|
-
const context = resolveSlackConversationContext({
|
|
12121
|
-
channelId: parseSlackThreadId(input.threadId)?.channelId,
|
|
12122
|
-
channelName: input.channelName
|
|
12123
|
-
});
|
|
12124
|
-
if (!context || !input.visibility) return context;
|
|
12125
|
-
return {
|
|
12126
|
-
...context,
|
|
12127
|
-
type: input.visibility === "private" && context.type === "public_channel" ? "private_channel" : context.type,
|
|
12128
|
-
visibility: input.visibility
|
|
12129
|
-
};
|
|
12130
|
-
}
|
|
12131
|
-
/** Render a human label for a privacy-preserving Slack conversation type. */
|
|
12132
|
-
function formatSlackConversationTypeLabel(type) {
|
|
12133
|
-
if (type === "public_channel") return "Public Channel";
|
|
12134
|
-
if (type === "private_channel") return "Private Channel";
|
|
12135
|
-
if (type === "group_dm") return "Group DM";
|
|
12136
|
-
if (type === "direct_message") return "Direct Message";
|
|
12137
|
-
return "Private Channel or Group DM";
|
|
12138
|
-
}
|
|
12139
|
-
/** Render a Slack conversation label without exposing conversation names. */
|
|
12140
|
-
function formatSlackConversationRedactedLabel(context) {
|
|
12141
|
-
if (!context) return void 0;
|
|
12142
|
-
return formatSlackConversationTypeLabel(context.type);
|
|
12143
|
-
}
|
|
12144
10886
|
// src/chat/slack/location-url.ts
|
|
12145
10887
|
/** Parse a Slack workspace subdomain used in `https://{domain}.slack.com` URLs. */
|
|
12146
10888
|
function parseSlackTeamDomain(value) {
|
|
@@ -13237,11 +11979,12 @@ async function loadWebPage(url) {
|
|
|
13237
11979
|
* viewer, so one cached card per URL serves them all. Junior's own dashboard
|
|
13238
11980
|
* pages get no card.
|
|
13239
11981
|
*/
|
|
13240
|
-
async function resolveWebPageLink(url) {
|
|
11982
|
+
async function resolveWebPageLink(url, cacheOnly) {
|
|
13241
11983
|
if (isDashboardLink(url)) return void 0;
|
|
13242
11984
|
if (url.username || url.password) return void 0;
|
|
13243
11985
|
const key = createHash("sha256").update(url.href).digest("hex");
|
|
13244
|
-
|
|
11986
|
+
const cache = createCache(getStateAdapter(), "web-pages");
|
|
11987
|
+
return (cacheOnly ? await cache.get(key) : await cache.getOrLoad(key, () => loadWebPage(url))) ?? void 0;
|
|
13245
11988
|
}
|
|
13246
11989
|
/**
|
|
13247
11990
|
* The least specific link type. Any plugin or core link type that matches a
|
|
@@ -13249,11 +11992,12 @@ async function resolveWebPageLink(url) {
|
|
|
13249
11992
|
*/
|
|
13250
11993
|
function webPageLinkType() {
|
|
13251
11994
|
return {
|
|
11995
|
+
cacheOnlyReads: true,
|
|
13252
11996
|
canView: async () => true,
|
|
13253
11997
|
filters: [{ scheme: "https" }],
|
|
13254
11998
|
objectTypes: ["web_page"],
|
|
13255
11999
|
owner: "junior",
|
|
13256
|
-
resolve: (_viewer, url) => resolveWebPageLink(url)
|
|
12000
|
+
resolve: (_viewer, url, _prefetched, read) => resolveWebPageLink(url, Boolean(read?.cacheOnly))
|
|
13257
12001
|
};
|
|
13258
12002
|
}
|
|
13259
12003
|
// src/api/objects/resolve.ts
|
|
@@ -13271,10 +12015,43 @@ const DEFAULT_HTTP_CACHE = {
|
|
|
13271
12015
|
staleIfError: true,
|
|
13272
12016
|
ttlMs: OBJECT_LINK_TTL_MS
|
|
13273
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
|
+
}
|
|
13274
12048
|
const OBJECT_LINK_SYSTEM_ACTOR = {
|
|
13275
12049
|
platform: "system",
|
|
13276
12050
|
name: "object-link"
|
|
13277
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 };
|
|
13278
12055
|
function coreLinkTypes() {
|
|
13279
12056
|
const slack = {
|
|
13280
12057
|
cacheCards: true,
|
|
@@ -13295,6 +12072,7 @@ function coreLinkTypes() {
|
|
|
13295
12072
|
{
|
|
13296
12073
|
canView: canViewAutomationLink,
|
|
13297
12074
|
filters: [automations],
|
|
12075
|
+
cacheOnlyReads: true,
|
|
13298
12076
|
label: () => "Automation",
|
|
13299
12077
|
objectTypes: ["automation"],
|
|
13300
12078
|
owner: "junior",
|
|
@@ -13302,6 +12080,7 @@ function coreLinkTypes() {
|
|
|
13302
12080
|
},
|
|
13303
12081
|
{
|
|
13304
12082
|
cacheCards: true,
|
|
12083
|
+
cacheOnlyReads: true,
|
|
13305
12084
|
canView: canViewConversationLink,
|
|
13306
12085
|
filters: [conversations],
|
|
13307
12086
|
objectTypes: ["conversation"],
|
|
@@ -13309,6 +12088,7 @@ function coreLinkTypes() {
|
|
|
13309
12088
|
resolve: resolveConversationLink
|
|
13310
12089
|
},
|
|
13311
12090
|
{
|
|
12091
|
+
cacheOnlyReads: true,
|
|
13312
12092
|
canView: async () => true,
|
|
13313
12093
|
filters: [people, { scheme: "mailto" }],
|
|
13314
12094
|
objectTypes: ["person"],
|
|
@@ -13324,7 +12104,7 @@ function coreLinkTypes() {
|
|
|
13324
12104
|
*/
|
|
13325
12105
|
function cardReadCache(cache, servedStale) {
|
|
13326
12106
|
return {
|
|
13327
|
-
get: async (key) => await cache.get(key),
|
|
12107
|
+
get: async (key, options) => await cache.get(key, options),
|
|
13328
12108
|
async getOrLoad(key, load, options) {
|
|
13329
12109
|
return await cache.getOrLoad(key, async () => {
|
|
13330
12110
|
const entry = await load();
|
|
@@ -13360,6 +12140,7 @@ function objectLinkContext(name, link, viewer, prefetched, read = {}) {
|
|
|
13360
12140
|
db: getDb(),
|
|
13361
12141
|
egress: createPluginEgress({
|
|
13362
12142
|
credentialContext: credentialContextForActor(OBJECT_LINK_SYSTEM_ACTOR),
|
|
12143
|
+
fetch: cardReadFetch(read.signal),
|
|
13363
12144
|
httpCache,
|
|
13364
12145
|
pluginAuth: { async handleAuthRequired() {} }
|
|
13365
12146
|
}),
|
|
@@ -13373,21 +12154,29 @@ function objectLinkContext(name, link, viewer, prefetched, read = {}) {
|
|
|
13373
12154
|
viewer,
|
|
13374
12155
|
viewerEgress: createPluginEgress({
|
|
13375
12156
|
credentialContext: credentialContextForActor(webActorFromUser(viewer)),
|
|
12157
|
+
fetch: cardReadFetch(read.signal),
|
|
13376
12158
|
httpCache,
|
|
13377
12159
|
pluginAuth: { async handleAuthRequired() {} },
|
|
13378
12160
|
userOAuthOnly: true
|
|
13379
12161
|
}),
|
|
13380
|
-
viewerMcp: createViewerMcp(name, viewer.id),
|
|
12162
|
+
viewerMcp: createViewerMcp(name, viewer.id, read.signal),
|
|
13381
12163
|
replaceSubjectId: (subject) => replaceAnnotationSubjectId(getDb(), {
|
|
13382
12164
|
...subject,
|
|
13383
12165
|
plugin: name
|
|
13384
|
-
})
|
|
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
|
|
13385
12173
|
};
|
|
13386
12174
|
}
|
|
13387
12175
|
function pluginLinkTypes(plugin) {
|
|
13388
12176
|
const name = plugin.manifest.name;
|
|
13389
12177
|
return (plugin.objectLinks ?? []).map((link) => ({
|
|
13390
12178
|
...link.cacheCards ? { cacheCards: true } : void 0,
|
|
12179
|
+
...link.cacheOnlyReads ? { cacheOnlyReads: true } : void 0,
|
|
13391
12180
|
canView: (viewer, url, prefetched, read) => link.canView(objectLinkContext(name, link, viewer, prefetched, read), url),
|
|
13392
12181
|
filters: link.filters,
|
|
13393
12182
|
...link.label ? { label: link.label } : void 0,
|
|
@@ -13420,9 +12209,8 @@ function readLinkObjectType(url, linkTypes = readObjectLinkTypes()) {
|
|
|
13420
12209
|
const objectTypes = findObjectLinkType(linkTypes, new URL(url))?.objectTypes;
|
|
13421
12210
|
return objectTypes?.length === 1 ? objectTypes[0] : void 0;
|
|
13422
12211
|
}
|
|
13423
|
-
async function resolveWithLinkType(linkType, viewer, url, prefetched,
|
|
13424
|
-
|
|
13425
|
-
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;
|
|
13426
12214
|
let fetchedAtMs;
|
|
13427
12215
|
const resolved = await linkType.resolve(viewer, url, prefetched, {
|
|
13428
12216
|
...read,
|
|
@@ -13451,7 +12239,10 @@ async function resolveWithLinkType(linkType, viewer, url, prefetched, now) {
|
|
|
13451
12239
|
async function resolveObjectLinkNow(viewer, url) {
|
|
13452
12240
|
const linkType = findObjectLinkType(readObjectLinkTypes(), url);
|
|
13453
12241
|
if (!linkType) return void 0;
|
|
13454
|
-
return await resolveWithLinkType(linkType, viewer, url, void 0,
|
|
12242
|
+
return await withCardReadDeadline((signal) => resolveWithLinkType(linkType, viewer, url, void 0, {
|
|
12243
|
+
now: true,
|
|
12244
|
+
signal
|
|
12245
|
+
})) ?? void 0;
|
|
13455
12246
|
}
|
|
13456
12247
|
/**
|
|
13457
12248
|
* Return whether a link type of `plugin` claims the URL, lets the viewer
|
|
@@ -13461,8 +12252,14 @@ async function resolveObjectLinkNow(viewer, url) {
|
|
|
13461
12252
|
*/
|
|
13462
12253
|
async function viewerCanViewPluginLink(viewer, url, plugin) {
|
|
13463
12254
|
const linkType = findObjectLinkType(readObjectLinkTypes(), url);
|
|
13464
|
-
|
|
13465
|
-
return
|
|
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
|
+
});
|
|
13466
12263
|
}
|
|
13467
12264
|
async function prefetchLinks(viewer, links) {
|
|
13468
12265
|
const byType = /* @__PURE__ */ new Map();
|
|
@@ -13481,9 +12278,10 @@ async function prefetchLinks(viewer, links) {
|
|
|
13481
12278
|
/**
|
|
13482
12279
|
* Resolve links to object cards for one viewer. A link without a link type,
|
|
13483
12280
|
* without access, or with a failed read gets no card. Nothing is saved on a
|
|
13484
|
-
* Conversation.
|
|
12281
|
+
* Conversation. `cacheOnly` reads, for a page load or a poll, make
|
|
12282
|
+
* no provider call: they show only what the caches hold.
|
|
13485
12283
|
*/
|
|
13486
|
-
async function resolveObjectLinks(viewer, urls) {
|
|
12284
|
+
async function resolveObjectLinks(viewer, urls, read = {}) {
|
|
13487
12285
|
const linkTypes = readObjectLinkTypes();
|
|
13488
12286
|
const links = [...new Set(urls)].flatMap((url) => {
|
|
13489
12287
|
const parsed = URL.canParse(url) ? new URL(url) : void 0;
|
|
@@ -13494,11 +12292,22 @@ async function resolveObjectLinks(viewer, urls) {
|
|
|
13494
12292
|
url
|
|
13495
12293
|
}] : [];
|
|
13496
12294
|
});
|
|
13497
|
-
const prefetched = await prefetchLinks(viewer, links);
|
|
12295
|
+
const prefetched = read.cacheOnly ? /* @__PURE__ */ new Map() : await prefetchLinks(viewer, links);
|
|
13498
12296
|
return (await mapBounded(links, async ({ linkType, parsed, url }) => {
|
|
12297
|
+
const reads = !read.cacheOnly || linkType.cacheOnlyReads;
|
|
13499
12298
|
const key = `${viewer.id}:${createHash("sha256").update(url).digest("hex")}`;
|
|
13500
|
-
const resolve = async () => (await resolveWithLinkType(linkType, viewer, parsed, prefetched.get(linkType)?.get(parsed.href)
|
|
12299
|
+
const resolve = async () => (await withCardReadDeadline((signal) => resolveWithLinkType(linkType, viewer, parsed, prefetched.get(linkType)?.get(parsed.href), {
|
|
12300
|
+
...read,
|
|
12301
|
+
signal
|
|
12302
|
+
})))?.object ?? null;
|
|
13501
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
|
+
}
|
|
13502
12311
|
if (!linkType.cacheCards) {
|
|
13503
12312
|
const object = await resolve();
|
|
13504
12313
|
return object ? [{
|
|
@@ -13545,9 +12354,10 @@ function ownerLinkLabel(plugin, url, linkTypes = readObjectLinkTypes()) {
|
|
|
13545
12354
|
* Read the link and live card of each source for one viewer, in source
|
|
13546
12355
|
* order, in one call for the page. The link is the subject link, else the
|
|
13547
12356
|
* stored one. A source with no link or link type gets nothing. A viewer who
|
|
13548
|
-
* 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.
|
|
13549
12359
|
*/
|
|
13550
|
-
async function resolveObjectCards(viewer, sources) {
|
|
12360
|
+
async function resolveObjectCards(viewer, sources, mode = {}) {
|
|
13551
12361
|
const subjects = sources.flatMap(({ subject }) => subject ? [{ subject }] : []);
|
|
13552
12362
|
const links = subjects.length > 0 ? await readSubjectLinks(getDb(), subjects) : /* @__PURE__ */ new Map();
|
|
13553
12363
|
const linkTypes = readObjectLinkTypes();
|
|
@@ -13563,7 +12373,7 @@ async function resolveObjectCards(viewer, sources) {
|
|
|
13563
12373
|
return url;
|
|
13564
12374
|
});
|
|
13565
12375
|
const read = [...new Set(urls.filter((url) => url !== void 0))];
|
|
13566
|
-
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]) : []);
|
|
13567
12377
|
return urls.map((url, index) => {
|
|
13568
12378
|
if (!url) return void 0;
|
|
13569
12379
|
const object = cards.get(url);
|
|
@@ -13639,9 +12449,10 @@ function liveAnnotation(annotation, view, fallback) {
|
|
|
13639
12449
|
/**
|
|
13640
12450
|
* Return the Annotations with the live card of each object for one viewer,
|
|
13641
12451
|
* in the same order. Reads every Annotation in one call, so pass a whole
|
|
13642
|
-
* 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.
|
|
13643
12454
|
*/
|
|
13644
|
-
async function readLiveAnnotations(viewer, annotations, fallback = "label") {
|
|
12455
|
+
async function readLiveAnnotations(viewer, annotations, fallback = "label", mode = {}) {
|
|
13645
12456
|
const views = await resolveObjectCards(viewer, annotations.map((annotation) => {
|
|
13646
12457
|
if (!annotation.objectType) return {};
|
|
13647
12458
|
const subject = annotationSubject(annotation.plugin, annotation);
|
|
@@ -13653,16 +12464,17 @@ async function readLiveAnnotations(viewer, annotations, fallback = "label") {
|
|
|
13653
12464
|
...subject ? { subject } : void 0,
|
|
13654
12465
|
url: annotation.url
|
|
13655
12466
|
};
|
|
13656
|
-
}));
|
|
12467
|
+
}), mode);
|
|
13657
12468
|
return annotations.map((annotation, index) => liveAnnotation(annotation, views[index], fallback));
|
|
13658
12469
|
}
|
|
13659
12470
|
/**
|
|
13660
|
-
* Return the
|
|
13661
|
-
* does
|
|
12471
|
+
* Return the Annotations of each Conversation for a page load, as
|
|
12472
|
+
* `readLiveAnnotations` does with `cacheOnly`, with one read for every
|
|
12473
|
+
* Conversation.
|
|
13662
12474
|
*/
|
|
13663
12475
|
async function readLiveAnnotationsById(viewer, byConversation) {
|
|
13664
12476
|
const entries = [...byConversation];
|
|
13665
|
-
const live = await readLiveAnnotations(viewer, entries.flatMap(([, annotations]) => annotations));
|
|
12477
|
+
const live = await readLiveAnnotations(viewer, entries.flatMap(([, annotations]) => annotations), "title", { cacheOnly: true });
|
|
13666
12478
|
let offset = 0;
|
|
13667
12479
|
return new Map(entries.map(([conversationId, annotations]) => {
|
|
13668
12480
|
const slice = live.slice(offset, offset + annotations.length);
|
|
@@ -20842,13 +19654,11 @@ async function runConversation(context, workers) {
|
|
|
20842
19654
|
if (dispatchId) return await workers.runDispatch(context, dispatchId);
|
|
20843
19655
|
}
|
|
20844
19656
|
const destination = context.destination;
|
|
20845
|
-
|
|
20846
|
-
|
|
20847
|
-
|
|
20848
|
-
|
|
20849
|
-
|
|
20850
|
-
if (!runDestination) throw new Error(`Conversation ${context.conversationId} has a ${destination.platform} destination but no matching conversation worker`);
|
|
20851
|
-
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" };
|
|
20852
19662
|
}
|
|
20853
19663
|
// src/chat/providers/slack/system-turn.ts
|
|
20854
19664
|
/**
|
|
@@ -21762,193 +20572,6 @@ function contentPartText(part) {
|
|
|
21762
20572
|
default: return "";
|
|
21763
20573
|
}
|
|
21764
20574
|
}
|
|
21765
|
-
// src/chat/inbox-items/messages.ts
|
|
21766
|
-
/**
|
|
21767
|
-
* Return the record that a message about a person change carries. A reply or
|
|
21768
|
-
* an agent close is not a person change, so it has no record.
|
|
21769
|
-
*/
|
|
21770
|
-
function inboxItemChangeRecord(item, change) {
|
|
21771
|
-
return "user" in change ? {
|
|
21772
|
-
kind: change.kind,
|
|
21773
|
-
reviewItemId: item.id
|
|
21774
|
-
} : void 0;
|
|
21775
|
-
}
|
|
21776
|
-
function personName(user) {
|
|
21777
|
-
return user.displayName ? `${user.displayName} (${user.email})` : user.email;
|
|
21778
|
-
}
|
|
21779
|
-
/**
|
|
21780
|
-
* Write the message that tells a linked Conversation about a change. It has
|
|
21781
|
-
* the item title, what happened, who did it, and the question or answer, so
|
|
21782
|
-
* the agent has context even when the Conversation moved on.
|
|
21783
|
-
*/
|
|
21784
|
-
function renderInboxItemMessage(item, change) {
|
|
21785
|
-
const label = `inbox item "${item.title}" (${item.id})`;
|
|
21786
|
-
const request = inboxItemQuestion(item.request);
|
|
21787
|
-
const question = request ? [`Question: ${request.question}`] : [];
|
|
21788
|
-
switch (change.kind) {
|
|
21789
|
-
case "submitted": return [
|
|
21790
|
-
`${personName(change.user)} answered ${label}. The item is done.`,
|
|
21791
|
-
"",
|
|
21792
|
-
request && item.answer ? formatUserInputAnswer(request, item.answer) : "(no answer)"
|
|
21793
|
-
].join("\n");
|
|
21794
|
-
case "dismissed": return [`${personName(change.user)} dismissed ${label}.`, ...question].join("\n");
|
|
21795
|
-
case "taken": return [`${personName(change.user)} took ${label}. They are now its only assignee.`, ...question].join("\n");
|
|
21796
|
-
case "replied": return [
|
|
21797
|
-
`[inbox item]`,
|
|
21798
|
-
"",
|
|
21799
|
-
`${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.`,
|
|
21800
|
-
...question
|
|
21801
|
-
].join("\n");
|
|
21802
|
-
case "closed": return [
|
|
21803
|
-
`[inbox item]`,
|
|
21804
|
-
"",
|
|
21805
|
-
`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.`,
|
|
21806
|
-
`Reason: ${change.reason}`,
|
|
21807
|
-
...question
|
|
21808
|
-
].join("\n");
|
|
21809
|
-
}
|
|
21810
|
-
}
|
|
21811
|
-
async function openConversationIds(conversationIds) {
|
|
21812
|
-
if (conversationIds.length === 0) return [];
|
|
21813
|
-
return (await getDb().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), isNull(juniorConversations.transcriptPurgedAt)))).map((row) => row.conversationId).sort();
|
|
21814
|
-
}
|
|
21815
|
-
function recordedChange(item, change) {
|
|
21816
|
-
if (change.kind === "taken" || change.kind === "dismissed") return change;
|
|
21817
|
-
return change.kind === "submitted" && isPluginInboxItem(item) ? change : void 0;
|
|
21818
|
-
}
|
|
21819
|
-
function recordedMessageId(item, change) {
|
|
21820
|
-
return change.kind === "taken" ? `inbox-item:${item.id}:taken:${change.user.id}:${item.updatedAt.getTime()}` : `inbox-item:${item.id}:closed`;
|
|
21821
|
-
}
|
|
21822
|
-
/**
|
|
21823
|
-
* Save a take, a dismiss, or the answer to a plugin item as a handled
|
|
21824
|
-
* Message in one Conversation. None starts a Turn or reaches the model as a
|
|
21825
|
-
* Message: a take or a dismiss is not a decision, and the plugin does the
|
|
21826
|
-
* work of its answer. The dashboard shows the Message from its record. A
|
|
21827
|
-
* dismiss also adds a Conversation note, so the next Turn knows the item
|
|
21828
|
-
* closed. Without it, the agent only has its own `addInboxItem` result and
|
|
21829
|
-
* still treats the item as open. A retry is safe, because the Message id and
|
|
21830
|
-
* the note key are the change key.
|
|
21831
|
-
*/
|
|
21832
|
-
async function recordInboxItemChange(args) {
|
|
21833
|
-
const { change } = args;
|
|
21834
|
-
const messageId = recordedMessageId(args.item, change);
|
|
21835
|
-
if (change.kind === "dismissed") await addConversationNote({
|
|
21836
|
-
conversationId: args.conversationId,
|
|
21837
|
-
createdAtMs: args.nowMs,
|
|
21838
|
-
key: messageId,
|
|
21839
|
-
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.`
|
|
21840
|
-
});
|
|
21841
|
-
const authorIdentityId = await resolveActorIdentityId(getSqlExecutor(), webActorFromUser(change.user), args.nowMs);
|
|
21842
|
-
await getConversationEventStore().append(args.conversationId, [{
|
|
21843
|
-
idempotencyKey: `message:${messageId}`,
|
|
21844
|
-
createdAtMs: args.nowMs,
|
|
21845
|
-
data: {
|
|
21846
|
-
type: "message",
|
|
21847
|
-
messageId,
|
|
21848
|
-
role: "user",
|
|
21849
|
-
...authorIdentityId ? { authorIdentityId } : void 0,
|
|
21850
|
-
text: renderInboxItemMessage(args.item, change),
|
|
21851
|
-
meta: {
|
|
21852
|
-
author: {
|
|
21853
|
-
email: change.user.email,
|
|
21854
|
-
...change.user.displayName ? { fullName: change.user.displayName } : void 0
|
|
21855
|
-
},
|
|
21856
|
-
replied: false,
|
|
21857
|
-
reviewItemChanges: [inboxItemChangeRecord(args.item, change)]
|
|
21858
|
-
}
|
|
21859
|
-
}
|
|
21860
|
-
}, {
|
|
21861
|
-
idempotencyKey: `message:${messageId}:handled`,
|
|
21862
|
-
createdAtMs: args.nowMs,
|
|
21863
|
-
data: {
|
|
21864
|
-
type: "message_handled",
|
|
21865
|
-
messageId
|
|
21866
|
-
}
|
|
21867
|
-
}]);
|
|
21868
|
-
}
|
|
21869
|
-
async function sendOne(args) {
|
|
21870
|
-
const recorded = recordedChange(args.item, args.change);
|
|
21871
|
-
if (recorded) {
|
|
21872
|
-
await recordInboxItemChange({
|
|
21873
|
-
change: recorded,
|
|
21874
|
-
conversationId: args.conversationId,
|
|
21875
|
-
item: args.item,
|
|
21876
|
-
nowMs: args.nowMs
|
|
21877
|
-
});
|
|
21878
|
-
return;
|
|
21879
|
-
}
|
|
21880
|
-
const key = `inbox-item:${args.item.id}:closed`;
|
|
21881
|
-
const record = inboxItemChangeRecord(args.item, args.change);
|
|
21882
|
-
if ("user" in args.change) {
|
|
21883
|
-
const conversation = await getConversationStore().get({ conversationId: args.conversationId });
|
|
21884
|
-
if (conversation && acceptsWebMessages(conversation)) {
|
|
21885
|
-
await appendAndEnqueueWebMessage({
|
|
21886
|
-
actor: webActorFromUser(args.change.user),
|
|
21887
|
-
conversationId: args.conversationId,
|
|
21888
|
-
idempotencyKey: key,
|
|
21889
|
-
message: args.text,
|
|
21890
|
-
reviewItemChange: record
|
|
21891
|
-
}, {
|
|
21892
|
-
nowMs: args.nowMs,
|
|
21893
|
-
queue: args.queue
|
|
21894
|
-
});
|
|
21895
|
-
return;
|
|
21896
|
-
}
|
|
21897
|
-
}
|
|
21898
|
-
const metadata = {
|
|
21899
|
-
kind: "event",
|
|
21900
|
-
event: {
|
|
21901
|
-
eventKey: key,
|
|
21902
|
-
eventType: `inbox_item.${args.change.kind}`,
|
|
21903
|
-
identifier: args.item.id,
|
|
21904
|
-
namespace: "junior",
|
|
21905
|
-
trustedSummary: `Inbox item "${args.item.title}" changed: ${args.change.kind}.`
|
|
21906
|
-
}
|
|
21907
|
-
};
|
|
21908
|
-
await appendAndEnqueueInboundMessage({
|
|
21909
|
-
message: {
|
|
21910
|
-
conversationId: args.conversationId,
|
|
21911
|
-
createdAtMs: args.nowMs,
|
|
21912
|
-
delivery: "defer",
|
|
21913
|
-
inboundMessageId: `${key}:${args.conversationId}`,
|
|
21914
|
-
input: {
|
|
21915
|
-
authorId: EVENT_AUTHOR_ID,
|
|
21916
|
-
authorIdentityId: SYSTEM_IDENTITY_ID,
|
|
21917
|
-
metadata,
|
|
21918
|
-
...record ? { reviewItemChange: record } : void 0,
|
|
21919
|
-
text: args.text
|
|
21920
|
-
},
|
|
21921
|
-
receivedAtMs: args.nowMs,
|
|
21922
|
-
source: "event"
|
|
21923
|
-
},
|
|
21924
|
-
queue: args.queue,
|
|
21925
|
-
queueDelayMs: EVENT_WAIT_MS
|
|
21926
|
-
});
|
|
21927
|
-
}
|
|
21928
|
-
/**
|
|
21929
|
-
* Send one change to every open linked Conversation, except the
|
|
21930
|
-
* Conversation that made the change. A Conversation is open until Junior
|
|
21931
|
-
* purges its transcript; archive is only a per-viewer list state. Each
|
|
21932
|
-
* message starts a new Turn, except a take or a dismiss, which is only
|
|
21933
|
-
* recorded. Repeat calls for the same change are safe.
|
|
21934
|
-
*/
|
|
21935
|
-
async function sendInboxItemMessages(args) {
|
|
21936
|
-
const conversationIds = (await openConversationIds(args.item.conversationIds)).filter((id) => id !== args.exceptConversationId);
|
|
21937
|
-
const text = renderInboxItemMessage(args.item, args.change);
|
|
21938
|
-
const limit = pLimit(8);
|
|
21939
|
-
const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(() => sendOne({
|
|
21940
|
-
...args,
|
|
21941
|
-
conversationId,
|
|
21942
|
-
text
|
|
21943
|
-
}))));
|
|
21944
|
-
for (const [index, result] of results.entries()) if (result.status === "rejected") logWarn("inbox_item.message.failed", {
|
|
21945
|
-
"app.inbox_item.id": args.item.id,
|
|
21946
|
-
"app.inbox_item.change": args.change.kind,
|
|
21947
|
-
"gen_ai.conversation.id": conversationIds[index]
|
|
21948
|
-
});
|
|
21949
|
-
const failed = results.find((result) => result.status === "rejected");
|
|
21950
|
-
if (failed) throw failed.reason;
|
|
21951
|
-
}
|
|
21952
20575
|
// src/chat/inbox-items/changes.ts
|
|
21953
20576
|
/**
|
|
21954
20577
|
* Deliver one saved Inbox item change. Every surface shows the new state.
|
|
@@ -21998,9 +20621,7 @@ const updateInboxItemToolDefinition = zodToolDefinition({
|
|
|
21998
20621
|
},
|
|
21999
20622
|
inputSchema: z.object({
|
|
22000
20623
|
id: z.string().trim().min(1),
|
|
22001
|
-
|
|
22002
|
-
body: bodySchema.nullable().optional(),
|
|
22003
|
-
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."),
|
|
22004
20625
|
assignees: assigneesSchema.nullable().optional().describe("Replaces every assignee."),
|
|
22005
20626
|
conversation_ids: conversationIdsSchema.nullable().optional().describe("Replaces every other linked Conversation. The Conversation that added the item stays linked."),
|
|
22006
20627
|
status: z.enum(["done", "dismissed"]).nullable().optional().describe("Close the item, for example when its pull request merged."),
|
|
@@ -22019,18 +20640,23 @@ function createUpdateInboxItemTool(context, services) {
|
|
|
22019
20640
|
const db = getDb();
|
|
22020
20641
|
const scope = await readInboxItemAgentScope(context);
|
|
22021
20642
|
const item = await readableItem(input.id, scope);
|
|
22022
|
-
const changesContent = input.
|
|
20643
|
+
const changesContent = input.questions || input.assignees || input.conversation_ids;
|
|
22023
20644
|
const retriesClose = item.status !== "open" && !changesContent && !item.closedBy && input.status === item.status && input.reason === item.closeReason;
|
|
22024
20645
|
const closesOnly = !changesContent && input.status && input.reason;
|
|
22025
|
-
if (item.status !== "open" && !retriesClose && !closesOnly) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up,
|
|
20646
|
+
if (item.status !== "open" && !retriesClose && !closesOnly) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, ask again with askUserQuestion.`);
|
|
22026
20647
|
if (isPluginInboxItem(item)) throw new ToolInputError("A plugin added this item. Only the plugin or a person can change it.");
|
|
22027
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.");
|
|
22028
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.");
|
|
22029
20650
|
if (item.status !== "open" && !retriesClose) return alreadyClosedResult(item);
|
|
22030
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.");
|
|
22031
20653
|
if (changesContent) {
|
|
22032
|
-
const
|
|
22033
|
-
const
|
|
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;
|
|
22034
20660
|
const conversationIds = [.../* @__PURE__ */ new Set([...ownerLinks(item), ...input.conversation_ids ?? item.conversationIds])];
|
|
22035
20661
|
const visibility = item.visibility;
|
|
22036
20662
|
await requireInboxItemLinks({
|
|
@@ -22039,7 +20665,7 @@ function createUpdateInboxItemTool(context, services) {
|
|
|
22039
20665
|
...ownerLinks(item),
|
|
22040
20666
|
...item.conversationIds
|
|
22041
20667
|
]),
|
|
22042
|
-
conversationIds
|
|
20668
|
+
conversationIds,
|
|
22043
20669
|
scope,
|
|
22044
20670
|
tenant: item.tenant,
|
|
22045
20671
|
visibility
|
|
@@ -22058,15 +20684,15 @@ function createUpdateInboxItemTool(context, services) {
|
|
|
22058
20684
|
if (!await updateInboxItemContent(db, {
|
|
22059
20685
|
assignedToEveryone: assignees.everyone,
|
|
22060
20686
|
assigneeUserIds: assignees.userIds,
|
|
22061
|
-
body:
|
|
20687
|
+
body: asked?.body ?? item.body,
|
|
22062
20688
|
conversationIds,
|
|
22063
20689
|
id: item.id,
|
|
22064
20690
|
kind: item.kind,
|
|
22065
20691
|
nowMs: Date.now(),
|
|
22066
|
-
title:
|
|
20692
|
+
title: asked?.title ?? item.title,
|
|
22067
20693
|
subject: item.subject,
|
|
22068
20694
|
...request ? { request } : void 0
|
|
22069
|
-
})) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up,
|
|
20695
|
+
})) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, ask again with askUserQuestion.`);
|
|
22070
20696
|
}
|
|
22071
20697
|
if (input.status && input.reason) {
|
|
22072
20698
|
const nowMs = Date.now();
|
|
@@ -22076,7 +20702,7 @@ function createUpdateInboxItemTool(context, services) {
|
|
|
22076
20702
|
reason: input.reason,
|
|
22077
20703
|
status: input.status
|
|
22078
20704
|
}))) {
|
|
22079
|
-
if (changesContent) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up,
|
|
20705
|
+
if (changesContent) throw new ToolInputError(`Inbox item ${item.id} is already closed. To follow up, ask again with askUserQuestion.`);
|
|
22080
20706
|
return alreadyClosedResult(await readableItem(item.id, scope));
|
|
22081
20707
|
}
|
|
22082
20708
|
const closedItem = await readableItem(item.id, scope);
|
|
@@ -22102,14 +20728,13 @@ function createUpdateInboxItemTool(context, services) {
|
|
|
22102
20728
|
}
|
|
22103
20729
|
});
|
|
22104
20730
|
}
|
|
22105
|
-
// src/chat/inbox-items/tools/
|
|
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.`;
|
|
22106
20733
|
/**
|
|
22107
|
-
* Pick the assignees
|
|
22108
|
-
*
|
|
22109
|
-
*
|
|
22110
|
-
*
|
|
22111
|
-
* without a Junior User gets an item with no assignees, so that the agent can
|
|
22112
|
-
* 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.
|
|
22113
20738
|
*/
|
|
22114
20739
|
async function defaultAssignees(scope, conversationId) {
|
|
22115
20740
|
const userId = scope.user?.id ?? (scope.reader.automationId ? await automationCreatorUserId(getDb(), scope.reader.automationId) : void 0);
|
|
@@ -22126,8 +20751,8 @@ async function defaultAssignees(scope, conversationId) {
|
|
|
22126
20751
|
userIds: (await activeParticipantUserIds(getDb(), conversationId)).filter((id) => id !== scope.appUserId)
|
|
22127
20752
|
};
|
|
22128
20753
|
}
|
|
22129
|
-
const
|
|
22130
|
-
description:
|
|
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.",
|
|
22131
20756
|
annotations: {
|
|
22132
20757
|
destructiveHint: false,
|
|
22133
20758
|
idempotentHint: true,
|
|
@@ -22135,53 +20760,47 @@ const addInboxItemToolDefinition = zodToolDefinition({
|
|
|
22135
20760
|
readOnlyHint: false
|
|
22136
20761
|
},
|
|
22137
20762
|
inputSchema: z.object({
|
|
22138
|
-
|
|
22139
|
-
|
|
22140
|
-
body: bodySchema,
|
|
22141
|
-
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."),
|
|
22142
|
-
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."),
|
|
22143
|
-
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.")
|
|
22144
20765
|
}).strict(),
|
|
22145
20766
|
outputSchema: juniorToolOutputSchema
|
|
22146
20767
|
});
|
|
22147
|
-
/** Create the tool that
|
|
22148
|
-
function
|
|
20768
|
+
/** Create the tool that asks a person questions in a new Inbox item. */
|
|
20769
|
+
function createAskUserQuestionTool(context, services) {
|
|
22149
20770
|
return zodTool({
|
|
22150
|
-
...
|
|
20771
|
+
...askUserQuestionToolDefinition,
|
|
22151
20772
|
execute: async (input, options) => {
|
|
22152
|
-
const
|
|
22153
|
-
const related = relatedInput(input.request?.related);
|
|
20773
|
+
const content = questionContent(input.questions);
|
|
22154
20774
|
const db = getDb();
|
|
22155
20775
|
const scope = await readInboxItemAgentScope(context);
|
|
22156
|
-
const subject = questionSubject(
|
|
20776
|
+
const subject = questionSubject(options.toolCallId ? askQuestionId(context.conversationId, options.toolCallId) : `question:${randomUUID()}`);
|
|
22157
20777
|
const visibility = scope.inPrivateConversation ? "private" : "public";
|
|
22158
|
-
const conversationIds = [
|
|
20778
|
+
const conversationIds = [context.conversationId];
|
|
22159
20779
|
await requireInboxItemLinks({
|
|
22160
|
-
allowedIds:
|
|
22161
|
-
conversationIds
|
|
20780
|
+
allowedIds: new Set(conversationIds),
|
|
20781
|
+
conversationIds,
|
|
22162
20782
|
scope,
|
|
22163
20783
|
tenant: scope.tenant,
|
|
22164
20784
|
visibility
|
|
22165
20785
|
});
|
|
22166
20786
|
const assignees = input.assignees ? await resolveAssignees(db, input.assignees, scope.tenant, services.findMentionedUserId) : await defaultAssignees(scope, context.conversationId);
|
|
22167
|
-
if (!assignees.everyone && assignees.userIds.length === 0 && !scope.actorIsPerson) throw new ToolInputError("Only people
|
|
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.");
|
|
22168
20788
|
await requireInboxItemAssignees({
|
|
22169
20789
|
assignees,
|
|
22170
20790
|
automationId: scope.reader.automationId,
|
|
22171
|
-
conversationIds
|
|
20791
|
+
conversationIds,
|
|
22172
20792
|
scope,
|
|
22173
20793
|
visibility
|
|
22174
20794
|
});
|
|
22175
|
-
const request = requestInput(question, related);
|
|
22176
20795
|
const item = await insertInboxItem(db, {
|
|
22177
20796
|
assignedToEveryone: assignees.everyone,
|
|
22178
20797
|
assigneeUserIds: assignees.userIds,
|
|
22179
|
-
body:
|
|
20798
|
+
body: content.body,
|
|
22180
20799
|
conversationIds,
|
|
22181
|
-
kind:
|
|
20800
|
+
kind: "action",
|
|
22182
20801
|
subject,
|
|
22183
|
-
title:
|
|
22184
|
-
|
|
20802
|
+
title: content.title,
|
|
20803
|
+
request: content.request,
|
|
22185
20804
|
owner: {
|
|
22186
20805
|
id: context.conversationId,
|
|
22187
20806
|
kind: "conversation"
|
|
@@ -22189,23 +20808,25 @@ function createAddInboxItemTool(context, services) {
|
|
|
22189
20808
|
...context.turnId ? { addedByTurnId: context.turnId } : void 0,
|
|
22190
20809
|
nowMs: Date.now()
|
|
22191
20810
|
}) ?? await getOpenInboxItemBySubject(db, subject);
|
|
22192
|
-
if (!item) throw new ToolInputError("This tool call already
|
|
20811
|
+
if (!item) throw new ToolInputError("This tool call already asked its question. To change it, update its Inbox item by its id.");
|
|
22193
20812
|
await deliverInboxItemChange({
|
|
22194
20813
|
delivery: inboxItemDelivery(services),
|
|
22195
20814
|
item,
|
|
22196
20815
|
nowMs: Date.now()
|
|
22197
20816
|
});
|
|
22198
20817
|
await publishWaiting(services, context.conversationId, item);
|
|
22199
|
-
return {
|
|
20818
|
+
return {
|
|
20819
|
+
item: itemResult(item),
|
|
20820
|
+
next_step: ASKED_NEXT_STEP
|
|
20821
|
+
};
|
|
22200
20822
|
}
|
|
22201
20823
|
});
|
|
22202
20824
|
}
|
|
22203
20825
|
/**
|
|
22204
|
-
* Report that the Conversation that asked waits on a person
|
|
22205
|
-
* is
|
|
20826
|
+
* Report that the Conversation that asked waits on a person. The Event key
|
|
20827
|
+
* is the item, so it reports each item once.
|
|
22206
20828
|
*/
|
|
22207
20829
|
async function publishWaiting(services, conversationId, item) {
|
|
22208
|
-
if (item.kind !== "action") return;
|
|
22209
20830
|
await publishAgentUpdate(conversationId, {
|
|
22210
20831
|
type: "waiting",
|
|
22211
20832
|
inboxItemId: item.id
|
|
@@ -22213,7 +20834,7 @@ async function publishWaiting(services, conversationId, item) {
|
|
|
22213
20834
|
queue: services.queue(),
|
|
22214
20835
|
update: async () => ({
|
|
22215
20836
|
status: "waiting",
|
|
22216
|
-
text:
|
|
20837
|
+
text: item.body
|
|
22217
20838
|
})
|
|
22218
20839
|
});
|
|
22219
20840
|
}
|
|
@@ -22854,6 +21475,15 @@ const startAgentOutputSchema = juniorToolOutputSchema.extend({
|
|
|
22854
21475
|
conversation_id: z.string().min(1).describe("Conversation ID of the new agent. Pass it to messageAgent, stopAgent, or archiveAgent."),
|
|
22855
21476
|
url: z.string().url().optional().describe("Link to the conversation. People can message it there.")
|
|
22856
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();
|
|
22857
21487
|
/** Static definition of `startAgent`. */
|
|
22858
21488
|
const startAgentToolDefinition = zodToolDefinition({
|
|
22859
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).",
|
|
@@ -22865,15 +21495,7 @@ const startAgentToolDefinition = zodToolDefinition({
|
|
|
22865
21495
|
openWorldHint: false,
|
|
22866
21496
|
readOnlyHint: false
|
|
22867
21497
|
},
|
|
22868
|
-
inputSchema:
|
|
22869
|
-
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."),
|
|
22870
|
-
title: z.string().trim().min(1).max(60).nullable().optional().describe("Short display title. Omit it to generate one from the task."),
|
|
22871
|
-
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."),
|
|
22872
|
-
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."),
|
|
22873
|
-
agent_type: z.enum(AGENT_TYPES).nullable().optional().describe(`Child agent type. ${formatAgentTypes()} Omit it for a general child.`),
|
|
22874
|
-
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."),
|
|
22875
|
-
reasoning_level: z.enum(TURN_REASONING_LEVELS).nullable().optional().describe("Reasoning level of the child. Omit it to use the default.")
|
|
22876
|
-
}).strict(),
|
|
21498
|
+
inputSchema: childInputSchema,
|
|
22877
21499
|
outputSchema: startAgentOutputSchema
|
|
22878
21500
|
});
|
|
22879
21501
|
/** Create the `startAgent` tool that starts child agents of one Turn. */
|
|
@@ -23601,6 +22223,15 @@ function createStopWatchingResourcesTool(context) {
|
|
|
23601
22223
|
}
|
|
23602
22224
|
});
|
|
23603
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
|
+
});
|
|
23604
22235
|
const systemTimeToolDefinition = zodToolDefinition({
|
|
23605
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.",
|
|
23606
22237
|
annotations: {
|
|
@@ -23609,14 +22240,8 @@ const systemTimeToolDefinition = zodToolDefinition({
|
|
|
23609
22240
|
openWorldHint: false,
|
|
23610
22241
|
readOnlyHint: true
|
|
23611
22242
|
},
|
|
23612
|
-
inputSchema:
|
|
23613
|
-
outputSchema:
|
|
23614
|
-
unix_ms: z.number().describe("Current time in epoch milliseconds, for millisecond inputs."),
|
|
23615
|
-
iso_utc: z.string(),
|
|
23616
|
-
iso_local: z.string(),
|
|
23617
|
-
timezone: z.string().nullable(),
|
|
23618
|
-
timezone_offset_minutes: z.number()
|
|
23619
|
-
}),
|
|
22243
|
+
inputSchema: systemTimeInputSchema,
|
|
22244
|
+
outputSchema: systemTimeOutputSchema,
|
|
23620
22245
|
privateTraceResult: (result) => ({
|
|
23621
22246
|
unix_ms: result.unix_ms,
|
|
23622
22247
|
iso_utc: result.iso_utc,
|
|
@@ -23672,6 +22297,9 @@ function getTimeZoneOffsetMinutes(timestampMs, timezone) {
|
|
|
23672
22297
|
const asUtcMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
23673
22298
|
return Math.round((timestampMs - asUtcMs) / 6e4);
|
|
23674
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.") });
|
|
23675
22303
|
const submitFeedbackToolDefinition = zodToolDefinition({
|
|
23676
22304
|
annotations: {
|
|
23677
22305
|
destructiveHint: false,
|
|
@@ -23680,8 +22308,8 @@ const submitFeedbackToolDefinition = zodToolDefinition({
|
|
|
23680
22308
|
readOnlyHint: false
|
|
23681
22309
|
},
|
|
23682
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.",
|
|
23683
|
-
inputSchema:
|
|
23684
|
-
outputSchema:
|
|
22311
|
+
inputSchema: submitFeedbackInputSchema,
|
|
22312
|
+
outputSchema: submitFeedbackOutputSchema
|
|
23685
22313
|
});
|
|
23686
22314
|
/**
|
|
23687
22315
|
* Send the agent's report of a tool or runtime problem to the maintainers as
|
|
@@ -25879,7 +24507,7 @@ const CORE_TOOLS = {
|
|
|
25879
24507
|
definition: () => slackChannelListMessagesToolDefinition
|
|
25880
24508
|
},
|
|
25881
24509
|
addReaction: RUN_BUILT,
|
|
25882
|
-
|
|
24510
|
+
askUserQuestion: always(askUserQuestionToolDefinition),
|
|
25883
24511
|
searchInboxItems: always(searchInboxItemsToolDefinition),
|
|
25884
24512
|
updateInboxItem: always(updateInboxItemToolDefinition)
|
|
25885
24513
|
};
|
|
@@ -25940,7 +24568,7 @@ function staticToolDefinitions(key) {
|
|
|
25940
24568
|
* leaves out MCP providers that are connected or active and their tool
|
|
25941
24569
|
* schemas: they differ per person, and providers change them, not deploys.
|
|
25942
24570
|
*/
|
|
25943
|
-
const RECORD_TTL_MS = 10080 * MINUTE_MS
|
|
24571
|
+
const RECORD_TTL_MS = 10080 * MINUTE_MS;
|
|
25944
24572
|
const firstSeenKey = (deploymentId) => `${KEY_PREFIX}:defs:first_seen:${deploymentId}`;
|
|
25945
24573
|
const fingerprintKey = (key) => `${KEY_PREFIX}:defs:fingerprint:${key.platform}:${key.mode}`;
|
|
25946
24574
|
function configuredMcpProviders() {
|
|
@@ -27545,11 +26173,10 @@ function earliestTimerDueIdleMs(watches, sinceMs, maxDueIdleMs) {
|
|
|
27545
26173
|
const dueIdleMs = Math.min(...watches.map((watch) => watch.firesAtMs ?? 1e400)) - sinceMs;
|
|
27546
26174
|
return dueIdleMs <= maxDueIdleMs ? dueIdleMs : void 0;
|
|
27547
26175
|
}
|
|
27548
|
-
const ADD_INBOX_ITEM_TOOL_NAMES = /* @__PURE__ */ new Set(["addInboxItem", "addReviewItem"]);
|
|
27549
26176
|
function askedInboxItem(messages, final) {
|
|
27550
26177
|
for (const message of [final, ...[...messages].reverse()]) {
|
|
27551
26178
|
if (message.role === "user") return false;
|
|
27552
|
-
if (message.role === "assistant" && message.content.some((part) => part.type === "toolCall" &&
|
|
26179
|
+
if (message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && ASK_TOOL_NAMES.has(part.name))) return true;
|
|
27553
26180
|
}
|
|
27554
26181
|
return false;
|
|
27555
26182
|
}
|
|
@@ -27726,10 +26353,10 @@ var warmup_exports = /* @__PURE__ */ __exportAll({ runCacheWarmup: () => runCach
|
|
|
27726
26353
|
/** Gaps kept in each segment list. */
|
|
27727
26354
|
const GLOBAL_GAPS_MAX = 2e3;
|
|
27728
26355
|
/** A segment list expires this long after its last gap. */
|
|
27729
|
-
const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS
|
|
26356
|
+
const GLOBAL_GAPS_TTL_MS = 43200 * MINUTE_MS;
|
|
27730
26357
|
const CONVERSATION_GAPS_MAX = 50;
|
|
27731
26358
|
/** The Turn count of a Conversation resets after this long with no call. */
|
|
27732
|
-
const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS
|
|
26359
|
+
const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
|
|
27733
26360
|
/**
|
|
27734
26361
|
* Answer tools that end the run without a final response. An Automation run
|
|
27735
26362
|
* posts with `reply`. People often answer a Turn that posted nothing or that
|
|
@@ -31318,6 +29945,7 @@ function createCallMcpToolTool(mcpToolManager) {
|
|
|
31318
29945
|
...activeTool.annotations ? { annotations: activeTool.annotations } : void 0,
|
|
31319
29946
|
description: activeTool.description,
|
|
31320
29947
|
name: tool_name,
|
|
29948
|
+
...activeTool.skipReview ? { skipReview: true } : void 0,
|
|
31321
29949
|
source: {
|
|
31322
29950
|
id: activeTool.provider,
|
|
31323
29951
|
description: `MCP provider ${activeTool.provider}`
|
|
@@ -33013,7 +31641,7 @@ const STATIC_TOOL_BINDERS = {
|
|
|
33013
31641
|
slackListGetItems: () => createSlackListGetItemsTool(),
|
|
33014
31642
|
slackListUpdateItem: (run) => createSlackListUpdateItemTool(run.state),
|
|
33015
31643
|
slackChannelListMessages: (run) => createSlackChannelListMessagesTool(slackOf(run)),
|
|
33016
|
-
|
|
31644
|
+
askUserQuestion: (run) => createAskUserQuestionTool(run.context, run.inboxItemServices()),
|
|
33017
31645
|
searchInboxItems: (run) => createSearchInboxItemsTool(run.context, run.inboxItemServices()),
|
|
33018
31646
|
updateInboxItem: (run) => createUpdateInboxItemTool(run.context, run.inboxItemServices())
|
|
33019
31647
|
};
|
|
@@ -33026,7 +31654,7 @@ const TURN_TOOL_LIMITS = {
|
|
|
33026
31654
|
setConversationSubscription: (turnTools) => turnTools.subscriptions ? void 0 : "Only a person's Turn can change subscriptions.",
|
|
33027
31655
|
moveConversationToSpace: (turnTools) => turnTools.settings ? void 0 : "Only a person's request moves a conversation to a Space.",
|
|
33028
31656
|
setConfiguration: (turnTools) => turnTools.settings ? void 0 : "Only a person's request changes configuration.",
|
|
33029
|
-
|
|
31657
|
+
askUserQuestion: INBOX_LIMIT,
|
|
33030
31658
|
searchInboxItems: INBOX_LIMIT,
|
|
33031
31659
|
updateInboxItem: INBOX_LIMIT
|
|
33032
31660
|
};
|
|
@@ -37372,4 +36000,4 @@ async function executeAgentRunInPrivacyContext(run, storedConversation, conversa
|
|
|
37372
36000
|
await closeTools?.();
|
|
37373
36001
|
}
|
|
37374
36002
|
}
|
|
37375
|
-
export {
|
|
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 };
|