@sentry/junior 0.317.0 → 0.318.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{admin-CAugg87B.js → admin-UOHix_5P.js} +1 -1
  2. package/dist/{agent-runner-AjrEV6Qe.js → agent-runner-DeYymwh2.js} +183 -113
  3. package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-DH8bx7jU.js} +5 -5
  4. package/dist/api/schema.d.ts +42 -28
  5. package/dist/api/schema.js +3 -3
  6. package/dist/api.js +38 -41
  7. package/dist/{app-MoNAsVV5.d.ts → app-DKAOuaoC.d.ts} +4 -9
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +62 -91
  10. package/dist/{thread-context-CqZDKErp.js → auth-pause-state-f9hJM_zO.js} +6 -59
  11. package/dist/{catalog-runtime-DfSpJZdY.js → catalog-runtime-BfdAnztW.js} +1 -1
  12. package/dist/{channel-access-j-YAVYK4.js → channel-access-A0de5lRv.js} +1 -1
  13. package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-D3Wd7f5n.js} +6 -6
  14. package/dist/{child-message-DHjQLEd1.js → child-message-peFWLcCZ.js} +1 -5
  15. package/dist/cli/chat.js +32 -24
  16. package/dist/cli/check.js +4 -4
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -5
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/context-BKF_5zzI.js +1833 -0
  22. package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-YxwMQVeR.js} +3 -2
  23. package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-Cj7IuBtM.js} +1 -1
  24. package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-Cr_dNW1p.js} +1 -1
  25. package/dist/{conversation-turn-BUE_7xaN.js → conversation-turn-Bru4w_FD.js} +111 -18
  26. package/dist/{create-DoDIYgtZ.js → create-Btl1y1rq.js} +13 -15
  27. package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DTarZ63K.js} +17 -17
  28. package/dist/{db-BFmyYZtJ.js → db-of6e3sGt.js} +1943 -1189
  29. package/dist/{deployment-DXq9ZLU4.js → deployment-C0qXa0FD.js} +1 -1
  30. package/dist/{engine-context-CgQ7mlHt.js → engine-context-C_QL_bMQ.js} +52 -21
  31. package/dist/{html-B3VKTGbJ.js → html-9_pS9SjY.js} +6 -6
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{job-runner-A1lCkybD.js → job-runner-B2XEvpif.js} +11 -12
  34. package/dist/{lineage-Bktb0UcV.js → lineage-nh4z9iQN.js} +1 -1
  35. package/dist/{list-Bxvg5wXf.js → list-HRP3TIRl.js} +45 -37
  36. package/dist/{logging--smS7XRK.js → logging-BnOG0qz2.js} +3 -49
  37. package/dist/{mailbox-turn-uSXhUFc9.js → mailbox-turn-Byrry9o1.js} +220 -223
  38. package/dist/{parent-result-Ck1rFYRQ.js → markers-CTTtJqYn.js} +84 -52
  39. package/dist/{message-BNenhsmB.js → message-BRUuLgrY.js} +9 -10
  40. package/dist/{model-input-BReSnwHp.js → model-input-CFC62mf-.js} +2 -2
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +4 -4
  43. package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-CjnnUr4o.js} +2 -2
  44. package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-BvHFH0fV.js} +1 -1
  45. package/dist/{profile-BQ-iBDsZ.js → profile-iHw1uu32.js} +7 -7
  46. package/dist/{prompt-Dv7gkpD6.js → prompt-DEkStuxG.js} +10 -10
  47. package/dist/{registry-iXMT5Jmh.js → registry-Cl7Labpe.js} +7 -7
  48. package/dist/{reports-WKHfGTsU.js → reports-C1d9azyV.js} +2 -2
  49. package/dist/{resolve-tony4ibz.js → resolve-DC6zBuDV.js} +5 -5
  50. package/dist/{result-Bta_dlWa.js → result-DxewDuXb.js} +12 -12
  51. package/dist/{run-conversation-DL6ru7iW.js → run-conversation-Cz2ubZK-.js} +6 -5
  52. package/dist/{runner-BstDRbD9.js → runner-99YxVN_r.js} +10 -18
  53. package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
  54. package/dist/{schema-DfqrHACA.js → schema-BTojNBr5.js} +2 -2
  55. package/dist/{sender-actors-CPglLd5R.js → sender-actors-77zTQbSG.js} +7 -6
  56. package/dist/{service-account-CTV_jaNu.js → service-account-YDCPSByj.js} +3 -3
  57. package/dist/{skills-BCEU41zM.js → skills-CleC0Hze.js} +5 -4
  58. package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-BNQLC12R.js} +7 -7
  59. package/dist/{spawn-frczVPIr.js → spawn-DuZfodPa.js} +7 -10
  60. package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-Ci6Ck4gk.js} +2 -2
  61. package/dist/{task-runner-C9Yc2_ae.js → task-runner-BJ9Up3bG.js} +18 -15
  62. package/dist/{topics-SRN7IVX-.js → topics-BoCkoPJJ.js} +2 -5
  63. package/dist/{turn-membership-CENFf3kI.js → turn-membership-VT7XZh-L.js} +4 -4
  64. package/dist/{turn-wake-BhloiI2h.js → turn-wake-C7HeLHAM.js} +4 -4
  65. package/dist/{types-C4iC-IMC.js → types-DCzTAA63.js} +55 -49
  66. package/dist/{users-ByG5RCEJ.js → users-Cb9c1k9q.js} +1 -1
  67. package/dist/{validation-8gjfR91V.js → validation-BiUmWPhy.js} +1 -1
  68. package/dist/{version-BeZhWWBE.js → version-VEXiEcZu.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{worker-BqMQQNRk.js → worker-ChWYQdhm.js} +5 -5
  71. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  72. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  73. package/package.json +5 -5
  74. package/dist/config-CHQ8X251.js +0 -2422
@@ -1,4 +1,4 @@
1
- import { $s as listAdminUsersFromSql, a as getDb, ic as setUserAdminFromSql } from "./db-BFmyYZtJ.js";
1
+ import { Ks as listAdminUsersFromSql, Zs as setUserAdminFromSql, a as getDb } from "./db-of6e3sGt.js";
2
2
  import { CLI_USAGE } from "./cli/run.js";
3
3
  // src/cli/admin.ts
4
4
  /**
@@ -1,40 +1,40 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $ as canReadInboxItem, $a as resolveAssignees, $r as getDispatchIdForConversation, $u as isLeadConversation, Aa as readAutomationExecutionStatusDays, At as makeStructuredToolOutput, Au as embedConversationQuery, Br as getQueueProvider, Bs as isConversationChannel, Bt as appendAndEnqueueExclusiveInboundMessage, Cc as closeReadReplyNotice, Cd as topLevelConversation, Cl as getDashboardConversationLink, Co as getWatch, Cu as excerptTerms, Dc as getInboxItem, Dn as withIdleConversation, E as latestUserMessageQuery, Ea as emptyAutomationRunWindows, Ec as dismissOpenInboxItems, Eo as listWatches, Es as isUserActor, Eu as isEventEmbeddingsEnabled, Fa as readAutomationRuns, Fd as juniorAutomationRuns, Fi as createPluginDecider, Fn as createSlackInboxItemToolServices, Fs as SlackActionError, Ft as agentNameSchema, Fu as generateImages, Gc as identityAvatarUrl, Gi as buildCommandScript, H as conversationStatusSql, Hi as createSandboxCapability, Ii as createPluginEmbedder, Is as downloadPrivateSlackFile, Iu as searchWeb, Ja as resolveTaskTitle, Jc as readUserAvatarUrls, Jd as juniorConversationEventLexemes, Ji as createPluginCache, Js as sleep, Ju as setStateValues, Ka as fallbackShortTitle, Kd as juniorConversationReadPositions, Ki as buildNonInteractiveShellScript, Ku as getStateAdapter, Li as createPluginModel, Lr as QUEUE_SIGNATURE_MAX_AGE_MS, Ls as getFilePermalink, Lu as transcribeFromUrl, Ma as readAutomationExecutionSummaries, Mc as searchInboxItems, Mn as readParentMessage, Mo as createSlackDirectCredentialSubject, Na as readAutomationExecutions, Ni as pluginMcpContext, Nn as readInboundMessageSender, Nt as CHILD_AGENT_KINDS, Nu as completeObject, O as withConversationMutationLock, Oc as getOpenInboxItemBySubject, Oi as slackMention, Ol as getDashboardSpaceLink, Oo as turnEvents, Ot as injectContinuationToolName, Pa as readAutomationRowStats, Pc as updateInboxItemContent, Pi as createPluginState, Pt as PARENT_AGENT_TARGET, Pu as completeText, Qa as resolveAssignee, Qd as juniorConversationEvents, Qi as deleteScheduledAutomation, Qo as isConversationDeliveryPaused, Qu as hasAgentTurnUsage, Rd as juniorAutomations, Ri as createPluginModelCostRecorder, Rr as signQueueMessage, Ru as NoAudioError, S as setArchivedAt, Sa as sameDefinitionValue, Sl as isToolInputError, Sr as readConversationAccessFromSql, St as getRegistrations, Su as eventExcerpt, Ta as requireAutomationRevision, Tc as closeInboxItem, Tn as releaseInboundMessage, Va as usdToMicroUsd, Vi as basePluginContext, Vs as isConversationScopedChannel, Vt as appendAndEnqueueInboundMessage, W as conversationWaitsOnUserSql, Wo as credentialUserSubjectId, Ws as normalizeSlackConversationId, Xa as activeParticipantUserIds, Xl as canMoveToSpace, Xu as agentTurnCostUsd, Ya as EVERYONE_ASSIGNEE, Yd as juniorConversationEventEmbeddings, Yl as fuseRankedLists, Yu as addAgentTurnUsage, Z as canAgentChangeInboxItem, Za as automationCreatorUserId, Zi as createScheduledAutomation, _f as guardedCosineDistance, _l as registeredEventTypeSchema, _o as cancelWatch, _r as canInviteToConversation, _s as defaultTimezone, _t as requireInboxItemAssignees, _u as searchedEventTextSql, a as getDb, au as isTopLevelWork, b as conversationDescendants, ba as listAutomationVersions, bf as getConfigDefaults, bl as requireValidEventTrigger, bo as createWatch, bu as SEARCHABLE_EVENT_TYPES, ca as createEventAutomation, cd as parseSlackChannelId, co as WORKSPACE_SNAPSHOT_READY_EVENT, cs as isPublicConversation, cu as promptModeTurnTools, da as getEventAutomation, dd as parseSlackUserId, df as juniorSpaces, du as watcherStartedConversation, ea as parseScheduledAutomationRow, ec as readActorIdentity, ei as getDispatchInputMessageId, en as dropPendingMessages, eo as getEventCatalog, eu as dispatchInstructionsInvokeSkills, f as eventFromRow, fa as listDeletedEventAutomationsCreatedBy, ff as juniorIdentities, fi as addReactionToMessage, fl as eventNamespaceSchema, fo as agentWatch, fs as conversationSubtree, gc as readCachedLinkedHandle, gd as parseSlackMessageTs, gf as juniorDestinations, gl as registeredEventTriggerProblems, gt as readInboxItemAgentScope, gu as lexemesSql, ha as setEventAutomationStatus, hf as juniorUsers, hi as openSlackDirectMessage, hl as registeredEventMatchSchema, ho as starterWatchId, ht as questionSubject, i as getConversationStore, id as touchConversationDetail, iu as isTopLevel, ja as readAutomationExecutionStatusHours, jc as ownerConversationId, jr as getVercelConversationWorkQueue, ka as readAutomationExecutionByConversationId, kc as insertInboxItem, kl as getDashboardTaskLink, kt as juniorToolOutputSchema, ku as createConversationEmbedder, la as deleteEventAutomation, ld as parseSlackChannelReferenceId, lf as juniorConversations, ll as automationEventCatalog, lr as createPluginCodeChanges, ma as saveEventAutomation, mi as getSlackMessagePermalink, ml as hasEventCatalogEntries, mo as publishAgentUpdate, n as getConversationEventStore, na as saveScheduledAutomation, no as requireSlackChannelMessageScope, ns as createPluginAnnotations, nu as isPersonInput, o as getSqlExecutor, oc as SYSTEM_IDENTITY_ID, of as juniorAttachmentUploads, oo as slackChannelMessageTrigger, ou as ownsLocation, pa as parseEventAutomationRow, pl as eventWatchUnavailable, ps as conversationSubtreeColumns, pt as isPluginInboxItem, qd as juniorConversationParticipants, qi as runNonInteractiveCommand, qs as withSlackRetries, qt as claimInboundMessage, qu as getStateValues, r as getConversationMessageSearchStore, rd as nextDetailVersion, rn as getConversationWorkState, ru as isThread, sc as resolveActorIdentityId, sd as sameDestination, sf as juniorAttachments, so as WORKSPACE_SNAPSHOT_FAILED_EVENT, sr as queueCallback, ta as readScheduledAutomation, tc as readIdentityById, td as rootConversationIsArchived, ti as getDispatchRecord, tn as ensureConversationWake, ts as searchConversations, ud as parseSlackTeamId, ul as describeRegisteredEventTrigger, uo as workspaceSnapshotWatch, us as setMovedWorkVisibility, uu as turnBehavior, va as automationDefinition, vf as juniorArtifacts, vl as registeredResourceTypeSchema, vr as canReadConversation, vt as requireInboxItemLinks, vu as seqIn, wa as automationRevision, wr as readableSlackTeamId, x as readConversationTrees, xa as readAutomationVersion, xi as uploadFilesToConversation, xl as ToolInputError, xr as leaveEndsAccess, xt as getPlugins, xu as callsToolSql, y as conversationAncestors, yd as rootSpaceIdSql, yf as resolveConversationDestination, yl as requireEventIdentifier, yn as hasConversationStop, yo as createTimerWatch, ys as resolveUserTimezone, zd as juniorStats, zo as actorLogContext, zr as verifyQueueMessage, zs as getSlackClient } from "./db-BFmyYZtJ.js";
3
- import { n as CACHE_WARMUP_QUEUE_TOPIC, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./topics-SRN7IVX-.js";
4
- import { $ as isProviderRetryError, B as textCharsForTokens, C as resolveGatewayModel, F as requestPrefixAttributes, G as isCompactionSummaryText, H as gatewayRoutingAttributes, I as claudeMaxImageSize, J as createProviderError, K as ProviderError, L as estimateMessagesTokens, Q as isProviderRefusal, R as estimateRequestOverheadTokens, U as COMPACTION_SUMMARY_PREFIX, V as readImageDimensions, W as hasCompactedConversationContext, X as getProviderErrorAttributes, Y as findProviderError, d as normalizeSlackEmojiName, et as getGatewayApiKey, f as TURN_REASONING_LEVELS, h as GEN_AI_SERVER_ADDRESS, m as GEN_AI_PROVIDER_NAME, n as getChatConfig, p as toPiReasoningLevel, q as createAssistantProviderError, t as botConfig, z as estimateTextTokens } from "./config-CHQ8X251.js";
5
- import { A as runWithLogAttributes, C as summarizeMessageText, E as withSpan, N as normalizeIdentityEmail, P as toOptionalString, S as setTags, T as withLogContext, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging--smS7XRK.js";
2
+ import { n as CACHE_WARMUP_QUEUE_TOPIC, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./topics-BoCkoPJJ.js";
3
+ import { $ as resolveGatewayModel, D as parseSlackChannelReferenceId, E as parseSlackChannelId, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, R as getChatConfig, X as toPiReasoningLevel, Y as TURN_REASONING_LEVELS, b as getStateValues, f as isUserActor, k as parseSlackUserId, o as credentialUserSubjectId, t as actorLogContext, x as setStateValues, y as getStateAdapter } from "./context-BKF_5zzI.js";
4
+ import { $ as canAgentChangeInboxItem, $a as fallbackShortTitle, $d as juniorConversationParticipants, $i as runNonInteractiveCommand, $l as registeredEventMatchSchema, $o as isConversationDeliveryPaused, $s as SYSTEM_IDENTITY_ID, $u as findProviderError, Ao as getWatch, As as getFilePermalink, At as injectContinuationToolName, Au as transcribeFromUrl, Ba as readAutomationExecutions, Bi as createPluginState, Bl as EVENT_AUTHOR_ID, Br as QUEUE_SIGNATURE_MAX_AGE_MS, Bs as withSlackRetries, Bu as claudeMaxImageSize, Cd as sameDestination, Cf as guardedCosineDistance, Cr as leaveEndsAccess, Ct as getPlugins, Cu as embedConversationQuery, Da as listAutomationVersions, Dc as updateInboxItemContent, Di as uploadFilesToConversation, Dn as releaseInboundMessage, Do as createWatch, Du as completeText, E as latestUserMessageQuery, El as canMoveToSpace, Eo as createTimerWatch, Er as readableSlackTeamId, Eu as completeObject, F as destinationUpsertFromDestination, Fn as readInboundMessageSender, Fo as turnEvents, Ft as CHILD_AGENT_KINDS, Gd as juniorStats, Gu as readImageDimensions, Ha as readAutomationRuns, Hi as createPluginEmbedder, Hl as EVENT_SYSTEM_ACTOR, Hr as verifyQueueMessage, Ht as appendAndEnqueueExclusiveInboundMessage, Hu as estimateRequestOverheadTokens, I as upsertDestination, Ia as readAutomationExecutionByConversationId, Il as promptModeTurnTools, It as PARENT_AGENT_TARGET, Ja as usdToMicroUsd, Ji as createSandboxCapability, Jl as describeRegisteredEventTrigger, Js as readIdentityById, Ju as hasCompactedConversationContext, K as conversationWaitsOnUserSql, Ku as gatewayRoutingAttributes, La as readAutomationExecutionStatusDays, Ln as createSlackInboxItemToolServices, Ls as normalizeSlackConversationId, Lt as agentNameSchema, Ma as requireAutomationRevision, Ml as isThread, Ms as getSlackClient, Mt as makeStructuredToolOutput, Mu as GEN_AI_PROVIDER_NAME, Na as emptyAutomationRunWindows, Nl as isTopLevel, No as listWatches, Nr as getVercelConversationWorkQueue, Ns as isConversationChannel, Nu as GEN_AI_SERVER_ADDRESS, O as withConversationMutationLock, Oa as readAutomationVersion, Ol as dispatchInstructionsInvokeSkills, Os as SlackActionError, Ou as generateImages, Pi as slackMention, Pl as parentResultActor, Pn as readParentMessage, Ps as isConversationScopedChannel, Qd as juniorConversationReadPositions, Qi as buildNonInteractiveShellScript, Ql as hasEventCatalogEntries, Qu as createProviderError, Ra as readAutomationExecutionStatusHours, Rc as identityAvatarUrl, Rl as turnBehavior, S as setArchivedAt, Sa as setEventAutomationStatus, Sc as insertInboxItem, Sf as juniorDestinations, So as starterWatchId, Su as createConversationEmbedder, Ta as automationDefinition, Tc as searchInboxItems, Td as rootSpaceIdSql, Tl as fuseRankedLists, Ui as createPluginModel, Ur as getQueueProvider, Ut as appendAndEnqueueInboundMessage, Uu as estimateTextTokens, Va as readAutomationRowStats, Vc as readUserAvatarUrls, Vd as juniorAutomationRuns, Vi as createPluginDecider, Vr as signQueueMessage, Vs as sleep, Vu as estimateMessagesTokens, W as conversationStatusSql, Wd as juniorAutomations, Wi as createPluginModelCostRecorder, Wu as textCharsForTokens, Xl as eventNamespaceSchema, Xu as ProviderError, Yt as claimInboundMessage, Yu as isCompactionSummaryText, Zi as buildCommandScript, Zl as eventWatchUnavailable, Zu as createAssistantProviderError, _d as rootConversationIsArchived, _f as juniorSpaces, _o as workspaceSnapshotWatch, _s as defaultTimezone, _t as questionSubject, _u as eventExcerpt, a as getDb, aa as deleteScheduledAutomation, ai as getDispatchIdForConversation, an as getConversationWorkState, ao as resolveAssignee, au as ToolInputError, b as conversationDescendants, ba as parseEventAutomationRow, bc as getInboxItem, bd as touchConversationDetail, bi as getSlackMessagePermalink, br as canReadConversation, bt as requireInboxItemLinks, bu as isEventEmbeddingsEnabled, ca as readScheduledAutomation, cs as conversationSubtreeColumns, dd as agentTurnCostUsd, dr as createPluginCodeChanges, du as lexemesSql, ea as createPluginCache, ec as resolveActorIdentityId, ed as getProviderErrorAttributes, ef as juniorConversationEventLexemes, eu as registeredEventTriggerProblems, f as eventFromRow, ff as juniorAttachmentUploads, fs as isPublicConversation, fu as searchedEventTextSql, ga as deleteEventAutomation, gc as closeReadReplyNotice, gu as callsToolSql, ha as createEventAutomation, hd as isLeadConversation, hf as juniorConversations, ho as WORKSPACE_SNAPSHOT_READY_EVENT, ht as isPluginInboxItem, hu as SEARCHABLE_EVENT_TYPES, i as getConversationStore, ia as createScheduledAutomation, id as getGatewayApiKey, if as juniorConversationEvents, io as automationCreatorUserId, iu as requireValidEventTrigger, ja as automationRevision, jl as isPersonInput, jt as juniorToolOutputSchema, ju as NoAudioError, ka as sameDefinitionValue, kn as withIdleConversation, ks as downloadPrivateSlackFile, ku as searchWeb, la as saveScheduledAutomation, lc as readCachedLinkedHandle, lo as requireSlackChannelMessageScope, lr as queueCallback, md as hasAgentTurnUsage, mo as WORKSPACE_SNAPSHOT_FAILED_EVENT, n as getConversationEventStore, nd as isProviderRefusal, nn as dropPendingMessages, no as EVERYONE_ASSIGNEE, ns as searchConversations, nu as registeredResourceTypeSchema, o as getSqlExecutor, oi as getDispatchInputMessageId, ol as getDashboardSpaceLink, oo as resolveAssignees, ou as isToolInputError, pf as juniorAttachments, po as slackChannelMessageTrigger, pu as seqIn, qi as basePluginContext, ql as automationEventCatalog, qs as readActorIdentity, qu as COMPACTION_SUMMARY_PREFIX, r as getConversationMessageSearchStore, rd as isProviderRetryError, rn as ensureConversationWake, ro as activeParticipantUserIds, rs as createPluginAnnotations, ru as requireEventIdentifier, sa as parseScheduledAutomationRow, si as getDispatchRecord, sl as getDashboardTaskLink, so as getEventCatalog, ss as conversationSubtree, ta as getConfigDefaults, tf as juniorConversationEventEmbeddings, tl as getDashboardConversationLink, to as resolveTaskTitle, tt as canReadInboxItem, tu as registeredEventTypeSchema, ud as addAgentTurnUsage, va as getEventAutomation, vc as closeInboxItem, vf as juniorIdentities, vi as addReactionToMessage, vt as readInboxItemAgentScope, vu as excerptTerms, wc as ownerConversationId, wd as isLeadSql, wf as juniorArtifacts, wo as cancelWatch, wr as readConversationAccessFromSql, wt as getRegistrations, x as readConversationTrees, xa as saveEventAutomation, xc as getOpenInboxItemBySubject, xf as juniorUsers, xi as openSlackDirectMessage, xn as hasConversationStop, xo as publishAgentUpdate, y as conversationAncestors, ya as listDeletedEventAutomationsCreatedBy, yc as dismissOpenInboxItems, yd as nextDetailVersion, yo as agentWatch, yr as canInviteToConversation, ys as resolveUserTimezone, yt as requireInboxItemAssignees, za as readAutomationExecutionSummaries, zi as pluginMcpContext, zl as watcherStartedConversation, zo as createSlackDirectCredentialSubject, zu as requestPrefixAttributes } from "./db-of6e3sGt.js";
5
+ import { $t as automationTitleSchema, Cn as userInputRequestSchema, Ct as instructionActors, Dn as automationTaskSchema, En as automationTaskDescription, Kt as MAX_ATTACHMENT_BYTES, Ln as apiErrorSchema, Mn as getFirstRunAtMs, On as automationTaskText, Qt as automationInstructionToolSchema, Sn as userInputQuestionSchema, St as contextProvenance, Tt as sameActorIdentity, Wt as removedCardSchema, Zt as automationContextToolSchema, _ as automationListQuerySchema, an as compileScheduleIntent, at as KNOWN_CONVERSATION_EVENT_TYPES, cn as weekdaySchema, en as taskOutcomeInputSchema, fn as inboxItemQuestion, gt as historyItemFromPiMessage, in as ScheduleIntentError, it as formatAgentTypes, on as scheduleIntentFromTool, sn as toolScheduleIntentSchema, tn as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, tt as AGENT_TYPES, un as eventAutomationTriggerSchema, vn as formatUserInputAnswer, wn as automationSkillNameSchema, wt as instructionProvenanceFor, xn as userInputFieldsSchema, yt as piMessageFromHistoryItem, zn as AGENT_UPDATE_EVENT_TYPE } from "./types-DCzTAA63.js";
6
+ 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, p as logInfo, r as extractGenAiUsageAttributes, u as logAudit, w as withLogContext, x as setTags, y as setSpanAttributes } from "./logging-BnOG0qz2.js";
6
7
  import { g as withActiveSpan, h as startSpan, i as getActiveSpan, m as startInactiveSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.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-B1uXn5sf.js";
8
- import { A as retainRuntimeTurnContext, D as isToolResultError, E as isStandaloneRuntimeContextMessage, G as renderThreadContext, H as readParentAgentTask, L as mapBounded, M as trimTrailingAssistantMessages, N as CAPABILITY_SECTION_TAG, O as isToolResultMessage, P as REQUEST_CONTEXT_SECTION_TAG, S as hasTurnInput, T as isContinuablePiBoundary, _ as extractAssistantText, a as SANDBOX_COMMAND_PATH, b as getUserMessageInstructionText, 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, u as SANDBOX_SKILLS_ROOT, v as getPiMessageRole, w as isAssistantMessage, z as unwrapCurrentInstruction } from "./prompt-Dv7gkpD6.js";
9
- import { $t as automationTitleSchema, Cn as userInputRequestSchema, Ct as instructionActors, En as AGENT_UPDATE_EVENT_TYPE, Fn as automationTaskText, Kt as MAX_ATTACHMENT_BYTES, Nn as automationTaskDescription, Pn as automationTaskSchema, Qt as automationInstructionToolSchema, Sn as userInputQuestionSchema, St as contextProvenance, Tt as sameActorIdentity, Wn as apiErrorSchema, Wt as removedCardSchema, Zt as automationContextToolSchema, _ as automationListQuerySchema, an as compileScheduleIntent, at as KNOWN_CONVERSATION_EVENT_TYPES, cn as weekdaySchema, en as taskOutcomeInputSchema, fn as inboxItemQuestion, gt as historyItemFromPiMessage, in as ScheduleIntentError, it as formatAgentTypes, jn as automationSkillNameSchema, on as scheduleIntentFromTool, sn as toolScheduleIntentSchema, tn as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, tt as AGENT_TYPES, un as eventAutomationTriggerSchema, vn as formatUserInputAnswer, wt as instructionProvenanceFor, xn as userInputFieldsSchema, yt as piMessageFromHistoryItem, zn as getFirstRunAtMs } from "./types-C4iC-IMC.js";
8
+ import { A as retainRuntimeTurnContext, D as isToolResultError, E as isStandaloneRuntimeContextMessage, G as mapBounded, 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, 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, u as SANDBOX_SKILLS_ROOT, v as getPiMessageRole, w as isAssistantMessage } from "./prompt-DEkStuxG.js";
9
+ 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-Cr_dNW1p.js";
10
10
  import { l as sumUtcHoursIntoSixHours, m as CHILD_AGENT_RESULTS, n as webMessageId, t as AGENT_STATUSES } from "./agent-status-BA5x3Xtp.js";
11
- import { $n as calculateContextCompactionTargetTokens, $r as CODEMODE_TOOL_NAME, Ar as TURN_LIMIT_WRAP_UP_MESSAGE, At as turnRequestText, Bt as deleteWorkspace, C as getChildAgentLockName, Cn as recordAttachmentsDelivered, Dn as recordGuardianActionReviewed, Dr as loadTurnStart, En as recordAuthorizationRequested, Et as buildSteeringPiMessage, Fr as createTurnLimitGate, Ft as saveUserCustomization, Gr as ToolActionReviewUnavailableError, H as resolveBotSlackTeamId, Hr as isCutOffStopReason, Ht as getWorkspaceByName, Ir as isTurnExecutionLimitExceededError, It as addConversationNote, J as stopConversationTree, Jr as getToolActionRejectionMarker, Jt as tryWorkspaceRepoCheckoutPath, Kr as createToolActionReview, Kt as updateWorkspace, Lr as captureTurnFailure, Mr as TurnSliceLimitExceededError, Mt as readTaskInstructions, Nr as TurnToolCallLimitExceededError, O as EVENT_WAIT_MS, On as recordMcpProviderConnected, Qr as USER_AUTHORIZATION_LEVELS, Rt as buildDeterministicTurnId, Sn as recordAgentsInstructionsUpdated, Tt as buildPromptInput, Ur as ToolActionRejectedError, Ut as listWorkspaceNamesByRepository, Vr as buildTurnResult, Vt as getWorkspace, W as getConversationStoppedAtMs, Wr as ToolActionReviewLimitError, Wt as listWorkspaces, Xn as EVENT_SYSTEM_ACTOR, Xr as RISK_LEVELS, Yn as EVENT_AUTHOR_ID, Yr as restoreToolActionRejections, Yt as workspaceRepoCheckoutPath, Zr as ROOT_LINE_BREAK, an as AGENTS_REPLACEMENT_NOTICE, ar as createPluginAuthOrchestration, b as readAgentConfig, bn as loadConversationSkillNames, ci as validateConfigValue, cn as readRepositoryInstructions, cr as AuthorizationFlowDisabledError, dn as foldLeadingSystemMessages, dr as canReusePendingAuthLink, ei as CODE_MODE_CALL_STATUS_TEXT, er as getAgentBackgroundCompactionMarkTokens, fn as foldSystemMessages, hn as writeAgentHistory, hr as loadTurnCheckpoint, i as listActiveMailboxTurns, in as AGENTS_REMOVAL_NOTICE, ir as PluginCredentialFailureError, jn as recordToolExecutionStarted, jr as TurnBudgetExceededError, kn as recordSkillLoaded, kr as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, kt as loadPromptTurnContext, li as configValueSchema, ln as renderAgentsInstructions, lr as AuthorizationPauseError, m as isParentMessageAuthor, mn as withAgentRequest, mr as continuableMessages, ni as deliverOAuthAuthorization, nr as getAgentContextInputLimitTokens, nt as TurnInputCommitLostError, oi as projectConversationEvents, on as buildAgentsInstructionsMessage, or as authorizationId, ot as isTurnInputCommitLostError, p as dropWaitingParentMessages, pn as readAgentHistory, qr as reviewToolActions, qt as WorkspaceValidationError, ri as formatProviderLabel, rn as buildDeploymentSystemPrompt, rr as createPluginEgress, si as validateConfigKey, sn as findVisibleAgentsInstructions, sr as AuthPausePersistenceError, tn as isExperimentalFeatureEnabled, tr as getAgentContextCompactionTriggerTokens, tt as CooperativeTurnYieldError, un as showsAgentsInstructions, ur as abandonReplacedPendingAuth, v as readLastParentMessageAtMs, vn as loadConnectedMcpProviders, vr as saveTurnCheckpoint, wt as assemblePrompt, yn as loadConversationProjection, zt as createWorkspace } from "./mailbox-turn-uSXhUFc9.js";
12
- import { A as annotateToolResult, C as restoreLineEndings, D as normalizeToLf$1, E as isMissingPathError, F as listSpaceConfiguration, I as readConversationSpaceConfiguration, L as readConversationSpaceId, M as parseToolInput, N as zodTool, O as positiveInteger$1, P as zodToolDefinition, R as setSpaceConfiguration, S as prepareTextReplacementArguments, T as validateAndApplyTextEdits, _ as editFileToolDefinition, a as prepareWorkspaceSnapshot, b as buildCompactDiff, c as renderToolResultNudge, d as systemTimeToolDefinition, f as createWriteFileTool, g as createEditFileTool, h as readFileToolDefinition, i as requireReadyWorkspaceSnapshot, j as saveObjectAnnotations, k as resolveWorkspacePath, l as PluginToolDeniedError, m as createReadFileTool, p as writeFileToolDefinition, s as createPluginHookRunner, t as ensureWorkspaceSnapshotBuild, u as createSystemTimeTool, v as bashToolDefinition, w as stripBom, x as detectLineEnding, y as createBashTool, z as unsetSpaceConfiguration } from "./job-runner-A1lCkybD.js";
11
+ import { $n as getAgentContextCompactionTriggerTokens, $r as CODE_MODE_CALL_STATUS_TEXT, An as recordSkillLoaded, Ar as TurnSliceLimitExceededError, Br as buildTurnResult, C as getChildAgentLockName, Cn as recordAgentsInstructionsUpdated, Dn as recordAuthorizationRequested, Dr as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Dt as assemblePrompt, Ft as readTaskInstructions, Gr as createToolActionReview, Gt as getWorkspaceByName, Hr as ToolActionRejectedError, Ht as createWorkspace, Ir as captureTurnFailure, Jr as restoreToolActionRejections, Kr as reviewToolActions, Kt as listWorkspaceNamesByRepository, Mn as recordToolExecutionStarted, Mt as loadPromptTurnContext, Nr as createTurnLimitGate, Nt as turnRequestText, O as EVENT_WAIT_MS, On as recordGuardianActionReviewed, Or as TURN_LIMIT_WRAP_UP_MESSAGE, Ot as buildPromptInput, Pr as isTurnExecutionLimitExceededError, Qn as getAgentBackgroundCompactionMarkTokens, Qr as CODEMODE_TOOL_NAME, Qt as workspaceRepoCheckoutPath, Rt as saveUserCustomization, Tr as loadTurnStart, U as getConversationStoppedAtMs, Ur as ToolActionReviewLimitError, Ut as deleteWorkspace, V as resolveBotSlackTeamId, Vr as isCutOffStopReason, Vt as buildDeterministicTurnId, Wr as ToolActionReviewUnavailableError, Wt as getWorkspace, Xr as ROOT_LINE_BREAK, Xt as WorkspaceValidationError, Yr as RISK_LEVELS, Yt as updateWorkspace, Zn as calculateContextCompactionTargetTokens, Zr as USER_AUTHORIZATION_LEVELS, Zt as tryWorkspaceRepoCheckoutPath, ai as projectConversationEvents, an as AGENTS_REMOVAL_NOTICE, ar as AuthPausePersistenceError, at as isTurnInputCommitLostError, b as readAgentConfig, bn as loadConversationProjection, ci as configValueSchema, cn as findVisibleAgentsInstructions, cr as abandonReplacedPendingAuth, dn as showsAgentsInstructions, er as getAgentContextInputLimitTokens, et as CooperativeTurnYieldError, fn as foldLeadingSystemMessages, fr as continuableMessages, gn as writeAgentHistory, gr as saveTurnCheckpoint, h as isParentMessageAuthor, hn as withAgentRequest, i as listActiveMailboxTurns, in as buildDeploymentSystemPrompt, ir as authorizationId, jr as TurnToolCallLimitExceededError, kn as recordMcpProviderConnected, kr as TurnBudgetExceededError, kt as buildSteeringPiMessage, ln as readRepositoryInstructions, lr as canReusePendingAuthLink, mn as readAgentHistory, ni as formatProviderLabel, nr as PluginCredentialFailureError, oi as validateConfigKey, on as AGENTS_REPLACEMENT_NOTICE, or as AuthorizationFlowDisabledError, p as dropWaitingParentMessages, pn as foldSystemMessages, pr as loadTurnCheckpoint, q as stopConversationTree, qr as getToolActionRejectionMarker, qt as listWorkspaces, rn as isExperimentalFeatureEnabled, rr as createPluginAuthOrchestration, si as validateConfigValue, sn as buildAgentsInstructionsMessage, sr as AuthorizationPauseError, ti as deliverOAuthAuthorization, tr as createPluginEgress, tt as TurnInputCommitLostError, un as renderAgentsInstructions, v as readLastParentMessageAtMs, wn as recordAttachmentsDelivered, xn as loadConversationSkillNames, yn as loadConnectedMcpProviders, zt as addConversationNote } from "./mailbox-turn-Byrry9o1.js";
12
+ import { A as annotateToolResult, C as restoreLineEndings, D as normalizeToLf$1, E as isMissingPathError, F as listSpaceConfiguration, I as readConversationSpaceConfiguration, L as readConversationSpaceId, M as parseToolInput, N as zodTool, O as positiveInteger$1, P as zodToolDefinition, R as setSpaceConfiguration, S as prepareTextReplacementArguments, T as validateAndApplyTextEdits, _ as editFileToolDefinition, a as prepareWorkspaceSnapshot, b as buildCompactDiff, c as renderToolResultNudge, d as systemTimeToolDefinition, f as createWriteFileTool, g as createEditFileTool, h as readFileToolDefinition, i as requireReadyWorkspaceSnapshot, j as saveObjectAnnotations, k as resolveWorkspacePath, l as PluginToolDeniedError, m as createReadFileTool, p as writeFileToolDefinition, s as createPluginHookRunner, t as ensureWorkspaceSnapshotBuild, u as createSystemTimeTool, v as bashToolDefinition, w as stripBom, x as detectLineEnding, y as createBashTool, z as unsetSpaceConfiguration } from "./job-runner-B2XEvpif.js";
13
13
  import { a as listReferenceFiles } from "./package-discovery-DD9vencX.js";
14
- import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-BCEU41zM.js";
15
- import { B as getMcpAwareErrorType, C as getMcpAuthSession, D as putMcpAuthSession, E as patchMcpAuthSession, F as resolvePluginHeaderEnvRefs, G as fetchWithBoundedOAuthErrorBodies, H as getMcpProviderErrorAttributes, K as getOAuthProviderErrorAttributes, L as McpProviderError, O as putMcpServerSessionId, R as McpServiceAccountRequiredError, T as getMcpStoredOAuthCredentials, U as toMcpProviderError, V as getMcpAwareTelemetryMessage, W as OAuthProviderError, _ as McpAuthorizationRequiredError, c as serviceAccountAllows, g as getMcpServiceAccountCredentials, h as createMcpServiceAccountClientProvider, k as putMcpStoredOAuthCredentials, l as serviceAccountOnly, v as PluginMcpClient, w as getMcpServerSessionId, x as deleteMcpServerSessionId, y as deleteMcpAuthSession, z as McpToolError } from "./registry-iXMT5Jmh.js";
16
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
17
- 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, 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, s as isRetryableSandboxFailure, u as SANDBOX_RUNTIME, v as getWorkspaceSnapshotNotReadyError, w as consumeSandboxEgressAuthRequiredSignal, y as isWorkspaceSnapshotNotReadyError } from "./profile-BQ-iBDsZ.js";
18
- 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-CiXy0eNR.js";
19
- import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-ByG5RCEJ.js";
14
+ import { n as findSkillByName, o as parseSkillInvocations, r as loadSkillsByName, t as discoverSkills } from "./skills-CleC0Hze.js";
15
+ import { B as getMcpAwareErrorType, C as getMcpAuthSession, D as putMcpAuthSession, E as patchMcpAuthSession, F as resolvePluginHeaderEnvRefs, G as fetchWithBoundedOAuthErrorBodies, H as getMcpProviderErrorAttributes, K as getOAuthProviderErrorAttributes, L as McpProviderError, O as putMcpServerSessionId, R as McpServiceAccountRequiredError, T as getMcpStoredOAuthCredentials, U as toMcpProviderError, V as getMcpAwareTelemetryMessage, W as OAuthProviderError, _ as McpAuthorizationRequiredError, c as serviceAccountAllows, g as getMcpServiceAccountCredentials, h as createMcpServiceAccountClientProvider, k as putMcpStoredOAuthCredentials, l as serviceAccountOnly, v as PluginMcpClient, w as getMcpServerSessionId, x as deleteMcpServerSessionId, y as deleteMcpAuthSession, z as McpToolError } from "./registry-Cl7Labpe.js";
16
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BfdAnztW.js";
17
+ 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, 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, s as isRetryableSandboxFailure, u as SANDBOX_RUNTIME, v as getWorkspaceSnapshotNotReadyError, w as consumeSandboxEgressAuthRequiredSignal, y as isWorkspaceSnapshotNotReadyError } from "./profile-iHw1uu32.js";
18
+ 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-Ci6Ck4gk.js";
19
+ import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-Cb9c1k9q.js";
20
20
  import { o as detectImageMediaType, r as userCustomizationTextSchema, s as isVisionImageMediaType, t as USER_CUSTOMIZATION_MAX_CHARS } from "./user-customization-CvfuY9Eo.js";
21
- import { _ as AttachmentSourceUnavailableError, d as readLiveAttachment, f as recordUploadedAttachment, g as storeDeferredAttachment, h as storeAttachments, i as matchSlackAttachments, n as savedTurnMessages, o as readSlackAttachmentSource, t as isTurnMessage, v as bufferBody } from "./turn-membership-CENFf3kI.js";
22
- import { c as listChannelMessages, l as listThreadReplies, n as joinPublicChannelForRead, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-j-YAVYK4.js";
23
- import { a as listChildAgents, i as listAgentRelatives, n as recordChildAgentEnded, o as listDescendantAgents, p as isStopResult, t as parentResultActor } from "./parent-result-Ck1rFYRQ.js";
24
- import { a as setSnapshotSpanAttributes, n as resolve$1, o as getSandboxResources } from "./resolve-tony4ibz.js";
21
+ import { _ as AttachmentSourceUnavailableError, d as readLiveAttachment, f as recordUploadedAttachment, g as storeDeferredAttachment, h as storeAttachments, i as matchSlackAttachments, n as savedTurnMessages, o as readSlackAttachmentSource, t as isTurnMessage, v as bufferBody } from "./turn-membership-VT7XZh-L.js";
22
+ import { c as listChannelMessages, l as listThreadReplies, n as joinPublicChannelForRead, s as joinPublicChannel, t as checkSlackChannelReadAccess } from "./channel-access-A0de5lRv.js";
23
+ import { a as listDescendantAgents, f as isStopResult, i as listChildAgents, r as listAgentRelatives, t as recordChildAgentEnded } from "./markers-CTTtJqYn.js";
24
+ import { a as setSnapshotSpanAttributes, n as resolve$1, o as getSandboxResources } from "./resolve-DC6zBuDV.js";
25
25
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
26
26
  import * as z from "zod";
27
27
  import { streamSimple } from "@earendil-works/pi-ai/compat";
28
28
  import path from "node:path";
29
+ import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notInArray, or, sql } from "drizzle-orm";
30
+ import { alias, unionAll } from "drizzle-orm/pg-core";
31
+ import { agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, escapeTagText, escapeTagTextAndQuotes, eventMatchFieldSchema, eventTriggerText, findTag, localDestinationSchema, missingToolAnnotationKeys, normalizeEventIdentifier, ownedObjectAnnotationSchema, pluginProviderAccountSchema, pluginToolReplySchema, promptMessageSchema, renderEmptyTag, renderInlineTag, renderTag, stableEventMatchKey, startsWithTag, stripTags, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
29
32
  import { isDeepStrictEqual, promisify } from "node:util";
30
33
  import { AsyncLocalStorage } from "node:async_hooks";
31
34
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
32
- import { getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
33
- import { agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, escapeTagText, escapeTagTextAndQuotes, eventMatchFieldSchema, eventTriggerText, findTag, missingToolAnnotationKeys, normalizeEventIdentifier, ownedObjectAnnotationSchema, pluginProviderAccountSchema, pluginToolReplySchema, promptMessageSchema, renderEmptyTag, renderInlineTag, renderTag, stableEventMatchKey, startsWithTag, stripTags, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
34
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
35
- import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notInArray, or, sql } from "drizzle-orm";
36
- import { alias, unionAll } from "drizzle-orm/pg-core";
37
35
  import pLimit from "p-limit";
36
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
37
+ import { getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
38
38
  import { Kind } from "@sinclair/typebox";
39
39
  import { Value } from "@sinclair/typebox/value";
40
40
  import { Agent, DEFAULT_AGENT_IDENTITY } from "@earendil-works/pi-agent-core";
@@ -1646,7 +1646,6 @@ function periodCounts(savings, warmed) {
1646
1646
  };
1647
1647
  }
1648
1648
  async function addSavingsStats(modelId, counts) {
1649
- if (!process.env["DATABASE_URL"]) return;
1650
1649
  try {
1651
1650
  await addStats(savingsStats(modelId, counts));
1652
1651
  } catch (error) {
@@ -7384,7 +7383,10 @@ async function inviteToConversation(viewer, conversationId, body) {
7384
7383
  async function readInvitableConversation(viewer, conversationId) {
7385
7384
  const access = (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId);
7386
7385
  const rootConversationId = access?.rootConversationId;
7387
- if (!rootConversationId || !canInviteToConversation(access)) return;
7386
+ if (!rootConversationId || !canInviteToConversation(access)) {
7387
+ if (access?.canViewPrivateContent && !access.isParticipant) throwApiError(403, "Only participants can invite people. Join the conversation first.");
7388
+ return;
7389
+ }
7388
7390
  return {
7389
7391
  rootConversationId,
7390
7392
  slackTeamId: readableSlackTeamId(access),
@@ -7679,6 +7681,38 @@ async function collectAttachmentUploadGarbage(args) {
7679
7681
  await args.storage.delete(unusedKeys);
7680
7682
  return { deleted: (await args.db.db().delete(juniorAttachmentUploads).where(inArray(juniorAttachmentUploads.id, rows.map((row) => row.id))).returning({ id: juniorAttachmentUploads.id })).length };
7681
7683
  }
7684
+ // src/chat/conversations/destination.ts
7685
+ function requireLocalDestination(conversationId) {
7686
+ const parsed = localDestinationSchema.safeParse({
7687
+ platform: "local",
7688
+ conversationId
7689
+ });
7690
+ if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
7691
+ return parsed.data;
7692
+ }
7693
+ /**
7694
+ * Keep a stored Destination, or create the temporary local Destination.
7695
+ *
7696
+ * TODO(dcramer): Delete this module after Conversation and AgentRun use
7697
+ * Location, and web and event Turns no longer need a local
7698
+ * Destination.
7699
+ */
7700
+ function resolveConversationDestination(args) {
7701
+ return args.existing ?? requireLocalDestination(args.conversationId);
7702
+ }
7703
+ /**
7704
+ * Create the local Destination of a Conversation that needs its own, such as
7705
+ * one that leaves its Space. A local id is its own Destination. Another id,
7706
+ * such as a child agent's or a Slack thread's, maps to a stable local one.
7707
+ */
7708
+ function ownLocalDestination(conversationId) {
7709
+ const own = localDestinationSchema.safeParse({
7710
+ platform: "local",
7711
+ conversationId
7712
+ });
7713
+ if (own.success) return own.data;
7714
+ return requireLocalDestination(`local:conversation:${createHash("sha256").update(conversationId).digest("hex").slice(0, 32)}`);
7715
+ }
7682
7716
  // src/chat/conversations/web-input.ts
7683
7717
  function normalizeEmail(email) {
7684
7718
  return email.trim().toLowerCase();
@@ -7805,7 +7839,7 @@ async function recordWebConversationActivity(args) {
7805
7839
  ...isNewRoot && args.rootKind ? { kind: args.rootKind } : void 0,
7806
7840
  ...isNewRoot && args.rootSpaceId ? { spaceId: args.rootSpaceId } : void 0
7807
7841
  });
7808
- return existing && !ownsLocation(existing) ? void 0 : destination;
7842
+ return existing && !isTopLevel(existing) ? void 0 : destination;
7809
7843
  }
