@sentry/junior 0.306.0 → 0.307.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 (91) hide show
  1. package/dist/{adapter-context-CnY-i32r.js → adapter-context-B69WPn6b.js} +2 -2
  2. package/dist/{admin-BLLdLnXh.js → admin-nCJXMgkp.js} +2 -2
  3. package/dist/{agent-runner-BaLjEjPR.js → agent-runner-DdFcxAxG.js} +226 -137
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -4
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +328 -298
  8. package/dist/{app-DvYbM9UD.d.ts → app-EZur8cVC.d.ts} +12 -3
  9. package/dist/app.d.ts +2 -2
  10. package/dist/app.js +84 -44
  11. package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
  12. package/dist/{briefs-DvyzXfrF.js → briefs-Dl9lxi7J.js} +2 -2
  13. package/dist/{catalog-runtime-B1R-nHd3.js → catalog-runtime-OXrv2Ewn.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +17 -16
  16. package/dist/cli/check.js +58 -48
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.d.ts +1 -1
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +2 -2
  22. package/dist/cli/upgrade.js +3 -8
  23. package/dist/{config-DUD-zMvp.js → config-362yMSIz.js} +74 -38
  24. package/dist/{connections-CDhsqPcC.js → connections-BJv3EjmB.js} +10 -8
  25. package/dist/{continue-in-slack-BXQizz9o.js → continue-in-slack-CFEevC7z.js} +5 -5
  26. package/dist/{conversation-privacy-YE54gMN8.js → conversation-privacy-Tjj5P2W6.js} +1 -1
  27. package/dist/{conversation-turn-BzdmrHb0.js → conversation-turn-DU0_WDAr.js} +19 -47
  28. package/dist/{credential-sync-Cdm-e1vJ.js → credential-sync-D6aFARKE.js} +28 -28
  29. package/dist/{db-DV2ZUb1Y.js → db-Bcbd9zQc.js} +140 -11
  30. package/dist/{db-pH357Dkt.d.ts → db-C41UgdBj.d.ts} +1 -1
  31. package/dist/{executor-CjNhwwnj.js → executor-DBMBrpNV.js} +93 -32
  32. package/dist/{install-DbD7C5td.js → install-CgoAbzfF.js} +2 -2
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{lineage-BFdIPb3o.js → lineage-CsZDmz3e.js} +2 -2
  35. package/dist/{logging-oYpJYr-S.js → logging-CHCuQ5iz.js} +1 -1
  36. package/dist/{message-BBPcMKJY.js → message-B8vCbZZB.js} +8 -8
  37. package/dist/{model-input-DYYF3a8B.js → model-input-Xluiy-1W.js} +3 -3
  38. package/dist/nitro.d.ts +2 -2
  39. package/dist/nitro.js +3 -4
  40. package/dist/{oauth-callback-server-C7Q987su.js → oauth-callback-server-BUuNvfvu.js} +2 -2
  41. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
  42. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  43. package/dist/{projection-CWXDE0f6.js → projection-xPpvqexa.js} +1112 -693
  44. package/dist/{prompt-P3eRqO8C.js → prompt-D8u4jFs_.js} +3 -3
  45. package/dist/{registry-1pzXmplY.js → registry-D20hG3r6.js} +19 -9
  46. package/dist/{resolve-n87oXY-d.js → resolve-BhCySRCW.js} +3 -3
  47. package/dist/{result-BmF9v9bv.js → result-DddO63S9.js} +13 -11
  48. package/dist/{runner-4j7ZsxP5.js → runner-DQR9vYce.js} +9 -9
  49. package/dist/{sandbox-egress-signals-BRQI8HvT.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
  50. package/dist/{schedule-CHPWQn-x.js → schedule-BG1tEbRF.js} +34 -4
  51. package/dist/{schema-CVbIjrF3.d.ts → schema-CRXcj4fj.d.ts} +350 -143
  52. package/dist/{schema-D7iIEh6t.js → schema-D4jdesIu.js} +12 -4
  53. package/dist/{service-account-DzQiOmqa.js → service-account-Bv5QwrEq.js} +8 -6
  54. package/dist/{service-account-BDQ9xzta.js → service-account-CNfycv0z.js} +3 -3
  55. package/dist/{session-stop-BQxgHR4X.js → session-stop-BDdwyZaa.js} +36 -23
  56. package/dist/{skills-CPf4vNuC.js → skills-63i1Bcv1.js} +32 -28
  57. package/dist/{slack-conversation-unfurl-B1KEptUg.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -10
  58. package/dist/{spawn-CjGddiAU.js → spawn-mwimEY9_.js} +6 -6
  59. package/dist/{state-9wfj6aSD.js → state-BBn9L6gC.js} +4 -4
  60. package/dist/{stop-CsQGuN5n.js → stop-Da-Ug7tg.js} +146 -158
  61. package/dist/{store-Dz3YZ7gQ.js → store-CdWg2r2L.js} +5 -5
  62. package/dist/{background-compaction-queue-D2wzxtGU.js → task-queue-BcjAYWyB.js} +164 -180
  63. package/dist/{task-runner-frzlUvFD.js → task-runner-CoXmMlsW.js} +11 -8
  64. package/dist/{thread-context-C4QuZlM8.js → thread-context-ZPGqOjW7.js} +6 -6
  65. package/dist/{turn-session-routing-BXaubz2w.js → turn-session-routing-DFYak28Q.js} +24 -5
  66. package/dist/{turn-user-message-DNC0eRZ7.js → turn-user-message-B1S8nOnG.js} +3 -3
  67. package/dist/{users-XCCKn3xW.js → users-DDbENg-I.js} +1 -1
  68. package/dist/{validation-L5fdjmFX.js → validation-fl21ps-k.js} +1 -1
  69. package/dist/{version-BFmuwgxP.js → version-DCdMMx_0.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-DKOeHpv3.js → viewer-DN_xzVKj.js} +3 -3
  72. package/dist/{warmup-mTMIatCV.js → warmup-CxhEhm71.js} +596 -281
  73. package/dist/{web-message-id-CUaSiGme.js → web-message-id-BT8Mg8LL.js} +1 -1
  74. package/dist/{worker-Bz4KNxjI.js → worker-Btb1SB5h.js} +8 -7
  75. package/migrations/0115_automation_creator_slack_index.sql +1 -0
  76. package/migrations/0116_conversation_event_search.sql +25 -0
  77. package/migrations/0117_automation_last_run.sql +46 -0
  78. package/migrations/0118_automation_last_run_index.sql +1 -0
  79. package/migrations/0119_money_micro_usd.sql +29 -0
  80. package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
  81. package/migrations/meta/0115_snapshot.json +5225 -0
  82. package/migrations/meta/0116_snapshot.json +5388 -0
  83. package/migrations/meta/0117_snapshot.json +5413 -0
  84. package/migrations/meta/0118_snapshot.json +5428 -0
  85. package/migrations/meta/0119_snapshot.json +5441 -0
  86. package/migrations/meta/0120_snapshot.json +5441 -0
  87. package/migrations/meta/_journal.json +42 -0
  88. package/package.json +10 -9
  89. package/dist/queue-7FSijgqG.js +0 -115
  90. package/dist/secrets-DHaJ5TTn.js +0 -18
  91. package/dist/task-queue-CFlrJguF.js +0 -89
@@ -1,31 +1,33 @@
1
- import { $c as historyItemFromPiMessage, $i as wrapSandboxSetupError, Ac as ToolInputError, An as isToolResultMessage, As as createScheduledAutomation, B as PluginCredentialFailureError, Bi as isRetryableSandboxFailure, Bn as createUserTokenStore, Ca as SANDBOX_WORKSPACE_ROOT, Cr as getReviewItem, Cs as normalizeSlackReplyMarkdown, Da as buildCommandScript, Dn as isContinuablePiBoundary, Ea as sandboxSkillPathResolution, En as isAssistantMessage, F as calculateContextCompactionTargetTokens, Fn as CAPABILITY_SECTION_TAG, Fs as saveScheduledAutomation, G as AuthorizationPauseError, H as authorizationId, I as getAgentBackgroundCompactionMarkTokens, Ii as hash, In as REQUEST_CONTEXT_SECTION_TAG, Jc as credentialAuditAttributes, Ji as SandboxCallTimeoutError, Jt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, K as abandonReplacedPendingAuth, Ki as resolveBaseUrl, Kn as createPluginHookRunner, Ko as addReactionToMessage, L as getAgentContextCompactionTriggerTokens, Mn as retainRuntimeTurnContext, Nn as stripRuntimeTurnContext, Oa as buildNonInteractiveShellScript, Oc as automationRevision, On as isStandaloneRuntimeContextMessage, Pn as trimTrailingAssistantMessages, Ps as readScheduledAutomation, Qi as throwSandboxOperationError, Qo as postSlackMessage, Qs as createEventAutomation, Qt as TurnToolCallLimitExceededError, R as getAgentContextInputLimitTokens, Ri as ensureDockerDaemon, Rn as TURN_CONTEXT_TAG, Sa as SANDBOX_SKILLS_ROOT, Si as renderToolResultNudge, Sn as getUserMessageInstructionText, Ta as sandboxSkillFile, Ti as getWorkspace, U as AuthPausePersistenceError, Uc as resolveTaskTitle, Ui as deliverOAuthAuthorization, Us as getDashboardReviewItemLink, V as createPluginAuthOrchestration, W as AuthorizationFlowDisabledError, Wi as formatProviderLabel, X as continuableMessages, Xr as resolveChannelCapabilities, Xt as TurnBudgetExceededError, Yc as credentialAuditSource, Yi as findInErrorChain, Yt as TURN_LIMIT_WRAP_UP_MESSAGE, Z as loadTurnCheckpoint, Zi as isAlreadyExistsError, Zn as getPluginTools, Zr as getSlackToolContext, Zt as TurnSliceLimitExceededError, _n as readBlockedReport, _o as createConversationEmbedder, _s as sleep, aa as consumeSandboxEgressAuthRequiredSignal, an as remindMissingAnswer, as as SlackActionError, ba as SANDBOX_DATA_ROOT, bn as getPiMessageRole, c as recordAgentsInstructionsUpdated, cn as getAssistantReplyText, co as readLiveAttachment, da as resolveSandboxCommandEnvironment, el as piMessageFromHistoryItem, en as createTurnLimitGate, et as saveTurnCheckpoint, f as recordAuthorizationRequested, fn as isLegacyNoReplyMarker, fo as storeAttachments, g as recordToolExecutionStarted, ga as PluginToolDeniedError, gn as REPORT_BLOCKED_TOOL_NAME, hn as CODE_MODE_CALL_STATUS_TEXT, i as loadConversationProjection, ia as clearSandboxEgressSignals, ic as saveEventAutomation, in as readTurnAnswer, jc as isToolInputError, jn as normalizeToolNameFromResult, ka as runNonInteractiveCommand, kn as isToolResultError, l as recordAttachmentsDelivered, ln as sanitizeAssistantText, m as recordMcpProviderConnected, ma as tryWorkspaceRepoCheckoutPath, mn as CODEMODE_TOOL_NAME, mo as AttachmentSourceUnavailableError, na as isWorkspaceSnapshotNotReadyError, nl as getConfigDefaults, nn as REPLY_TOOL_NAME, ns as uploadFilesToConversation, oa as consumeSandboxEgressPermissionDeniedSignal, p as recordGuardianActionReviewed, pa as SANDBOX_RUNTIME, pn as readNoReply, po as storeDeferredAttachment, q as canReusePendingAuthLink, qo as deleteSlackMessage, r as loadConnectedMcpProviders, ra as workspaceSnapshotNotReadyUserMessage, rn as isAnswerToolName, ro as readSlackAttachmentSource, sa as createSandboxEgressCredentialToken, sn as decideReply, ta as getWorkspaceSnapshotNotReadyError, tc as getEventAutomation, tl as projectConversationEvents, tn as isTurnExecutionLimitExceededError, ts as updateSlackMessage, ua as buildSandboxEgressNetworkPolicy, un as NO_REPLY_TOOL_NAME, us as isConversationScopedChannel, wa as sandboxSkillDir, wn as hasTurnInput, wo as resolveUserTimezone, xn as getTerminalAssistantMessages, xs as escapeSlackMrkdwnText, ya as SANDBOX_COMMAND_PATH, yn as extractAssistantText, z as createPluginEgress, zi as getSandboxProvider } from "./projection-CWXDE0f6.js";
2
- import { $ as ProviderError, B as unwrapCurrentInstruction, F as textCharsForTokens, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, J as readParentAgentTask, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, V as escapeXml, at as isProviderRefusal, b as GEN_AI_PROVIDER_NAME, et as createAssistantProviderError, it as getProviderErrorUserMessage, j as requestPrefixAttributes, k as resolveGatewayModel, lt as bufferBody, n as botConfig, nt as findProviderError, ot as isProviderRetryError, rt as getProviderErrorAttributes, st as getGatewayApiKey, tt as createProviderError, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-DUD-zMvp.js";
3
- import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, 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, p as logException, t as buildTurnFailureResponse, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-oYpJYr-S.js";
1
+ import { $n as getTerminalAssistantMessages, Aa as SANDBOX_COMMAND_PATH, Ao as createConversationEmbedder, B as PluginCredentialFailureError, Ba as buildNonInteractiveShellScript, Da as PluginToolDeniedError, En as createPluginHookRunner, Eo as AttachmentSourceUnavailableError, F as calculateContextCompactionTargetTokens, Fa as SANDBOX_WORKSPACE_ROOT, G as AuthorizationPauseError, Gc as ToolInputError, Gs as createScheduledAutomation, H as authorizationId, I as getAgentBackgroundCompactionMarkTokens, Ia as sandboxSkillDir, Ii as getWorkspace, Is as escapeSlackMrkdwnText, Jt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, K as abandonReplacedPendingAuth, Kc as isToolInputError, L as getAgentContextCompactionTriggerTokens, La as sandboxSkillFile, Ms as sleep, Na as SANDBOX_SCRATCH_ROOT, Ni as renderToolResultNudge, Pa as SANDBOX_SKILLS_ROOT, Pr as getReviewItem, Qn as getPiMessageRole, Qt as TurnToolCallLimitExceededError, R as getAgentContextInputLimitTokens, Ra as sandboxSkillPathResolution, Ro as resolveUserTimezone, Rs as normalizeSlackReplyMarkdown, Sa as resolveSandboxCommandEnvironment, Ta as tryWorkspaceRepoCheckoutPath, To as storeDeferredAttachment, Ts as isConversationScopedChannel, U as AuthPausePersistenceError, Uc as automationRevision, V as createPluginAuthOrchestration, Va as runNonInteractiveCommand, W as AuthorizationFlowDisabledError, X as continuableMessages, Xi as getSandboxProvider, Xs as saveScheduledAutomation, Xt as TurnBudgetExceededError, Yi as ensureDockerDaemon, Ys as readScheduledAutomation, Yt as TURN_LIMIT_WRAP_UP_MESSAGE, Z as loadTurnCheckpoint, Zi as isRetryableSandboxFailure, Zn as extractAssistantText, Zt as TurnSliceLimitExceededError, _a as consumeSandboxEgressPermissionDeniedSignal, _n as readBlockedReport, aa as SandboxCallTimeoutError, an as remindMissingAnswer, ar as isContinuablePiBoundary, bn as createUserTokenStore, bo as readLiveAttachment, bs as SlackActionError, c as recordAgentsInstructionsUpdated, ca as isAlreadyExistsError, ci as getSlackToolContext, cl as credentialAuditAttributes, cn as getAssistantReplyText, cr as isToolResultMessage, dr as stripRuntimeTurnContext, ea as deliverOAuthAuthorization, en as createTurnLimitGate, er as getUserMessageInstructionText, et as saveTurnCheckpoint, f as recordAuthorizationRequested, fa as getWorkspaceSnapshotNotReadyError, fn as isLegacyNoReplyMarker, fr as trimTrailingAssistantMessages, fs as postSlackMessage, g as recordToolExecutionStarted, ga as consumeSandboxEgressAuthRequiredSignal, gc as getEventAutomation, gl as getConfigDefaults, gn as REPORT_BLOCKED_TOOL_NAME, gr as TURN_CONTEXT_TAG, gs as uploadFilesToConversation, ha as clearSandboxEgressSignals, hl as projectConversationEvents, hn as CODE_MODE_CALL_STATUS_TEXT, ho as readSlackAttachmentSource, hs as updateSlackMessage, i as loadConversationProjection, ic as getDashboardReviewItemLink, in as readTurnAnswer, ir as isAssistantMessage, ja as SANDBOX_DATA_ROOT, jn as getPluginTools, l as recordAttachmentsDelivered, la as throwSandboxOperationError, ll as credentialAuditSource, ln as sanitizeAssistantText, lr as normalizeToolNameFromResult, m as recordMcpProviderConnected, ma as workspaceSnapshotNotReadyUserMessage, ml as piMessageFromHistoryItem, mn as CODEMODE_TOOL_NAME, mr as REQUEST_CONTEXT_SECTION_TAG, nn as REPLY_TOOL_NAME, nr as hasTurnInput, oa as findInErrorChain, ol as resolveTaskTitle, or as isStandaloneRuntimeContextMessage, os as addReactionToMessage, p as recordGuardianActionReviewed, pa as isWorkspaceSnapshotNotReadyError, pc as createEventAutomation, pl as historyItemFromPiMessage, pn as readNoReply, pr as CAPABILITY_SECTION_TAG, q as canReusePendingAuthLink, qi as hash, r as loadConnectedMcpProviders, ra as resolveBaseUrl, rn as isAnswerToolName, si as resolveChannelCapabilities, sn as decideReply, sr as isToolResultError, ss as deleteSlackMessage, ta as formatProviderLabel, tn as isTurnExecutionLimitExceededError, ua as wrapSandboxSetupError, un as NO_REPLY_TOOL_NAME, ur as retainRuntimeTurnContext, va as createSandboxEgressCredentialToken, wa as SANDBOX_RUNTIME, wo as storeAttachments, xa as buildSandboxEgressNetworkPolicy, yc as saveEventAutomation, z as createPluginEgress, za as buildCommandScript, zn as isEventEmbeddingsEnabled } from "./projection-xPpvqexa.js";
2
+ import { $ as ProviderError, B as unwrapCurrentInstruction, F as textCharsForTokens, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, J as readParentAgentTask, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, V as escapeXml, at as isProviderRefusal, b as GEN_AI_PROVIDER_NAME, et as createAssistantProviderError, it as getProviderErrorUserMessage, j as requestPrefixAttributes, k as resolveGatewayModel, lt as bufferBody, n as botConfig, nt as findProviderError, ot as isProviderRetryError, rt as getProviderErrorAttributes, st as getGatewayApiKey, tt as createProviderError, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-362yMSIz.js";
3
+ import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, 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, p as logException, t as buildTurnFailureResponse, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-CHCuQ5iz.js";
4
4
  import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan } from "./sentry-CPbZjomA.js";
5
- 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-YE54gMN8.js";
5
+ 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-Tjj5P2W6.js";
6
6
  import { f as parseSlackTeamId, n as createSlackActor, o as isUserActor, p as parseSlackUserId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
7
- import { $ as getStateAdapter, O as promptModeTurnTools, St as sameDestination, T as isPersonInput, a as getConversationStore, at as withLock, k as turnBehavior, lt as addAgentTurnUsage, o as getDb, pt as hasAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, ut as agentTurnCostUsd } from "./db-DV2ZUb1Y.js";
8
- import { f as juniorAutomationRuns, u as juniorReviewItemSlackCards, z as juniorArtifacts } from "./executor-CjNhwwnj.js";
7
+ import { $ as getStateAdapter, E as isTopLevelKind, O as promptModeTurnTools, T as isPersonInput, _t as agentTurnCostUsd, a as getConversationStore, at as withLock, bt as hasAgentTurnUsage, gt as addAgentTurnUsage, k as turnBehavior, kt as sameDestination, o as getDb, r as getConversationEventStore, s as getSqlExecutor, wt as nextDetailVersion } from "./db-Bcbd9zQc.js";
8
+ import { H as juniorArtifacts, R as juniorConversations, d as juniorReviewItemSlackCards, p as juniorAutomationRuns } from "./executor-DBMBrpNV.js";
9
9
  import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-N7IVbUom.js";
10
10
  import { a as listReferenceFiles } from "./package-discovery-x4AvVhMj.js";
11
- import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-1pzXmplY.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.js";
13
- import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CPf4vNuC.js";
14
- import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-DzQiOmqa.js";
15
- import { d as completeText, g as NoAudioError, h as transcribeFromUrl, p as generateImages, u as completeObject } from "./prompt-P3eRqO8C.js";
16
- import { A as automationTitleSchema, J as automationTaskDescription, L as ScheduleIntentError, O as automationContextToolSchema, P as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, R as compileScheduleIntent, j as taskOutcomeInputSchema, k as automationInstructionToolSchema, z as scheduleIntentFromTool } from "./schedule-CHPWQn-x.js";
11
+ import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, s as skillReferences, t as discoverSkills } from "./skills-63i1Bcv1.js";
12
+ import { _ as credentialUserSubjectId, c as OAuthProviderError, f as actorLogContext, i as resolvePluginHeaderEnvRefs, l as fetchWithBoundedOAuthErrorBodies, u as getOAuthProviderErrorAttributes } from "./registry-D20hG3r6.js";
13
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-OXrv2Ewn.js";
14
+ import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-Bv5QwrEq.js";
15
+ import { d as completeText, g as NoAudioError, h as transcribeFromUrl, p as generateImages, u as completeObject } from "./prompt-D8u4jFs_.js";
16
+ import { A as automationContextToolSchema, B as compileScheduleIntent, I as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, M as automationTitleSchema, N as taskOutcomeInputSchema, V as scheduleIntentFromTool, X as automationTaskDescription, j as automationInstructionToolSchema, z as ScheduleIntentError } from "./schedule-BG1tEbRF.js";
17
17
  import { Z as MAX_ATTACHMENT_BYTES } from "./conversation--f85g4zL.js";
18
- import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-DKOeHpv3.js";
19
- import { At as findVisibleAgentsInstructions, C as PLAN_DELTA_TAG, Dt as AGENTS_REMOVAL_NOTICE, Et as JUNIOR_PERSONALITY, Ft as foldSystemMessages, It as readAgentHistory, Lt as withAgentRequest, Mt as renderAgentsInstructions, Nt as showsAgentsInstructions, Ot as AGENTS_REPLACEMENT_NOTICE, Pt as foldLeadingSystemMessages, Rt as writeAgentHistory, T as renderPlanSnapshot, bt as slackChannelMessageTrigger, d as buildPromptInput, et as resolveSlackReplyTarget, f as buildSteeringPiMessage, gt as requireSlackChannelMessageScope, h as loadPromptTurnContext, jt as readRepositoryInstructions, kt as buildAgentsInstructionsMessage, mt as getEventCatalog, u as assemblePrompt, x as listPlanItems } from "./session-stop-BQxgHR4X.js";
20
- import { $ as createStopAgentTool, $n as createSlackListGetItemsTool, $r as requireToolDestination, A as createWebSearchTool, Ar as createDeleteAutomationTool, B as createSearchEventTypesTool, Br as automationTriggerSchema, C as incrementStat, Cr as isMissingPathError, D as requireReadyWorkspaceSnapshot, Dr as createCanvas, Er as createOperationKey, F as userLookupIdentityProviders, Fr as automationIdForToolCall, G as missingFileResult, Gr as juniorToolOutputSchema, Gt as listAgentInvocationsForConversation, H as createSearchConversationsTool, Hn as createSetConversationSubscriptionTool, Hr as newAutomationTask, I as createUpdateUserCustomizationTool, Ir as automationSkillToolSchema, J as capToolResult, Jr as automationToolContext, K as sliceFileContent, Kr as makeStructuredToolOutput, L as createSubmitFeedbackTool, Lr as automationToolResult, M as createWatchTimerTool, Mr as parseToolInput, Mt as createReadConversationEventTool, N as createWatchEventsTool, Nr as zodTool, Nt as createRunOperatorSqlTool, O as prepareWorkspaceSnapshot, Or as createSearchAutomationsTool, P as createUserLookupTool, Pr as zodToolDefinition, Pt as createListWatchesTool, Q as createUpdatePlanTool, Qn as createSlackListUpdateItemTool, Qr as requireToolCreator, R as createSystemTimeTool, Rr as automationToolResultSchema, S as createWorkspaceTools, Si as missingAutomationSkillReason, Sr as SLACK_TOOL_SOURCE, T as ensureWorkspaceSnapshotBuild, Ti as resolveTaskOutcomes, Tr as resolveWorkspacePath, U as createWriteFileTool, Ur as triggerKind, V as createSearchConversationEventsTool, Vr as editedAutomationTask, W as createReadFileTool, Wr as injectContinuationToolName, X as editFile, Xr as requireToolAutomation, Y as createEditFileTool, Yr as automationToolsDisabledReason, Z as createBashTool, Zn as createSlackPublicSearchTool, Zr as requireToolCaller, _i as requireEventAutomationTrigger, a as createCacheWarmingRecorder, at as createNoReplyTool, b as coreToolSlots, bi as requireAutomationSkill, br as createSlackCanvasReadTool, cr as createSlackChannelJoinTool, dr as checkSlackChannelReadAccess, er as createSlackListCreateTool, et as createSpawnAgentTool, fr as joinPublicChannelForRead, gi as changedEventMatch, hi as editEventAutomation, ht as createUpdateReviewItemTool, ir as createSlackChannelListMessagesTool, it as createReplyTool, j as createWebFetchTool, jr as AUTOMATIONS_TOOL_SOURCE, kr as createRunAutomationNowTool, lr as resolveSlackChannelRef, mi as editScheduledAutomation, mt as createSearchReviewItemsTool, ni as changeAutomationLifecycle, nn as isParentMessageMeta, nr as createSlackConversationMessageSearchTool, nt as createReportProgressTool, ot as createMessageAgentTool, pt as createAddReviewItemTool, q as TOOL_RESULT_MAX_CHARS, qn as createSlackThreadReadTool, qr as getConversationAccess, rr as createSlackConversationSearchChannelPort, rt as createReportBlockedTool, st as createArchiveAgentTool, ti as automationEditor, tr as createSlackListAddItemsTool, tt as createListAgentsTool, ur as slackChannelRefParam, vi as requireAutomationTaskText, wi as moveTaskOutcomes, wr as positiveInteger, x as enabledMode, xr as createSlackCanvasEditTool, yr as createSlackCanvasWriteTool, z as createStopWatchingResourcesTool, zr as automationTriggerChangesSchema } from "./warmup-mTMIatCV.js";
21
- import { a as USER_INPUT_LIMITS, i as AGENT_INVOCATION_STATUSES, m as detectImageMediaType, o as USER_INPUT_NOTE, s as buttonUserInputField, u as normalizeUserInputAnswer } from "./web-message-id-CUaSiGme.js";
22
- import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-DNC0eRZ7.js";
23
- import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-D2wzxtGU.js";
24
- import { t as resolveConversationRouting } from "./turn-session-routing-BXaubz2w.js";
25
- import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-DbD7C5td.js";
26
- import { n as resolve$1 } from "./resolve-n87oXY-d.js";
27
- import { t as runWithSlackInstallation } from "./adapter-context-CnY-i32r.js";
18
+ import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-DN_xzVKj.js";
19
+ import { c as QUEUE_SIGNATURE_MAX_AGE_MS } from "./task-queue-BcjAYWyB.js";
20
+ import { At as findVisibleAgentsInstructions, C as PLAN_DELTA_TAG, Dt as AGENTS_REMOVAL_NOTICE, Et as JUNIOR_PERSONALITY, Ft as foldSystemMessages, It as readAgentHistory, Lt as withAgentRequest, Mt as renderAgentsInstructions, Nt as showsAgentsInstructions, Ot as AGENTS_REPLACEMENT_NOTICE, Pt as foldLeadingSystemMessages, Rt as writeAgentHistory, T as renderPlanSnapshot, bt as slackChannelMessageTrigger, d as buildPromptInput, et as resolveSlackReplyTarget, f as buildSteeringPiMessage, gt as requireSlackChannelMessageScope, h as loadPromptTurnContext, jt as readRepositoryInstructions, kt as buildAgentsInstructionsMessage, mt as getEventCatalog, u as assemblePrompt, x as listPlanItems } from "./session-stop-BDdwyZaa.js";
21
+ import { $ as createStopAgentTool, $n as createSlackListUpdateItemTool, $r as requireToolCreator, A as createWebSearchTool, Ar as createRunAutomationNowTool, B as createSearchEventTypesTool, Br as automationTriggerChangesSchema, C as incrementStat, Cr as SLACK_TOOL_SOURCE, D as requireReadyWorkspaceSnapshot, Di as resolveTaskOutcomes, Dr as createOperationKey, Ei as moveTaskOutcomes, Er as resolveWorkspacePath, F as userLookupIdentityProviders, Fr as zodToolDefinition, G as missingFileResult, Gr as injectContinuationToolName, Gt as listAgentInvocationsForConversation, H as createSearchConversationsTool, Hr as editedAutomationTask, I as createUpdateUserCustomizationTool, Ir as automationIdForToolCall, J as capToolResult, Jn as createSlackThreadReadTool, Jr as getConversationAccess, K as sliceFileContent, Kr as juniorToolOutputSchema, L as createSubmitFeedbackTool, Lr as automationSkillToolSchema, M as createWatchTimerTool, Mr as AUTOMATIONS_TOOL_SOURCE, Mt as createReadConversationEventTool, N as createWatchEventsTool, Nr as parseToolInput, Nt as createRunOperatorSqlTool, O as prepareWorkspaceSnapshot, Or as createCanvas, P as createUserLookupTool, Pr as zodTool, Pt as createListWatchesTool, Q as createUpdatePlanTool, Qn as createSlackPublicSearchTool, Qr as requireToolCaller, R as createSystemTimeTool, Rr as automationToolResult, S as createWorkspaceTools, Si as requireAutomationSkill, Sr as createSlackCanvasEditTool, T as ensureWorkspaceSnapshotBuild, Tr as positiveInteger, U as createWriteFileTool, Un as createSetConversationSubscriptionTool, Ur as newAutomationTask, V as createSearchConversationEventsTool, Vr as automationTriggerSchema, W as createReadFileTool, Wr as triggerKind, X as editFile, Xr as automationToolsDisabledReason, Y as createEditFileTool, Yr as automationToolContext, Z as createBashTool, Zr as requireToolAutomation, _i as changedEventMatch, a as createCacheWarmingRecorder, ar as createSlackChannelListMessagesTool, at as createNoReplyTool, b as coreToolSlots, bi as requireAutomationTaskText, br as createSlackCanvasWriteTool, dr as slackChannelRefParam, ei as requireToolDestination, er as createSlackListGetItemsTool, et as createSpawnAgentTool, fr as checkSlackChannelReadAccess, gi as editEventAutomation, hi as editScheduledAutomation, ht as createUpdateReviewItemTool, ir as createSlackConversationSearchChannelPort, it as createReplyTool, j as createWebFetchTool, jr as createDeleteAutomationTool, kr as createSearchAutomationsTool, lr as createSlackChannelJoinTool, mt as createSearchReviewItemsTool, ni as automationEditor, nn as isParentMessageMeta, nr as createSlackListAddItemsTool, nt as createReportProgressTool, ot as createMessageAgentTool, pr as joinPublicChannelForRead, pt as createAddReviewItemTool, q as TOOL_RESULT_MAX_CHARS, qr as makeStructuredToolOutput, ri as changeAutomationLifecycle, rr as createSlackConversationMessageSearchTool, rt as createReportBlockedTool, st as createArchiveAgentTool, tr as createSlackListCreateTool, tt as createListAgentsTool, ur as resolveSlackChannelRef, vi as requireEventAutomationTrigger, wi as missingAutomationSkillReason, wr as isMissingPathError, x as enabledMode, xr as createSlackCanvasReadTool, z as createStopWatchingResourcesTool, zr as automationToolResultSchema } from "./warmup-CxhEhm71.js";
22
+ import { a as USER_INPUT_LIMITS, i as AGENT_INVOCATION_STATUSES, m as detectImageMediaType, o as USER_INPUT_NOTE, s as buttonUserInputField, u as normalizeUserInputAnswer } from "./web-message-id-BT8Mg8LL.js";
23
+ import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-B1S8nOnG.js";
24
+ import { m as getVercelConversationWorkQueue, n as backgroundCompactionId } from "./background-compaction-queue-BhEe4UfU.js";
25
+ import { t as resolveConversationRouting } from "./turn-session-routing-DFYak28Q.js";
26
+ import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-CgoAbzfF.js";
27
+ import { n as resolve$1 } from "./resolve-BhCySRCW.js";
28
+ import { t as runWithSlackInstallation } from "./adapter-context-B69WPn6b.js";
28
29
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
30
+ import pLimit from "p-limit";
29
31
  import * as z from "zod";
30
32
  import { streamSimple } from "@earendil-works/pi-ai/compat";
31
33
  import path from "node:path";
@@ -33,14 +35,16 @@ import { isDeepStrictEqual } from "node:util";
33
35
  import { AsyncLocalStorage } from "node:async_hooks";
34
36
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
35
37
  import { createAssistantMessageEventStream, getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
36
- import { and, eq, inArray, isNull } from "drizzle-orm";
38
+ import { and, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
37
39
  import { declaredEventKeys, missingToolAnnotationKeys, ownedObjectAnnotationSchema } from "@sentry/junior-plugin-api";
40
+ import { alias } from "drizzle-orm/pg-core";
38
41
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
39
42
  import { Agent, DEFAULT_AGENT_IDENTITY } from "@earendil-works/pi-agent-core";
40
43
  import fs from "node:fs/promises";
41
44
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
42
45
  import { SignJWT, importPKCS8 } from "jose";
43
46
  import { performance as performance$1 } from "node:perf_hooks";
47
+ import { bm25InverseDocumentFrequency, bm25NormalizedFrequency, bm25Saturation } from "@sentry/junior-search";
44
48
  import { Bash, defineCommand } from "just-bash";
45
49
  import { Kind } from "@sinclair/typebox";
46
50
  import { Value } from "@sinclair/typebox/value";
@@ -368,16 +372,12 @@ var McpToolManager = class {
368
372
  }
369
373
  }
370
374
  async close() {
371
- let firstError;
372
- for (const client of [
375
+ const limit = pLimit(8);
376
+ const firstError = (await Promise.allSettled([
373
377
  ...this.clientsByProvider.values(),
374
378
  ...this.actorClientsByProvider.values(),
375
379
  ...this.forgottenClients
376
- ]) try {
377
- await client.close();
378
- } catch (error) {
379
- firstError ??= error;
380
- }
380
+ ].map((client) => limit(() => client.close())))).find((result) => result.status === "rejected")?.reason;
381
381
  this.clientsByProvider.clear();
382
382
  this.actorClientsByProvider.clear();
383
383
  this.forgottenClients.length = 0;
@@ -1459,11 +1459,15 @@ function upsertActiveSkill(activeSkills, next) {
1459
1459
  activeSkills.push(next);
1460
1460
  }
1461
1461
  /**
1462
- * Return the skills that the model can load with `loadSkill`. A user-callable
1463
- * skill is loadable only in the Turn where the user invoked it.
1462
+ * Return the skills that the model can load with `loadSkill`. A manual-only
1463
+ * skill is loadable only in a Turn where the user invoked it, or where a
1464
+ * skill loaded in that Turn references it as `$name` or `/name` in its
1465
+ * SKILL.md instructions. No other text, such as memory, thread messages, or
1466
+ * tool results, unlocks one.
1464
1467
  */
1465
- function loadableSkills(availableSkills, invokedSkillName) {
1466
- return availableSkills.filter((skill) => skill.disableModelInvocation !== true || skill.name === invokedSkillName);
1468
+ function loadableSkills(availableSkills, invokedSkillName, loadedSkills) {
1469
+ const referenced = new Set(loadedSkills.flatMap((loaded) => [loaded.name, ...skillReferences(loaded.body, availableSkills)]));
1470
+ return availableSkills.filter((skill) => skill.disableModelInvocation !== true || skill.name === invokedSkillName || referenced.has(skill.name));
1467
1471
  }
1468
1472
  /** Discover skills for one slice; emits the startup discovery summary once per process. */
1469
1473
  async function discoverRunSkills(args) {
@@ -1813,36 +1817,39 @@ async function listFilesRecursive(root) {
1813
1817
  return files;
1814
1818
  }
1815
1819
  async function buildSkillSyncFiles(availableSkills, referenceFiles) {
1816
- const filesToWrite = [];
1817
- const index = { skills: [] };
1818
- for (const skill of availableSkills) {
1819
- const skillFiles = await listFilesRecursive(skill.skillPath);
1820
- for (const absoluteFile of skillFiles) {
1821
- const relative = toPosixRelative(skill.skillPath, absoluteFile);
1822
- if (!relative || relative.startsWith("..")) continue;
1823
- filesToWrite.push({
1824
- path: `${sandboxSkillDir(skill.name)}/${relative}`,
1825
- content: await fs.readFile(absoluteFile)
1826
- });
1827
- }
1828
- index.skills.push({
1829
- name: skill.name,
1830
- description: skill.description,
1831
- root: sandboxSkillDir(skill.name)
1832
- });
1833
- }
1834
- filesToWrite.push({
1835
- path: `${SANDBOX_SKILLS_ROOT}/index.json`,
1836
- content: Buffer.from(JSON.stringify(index), "utf8")
1837
- });
1838
- if (referenceFiles && referenceFiles.length > 0) for (const absoluteFile of referenceFiles) {
1839
- const fileName = path.basename(absoluteFile);
1840
- filesToWrite.push({
1841
- path: `${SANDBOX_DATA_ROOT}/${fileName}`,
1842
- content: await fs.readFile(absoluteFile)
1843
- });
1844
- }
1845
- return filesToWrite;
1820
+ const limit = pLimit(8);
1821
+ const skillSources = (await Promise.all(availableSkills.map((skill) => limit(async () => ({
1822
+ files: await listFilesRecursive(skill.skillPath),
1823
+ skill
1824
+ }))))).flatMap(({ files, skill }) => files.flatMap((absoluteFile) => {
1825
+ const relative = toPosixRelative(skill.skillPath, absoluteFile);
1826
+ return !relative || relative.startsWith("..") ? [] : [{
1827
+ absoluteFile,
1828
+ path: `${sandboxSkillDir(skill.name)}/${relative}`
1829
+ }];
1830
+ }));
1831
+ const referenceSources = (referenceFiles ?? []).map((absoluteFile) => ({
1832
+ absoluteFile,
1833
+ path: `${SANDBOX_DATA_ROOT}/${path.basename(absoluteFile)}`
1834
+ }));
1835
+ const read = (source) => limit(async () => ({
1836
+ path: source.path,
1837
+ content: await fs.readFile(source.absoluteFile)
1838
+ }));
1839
+ const [skillFiles, referenceContents] = await Promise.all([Promise.all(skillSources.map(read)), Promise.all(referenceSources.map(read))]);
1840
+ const index = { skills: availableSkills.map((skill) => ({
1841
+ name: skill.name,
1842
+ description: skill.description,
1843
+ root: sandboxSkillDir(skill.name)
1844
+ })) };
1845
+ return [
1846
+ ...skillFiles,
1847
+ {
1848
+ path: `${SANDBOX_SKILLS_ROOT}/index.json`,
1849
+ content: Buffer.from(JSON.stringify(index), "utf8")
1850
+ },
1851
+ ...referenceContents
1852
+ ];
1846
1853
  }
1847
1854
  /** Resolve a virtual sandbox skill path back to the host filesystem when no sandbox exists yet. */
1848
1855
  function resolveHostSkillPath(availableSkills, sandboxPath) {
@@ -2932,7 +2939,8 @@ function createSandbox(options) {
2932
2939
  /** Maximum single file size accepted by model-facing upload tools. */
2933
2940
  const MAX_SANDBOX_FILE_UPLOAD_BYTES = 10485760;
2934
2941
  /** Sandbox directory for generated files that later tools can consume. */
2935
- const SANDBOX_ARTIFACTS_DIR = "/tmp/junior/artifacts";
2942
+ const SANDBOX_GENERATED_DIR = `${SANDBOX_SCRATCH_ROOT}/gen`;
2943
+ const MAX_GENERATED_FILENAME_CODE_POINTS = 60;
2936
2944
  /** Canonical model-facing reference to a file that already exists in the sandbox. */
2937
2945
  const sandboxFileReferenceSchema = z.object({
2938
2946
  path: z.string().min(1).describe("Exact source path of an existing sandbox file. Preserve paths returned by other tools unchanged; do not move or rewrite them before sending."),
@@ -2941,7 +2949,7 @@ const sandboxFileReferenceSchema = z.object({
2941
2949
  bytes: z.number().int().nonnegative().nullable().optional().describe("Optional known file size returned by a producing tool. Null is treated as omitted; sending tools validate the file contents directly.")
2942
2950
  });
2943
2951
  /** Generated file reference whose path and metadata can be passed directly to sendFiles. */
2944
- const generatedArtifactFileRefSchema = sandboxFileReferenceSchema.extend({
2952
+ const generatedFileRefSchema = sandboxFileReferenceSchema.extend({
2945
2953
  filename: z.string().min(1),
2946
2954
  mime_type: z.string().min(1).optional(),
2947
2955
  bytes: z.number().int().nonnegative()
@@ -2985,9 +2993,22 @@ function sanitizeFilename(value, fallbackPath) {
2985
2993
  if (derived && derived !== "." && derived !== "..") return derived;
2986
2994
  return "attachment.bin";
2987
2995
  }
2988
- /** Return the canonical sandbox artifact path for generated files. */
2989
- function sandboxArtifactPath(filename) {
2990
- return path.posix.join(SANDBOX_ARTIFACTS_DIR, sanitizeFilename(filename, "artifact.bin"));
2996
+ function capFilename(filename) {
2997
+ const codePoints = Array.from(filename);
2998
+ if (codePoints.length <= MAX_GENERATED_FILENAME_CODE_POINTS) return filename;
2999
+ const ext = Array.from(path.posix.extname(filename));
3000
+ const keepExt = ext.length < MAX_GENERATED_FILENAME_CODE_POINTS / 2;
3001
+ const stemLength = MAX_GENERATED_FILENAME_CODE_POINTS - (keepExt ? ext.length : 0);
3002
+ return [...codePoints.slice(0, stemLength), ...keepExt ? ext : []].join("");
3003
+ }
3004
+ /**
3005
+ * Return the sandbox path for one generated file. The content hash keeps
3006
+ * different files with the same name apart. The last segment keeps the
3007
+ * original name, so a send with only the path still shows that name.
3008
+ */
3009
+ function sandboxGeneratedFilePath(content, filename) {
3010
+ const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
3011
+ return path.posix.join(SANDBOX_GENERATED_DIR, hash, capFilename(sanitizeFilename(filename, "file.bin")));
2991
3012
  }
2992
3013
  /** Infer upload MIME type from an explicit value or filename extension. */
2993
3014
  function inferMimeType(filename, explicitMimeType) {
@@ -3030,37 +3051,32 @@ async function readSandboxFileUpload(workspace, input) {
3030
3051
  path: targetPath
3031
3052
  };
3032
3053
  }
3033
- // src/chat/tools/sandbox/generated-artifacts.ts
3054
+ // src/chat/tools/sandbox/generated-files.ts
3034
3055
  async function fileUploadDataToBuffer(data) {
3035
3056
  if (Buffer.isBuffer(data)) return data;
3036
3057
  if (data instanceof ArrayBuffer) return Buffer.from(data);
3037
3058
  return Buffer.from(await data.arrayBuffer());
3038
3059
  }
3039
- /** Persist generated artifacts into the sandbox before returning model-visible handles. */
3040
- async function writeSandboxGeneratedArtifacts(workspace, files) {
3041
- const mkdir = await workspace.runCommand({
3042
- cmd: "mkdir",
3043
- args: ["-p", SANDBOX_ARTIFACTS_DIR]
3044
- });
3045
- if (mkdir.exitCode !== 0) throw new Error(`failed to create generated artifact directory: ${mkdir.stderr}`);
3046
- const artifacts = await Promise.all(files.map(async (file) => {
3060
+ /** Write generated files into the sandbox before returning model-visible handles. */
3061
+ async function writeSandboxGeneratedFiles(workspace, files) {
3062
+ const limit = pLimit(8);
3063
+ const generated = await Promise.all(files.map((file) => limit(async () => {
3047
3064
  const content = await fileUploadDataToBuffer(file.data);
3048
- const artifactPath = sandboxArtifactPath(file.filename);
3049
3065
  return {
3050
3066
  content,
3051
3067
  ref: {
3052
3068
  bytes: content.byteLength,
3053
3069
  filename: file.filename,
3054
3070
  mime_type: file.mimeType,
3055
- path: artifactPath
3071
+ path: sandboxGeneratedFilePath(content, file.filename)
3056
3072
  }
3057
3073
  };
3058
- }));
3059
- await workspace.writeFiles(artifacts.map((artifact) => ({
3060
- content: artifact.content,
3061
- path: artifact.ref.path
3062
3074
  })));
3063
- return artifacts.map((artifact) => artifact.ref);
3075
+ await workspace.writeFiles(generated.map((file) => ({
3076
+ content: file.content,
3077
+ path: file.ref.path
3078
+ })));
3079
+ return generated.map((file) => file.ref);
3064
3080
  }
3065
3081
  // src/chat/tool-support/normalize-result.ts
3066
3082
  function isToolContent(value) {
@@ -3325,8 +3341,8 @@ function createAgentSandbox(options) {
3325
3341
  return await sandbox.tools.execute(params);
3326
3342
  }
3327
3343
  },
3328
- async writeGeneratedArtifacts(files) {
3329
- return await writeSandboxGeneratedArtifacts(sandbox.workspace, files);
3344
+ async writeGeneratedFiles(files) {
3345
+ return await writeSandboxGeneratedFiles(sandbox.workspace, files);
3330
3346
  }
3331
3347
  };
3332
3348
  }
@@ -3353,7 +3369,7 @@ function createCreatePreviewTool(createPreview) {
3353
3369
  openWorldHint: true,
3354
3370
  readOnlyHint: false
3355
3371
  },
3356
- approvalMode: "approve",
3372
+ approvalMode: "review",
3357
3373
  description: "Create a public HTTPS preview URL for a server running in the sandbox. Anyone with the URL can open it until the sandbox stops. The URL for a port stays the same while the sandbox runs. Use it after you build or change something that a person can open in a browser, such as a web page or app, so they can try it.",
3358
3374
  executionMode: "sequential",
3359
3375
  inputSchema: z.object({ port: z.number().int().min(1).max(65535).describe("Port that the server listens on. The server must listen on 0.0.0.0.") }).strict(),
@@ -3390,10 +3406,11 @@ async function renewPreviewOrigins(sandbox, resolveOwner) {
3390
3406
  await runBestEffort(async () => {
3391
3407
  const owner = await resolveOwner();
3392
3408
  if (!owner) return;
3393
- await Promise.all(urls.map(async (url) => await recordPreviewOrigin({
3409
+ const limit = pLimit(8);
3410
+ await Promise.all(urls.map((url) => limit(() => recordPreviewOrigin({
3394
3411
  ownerEmail: owner.email,
3395
3412
  url
3396
- })));
3413
+ }))));
3397
3414
  }, "sandbox.preview_origin.renew.failed");
3398
3415
  }
3399
3416
  /** Return true when Junior made the Preview at `origin` for this person. */
@@ -3445,7 +3462,7 @@ const imageGenerateOutputSchema = juniorToolOutputSchema.extend({
3445
3462
  prompt: z.string(),
3446
3463
  enriched_prompt: z.string(),
3447
3464
  image_count: z.number().int().nonnegative(),
3448
- images: z.array(generatedArtifactFileRefSchema),
3465
+ images: z.array(generatedFileRefSchema),
3449
3466
  delivery: z.string(),
3450
3467
  resized_images: z.array(resizedImageSchema).optional(),
3451
3468
  resize_notice: z.string().optional()
@@ -3547,7 +3564,7 @@ function extensionForMediaType(mediaType) {
3547
3564
  return "bin";
3548
3565
  }
3549
3566
  /**
3550
- * Create the image tool with sandbox artifact guidance matched to file-send capability.
3567
+ * Create the image tool with sandbox file guidance matched to file-send capability.
3551
3568
  *
3552
3569
  * @runBuilt imageGenerate
3553
3570
  */
@@ -3597,13 +3614,13 @@ function createImageGenerateTool(hooks, options, deps = {}) {
3597
3614
  mimeType: image.mediaType
3598
3615
  }));
3599
3616
  if (uploads.length > 0) {
3600
- const artifactRefs = await hooks.writeGeneratedArtifacts(uploads);
3617
+ const fileRefs = await hooks.writeGeneratedFiles(uploads);
3601
3618
  return {
3602
3619
  model,
3603
3620
  prompt,
3604
3621
  enriched_prompt: enrichedPrompt,
3605
- image_count: artifactRefs.length,
3606
- images: artifactRefs,
3622
+ image_count: fileRefs.length,
3623
+ images: fileRefs,
3607
3624
  ...resizeResult,
3608
3625
  delivery: options.canSendFilesToActiveConversation ? "Generated images were written to sandbox paths. To share them, pass the returned image objects unchanged as sendFiles files." : "Generated images were written to sandbox paths, but this runtime has no file-send tool for the active conversation."
3609
3626
  };
@@ -4452,6 +4469,38 @@ function createSlackMessageAddReactionTool(context, state) {
4452
4469
  }
4453
4470
  });
4454
4471
  }
4472
+ // src/chat/conversations/delivery-pause.ts
4473
+ /** True when the Conversation is a root that delivers to a Location. */
4474
+ function canPauseConversationDelivery(conversation) {
4475
+ return isTopLevelKind(conversation.kind) && conversation.location !== void 0;
4476
+ }
4477
+ const rootConversation = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId));
4478
+ /**
4479
+ * Stop Delivery of a root's Event Turn replies to its Location. Returns false
4480
+ * when Delivery was already paused or the root does not exist.
4481
+ */
4482
+ async function pauseConversationDelivery(conversationId) {
4483
+ return (await getSqlExecutor().db().update(juniorConversations).set({
4484
+ deliveryPausedAt: /* @__PURE__ */ new Date(),
4485
+ detailVersion: nextDetailVersion
4486
+ }).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
4487
+ }
4488
+ /** Deliver a root's Event Turn replies to its Location again. */
4489
+ async function resumeConversationDelivery(conversationId) {
4490
+ await getSqlExecutor().db().update(juniorConversations).set({
4491
+ deliveryPausedAt: null,
4492
+ detailVersion: nextDetailVersion
4493
+ }).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
4494
+ }
4495
+ /**
4496
+ * True while the root of this Conversation is detached from its Location.
4497
+ * Only a root stores the pause, so a child agent reads its root's.
4498
+ */
4499
+ async function isConversationDeliveryPaused(conversationId) {
4500
+ const root = alias(juniorConversations, "root");
4501
+ const [row] = await getSqlExecutor().db().select({ pausedAt: root.deliveryPausedAt }).from(juniorConversations).innerJoin(root, eq(root.conversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
4502
+ return Boolean(row?.pausedAt);
4503
+ }
4455
4504
  // src/chat/slack/user-input.ts
4456
4505
  const FIELD_BLOCK_ID_PREFIX = "field:";
4457
4506
  const OTHER_BLOCK_ID = "other";
@@ -4875,7 +4924,8 @@ function createSlackReviewItemShow(getSlackAdapter) {
4875
4924
  }
4876
4925
  /**
4877
4926
  * Show the current state of a Review item in its linked Slack threads. An
4878
- * open item gets one card in each linked thread that has none. Each existing
4927
+ * open item gets one card in each linked thread that has none and is not
4928
+ * detached. Each existing
4879
4929
  * card changes in place. A card in a thread that can no longer show the item
4880
4930
  * loses its content. A closed item posts no new cards. Syncs of one item run
4881
4931
  * one at a time under a state lock, so two syncs cannot post two cards in
@@ -4896,7 +4946,9 @@ async function syncReviewItemSlackCards(args) {
4896
4946
  const linkedThreads = /* @__PURE__ */ new Map();
4897
4947
  for (const thread of linked) if (thread && !linkedThreads.has(threadKey(thread))) linkedThreads.set(threadKey(thread), thread);
4898
4948
  const cardedKeys = new Set(carded.flatMap((thread) => thread ? [threadKey(thread)] : []));
4899
- const missing = item.status === "open" ? [...linkedThreads.values()].filter((thread) => !cardedKeys.has(threadKey(thread))) : [];
4949
+ const uncarded = item.status === "open" ? [...linkedThreads.values()].filter((thread) => !cardedKeys.has(threadKey(thread))) : [];
4950
+ const limit = pLimit(8);
4951
+ const missing = (await Promise.all(uncarded.map((thread) => limit(async () => await isConversationDeliveryPaused(thread.conversationId) ? [] : [thread])))).flat();
4900
4952
  const failed = (await Promise.allSettled([...rows.map((row, index) => {
4901
4953
  const thread = carded[index];
4902
4954
  const shown = !!thread && linkedThreads.has(threadKey(thread));
@@ -5777,7 +5829,13 @@ const STATIC_TOOL_BINDERS = {
5777
5829
  runOperatorSql: (run) => isPublic(run) ? void 0 : createRunOperatorSqlTool(),
5778
5830
  updateUserCustomization: (run) => createUpdateUserCustomizationTool(run.context),
5779
5831
  setConversationSubscription: (run) => createSetConversationSubscriptionTool(run.context),
5780
- searchConversationEvents: (run) => createSearchConversationEventsTool(run.context),
5832
+ searchConversationEvents: (run) => createSearchConversationEventsTool(run.context, isEventEmbeddingsEnabled() ? { embedder: createConversationEmbedder({
5833
+ cost: {
5834
+ conversationId: run.context.conversationId,
5835
+ ...run.context.turnId ? { turnId: run.context.turnId } : void 0
5836
+ },
5837
+ operation: "conversation_search_embedding"
5838
+ }) } : void 0),
5781
5839
  readConversationEvent: (run) => createReadConversationEventTool(run.context),
5782
5840
  searchConversations: (run) => createSearchConversationsTool({
5783
5841
  ...run.slack ? { channels: createSlackConversationSearchChannelPort(run.slack.teamId) } : void 0,
@@ -5866,7 +5924,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
5866
5924
  });
5867
5925
  },
5868
5926
  viewImage: (run) => run.context.supportsImageInput ? createViewImageTool(run.context.workspace, run.context.supportsImageInput, run.hooks.toolOverrides?.viewImage) : void 0,
5869
- imageGenerate: (run) => run.hooks.writeGeneratedArtifacts ? createImageGenerateTool({ writeGeneratedArtifacts: run.hooks.writeGeneratedArtifacts }, {
5927
+ imageGenerate: (run) => run.hooks.writeGeneratedFiles ? createImageGenerateTool({ writeGeneratedFiles: run.hooks.writeGeneratedFiles }, {
5870
5928
  modelId: botConfig.imageGenerationModelId,
5871
5929
  canSendFilesToActiveConversation: run.canSendFilesToActiveConversation,
5872
5930
  modelCost: run.modelCost,
@@ -6521,16 +6579,16 @@ function createToolActionReview(options) {
6521
6579
  }
6522
6580
  return state;
6523
6581
  });
6524
- states.forEach((state, index) => {
6582
+ for (const [index, state] of states.entries()) {
6525
6583
  const step = steps[index];
6526
- if (step.kind !== "reviewed" || state.rejected) return;
6584
+ if (step.kind !== "reviewed" || state.rejected) continue;
6527
6585
  if (step.decision.decision === "allow") {
6528
6586
  consecutiveRejections = 0;
6529
- return;
6587
+ continue;
6530
6588
  }
6531
6589
  state.rejected = true;
6532
6590
  consecutiveRejections = state.before + 1;
6533
- if (consecutiveRejections < MAX_CONSECUTIVE_REJECTIONS) return;
6591
+ if (consecutiveRejections < MAX_CONSECUTIVE_REJECTIONS) continue;
6534
6592
  state.exhausted = true;
6535
6593
  logException(new ToolActionReviewLimitError(), "guardian.action_review.exhausted", {
6536
6594
  "app.guardian.decision": step.decision.decision,
@@ -6539,7 +6597,7 @@ function createToolActionReview(options) {
6539
6597
  "gen_ai.tool.name": step.proposal.tool.name,
6540
6598
  "gen_ai.tool.call.id": actions[index].toolCallId
6541
6599
  });
6542
- });
6600
+ }
6543
6601
  return states;
6544
6602
  };
6545
6603
  /** Apply one review step to gate state and return the action's result. */
@@ -6783,7 +6841,10 @@ function asSchema(value) {
6783
6841
  function propertyList(schema) {
6784
6842
  const properties = asSchema(schema["properties"]);
6785
6843
  const required = new Set(Array.isArray(schema["required"]) ? schema["required"] : []);
6786
- return Object.entries(properties).map(([name, property]) => `${name}${required.has(name) ? "" : "?"}: ${schemaType(asSchema(property))}`).join(", ");
6844
+ return Object.entries(properties).map(([name, value]) => {
6845
+ const property = asSchema(value);
6846
+ return `${name}${!required.has(name) || "default" in property ? "?" : ""}: ${schemaType(property)}`;
6847
+ }).join(", ");
6787
6848
  }
6788
6849
  function schemaType(schema) {
6789
6850
  if ("const" in schema) return JSON.stringify(schema["const"]);
@@ -6808,6 +6869,7 @@ function schemaType(schema) {
6808
6869
  * schema.
6809
6870
  */
6810
6871
  function summarizeInputSchema(schema) {
6872
+ if (!schema["properties"] && (schema["anyOf"] ?? schema["oneOf"])) return schemaType(schema);
6811
6873
  return propertyList(schema) || "No arguments.";
6812
6874
  }
6813
6875
  // src/chat/tools/search-tools.ts
@@ -6821,7 +6883,6 @@ const SEARCH_FIELD_WEIGHTS = [
6821
6883
  1
6822
6884
  ];
6823
6885
  const MIN_RELATIVE_SCORE = .3;
6824
- const BM25_K1 = 1.2;
6825
6886
  const BM25_B = [
6826
6887
  .75,
6827
6888
  .3,
@@ -7082,7 +7143,7 @@ function scoreQueryTerms(query, documents) {
7082
7143
  const documentFrequency = documentTerms.filter((terms) => [...weights.keys()].some((term) => terms.has(term))).length;
7083
7144
  return {
7084
7145
  weights,
7085
- inverseDocumentFrequency: Math.log(1 + (documents.length - documentFrequency + .5) / (documentFrequency + .5))
7146
+ inverseDocumentFrequency: bm25InverseDocumentFrequency(documents.length, documentFrequency)
7086
7147
  };
7087
7148
  });
7088
7149
  }
@@ -7090,9 +7151,7 @@ function weightedTermFrequency(document, term, averageLengths) {
7090
7151
  return document.fields.reduce((weighted, field, fieldIndex) => {
7091
7152
  const termFrequency = field.filter((candidate) => candidate === term).length;
7092
7153
  if (termFrequency === 0) return weighted;
7093
- const averageLength = averageLengths[fieldIndex] ?? 0;
7094
- const lengthRatio = averageLength === 0 ? 1 : field.length / averageLength;
7095
- return weighted + SEARCH_FIELD_WEIGHTS[fieldIndex] * (termFrequency / (1 - BM25_B[fieldIndex] + BM25_B[fieldIndex] * lengthRatio));
7154
+ return weighted + SEARCH_FIELD_WEIGHTS[fieldIndex] * bm25NormalizedFrequency(termFrequency, field.length, averageLengths[fieldIndex] ?? 0, BM25_B[fieldIndex]);
7096
7155
  }, 0);
7097
7156
  }
7098
7157
  function scoreSearchDocument(document, query, averageLengths) {
@@ -7100,7 +7159,7 @@ function scoreSearchDocument(document, query, averageLengths) {
7100
7159
  let best = 0;
7101
7160
  for (const [term, weight] of weights) {
7102
7161
  const frequency = weightedTermFrequency(document, term, averageLengths);
7103
- best = Math.max(best, weight * frequency * 2.2 / (frequency + BM25_K1));
7162
+ best = Math.max(best, weight * bm25Saturation(frequency));
7104
7163
  }
7105
7164
  return score + inverseDocumentFrequency * best;
7106
7165
  }, 0);
@@ -7109,12 +7168,12 @@ function nameMatch(document, query) {
7109
7168
  const { action, objects } = document;
7110
7169
  if (!action || objects.length === 0) return 0;
7111
7170
  let best = 0;
7112
- query.forEach((term, actionIndex) => {
7171
+ for (const [actionIndex, term] of query.entries()) {
7113
7172
  const actionWeight = term.get(action) ?? 0;
7114
- if (actionWeight === 0) return;
7173
+ if (actionWeight === 0) continue;
7115
7174
  const covered = objects.filter((object) => query.some((other, index) => index !== actionIndex && other.has(object))).length;
7116
7175
  best = Math.max(best, actionWeight * covered / objects.length);
7117
- });
7176
+ }
7118
7177
  return best;
7119
7178
  }
7120
7179
  function namesActionAndObject(documents, query) {
@@ -7176,8 +7235,13 @@ function selectedSourceSummaries(tools, matches, requestedSource, knownSources)
7176
7235
  const matchedSourceIds = new Set(matches.map((name) => tools[name]?.source?.id).filter((source) => Boolean(source)));
7177
7236
  return knownSources.filter((source) => matchedSourceIds.has(source.id));
7178
7237
  }
7238
+ /**
7239
+ * Tell the model that a `params` preview is not enough to call a tool. Both
7240
+ * the searchTools description and the Code Mode hint use it.
7241
+ */
7242
+ const PARAMS_PREVIEW_HINT = "A result with only params is a preview: search its exact name to get its input_schema before you call it.";
7179
7243
  function renderSearchToolsDescription(knownSources) {
7180
- const intro = "Search the executable tool catalog. Deferred tools are grouped by source; use searchTools with source to inspect one source, then executeTool with the exact returned tool_name. The best match has its full input_schema. Other results have params, a preview for choosing a tool: before you call one, search its exact name to get its input_schema.";
7244
+ const intro = `Search the executable tool catalog. Deferred tools are grouped by source. List a source, or search with a query. The first result of a query has its full input_schema. ${PARAMS_PREVIEW_HINT} Then call the tool with executeTool and its exact tool_name.`;
7181
7245
  if (knownSources.length === 0) return intro;
7182
7246
  return [
7183
7247
  intro,
@@ -7606,13 +7670,13 @@ async function runCodeModeScript(run) {
7606
7670
  })), controller.signal);
7607
7671
  })();
7608
7672
  reviews.catch(() => void 0);
7609
- accepted.forEach(({ call, host, tool }, index) => {
7673
+ for (const [index, { call, host, tool }] of accepted.entries()) {
7610
7674
  const submission = submissions[index];
7611
7675
  track(runCall(host, call, tool, async (action) => {
7612
7676
  submission.resolve(action);
7613
7677
  return (await reviews).get(action.toolCallId);
7614
7678
  }).finally(() => submission.resolve(void 0)));
7615
- });
7679
+ }
7616
7680
  };
7617
7681
  const sandbox = new CodemodeSandbox();
7618
7682
  const startedAt = performance.now();
@@ -7766,7 +7830,7 @@ function renderScriptTools(tools) {
7766
7830
  ...shown.map((entry) => entry.text),
7767
7831
  "};"
7768
7832
  ] : [],
7769
- ...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. A result with only params is a preview: search its exact name to get its input_schema before you call it. A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
7833
+ ...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. ${PARAMS_PREVIEW_HINT} A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
7770
7834
  ...Object.hasOwn(tools, "callMcpTool") ? ["Call an MCP tool as `tools.callMcpTool({ tool_name, arguments })`. Its `result` field holds the structured content of the MCP tool, or its text. `tools.mcp__<provider>__<tool>` does not exist."] : []
7771
7835
  ].join("\n");
7772
7836
  }
@@ -8866,6 +8930,22 @@ ${renderRules("deny")}
8866
8930
  - Rate risk and user authorization first.
8867
8931
  - Then set the rule to the id of the one rule that the action clearly matches. When a hard rule and a confirmation rule both match, name the hard rule. When no definition clearly fits, use \`none\`. Do not name a rule only to express general doubt.
8868
8932
  - Keep the reason to one concise, specific sentence. For a confirmation rule, name the exact action, target, and material side effects the user must confirm. For a hard rule, name the risk. For \`none\`, say why the action is ordinary.`;
8933
+ /**
8934
+ * Build Guardian's system prompt: the fixed policy, then the destination
8935
+ * facts that the install's plugins declare. The facts are sorted by plugin
8936
+ * name, so the prompt is the same for every review in a deployment and stays
8937
+ * cached.
8938
+ */
8939
+ function guardianSystemPrompt(facts = []) {
8940
+ if (facts.length === 0) return GUARDIAN_ACTION_POLICY;
8941
+ const lines = [...facts].sort((left, right) => left.plugin.localeCompare(right.plugin)).map((fact) => `- \`${fact.plugin}\`: ${fact.text}`);
8942
+ return [
8943
+ GUARDIAN_ACTION_POLICY,
8944
+ "# Destination Facts",
8945
+ "The plugins of this installation declare these facts about where their writes go, such as which destinations people outside the organization can read. They are authoritative facts about destinations. Use them when you apply the block rules. They never authorize an action.",
8946
+ ...lines
8947
+ ].join("\n\n");
8948
+ }
8869
8949
  // src/chat/guardian/reviewer.ts
8870
8950
  const guardianAssessmentSchema = z.object({
8871
8951
  riskLevel: z.enum(RISK_LEVELS),
@@ -8874,7 +8954,7 @@ const guardianAssessmentSchema = z.object({
8874
8954
  reason: z.string().trim().min(1).max(500)
8875
8955
  }).strict();
8876
8956
  const GUARDIAN_REVIEW_TIMEOUT_MS = 6e4;
8877
- const GUARDIAN_REVIEW_MAX_TOKENS = 8e3;
8957
+ const GUARDIAN_REVIEW_MAX_TOKENS = 2e3;
8878
8958
  const MAX_PROPOSAL_CHARS = 192e3;
8879
8959
  const RUN_RULES = [
8880
8960
  "The root user instructions section below is the earlier visible conversation of this run. Each line has the real author of its message as a prefix. The `userIntent` in the planned action is the current request, and the last `user:` lines can repeat it.",
@@ -8952,13 +9032,14 @@ function guardianDecision(assessment, proposal) {
8952
9032
  }
8953
9033
  /** Create the structured Guardian reviewer used for permissioned tool actions. */
8954
9034
  function createGuardianActionReviewer(options) {
9035
+ const system = guardianSystemPrompt(options.destinationFacts);
8955
9036
  return { async review(proposal, reviewOptions) {
8956
9037
  const timeoutSignal = AbortSignal.timeout(GUARDIAN_REVIEW_TIMEOUT_MS);
8957
9038
  const signal = reviewOptions?.signal ? AbortSignal.any([reviewOptions.signal, timeoutSignal]) : timeoutSignal;
8958
9039
  const completeReview = () => options.completeObject({
8959
9040
  modelId: options.modelId,
8960
9041
  schema: guardianAssessmentSchema,
8961
- system: GUARDIAN_ACTION_POLICY,
9042
+ system,
8962
9043
  prompt: guardianPrompt(proposal),
8963
9044
  maxTokens: GUARDIAN_REVIEW_MAX_TOKENS,
8964
9045
  operation: "guardian_action_review",
@@ -9586,12 +9667,17 @@ async function wireAgentTools(args) {
9586
9667
  priorRejections: restoreToolActionRejections(args.currentTurnMessages),
9587
9668
  reviewer: createGuardianActionReviewer({
9588
9669
  completeObject,
9670
+ destinationFacts: pluginCatalogRuntime.getProviders().flatMap(({ manifest }) => manifest.reviewContext ? [{
9671
+ plugin: manifest.name,
9672
+ text: manifest.reviewContext
9673
+ }] : []),
9589
9674
  modelId: botConfig.guardianModelId
9590
9675
  })
9591
9676
  });
9592
- const tools = createTools(loadableSkills(args.availableSkills, args.invokedSkill?.name), {
9593
- writeGeneratedArtifacts: async (files) => {
9594
- const refs = await agentSandbox.writeGeneratedArtifacts(files);
9677
+ const skills = loadableSkills(args.availableSkills, args.invokedSkill?.name, args.activeSkills);
9678
+ const tools = createTools(skills, {
9679
+ writeGeneratedFiles: async (files) => {
9680
+ const refs = await agentSandbox.writeGeneratedFiles(files);
9595
9681
  args.generatedFiles.push(...files);
9596
9682
  return refs;
9597
9683
  },
@@ -9599,6 +9685,7 @@ async function wireAgentTools(args) {
9599
9685
  onSkillLoaded: async (loadedSkill) => {
9600
9686
  const effective = await args.skillSandbox.loadSkill(loadedSkill.name) ?? loadedSkill;
9601
9687
  upsertActiveSkill(args.activeSkills, effective);
9688
+ skills.splice(0, skills.length, ...loadableSkills(args.availableSkills, args.invokedSkill?.name, args.activeSkills));
9602
9689
  await tryRecordSkillLoadStat(effective);
9603
9690
  }
9604
9691
  }, toolRuntimeContext, {
@@ -10676,11 +10763,12 @@ async function loadRetainedUserMessages(conversationId, pendingMessages) {
10676
10763
  };
10677
10764
  });
10678
10765
  }
10679
- const COMPACTION_READ_BACK_NOTE = "The summary replaced earlier messages and tool results. When you need an exact detail that the summary lacks, read the full text with the searchConversationEvents and readConversationEvent tools.";
10766
+ const COMPACTION_READ_BACK_NOTE = "The summary replaced earlier messages and tool results and leaves out most of their details. Before you call a detail unknown or ask for it, search for it with a searchConversationEvents query, then read the full text with readConversationEvent.";
10680
10767
  /**
10681
10768
  * Keep generated text inside the existing evidence-only prompt boundary. The
10682
10769
  * last line says where replaced detail stays readable: without it, the model
10683
- * often decides an exact value from a compacted tool result is gone.
10770
+ * often decides a detail from a compacted tool result is gone, and asks the
10771
+ * person for it.
10684
10772
  */
10685
10773
  function renderCompactionSummary(summary) {
10686
10774
  return [
@@ -11006,9 +11094,7 @@ function trimResult(message, seq) {
11006
11094
  */
11007
11095
  function trimToolResults(entries) {
11008
11096
  let latestInstructionIndex = -1;
11009
- entries.forEach((entry, index) => {
11010
- if (hasTurnInput(entry.message)) latestInstructionIndex = index;
11011
- });
11097
+ for (const [index, entry] of entries.entries()) if (hasTurnInput(entry.message)) latestInstructionIndex = index;
11012
11098
  const trimming = {
11013
11099
  trimmedResults: 0,
11014
11100
  removedChars: 0
@@ -12304,7 +12390,7 @@ function createAgentRunner(execute, options) {
12304
12390
  }
12305
12391
  };
12306
12392
  const loadStoredAttachments = async (attachments) => {
12307
- const { loadInputAttachments } = await import("./model-input-DYYF3a8B.js").then((n) => n.r);
12393
+ const { loadInputAttachments } = await import("./model-input-Xluiy-1W.js").then((n) => n.r);
12308
12394
  const storage = nextRun.environment?.attachmentStorage;
12309
12395
  if (!storage) throw new Error("Attachment storage is unavailable.");
12310
12396
  return await loadInputAttachments({
@@ -12318,14 +12404,17 @@ function createAgentRunner(execute, options) {
12318
12404
  attachments: await loadStoredAttachments(run.instruction.storedAttachments)
12319
12405
  };
12320
12406
  const drainSteeringMessages = nextRun.durability?.drainSteeringMessages;
12321
- if (drainSteeringMessages) nextRun.durability = {
12322
- ...nextRun.durability,
12323
- drainSteeringMessages: (accept) => drainSteeringMessages(async (messages) => accept(await Promise.all(messages.map(async ({ storedAttachments, ...message }) => storedAttachments?.length ? {
12324
- ...message,
12325
- attachments: await loadStoredAttachments(storedAttachments)
12326
- } : message))))
12327
- };
12407
+ if (drainSteeringMessages) {
12408
+ const limit = pLimit(8);
12409
+ nextRun.durability = {
12410
+ ...nextRun.durability,
12411
+ drainSteeringMessages: (accept) => drainSteeringMessages(async (messages) => accept(await Promise.all(messages.map(({ storedAttachments, ...message }) => limit(async () => storedAttachments?.length ? {
12412
+ ...message,
12413
+ attachments: await loadStoredAttachments(storedAttachments)
12414
+ } : message)))))
12415
+ };
12416
+ }
12328
12417
  return await execute(nextRun, streamFn);
12329
12418
  } };
12330
12419
  }
12331
- export { RetryableDeliveryError as A, parseSlackReviewItemClick as C, AttachmentDownloadError as D, parseSlackUserInputSubmission as E, requireTurnFailureEventId as F, shouldEmitDevAgentTrace as I, toolInvocationDestination as M, finalizeFailedTurnReplyWithEvent as N, readAttachmentContent as O, getAgentTurnDiagnosticsAttributes as P, buildSlackReviewItemModal as S, safeLinkUrl as T, createSlackReviewItemShow as _, buildAuthPauseResponse as a, findSlackThreadOwnerId as b, createClientMetadata as c, publicArtifactHeaders as d, readPublicArtifact as f, scheduledAutomationRunAttributes as g, logScheduledAutomationRunSkipped as h, measureTurnCompactionWait as i, actorFromRun as j, previewOriginBelongsTo as k, readMcpClientInformation as l, resolveDestinationVisibility as m, executeAgentRun as n, finalizeMcpAuthorization as o, unpublishedArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, resolveSlackReviewItemCardConversationId as v, parseSlackReviewItemFormTarget as w, SLACK_REVIEW_ITEM_VIEW_ID as x, syncReviewItemSlackCards as y };
12420
+ export { resumeConversationDelivery as A, shouldEmitDevAgentTrace as B, parseSlackReviewItemClick as C, canPauseConversationDelivery as D, parseSlackUserInputSubmission as E, actorFromRun as F, toolInvocationDestination as I, finalizeFailedTurnReplyWithEvent as L, readAttachmentContent as M, previewOriginBelongsTo as N, isConversationDeliveryPaused as O, RetryableDeliveryError as P, getAgentTurnDiagnosticsAttributes as R, buildSlackReviewItemModal as S, safeLinkUrl as T, createSlackReviewItemShow as _, buildAuthPauseResponse as a, findSlackThreadOwnerId as b, createClientMetadata as c, publicArtifactHeaders as d, readPublicArtifact as f, scheduledAutomationRunAttributes as g, logScheduledAutomationRunSkipped as h, measureTurnCompactionWait as i, AttachmentDownloadError as j, pauseConversationDelivery as k, readMcpClientInformation as l, resolveDestinationVisibility as m, executeAgentRun as n, finalizeMcpAuthorization as o, unpublishedArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, resolveSlackReviewItemCardConversationId as v, parseSlackReviewItemFormTarget as w, SLACK_REVIEW_ITEM_VIEW_ID as x, syncReviewItemSlackCards as y, requireTurnFailureEventId as z };