7810
7844
  /** Create a Conversation from web input and enqueue its first Message. */
7811
7845
  async function createAndEnqueueConversation(input, options) {
@@ -7989,21 +8023,17 @@ async function createSpace(args) {
7989
8023
  */
7990
8024
  async function updateSpace(spaceId, changes) {
7991
8025
  const executor = getSqlExecutor();
7992
- await executor.db().update(juniorSpaces).set({
7993
- ...changes.description !== void 0 ? { description: changes.description } : void 0,
7994
- ...changes.name !== void 0 ? { name: changes.name } : void 0,
7995
- updatedAt: /* @__PURE__ */ new Date()
7996
- }).where(eq(juniorSpaces.id, spaceId));
7997
- if (changes.name === void 0) return;
7998
- const [lead] = await executor.db().select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.kind, "lead"), eq(juniorConversations.spaceId, spaceId))).limit(1);
7999
- if (lead) await setConversationTitle(executor, lead.id, changes.name);
8000
- }
8001
- /**
8002
- * Keep the archive time that 0.316.0 reads, so a rollback to it sees the
8003
- * Space's archive. The Lead's archive time is the one this release reads.
8004
- */
8005
- async function writeLegacySpaceArchive(spaceId, archivedAt) {
8006
- await getDb().update(juniorSpaces).set({ archivedAt }).where(eq(juniorSpaces.id, spaceId));
8026
+ await executor.transaction(async () => {
8027
+ if (changes.name !== void 0) {
8028
+ const [lead] = await executor.db().select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.kind, "lead"), eq(juniorConversations.spaceId, spaceId))).limit(1);
8029
+ if (lead) await setConversationTitle(executor, lead.id, changes.name);
8030
+ }
8031
+ await executor.db().update(juniorSpaces).set({
8032
+ ...changes.description !== void 0 ? { description: changes.description } : void 0,
8033
+ ...changes.name !== void 0 ? { name: changes.name } : void 0,
8034
+ updatedAt: /* @__PURE__ */ new Date()
8035
+ }).where(eq(juniorSpaces.id, spaceId));
8036
+ });
8007
8037
  }
8008
8038
  // src/chat/spaces/tool-source.ts
8009
8039
  /** Deferred tool catalog source for the Space tools. */
@@ -8099,47 +8129,49 @@ async function readSpaceRefs(db, spaceIds) {
8099
8129
  }]] : []));
8100
8130
  }
8101
8131
  /**
8102
- * Put one top-level Conversation in a Space, or take it out of every Space
8103
- * with null. In a Space it is a child of the Space's Lead, and its work is
8104
- * in the Lead's tree. Out of one it is a root again. Its child agents move
8105
- * with it. It gets a private Space's visibility, on its work and on its own
8106
- * Location. The caller checks who may move it out of `fromSpaceId`, the
8107
- * Space that it read before the move.
8132
+ * Put one public `thread`, a root or a Lead's child, in a public Space, or
8133
+ * take it out of its Space with null. In a Space it is a child of the Lead
8134
+ * and, like every child, stores its parent's Destination and Location, so a
8135
+ * Slack thread no longer gets its replies. Out of one it is a root again,
8136
+ * with its own Destination. Its child agents move with it. The caller checks
8137
+ * who may move it out of `fromSpaceId`, the Space that it read before the
8138
+ * move.
8108
8139
  */
8109
8140
  async function setConversationSpace(conversationId, target, fromSpaceId) {
8110
8141
  const executor = getSqlExecutor();
8111
- return await executor.transaction(async () => {
8142
+ return await withConversationMutationLock(executor, conversationId, async () => {
8112
8143
  const db = executor.db();
8113
- const [root] = await db.select({
8114
- locationId: juniorConversations.destinationId,
8115
- provider: juniorDestinations.provider,
8144
+ const [moving] = await db.select({
8116
8145
  spaceId: rootSpaceIdSql(juniorConversations),
8117
8146
  visibility: juniorConversations.visibility
8118
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(eq(juniorConversations.conversationId, conversationId), eq(juniorConversations.kind, "thread"), topLevelConversation())).limit(1).for("update", { of: juniorConversations });
8119
- if (!root) return "not_found";
8120
- const currentSpaceId = root.spaceId;
8121
- if (currentSpaceId !== fromSpaceId) return "moved";
8122
- const spaceIds = [currentSpaceId, target?.spaceId].filter((id) => typeof id === "string");
8123
- const spaces = spaceIds.length > 0 ? await db.select({
8124
- id: juniorConversations.spaceId,
8125
- visibility: juniorConversations.visibility
8126
- }).from(juniorConversations).where(and(eq(juniorConversations.kind, "lead"), inArray(juniorConversations.spaceId, spaceIds))) : [];
8127
- if (spaces.find((space) => space.id === currentSpaceId)?.visibility === "private") return "leaves_private";
8128
- const space = spaces.find((space) => space.id === target?.spaceId);
8129
- if (space?.visibility === "public" && root.visibility !== "public") return "private_into_public";
8130
- const work = inArray(juniorConversations.conversationId, sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`);
8131
- if (space?.visibility === "private") {
8132
- if (root.provider !== "local" || !root.locationId) return "shared_location";
8133
- await db.update(juniorDestinations).set({
8134
- visibility: "private",
8135
- updatedAt: /* @__PURE__ */ new Date()
8136
- }).where(eq(juniorDestinations.id, root.locationId));
8137
- await setMovedWorkVisibility(executor, conversationId, "private");
8138
- }
8147
+ }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, conversationId), eq(juniorConversations.kind, "thread"), or(isNull(juniorConversations.parentConversationId), isLeadSql(juniorConversations.parentConversationId)))).limit(1);
8148
+ if (!moving) return "not_found";
8149
+ if (moving.spaceId !== fromSpaceId) return "moved";
8150
+ if (moving.visibility !== "public") return "private";
8151
+ let place;
8152
+ if (target) {
8153
+ const [lead] = await db.select({
8154
+ destinationId: juniorConversations.destinationId,
8155
+ location: juniorConversations.location,
8156
+ visibility: juniorConversations.visibility
8157
+ }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, target.leadConversationId), eq(juniorConversations.kind, "lead"), eq(juniorConversations.spaceId, target.spaceId)));
8158
+ if (!lead) return "not_found";
8159
+ if (lead.visibility !== "public") return "private_space";
8160
+ place = lead;
8161
+ } else place = {
8162
+ destinationId: (await upsertDestination(executor, destinationUpsertFromDestination({
8163
+ conversationId,
8164
+ destination: ownLocalDestination(conversationId),
8165
+ visibility: "public"
8166
+ }), Date.now()))?.id ?? null,
8167
+ location: null
8168
+ };
8139
8169
  await db.update(juniorConversations).set({
8140
8170
  rootConversationId: target?.leadConversationId ?? conversationId,
8171
+ destinationId: place.destinationId,
8172
+ location: place.location,
8141
8173
  detailVersion: nextDetailVersion
8142
- }).where(work);
8174
+ }).where(inArray(juniorConversations.conversationId, sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`));
8143
8175
  await db.update(juniorConversations).set({
8144
8176
  parentConversationId: target?.leadConversationId ?? null,
8145
8177
  ...target ? { agentConfig: sql`coalesce(${juniorConversations.agentConfig}, '{}'::jsonb)` } : void 0,
@@ -8160,11 +8192,10 @@ async function requireSpaceForWork(viewer, spaceId) {
8160
8192
  return space;
8161
8193
  }
8162
8194
  /**
8163
- * Put one tree root in a Space, as a child of the Space's Lead, or make it a
8164
- * one-off root with null. Only a participant moves it. They must be a member
8165
- * of the Space that it leaves and of the Space that it joins. Only a public
8166
- * Conversation joins a Space. One in a private Space stays there, so its
8167
- * data stays with the members.
8195
+ * Put one Conversation in a Space, as a child of the Space's Lead, or make it
8196
+ * a one-off root with null. Only a participant moves it. They must be a
8197
+ * member of the Space that it leaves and of the Space that it joins. Only
8198
+ * public work moves, and only into a public Space.
8168
8199
  */
8169
8200
  async function setConversationSpaceForViewer(viewer, conversationId, body) {
8170
8201
  const [conversation, access] = await Promise.all([getConversationStore().get({ conversationId }), readConversationAccessFromSql(getDb(), [conversationId], viewer).then((byId) => byId.get(conversationId))]);
@@ -8181,7 +8212,6 @@ async function setConversationSpaceForViewer(viewer, conversationId, body) {
8181
8212
  const source = await readSpace(viewer.id, currentSpaceId);
8182
8213
  if (source && !source.viewerIsMember) throwApiError(403, "Join the Space that it is in to move it.");
8183
8214
  }
8184
- if (target && access.visibility !== "public") throwApiError(409, "Only a public conversation can join a Space.");
8185
8215
  const lead = target ? await getSpaceLead(target.id) : void 0;
8186
8216
  const refusal = await setConversationSpace(conversationId, target && lead ? {
8187
8217
  leadConversationId: lead.conversationId,
@@ -8189,9 +8219,8 @@ async function setConversationSpaceForViewer(viewer, conversationId, body) {
8189
8219
  } : null, currentSpaceId);
8190
8220
  if (refusal === "not_found") throwApiError(404, "Conversation not found.");
8191
8221
  if (refusal === "moved") throwApiError(409, "It moved to another Space. Reload and try again.");
8192
- if (refusal === "leaves_private") throwApiError(409, "A conversation in a private Space stays in it.");
8193
- if (refusal === "private_into_public") throwApiError(409, "Only a public conversation can join a Space.");
8194
- if (refusal === "shared_location") throwApiError(409, "A Slack conversation can't join a private Space.");
8222
+ if (refusal === "private") throwApiError(409, "Only a public conversation can move.");
8223
+ if (refusal === "private_space") throwApiError(409, "A conversation can't move into a private Space.");
8195
8224
  return response;
8196
8225
  }
8197
8226
  // src/chat/tools/move-conversation-to-space.ts
@@ -9577,8 +9606,8 @@ async function reportConversationRead(viewer, conversationId, body) {
9577
9606
  /**
9578
9607
  * Archive or restore one Conversation, root or child, for everyone. Archive
9579
9608
  * refuses while any descendant is unarchived, unless `applyToChildren`
9580
- * archives them too, and when the Conversation has activity after
9581
- * `lastSeenAt`. Without `lastSeenAt`, archive does not check activity.
9609
+ * archives them too, and when the unarchived Conversation has activity
9610
+ * after `lastSeenAt`. Without `lastSeenAt`, archive does not check activity.
9582
9611
  * Restore changes only this Conversation unless
9583
9612
  * `applyToChildren` also restores the descendants archived with it, and it
9584
9613
  * refuses while an ancestor is archived. A restore of a root by `userId`
@@ -9598,7 +9627,7 @@ async function setConversationArchive(args) {
9598
9627
  const tree = await readConversationTrees(db, [rootConversationId]);
9599
9628
  const descendants = conversationDescendants(tree, args.conversationId);
9600
9629
  if (args.archived) {
9601
- if (args.lastSeenAt !== void 0 && target.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
9630
+ if (!target.archivedAt && args.lastSeenAt !== void 0 && target.lastActivityAt.getTime() !== Date.parse(args.lastSeenAt)) return { status: "conflict" };
9602
9631
  const unarchived = descendants.filter((node) => !node.archivedAt);
9603
9632
  if (unarchived.length > 0 && !args.applyToChildren) return {
9604
9633
  status: "unarchived_children",
@@ -9823,7 +9852,7 @@ const messageAgentOutputSchema = juniorToolOutputSchema.extend({
9823
9852
  const messageAgentToolDefinition = zodToolDefinition({
9824
9853
  description: `Send a message to your parent agent or to a child agent that this conversation started. Use it to give an existing child agent more work, an answer, or a correction, and to send your parent agent a finding or a question while you keep working. A message to a child continues its history. If the child is still working, it reads the message at its next step or after its current work. A child replies when it has something to report. Its reply arrives later as a new task in this conversation; do not wait or poll for it. Make sure people know what is going on, but post only updates that matter to them. A message to your parent does not end your task. A top-level agent (its conversation is not a child agent, such as a Slack thread) can also message another top-level agent. Both conversations must be public, or both must be private conversations in the same place, such as one private channel or DM. The target runs the message as its own task and sends no result. It does not start a new agent.`,
9825
9854
  exposure: "modelOnly",
9826
- approvalMode: "auto",
9855
+ executionMode: "sequential",
9827
9856
  annotations: {
9828
9857
  destructiveHint: false,
9829
9858
  idempotentHint: true,
@@ -11795,7 +11824,6 @@ function createListWorkspacesTool(workspaces) {
11795
11824
  // src/chat/workspaces/tools/switch.ts
11796
11825
  /** Record optional reporting without changing the switchWorkspace outcome. */
11797
11826
  async function tryRecordWorkspaceSwitchStat(workspace) {
11798
- if (!process.env["DATABASE_URL"]) return;
11799
11827
  try {
11800
11828
  await incrementStat({
11801
11829
  namespace: "junior",
@@ -14631,7 +14659,7 @@ function createCacheWarmingRecorder(conversationId, turn, definitionsKey) {
14631
14659
  }
14632
14660
  // src/chat/runtime/dev-agent-trace.ts
14633
14661
  function shouldEmitDevAgentTrace() {
14634
- return process.env["NODE_ENV"] === "development";
14662
+ return getChatConfig().development.enabled;
14635
14663
  }
14636
14664
  // src/chat/services/provider-retry.ts
14637
14665
  const PROVIDER_RETRY_DELAYS_MS = [
@@ -20832,17 +20860,13 @@ function createToolPipeline(options) {
20832
20860
  const { error } = review;
20833
20861
  if (error instanceof ToolActionRejectedError) setSpanAttributes({
20834
20862
  "app.guardian.decision": error.decision,
20835
- ...error.riskLevel ? { "app.guardian.risk_level": error.riskLevel } : void 0,
20836
- ...error.rule ? { "app.guardian.rule": error.rule } : void 0,
20837
- ...error.userAuthorization ? { "app.guardian.user_consent": error.userAuthorization } : void 0
20863
+ ...error.rule ? { "app.guardian.rule": error.rule } : void 0
20838
20864
  });
20839
20865
  throw error;
20840
20866
  }
20841
20867
  if (review.decision) setSpanAttributes({
20842
20868
  "app.guardian.decision": review.decision.decision,
20843
- "app.guardian.risk_level": review.decision.riskLevel,
20844
- ...review.decision.rule ? { "app.guardian.rule": review.decision.rule } : void 0,
20845
- "app.guardian.user_consent": review.decision.userAuthorization
20869
+ ...review.decision.rule ? { "app.guardian.rule": review.decision.rule } : void 0
20846
20870
  });
20847
20871
  const sandboxInput = buildSandboxInput(toolName, executionInput);
20848
20872
  const isSandbox = Boolean(sandboxTools?.supports(toolName));
@@ -22005,6 +22029,54 @@ function createGuardianActionReviewer(options) {
22005
22029
  };
22006
22030
  } };
22007
22031
  }
22032
+ // src/chat/guardian/current.ts
22033
+ /**
22034
+ * The current Guardian behind the `Guardian` interface.
22035
+ *
22036
+ * It sends each action of the request to the model reviewer with the
22037
+ * proposal that the gate built for it, and keeps the reviewer's decision
22038
+ * and reason. The proposal holds the evidence that its prompt reads and
22039
+ * the request does not carry, such as recent tool calls and the credential,
22040
+ * so its decisions stay the same.
22041
+ */
22042
+ /** Most reviews of one batch that run at the same time. */
22043
+ const MAX_CONCURRENT_REVIEWS = 4;
22044
+ /** The rule of the interface that each rule of the current policy names. */
22045
+ const RULES = {
22046
+ withheld_step: "unrequested",
22047
+ unresolved_prior_ask: "unrequested",
22048
+ unclear_destination: "unrequested",
22049
+ different_change: "unrequested",
22050
+ unrequested_write: "unrequested",
22051
+ new_commitment: "unrequested",
22052
+ high_risk_low_authorization: "unrequested",
22053
+ data_exposure: "data_exposure",
22054
+ credential_probing: "credential_probing",
22055
+ security_weakening: "security_weakening",
22056
+ unrequested_destruction: "unrequested",
22057
+ untrusted_instruction: "untrusted_instruction",
22058
+ revoked_approval: "restriction",
22059
+ out_of_scope: "unrequested"
22060
+ };
22061
+ function isBlockRule(rule) {
22062
+ return Object.hasOwn(RULES, rule);
22063
+ }
22064
+ /** Create the current Guardian for one batch over one model reviewer. */
22065
+ function createCurrentGuardian(reviewer, batch) {
22066
+ return { async review(request, signal) {
22067
+ if (request.actions.length !== batch.proposals.length) throw new Error("Each action needs the proposal that the gate built.");
22068
+ return await mapBounded(batch.proposals, async (proposal) => {
22069
+ const review = await reviewer.review(proposal, { signal });
22070
+ const rule = review.rule && isBlockRule(review.rule) ? RULES[review.rule] : void 0;
22071
+ return {
22072
+ decision: review.decision,
22073
+ ...rule ? { rule } : void 0,
22074
+ reason: review.reason,
22075
+ ...review.costUsd !== void 0 ? { costUsd: review.costUsd } : void 0
22076
+ };
22077
+ }, MAX_CONCURRENT_REVIEWS);
22078
+ } };
22079
+ }
22008
22080
  // src/chat/guardian/evidence.ts
22009
22081
  const MAX_MESSAGE_TRANSCRIPT_TOKENS = 1e4;
22010
22082
  const MAX_TOOL_TRANSCRIPT_TOKENS = 1e4;
@@ -22473,7 +22545,6 @@ function createPromptHookContext(args) {
22473
22545
  }
22474
22546
  /** Record optional reporting without changing the loadSkill outcome. */
22475
22547
  async function tryRecordSkillLoadStat(skill) {
22476
- if (!process.env["DATABASE_URL"]) return;
22477
22548
  try {
22478
22549
  await incrementStat({
22479
22550
  namespace: skill.pluginProvider ?? "junior",
@@ -22611,7 +22682,7 @@ async function wireAgentTools(args) {
22611
22682
  surface: args.surface,
22612
22683
  ...args.run.actorIsApp ? { actorIsApp: true } : void 0,
22613
22684
  ...args.currentActor ? { resolveActorIdentity: async () => await readActorIdentity(args.currentActor) } : void 0,
22614
- ...bindTurnTools(args.run, args.behavior, args.topLevelWork)
22685
+ ...bindTurnTools(args.run, args.behavior)
22615
22686
  };
22616
22687
  const toolRoute = resolveToolRuntimeRoute({
22617
22688
  actor: args.currentActor,
@@ -22627,6 +22698,11 @@ async function wireAgentTools(args) {
22627
22698
  switch: agentSandbox.switchWorkspace
22628
22699
  }
22629
22700
  };
22701
+ const reviewer = createGuardianActionReviewer({
22702
+ completeObject,
22703
+ destinationFacts: guardianPluginFacts(pluginCatalogRuntime.getProviders().map(({ manifest }) => manifest)),
22704
+ modelId: botConfig.guardianModelId
22705
+ });
22630
22706
  const actionReview = createToolActionReview({
22631
22707
  context: {
22632
22708
  actor: args.currentActor,
@@ -22649,16 +22725,12 @@ async function wireAgentTools(args) {
22649
22725
  toolName,
22650
22726
  costUsd: decision.costUsd,
22651
22727
  decision: decision.decision,
22652
- riskLevel: decision.riskLevel,
22653
- userAuthorization: decision.userAuthorization
22728
+ rule: decision.rule,
22729
+ reason: decision.reason
22654
22730
  }),
22655
22731
  onFatal: args.onFatalToolError,
22656
22732
  priorRejections: restoreToolActionRejections(args.currentTurnMessages),
22657
- reviewer: createGuardianActionReviewer({
22658
- completeObject,
22659
- destinationFacts: guardianPluginFacts(pluginCatalogRuntime.getProviders().map(({ manifest }) => manifest)),
22660
- modelId: botConfig.guardianModelId
22661
- })
22733
+ guardian: (batch) => createCurrentGuardian(reviewer, batch)
22662
22734
  });
22663
22735
  const tools = createTools(loadableSkills(args.availableSkills, [...args.invokedSkillNames, ...args.conversationSkillNames]), {
22664
22736
  writeGeneratedFiles: async (files) => {
@@ -22791,7 +22863,7 @@ async function wireAgentTools(args) {
22791
22863
  * tool list. `createTools` disables each listed tool that the Turn cannot
22792
22864
  * use.
22793
22865
  */
22794
- function bindTurnTools(run, behavior, topLevelWork) {
22866
+ function bindTurnTools(run, behavior) {
22795
22867
  const listedTools = promptModeTurnTools(behavior.promptMode);
22796
22868
  return {
22797
22869
  turnTools: run.dispatch?.outcomes?.length === 0 ? {
@@ -22799,14 +22871,14 @@ function bindTurnTools(run, behavior, topLevelWork) {
22799
22871
  reply: false
22800
22872
  } : behavior.tools,
22801
22873
  listedTools,
22802
- ...bindAgentTools(run, listedTools.agents, topLevelWork)
22874
+ ...bindAgentTools(run, listedTools.agents)
22803
22875
  };
22804
22876
  }
22805
22877
  /** Bind the agent tools that the Turn lists. */
22806
- function bindAgentTools(run, agents, topLevelWork) {
22878
+ function bindAgentTools(run, agents) {
22807
22879
  const { bindSpawnAgent, bindMessageAgent } = run.environment ?? {};
22808
22880
  if (!bindSpawnAgent) return {};
22809
- const spawnAgent = agents === "children" || topLevelWork || botConfig.maxAgentDepth > 0 ? bindSpawnAgent(run) : void 0;
22881
+ const spawnAgent = agents === "children" || botConfig.maxAgentDepth > 0 ? bindSpawnAgent(run) : void 0;
22810
22882
  const messageAgent = spawnAgent || agents === "children_and_parent" ? bindMessageAgent?.(run, agents) : void 0;
22811
22883
  return {
22812
22884
  ...spawnAgent ? { spawnAgent } : void 0,
@@ -23185,8 +23257,7 @@ async function executeAgentRun(run, streamFn) {
23185
23257
  };
23186
23258
  return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, async () => reportFailedRun(await executeAgentRunInPrivacyContext(run, {
23187
23259
  kind: run.dispatch?.declaresResult ? "automation" : conversation?.kind ?? "thread",
23188
- hasParent: Boolean(conversation?.parentConversationId),
23189
- topLevelWork: conversation ? isTopLevelWork(conversation) : true
23260
+ hasParent: Boolean(conversation?.parentConversationId)
23190
23261
  }, conversationPrivacy, runLogContext, streamFn), run.signal)));
23191
23262
  }
23192
23263
  function reportFailedRun(outcome, signal) {
@@ -23458,7 +23529,6 @@ async function executeAgentRunInPrivacyContext(run, storedConversation, conversa
23458
23529
  const wiring = await wireAgentTools({
23459
23530
  abortAgent: () => agent?.abort(),
23460
23531
  behavior,
23461
- topLevelWork: storedConversation.topLevelWork,
23462
23532
  currentActor: actor,
23463
23533
  currentAgentMessages,
23464
23534
  currentTurnMessages,
@@ -24132,7 +24202,7 @@ function createAgentRunner(execute, options) {
24132
24202
  }
24133
24203
  };
24134
24204
  const loadStoredAttachments = async (attachments) => {
24135
- const { loadInputAttachments } = await import("./model-input-BReSnwHp.js").then((n) => n.i);
24205
+ const { loadInputAttachments } = await import("./model-input-CFC62mf-.js").then((n) => n.i);
24136
24206
  const storage = nextRun.environment?.attachmentStorage;
24137
24207
  if (!storage) throw new Error("Attachment storage is unavailable.");
24138
24208
  return await loadInputAttachments({
@@ -24156,4 +24226,4 @@ function createAgentRunner(execute, options) {
24156
24226
  return await execute(nextRun, streamFn);
24157
24227
  } };
24158
24228
  }
24159
- export { requireSpaceForWork as $, AutomationEditError as $t, vercelBackgroundCompactionQueue as A, parseSlackThreadId as At, archiveConversation as B, deleteViewerTask as Bt, CONVERSATION_STATE_TTL_MS as C, setConversationSubscription as Ct, isConversationWorkDone as D, renderAttachmentText as Dt, segmentGapsKey as E, throwApiError as Et, AgentMessageTargetError as F, unpublishedArtifactHeaders as Ft, reportConversationRead as G, collectionRowTitle as Gt, stopArchivedWork as H, takeViewerAutomationAlertStep as Ht, AgentNameInUseError as I, createPluginConversationWatches as It, stopChildAgentsOf as J, readViewerAutomationRuns as Jt, stopConversation as K, readConversationSourceTask as Kt, AgentStoppedError as L, readConversationAutomationRun as Lt, measureTurnCompactionWait as M, resolveSlackChannelIdFromMessage as Mt, createVercelCacheWarmupCallback as N, publicArtifactHeaders as Nt, listConversationWork as O, renderBlockText as Ot, AgentDepthLimitError as P, readPublicArtifact as Pt, listOwnedWatches as Q, automationCardStatus as Qt, ChildAgentLimitError as R, activateViewerAutomationVersion as Rt, ANSWER_TOOL_ENDINGS as S, resolveConversationConfiguration as Sn, leaveConversation as St, GLOBAL_GAPS_TTL_MS as T, jsonResponse as Tt, conversationReadPositionQuery as U, updateViewerAutomation as Ut, setConversationArchive as V, readViewerAutomationEdit as Vt, markConversationRead as W, ViewerTaskNotFoundError as Wt, inboxItemChangeRecord as X, readViewerAutomationVersions as Xt, deliverInboxItemChange as Y, readViewerAutomationSummary as Yt, renderInboxItemMessage as Z, readViewerAutomations as Zt, normalizeToolResult as _, IDLE_HORIZON_MS as _n, createAttachmentUpload as _t, getMcpOAuthCallbackPath as a, addHistoryPeriod as an, readSpace as at, actorFromRun as b, NO_REPLY_GAP_MS as bn, setConversationTitle as bt, buildSandboxInput as c, historyPeriodSavings as cn, acceptsWebMessages as ct, logScheduledAutomationRunSkipped as d, addStats as dn, createAndEnqueueConversation as dt, findAutomationSkill as en, setConversationSpaceForViewer as et, scheduledAutomationRunAttributes as f, readStats as fn, createConversationId as ft, createAgentSandbox as g, providerCacheTtlMs as gn, collectAttachmentUploadGarbage as gt, previewOriginBelongsTo as h, connectedState as hn, AttachmentUploadError as ht, finalizeMcpAuthorization as i, SAVINGS_NAMESPACE as in, listSpaces as it, verifyBackgroundCompactionMessage as j, readSlackRawMessageContext as jt, processBackgroundCompaction as k, parseSlackMessageReference as kt, latestProgressStatus as l, replaceHistorySavings as ln, appendAndEnqueueWebMessage as lt, readAttachmentContent as m, closeBreaker as mn, webActorFromUser as mt, executeAgentRun as n, effectiveTaskOutcomes as nn, getSpaceLead as nt, createClientMetadata as o, addHistoryWarmupCost as on, updateSpace as ot, AttachmentDownloadError as p, breakerStates as pn, recordWebConversationActivity as pt, stopConversationAndChildAgents as q, readViewerAutomationExecutions as qt, buildAuthPauseResponse as r, viewerAutomationCollection as rn, createSpace as rt, readMcpClientInformation as s, firstLiveSavingsDate as sn, writeLegacySpaceArchive as st, createAgentRunner as t, missingAutomationSkillReason as tn, readSpaceRefs as tt, resolveDestinationVisibility as u, savingsTotals as un, conversationTurnIdForMessage as ut, capToolResult as v, MINUTE_MS$1 as vn, verifyAttachmentUploads as vt, GLOBAL_GAPS_MAX as w, emptyResponse as wt, shouldEmitDevAgentTrace as x, gapSegment as xn, inviteToConversation as xt, RetryableDeliveryError as y, MIN_WARMUP_PREFIX_TOKENS as yn, writeAttachmentUpload as yt, readLastUserMessageAtByConversation as z, changeViewerAutomationLifecycle as zt };
24229
+ export { requireSpaceForWork as $, AutomationEditError as $t, vercelBackgroundCompactionQueue as A, parseSlackThreadId as At, archiveConversation as B, deleteViewerTask as Bt, CONVERSATION_STATE_TTL_MS as C, setConversationSubscription as Ct, isConversationWorkDone as D, renderAttachmentText as Dt, segmentGapsKey as E, throwApiError as Et, AgentMessageTargetError as F, unpublishedArtifactHeaders as Ft, reportConversationRead as G, collectionRowTitle as Gt, stopArchivedWork as H, takeViewerAutomationAlertStep as Ht, AgentNameInUseError as I, createPluginConversationWatches as It, stopChildAgentsOf as J, readViewerAutomationRuns as Jt, stopConversation as K, readConversationSourceTask as Kt, AgentStoppedError as L, readConversationAutomationRun as Lt, measureTurnCompactionWait as M, resolveSlackChannelIdFromMessage as Mt, createVercelCacheWarmupCallback as N, publicArtifactHeaders as Nt, listConversationWork as O, renderBlockText as Ot, AgentDepthLimitError as P, readPublicArtifact as Pt, listOwnedWatches as Q, automationCardStatus as Qt, ChildAgentLimitError as R, activateViewerAutomationVersion as Rt, ANSWER_TOOL_ENDINGS as S, resolveConversationConfiguration as Sn, leaveConversation as St, GLOBAL_GAPS_TTL_MS as T, jsonResponse as Tt, conversationReadPositionQuery as U, updateViewerAutomation as Ut, setConversationArchive as V, readViewerAutomationEdit as Vt, markConversationRead as W, ViewerTaskNotFoundError as Wt, inboxItemChangeRecord as X, readViewerAutomationVersions as Xt, deliverInboxItemChange as Y, readViewerAutomationSummary as Yt, renderInboxItemMessage as Z, readViewerAutomations as Zt, normalizeToolResult as _, IDLE_HORIZON_MS as _n, createAttachmentUpload as _t, getMcpOAuthCallbackPath as a, addHistoryPeriod as an, readSpace as at, actorFromRun as b, NO_REPLY_GAP_MS as bn, setConversationTitle as bt, buildSandboxInput as c, historyPeriodSavings as cn, appendAndEnqueueWebMessage as ct, logScheduledAutomationRunSkipped as d, addStats as dn, createConversationId as dt, findAutomationSkill as en, setConversationSpaceForViewer as et, scheduledAutomationRunAttributes as f, readStats as fn, recordWebConversationActivity as ft, createAgentSandbox as g, providerCacheTtlMs as gn, collectAttachmentUploadGarbage as gt, previewOriginBelongsTo as h, connectedState as hn, AttachmentUploadError as ht, finalizeMcpAuthorization as i, SAVINGS_NAMESPACE as in, listSpaces as it, verifyBackgroundCompactionMessage as j, readSlackRawMessageContext as jt, processBackgroundCompaction as k, parseSlackMessageReference as kt, latestProgressStatus as l, replaceHistorySavings as ln, conversationTurnIdForMessage as lt, readAttachmentContent as m, closeBreaker as mn, resolveConversationDestination as mt, executeAgentRun as n, effectiveTaskOutcomes as nn, getSpaceLead as nt, createClientMetadata as o, addHistoryWarmupCost as on, updateSpace as ot, AttachmentDownloadError as p, breakerStates as pn, webActorFromUser as pt, stopConversationAndChildAgents as q, readViewerAutomationExecutions as qt, buildAuthPauseResponse as r, viewerAutomationCollection as rn, createSpace as rt, readMcpClientInformation as s, firstLiveSavingsDate as sn, acceptsWebMessages as st, createAgentRunner as t, missingAutomationSkillReason as tn, readSpaceRefs as tt, resolveDestinationVisibility as u, savingsTotals as un, createAndEnqueueConversation as ut, capToolResult as v, MINUTE_MS$1 as vn, verifyAttachmentUploads as vt, GLOBAL_GAPS_MAX as w, emptyResponse as wt, shouldEmitDevAgentTrace as x, gapSegment as xn, inviteToConversation as xt, RetryableDeliveryError as y, MIN_WARMUP_PREFIX_TOKENS as yn, writeAttachmentUpload as yt, readLastUserMessageAtByConversation as z, changeViewerAutomationLifecycle as zt };