@sentry/junior 0.305.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 (98) hide show
  1. package/dist/{adapter-context-BpvbUki8.js → adapter-context-B69WPn6b.js} +2 -2
  2. package/dist/{admin-CoDt35ny.js → admin-nCJXMgkp.js} +2 -2
  3. package/dist/{agent-runner-C5d6rY5g.js → agent-runner-DdFcxAxG.js} +463 -303
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +19 -4
  7. package/dist/api.js +437 -310
  8. package/dist/{app-Cs157Zc5.d.ts → app-EZur8cVC.d.ts} +12 -3
  9. package/dist/app.d.ts +2 -2
  10. package/dist/app.js +532 -439
  11. package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
  12. package/dist/{briefs-BRdznF7c.js → briefs-Dl9lxi7J.js} +3 -3
  13. package/dist/{catalog-runtime-J52Tej47.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-CBZp0udd.js → config-362yMSIz.js} +183 -49
  24. package/dist/{connections-BYmuJ6Vm.js → connections-BJv3EjmB.js} +10 -8
  25. package/dist/{continue-in-slack-Cvot6S38.js → continue-in-slack-CFEevC7z.js} +5 -5
  26. package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
  27. package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
  28. package/dist/{conversation-privacy-D2pOzBNl.js → conversation-privacy-Tjj5P2W6.js} +1 -1
  29. package/dist/{conversation-turn-CI8WDpnK.js → conversation-turn-DU0_WDAr.js} +26 -72
  30. package/dist/{credential-sync-COqnZ1Dx.js → credential-sync-D6aFARKE.js} +28 -27
  31. package/dist/{db-DU84dCVu.js → db-Bcbd9zQc.js} +226 -18
  32. package/dist/{db-zbN5ZV_o.d.ts → db-C41UgdBj.d.ts} +1 -1
  33. package/dist/{executor-CFyrgOu1.js → executor-DBMBrpNV.js} +137 -33
  34. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  35. package/dist/{install-CQ76CfRw.js → install-CgoAbzfF.js} +2 -2
  36. package/dist/instrumentation.js +2 -2
  37. package/dist/{lineage-DLd2UxVP.js → lineage-CsZDmz3e.js} +2 -2
  38. package/dist/{logging-BPNTQVFu.js → logging-CHCuQ5iz.js} +1 -1
  39. package/dist/{message-BWJLeQ5e.js → message-B8vCbZZB.js} +8 -8
  40. package/dist/{model-input-DoM9Ht-d.js → model-input-Xluiy-1W.js} +3 -3
  41. package/dist/nitro.d.ts +2 -2
  42. package/dist/nitro.js +3 -4
  43. package/dist/{oauth-callback-server-DeHbnAQl.js → oauth-callback-server-BUuNvfvu.js} +2 -2
  44. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
  45. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  46. package/dist/{projection-CcFBVFUo.js → projection-xPpvqexa.js} +13423 -11432
  47. package/dist/{prompt-C5LREK2p.js → prompt-D8u4jFs_.js} +15 -7
  48. package/dist/{registry-BjZZqKqi.js → registry-D20hG3r6.js} +19 -9
  49. package/dist/{resolve-CeJgXuH1.js → resolve-BhCySRCW.js} +3 -3
  50. package/dist/{result-icDrueyB.js → result-DddO63S9.js} +13 -11
  51. package/dist/{runner-nVfMkMMB.js → runner-DQR9vYce.js} +13 -15
  52. package/dist/{sandbox-egress-signals-H9vQ5qRf.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
  53. package/dist/{automation-CuA3yEcD.js → schedule-BG1tEbRF.js} +380 -8
  54. package/dist/{schema-CKcu-IK6.d.ts → schema-CRXcj4fj.d.ts} +420 -143
  55. package/dist/{schema-Bx0Mlo32.js → schema-D4jdesIu.js} +62 -8
  56. package/dist/{service-account-DU5865XA.js → service-account-Bv5QwrEq.js} +8 -6
  57. package/dist/{service-account-Dw06p3zm.js → service-account-CNfycv0z.js} +3 -3
  58. package/dist/{session-stop-uotLtp4g.js → session-stop-BDdwyZaa.js} +878 -171
  59. package/dist/{skills-Bex1EaO5.js → skills-63i1Bcv1.js} +32 -28
  60. package/dist/{slack-conversation-unfurl-EPG3riWF.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -9
  61. package/dist/{spawn-CoD3vDuS.js → spawn-mwimEY9_.js} +6 -6
  62. package/dist/{state-nCR4Muhn.js → state-BBn9L6gC.js} +4 -4
  63. package/dist/{stop-BFVd0P0m.js → stop-Da-Ug7tg.js} +172 -239
  64. package/dist/{store-Ca6G962n.js → store-CdWg2r2L.js} +5 -5
  65. package/dist/{background-compaction-queue-BTqMIfTA.js → task-queue-BcjAYWyB.js} +164 -180
  66. package/dist/{task-runner-xsOPIxCZ.js → task-runner-CoXmMlsW.js} +13 -11
  67. package/dist/{thread-context-BOvZhsKK.js → thread-context-ZPGqOjW7.js} +8 -91
  68. package/dist/turn-session-routing-DFYak28Q.js +263 -0
  69. package/dist/{turn-user-message-BrhuyYrH.js → turn-user-message-B1S8nOnG.js} +3 -3
  70. package/dist/users-DDbENg-I.js +181 -0
  71. package/dist/{validation-BnY9K5WB.js → validation-fl21ps-k.js} +1 -1
  72. package/dist/{version-qROlRQGF.js → version-DCdMMx_0.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-CxUiOraX.js → viewer-DN_xzVKj.js} +3 -3
  75. package/dist/{warmup--Gkz7iB-.js → warmup-CxhEhm71.js} +842 -532
  76. package/dist/{web-message-id-lNodcCOI.js → web-message-id-BT8Mg8LL.js} +16 -1
  77. package/dist/{worker-DJ8d9fmD.js → worker-Btb1SB5h.js} +8 -7
  78. package/migrations/0114_plan_items.sql +22 -0
  79. package/migrations/0115_automation_creator_slack_index.sql +1 -0
  80. package/migrations/0116_conversation_event_search.sql +25 -0
  81. package/migrations/0117_automation_last_run.sql +46 -0
  82. package/migrations/0118_automation_last_run_index.sql +1 -0
  83. package/migrations/0119_money_micro_usd.sql +29 -0
  84. package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
  85. package/migrations/meta/0114_snapshot.json +5203 -0
  86. package/migrations/meta/0115_snapshot.json +5225 -0
  87. package/migrations/meta/0116_snapshot.json +5388 -0
  88. package/migrations/meta/0117_snapshot.json +5413 -0
  89. package/migrations/meta/0118_snapshot.json +5428 -0
  90. package/migrations/meta/0119_snapshot.json +5441 -0
  91. package/migrations/meta/0120_snapshot.json +5441 -0
  92. package/migrations/meta/_journal.json +49 -0
  93. package/package.json +10 -9
  94. package/dist/queue-B2AAL3ym.js +0 -115
  95. package/dist/schedule-cP0AACm1.js +0 -344
  96. package/dist/secrets-DHaJ5TTn.js +0 -18
  97. package/dist/task-queue-BLPZU6kC.js +0 -89
  98. package/dist/turn-session-routing-2bW2qfeb.js +0 -1792
@@ -1,31 +1,33 @@
1
- import { $ as loadTurnCheckpoint, $o as storeDeferredAttachment, $t as TurnSliceLimitExceededError, Aa as updateSlackMessage, An as isStandaloneRuntimeContextMessage, B as getAgentContextInputLimitTokens, Ba as isWorkspaceSnapshotNotReadyError, Bn as TURN_CONTEXT_TAG, Cn as getTerminalAssistantMessages, Da as postSlackMessage, Ds as credentialAuditAttributes, En as hasTurnInput, Fa as isAlreadyExistsError, Fn as stripRuntimeTurnContext, Fs as getConfigDefaults, G as AuthPausePersistenceError, Ga as createSandboxEgressCredentialToken, H as PluginCredentialFailureError, Ha as clearSandboxEgressSignals, Ia as throwSandboxOperationError, In as trimTrailingAssistantMessages, J as abandonReplacedPendingAuth, Ja as buildSandboxEgressNetworkPolicy, Jo as readLiveAttachment, K as AuthorizationFlowDisabledError, L as calculateContextCompactionTargetTokens, La as wrapSandboxSetupError, Ln as CAPABILITY_SECTION_TAG, Mn as isToolResultMessage, Mr as getReviewItem, Ms as historyItemFromPiMessage, Ni as getDashboardReviewItemLink, Nn as normalizeToolNameFromResult, Ns as piMessageFromHistoryItem, On as isAssistantMessage, Os as credentialAuditSource, Pn as retainRuntimeTurnContext, Ps as projectConversationEvents, Q as continuableMessages, Qa as tryWorkspaceRepoCheckoutPath, Qo as storeAttachments, Qt as TurnBudgetExceededError, R as getAgentBackgroundCompactionMarkTokens, Rn as REQUEST_CONTEXT_SECTION_TAG, Sa as deleteSlackMessage, Sn as getPiMessageRole, T as resolveTaskTitle, U as createPluginAuthOrchestration, Ua as consumeSandboxEgressAuthRequiredSignal, Un as readParentAgentTask, Uo as readSlackAttachmentSource, V as createPluginEgress, Va as workspaceSnapshotNotReadyUserMessage, Vi as renderToolResultNudge, W as authorizationId, Wa as consumeSandboxEgressPermissionDeniedSignal, Wi as getWorkspace, Xt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Y as canReusePendingAuthLink, Ya as resolveSandboxCommandEnvironment, Yn as createUserTokenStore, Za as SANDBOX_RUNTIME, Zt as TURN_LIMIT_WRAP_UP_MESSAGE, _n as CODE_MODE_CALL_STATUS_TEXT, ai as resolveChannelCapabilities, an as isAnswerToolName, ao as SANDBOX_COMMAND_PATH, as as isConversationScopedChannel, c as recordAgentsInstructionsUpdated, ca as formatProviderLabel, co as SANDBOX_SKILLS_ROOT, dn as sanitizeAssistantText, do as sandboxSkillFile, en as TurnToolCallLimitExceededError, eo as ToolInputError, es as SlackActionError, f as recordAuthorizationRequested, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, fs as sleep, g as recordToolExecutionStarted, gn as CODEMODE_TOOL_NAME, ha as normalizeSlackReplyMarkdown, hn as readNoReply, ho as runNonInteractiveCommand, hs as AttachmentSourceUnavailableError, i as loadConversationProjection, ia as getSandboxProvider, in as REPLY_TOOL_NAME, ja as uploadFilesToConversation, jn as isToolResultError, kn as isContinuablePiBoundary, l as recordAttachmentsDelivered, ln as decideReply, lo as SANDBOX_WORKSPACE_ROOT, m as recordMcpProviderConnected, mn as isLegacyNoReplyMarker, mo as buildNonInteractiveShellScript, nn as createTurnLimitGate, no as PluginToolDeniedError, nt as saveTurnCheckpoint, oi as getSlackToolContext, on as readTurnAnswer, oo as SANDBOX_DATA_ROOT, or as getPluginTools, p as recordGuardianActionReviewed, pa as escapeSlackMrkdwnText, po as buildCommandScript, q as AuthorizationPauseError, r as loadConnectedMcpProviders, ra as ensureDockerDaemon, rn as isTurnExecutionLimitExceededError, sa as deliverOAuthAuthorization, sn as remindMissingAnswer, ta as hash, to as isToolInputError, tr as createPluginHookRunner, ua as resolveBaseUrl, un as getAssistantReplyText, uo as sandboxSkillDir, vn as REPORT_BLOCKED_TOOL_NAME, vs as createConversationEmbedder, wn as getUserMessageInstructionText, ws as resolveUserTimezone, xa as addReactionToMessage, xn as extractAssistantText, yn as readBlockedReport, z as getAgentContextCompactionTriggerTokens, za as getWorkspaceSnapshotNotReadyError } from "./projection-CcFBVFUo.js";
2
- import { $ as bufferBody, B as unwrapCurrentInstruction, F as textCharsForTokens, G as createProviderError, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, K as findProviderError, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, U as ProviderError, V as escapeXml, W as createAssistantProviderError, X as isProviderRetryError, Y as isProviderRefusal, Z as getGatewayApiKey, b as GEN_AI_PROVIDER_NAME, j as requestPrefixAttributes, k as resolveGatewayModel, n as botConfig, q as getProviderErrorAttributes, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-CBZp0udd.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, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-BPNTQVFu.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-D2pOzBNl.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 { T as isPersonInput, X as getStateAdapter, a as getConversationStore, k as turnBehavior, nt as withLock, o as getDb, ot as addAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, st as agentTurnCostUsd, ut as hasAgentTurnUsage, yt as sameDestination } from "./db-DU84dCVu.js";
8
- import { L as juniorArtifacts, c as juniorReviewItemSlackCards, u as juniorAutomationRuns } from "./executor-CFyrgOu1.js";
9
- import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-m2-ceTTX.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
+ 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-BjZZqKqi.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-J52Tej47.js";
13
- import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-Bex1EaO5.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-DU5865XA.js";
15
- import { f as generateImages, h as NoAudioError, l as completeObject, m as transcribeFromUrl, u as completeText } from "./prompt-C5LREK2p.js";
16
- import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-CxUiOraX.js";
17
- import { W as MAX_ATTACHMENT_BYTES } from "./conversation-BOqdRtUx.js";
18
- import { Q as getEventCatalog, R as resolveSlackReplyTarget, St as writeAgentHistory, _t as showsAgentsInstructions, bt as readAgentHistory, d as buildPromptInput, dt as AGENTS_REMOVAL_NOTICE, et as requireSlackChannelMessageScope, f as buildSteeringPiMessage, ft as AGENTS_REPLACEMENT_NOTICE, gt as renderAgentsInstructions, h as loadPromptTurnContext, ht as readRepositoryInstructions, it as slackChannelMessageTrigger, mt as findVisibleAgentsInstructions, pt as buildAgentsInstructionsMessage, u as assemblePrompt, ut as JUNIOR_PERSONALITY, vt as foldLeadingSystemMessages, xt as withAgentRequest, yt as foldSystemMessages } from "./session-stop-uotLtp4g.js";
19
- import { $ as createBashTool, $n as createSlackPublicSearchTool, $r as requireToolCreator, A as createWebSearchTool, Ar as createSearchAutomationsTool, B as createSystemTimeTool, Br as automationTriggerChangesSchema, C as incrementStat, Ci as missingAutomationSkillReason, Cr as createSlackCanvasEditTool, D as requireReadyWorkspaceSnapshot, Dr as resolveWorkspacePath, Ei as resolveTaskOutcomes, Er as positiveInteger, F as userLookupIdentityProviders, Fr as zodToolDefinition, Ft as createRunOperatorSqlTool, G as createWriteFileTool, Gr as injectContinuationToolName, H as createSearchEventTypesTool, Hr as editedAutomationTask, Ir as automationIdForToolCall, It as createListWatchesTool, J as sliceFileContent, Jr as getConversationAccess, K as createReadFileTool, Kr as juniorToolOutputSchema, Lr as automationSkillToolSchema, M as createWatchTimerTool, Mr as createDeleteAutomationTool, N as createWatchEventsTool, Nr as AUTOMATIONS_TOOL_SOURCE, O as prepareWorkspaceSnapshot, Or as createOperationKey, P as createUserLookupTool, Pr as zodTool, Pt as createReadConversationEventTool, Q as editFile, Qr as requireToolCaller, R as createUpdateUserCustomizationTool, Rr as automationToolResult, S as createWorkspaceTools, Sr as createSlackCanvasReadTool, T as ensureWorkspaceSnapshotBuild, Ti as moveTaskOutcomes, Tr as isMissingPathError, U as createSearchConversationEventsTool, Ur as newAutomationTask, V as createStopWatchingResourcesTool, Vr as automationTriggerSchema, W as createSearchConversationsTool, Wn as createSetConversationSubscriptionTool, Wr as triggerKind, X as capToolResult, Xr as automationToolsDisabledReason, Y as TOOL_RESULT_MAX_CHARS, Yn as createSlackThreadReadTool, Yr as automationToolContext, Z as createEditFileTool, Zr as requireToolAutomation, _i as changedEventMatch, _t as createUpdateReviewItemTool, a as createCacheWarmingRecorder, ar as createSlackConversationSearchChannelPort, at as createReportBlockedTool, b as coreToolSlots, ct as createMessageAgentTool, dr as resolveSlackChannelRef, ei as requireToolDestination, er as createSlackListUpdateItemTool, et as createUpdatePlanTool, fr as slackChannelRefParam, gi as editEventAutomation, gt as createSearchReviewItemsTool, hi as editScheduledAutomation, ht as createAddReviewItemTool, in as isParentMessageMeta, ir as createSlackConversationMessageSearchTool, it as createReportProgressTool, j as createWebFetchTool, jr as createRunAutomationNowTool, kr as createCanvas, lt as createArchiveAgentTool, mr as joinPublicChannelForRead, ni as automationEditor, nr as createSlackListCreateTool, nt as createSpawnAgentTool, or as createSlackChannelListMessagesTool, ot as createReplyTool, pr as checkSlackChannelReadAccess, q as missingFileResult, qr as makeStructuredToolOutput, qt as listAgentInvocationsForConversation, ri as changeAutomationLifecycle, rr as createSlackListAddItemsTool, rt as createListAgentsTool, st as createNoReplyTool, tr as createSlackListGetItemsTool, tt as createStopAgentTool, ur as createSlackChannelJoinTool, vi as requireEventAutomationTrigger, wr as SLACK_TOOL_SOURCE, x as enabledMode, xi as requireAutomationSkill, xr as createSlackCanvasWriteTool, yi as requireAutomationTaskText, z as createSubmitFeedbackTool, zr as automationToolResultSchema } from "./warmup--Gkz7iB-.js";
20
- import { D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, I as scheduleIntentFromTool, O as taskOutcomeInputSchema, P as ScheduleIntentError, T as automationContextToolSchema, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR } from "./automation-CuA3yEcD.js";
21
- import { G as readScheduledAutomation, K as saveScheduledAutomation, Q as createEventAutomation, V as createScheduledAutomation, it as saveEventAutomation, mt as automationRevision, t as resolveConversationRouting, tt as getEventAutomation } from "./turn-session-routing-2bW2qfeb.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-lNodcCOI.js";
23
- import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-BrhuyYrH.js";
24
- import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-BTqMIfTA.js";
25
- import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-CQ76CfRw.js";
26
- import { n as resolve$1 } from "./resolve-CeJgXuH1.js";
27
- import { t as runWithSlackInstallation } from "./adapter-context-BpvbUki8.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
+ import { Z as MAX_ATTACHMENT_BYTES } from "./conversation--f85g4zL.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;
@@ -1023,6 +1023,106 @@ function buildGatedTurnResult(input, answer) {
1023
1023
  })
1024
1024
  };
1025
1025
  }
1026
+ // src/chat/interruption-marker.ts
1027
+ const INTERRUPTED_MARKER = "\n\n[Response interrupted before completion]";
1028
+ /** Return the marker added when a visible reply ended mid-execution. */
1029
+ function getInterruptionMarker() {
1030
+ return INTERRUPTED_MARKER;
1031
+ }
1032
+ // src/chat/services/turn-failure-response.ts
1033
+ /** Require captured turn failures to carry a real Sentry event reference. */
1034
+ function requireTurnFailureEventId(eventId, eventName) {
1035
+ if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
1036
+ return eventId;
1037
+ }
1038
+ function getExecutionFailureReason(reply) {
1039
+ const errorMessage = reply.diagnostics.errorMessage?.trim();
1040
+ if (errorMessage) return errorMessage;
1041
+ if (reply.diagnostics.toolErrorCount > 0) return `${reply.diagnostics.toolErrorCount} tool result error(s)`;
1042
+ if (reply.diagnostics.assistantMessageCount > 0) return "assistant returned no text";
1043
+ return "empty assistant turn";
1044
+ }
1045
+ /** Return a fixed reason label for a failed model turn. */
1046
+ function getTurnFailureReason(reply) {
1047
+ if (reply.diagnostics.outcome === "success") return;
1048
+ if (reply.diagnostics.outcome === "provider_error") return findProviderError(reply.diagnostics.providerError)?.kind ?? "unknown";
1049
+ if (reply.diagnostics.toolErrorCount > 0) return "tool_errors";
1050
+ if (reply.diagnostics.usedPrimaryText && reply.diagnostics.assistantMessageCount > 0) return "suppressed_output";
1051
+ return "empty_output";
1052
+ }
1053
+ function getFailureCapture(reply) {
1054
+ if (reply.diagnostics.outcome === "provider_error") {
1055
+ const providerError = findProviderError(reply.diagnostics.providerError);
1056
+ return {
1057
+ eventName: "agent.turn.provider_error",
1058
+ error: reply.diagnostics.providerError ?? new Error(reply.diagnostics.errorMessage ?? "Provider error without explicit message"),
1059
+ attributes: providerError ? getProviderErrorAttributes(providerError) : {},
1060
+ body: "Agent turn failed with provider error"
1061
+ };
1062
+ }
1063
+ const failureReason = getExecutionFailureReason(reply);
1064
+ return {
1065
+ eventName: "agent.turn.execution.failed",
1066
+ error: /* @__PURE__ */ new Error(`Agent turn execution failure: ${failureReason}`),
1067
+ attributes: { "app.ai.execution_failure_reason": failureReason },
1068
+ body: "Agent turn completed with execution failure"
1069
+ };
1070
+ }
1071
+ /** Keep failed-turn Sentry captures and completion spans on the same keys. */
1072
+ function getAgentTurnDiagnosticsAttributes(reply) {
1073
+ return {
1074
+ "app.ai.outcome": reply.diagnostics.outcome,
1075
+ "app.ai.assistant_messages": reply.diagnostics.assistantMessageCount,
1076
+ "app.ai.tool_results": reply.diagnostics.toolResultCount,
1077
+ "app.ai.tool_error_results": reply.diagnostics.toolErrorCount,
1078
+ "app.ai.tool_call_count": reply.diagnostics.toolCalls.length,
1079
+ "app.ai.used_primary_text": reply.diagnostics.usedPrimaryText,
1080
+ ...reply.diagnostics.reasoningLevel ? { "gen_ai.request.reasoning.level": reply.diagnostics.reasoningLevel } : void 0,
1081
+ ...reply.diagnostics.stopReason ? { "gen_ai.response.finish_reasons": [reply.diagnostics.stopReason] } : void 0,
1082
+ ...reply.diagnostics.errorMessage && reply.diagnostics.outcome !== "provider_error" ? { "exception.message": reply.diagnostics.errorMessage } : void 0
1083
+ };
1084
+ }
1085
+ /**
1086
+ * Report one failed agent run to Sentry and attach the event ID.
1087
+ *
1088
+ * The agent run is the only caller. It reports inside its log and privacy
1089
+ * context, so the event has the run's context and redaction. Callers read the
1090
+ * ID from `diagnostics.eventId` and never report the run again.
1091
+ */
1092
+ function captureTurnFailure(result, logException) {
1093
+ const failureReason = getTurnFailureReason(result);
1094
+ const capture = getFailureCapture(result);
1095
+ const eventId = requireTurnFailureEventId(logException(capture.error, capture.eventName, {
1096
+ ...getAgentTurnDiagnosticsAttributes(result),
1097
+ ...capture.attributes,
1098
+ ...failureReason ? { "app.ai.failure_reason": failureReason } : void 0
1099
+ }), capture.eventName);
1100
+ return {
1101
+ ...result,
1102
+ diagnostics: {
1103
+ ...result.diagnostics,
1104
+ eventId
1105
+ }
1106
+ };
1107
+ }
1108
+ /** Build the failure reply for a reported failed run, with its event ID. */
1109
+ function finalizeFailedTurnReplyWithEvent(args) {
1110
+ if (args.reply.diagnostics.outcome === "success") return { reply: args.reply };
1111
+ const failureReason = getTurnFailureReason(args.reply);
1112
+ const eventId = args.reply.diagnostics.eventId;
1113
+ if (!eventId) throw new Error("Failed agent run has no Sentry event ID");
1114
+ const providerPartialText = args.reply.diagnostics.outcome === "provider_error" && args.reply.diagnostics.assistantMessageCount > 0 ? args.reply.text.trim() : "";
1115
+ const providerUserMessage = args.reply.diagnostics.providerError instanceof ProviderError ? getProviderErrorUserMessage(args.reply.diagnostics.providerError) : "";
1116
+ const failureText = providerUserMessage ? `${providerUserMessage} Reference: \`event_id=${eventId}\`.` : buildTurnFailureResponse(eventId);
1117
+ return {
1118
+ eventId,
1119
+ ...failureReason ? { failureReason } : void 0,
1120
+ reply: {
1121
+ ...args.reply,
1122
+ text: providerPartialText ? `${providerPartialText}${getInterruptionMarker()}` : failureText
1123
+ }
1124
+ };
1125
+ }
1026
1126
  // src/chat/services/provider-retry.ts
1027
1127
  const PROVIDER_RETRY_DELAYS_MS = [
1028
1128
  2e3,
@@ -1359,11 +1459,15 @@ function upsertActiveSkill(activeSkills, next) {
1359
1459
  activeSkills.push(next);
1360
1460
  }
1361
1461
  /**
1362
- * Return the skills that the model can load with `loadSkill`. A user-callable
1363
- * 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.
1364
1467
  */
1365
- function loadableSkills(availableSkills, invokedSkillName) {
1366
- 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));
1367
1471
  }
1368
1472
  /** Discover skills for one slice; emits the startup discovery summary once per process. */
1369
1473
  async function discoverRunSkills(args) {
@@ -1713,36 +1817,39 @@ async function listFilesRecursive(root) {
1713
1817
  return files;
1714
1818
  }
1715
1819
  async function buildSkillSyncFiles(availableSkills, referenceFiles) {
1716
- const filesToWrite = [];
1717
- const index = { skills: [] };
1718
- for (const skill of availableSkills) {
1719
- const skillFiles = await listFilesRecursive(skill.skillPath);
1720
- for (const absoluteFile of skillFiles) {
1721
- const relative = toPosixRelative(skill.skillPath, absoluteFile);
1722
- if (!relative || relative.startsWith("..")) continue;
1723
- filesToWrite.push({
1724
- path: `${sandboxSkillDir(skill.name)}/${relative}`,
1725
- content: await fs.readFile(absoluteFile)
1726
- });
1727
- }
1728
- index.skills.push({
1729
- name: skill.name,
1730
- description: skill.description,
1731
- root: sandboxSkillDir(skill.name)
1732
- });
1733
- }
1734
- filesToWrite.push({
1735
- path: `${SANDBOX_SKILLS_ROOT}/index.json`,
1736
- content: Buffer.from(JSON.stringify(index), "utf8")
1737
- });
1738
- if (referenceFiles && referenceFiles.length > 0) for (const absoluteFile of referenceFiles) {
1739
- const fileName = path.basename(absoluteFile);
1740
- filesToWrite.push({
1741
- path: `${SANDBOX_DATA_ROOT}/${fileName}`,
1742
- content: await fs.readFile(absoluteFile)
1743
- });
1744
- }
1745
- 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
+ ];
1746
1853
  }
1747
1854
  /** Resolve a virtual sandbox skill path back to the host filesystem when no sandbox exists yet. */
1748
1855
  function resolveHostSkillPath(availableSkills, sandboxPath) {
@@ -2469,6 +2576,7 @@ function createWorkspaceSnapshotNotReadyToolResult(cause) {
2469
2576
  });
2470
2577
  }
2471
2578
  const VERCEL_FIREWALL_CHALLENGE_MARKER = "Vercel Security Checkpoint";
2579
+ const REPOSITORY_INSTRUCTIONS_READ_TIMEOUT_MS = 3e4;
2472
2580
  const SANDBOX_TOOL_NAMES = /* @__PURE__ */ new Set([
2473
2581
  "bash",
2474
2582
  "readFile",
@@ -2780,9 +2888,16 @@ function createSandbox(options) {
2780
2888
  const { runCommand } = await runtime.tools();
2781
2889
  const workspaceDirectories = activeWorkspace?.repos.map((repo) => tryWorkspaceRepoCheckoutPath(repo.repo)).filter((checkoutPath) => Boolean(checkoutPath)).map((checkoutPath) => `${SANDBOX_WORKSPACE_ROOT}/${checkoutPath}`) ?? [];
2782
2890
  return await withSandboxSpan("sandbox.repository_instructions.read", "sandbox.repository_instructions.read", {}, async (setSpanAttributes) => {
2891
+ const timeout = AbortSignal.timeout(REPOSITORY_INSTRUCTIONS_READ_TIMEOUT_MS);
2783
2892
  const { directories, instructions } = await readRepositoryInstructions({
2784
2893
  ...workspaceDirectories.length > 0 ? { directories: workspaceDirectories } : void 0,
2785
- runCommand
2894
+ runCommand: (input) => runCommand({
2895
+ ...input,
2896
+ signal: timeout
2897
+ })
2898
+ }).catch((error) => {
2899
+ if (!timeout.aborted) throw error;
2900
+ throw new SandboxCallTimeoutError("sandbox.repository_instructions.read", REPOSITORY_INSTRUCTIONS_READ_TIMEOUT_MS, { cause: error });
2786
2901
  });
2787
2902
  setSpanAttributes({
2788
2903
  "app.repository_instructions.repo_count": directories.length,
@@ -2824,7 +2939,8 @@ function createSandbox(options) {
2824
2939
  /** Maximum single file size accepted by model-facing upload tools. */
2825
2940
  const MAX_SANDBOX_FILE_UPLOAD_BYTES = 10485760;
2826
2941
  /** Sandbox directory for generated files that later tools can consume. */
2827
- const SANDBOX_ARTIFACTS_DIR = "/tmp/junior/artifacts";
2942
+ const SANDBOX_GENERATED_DIR = `${SANDBOX_SCRATCH_ROOT}/gen`;
2943
+ const MAX_GENERATED_FILENAME_CODE_POINTS = 60;
2828
2944
  /** Canonical model-facing reference to a file that already exists in the sandbox. */
2829
2945
  const sandboxFileReferenceSchema = z.object({
2830
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."),
@@ -2833,7 +2949,7 @@ const sandboxFileReferenceSchema = z.object({
2833
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.")
2834
2950
  });
2835
2951
  /** Generated file reference whose path and metadata can be passed directly to sendFiles. */
2836
- const generatedArtifactFileRefSchema = sandboxFileReferenceSchema.extend({
2952
+ const generatedFileRefSchema = sandboxFileReferenceSchema.extend({
2837
2953
  filename: z.string().min(1),
2838
2954
  mime_type: z.string().min(1).optional(),
2839
2955
  bytes: z.number().int().nonnegative()
@@ -2877,9 +2993,22 @@ function sanitizeFilename(value, fallbackPath) {
2877
2993
  if (derived && derived !== "." && derived !== "..") return derived;
2878
2994
  return "attachment.bin";
2879
2995
  }
2880
- /** Return the canonical sandbox artifact path for generated files. */
2881
- function sandboxArtifactPath(filename) {
2882
- 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")));
2883
3012
  }
2884
3013
  /** Infer upload MIME type from an explicit value or filename extension. */
2885
3014
  function inferMimeType(filename, explicitMimeType) {
@@ -2922,37 +3051,32 @@ async function readSandboxFileUpload(workspace, input) {
2922
3051
  path: targetPath
2923
3052
  };
2924
3053
  }
2925
- // src/chat/tools/sandbox/generated-artifacts.ts
3054
+ // src/chat/tools/sandbox/generated-files.ts
2926
3055
  async function fileUploadDataToBuffer(data) {
2927
3056
  if (Buffer.isBuffer(data)) return data;
2928
3057
  if (data instanceof ArrayBuffer) return Buffer.from(data);
2929
3058
  return Buffer.from(await data.arrayBuffer());
2930
3059
  }
2931
- /** Persist generated artifacts into the sandbox before returning model-visible handles. */
2932
- async function writeSandboxGeneratedArtifacts(workspace, files) {
2933
- const mkdir = await workspace.runCommand({
2934
- cmd: "mkdir",
2935
- args: ["-p", SANDBOX_ARTIFACTS_DIR]
2936
- });
2937
- if (mkdir.exitCode !== 0) throw new Error(`failed to create generated artifact directory: ${mkdir.stderr}`);
2938
- 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 () => {
2939
3064
  const content = await fileUploadDataToBuffer(file.data);
2940
- const artifactPath = sandboxArtifactPath(file.filename);
2941
3065
  return {
2942
3066
  content,
2943
3067
  ref: {
2944
3068
  bytes: content.byteLength,
2945
3069
  filename: file.filename,
2946
3070
  mime_type: file.mimeType,
2947
- path: artifactPath
3071
+ path: sandboxGeneratedFilePath(content, file.filename)
2948
3072
  }
2949
3073
  };
2950
- }));
2951
- await workspace.writeFiles(artifacts.map((artifact) => ({
2952
- content: artifact.content,
2953
- path: artifact.ref.path
2954
3074
  })));
2955
- 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);
2956
3080
  }
2957
3081
  // src/chat/tool-support/normalize-result.ts
2958
3082
  function isToolContent(value) {
@@ -3217,8 +3341,8 @@ function createAgentSandbox(options) {
3217
3341
  return await sandbox.tools.execute(params);
3218
3342
  }
3219
3343
  },
3220
- async writeGeneratedArtifacts(files) {
3221
- return await writeSandboxGeneratedArtifacts(sandbox.workspace, files);
3344
+ async writeGeneratedFiles(files) {
3345
+ return await writeSandboxGeneratedFiles(sandbox.workspace, files);
3222
3346
  }
3223
3347
  };
3224
3348
  }
@@ -3245,7 +3369,7 @@ function createCreatePreviewTool(createPreview) {
3245
3369
  openWorldHint: true,
3246
3370
  readOnlyHint: false
3247
3371
  },
3248
- approvalMode: "approve",
3372
+ approvalMode: "review",
3249
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.",
3250
3374
  executionMode: "sequential",
3251
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(),
@@ -3282,10 +3406,11 @@ async function renewPreviewOrigins(sandbox, resolveOwner) {
3282
3406
  await runBestEffort(async () => {
3283
3407
  const owner = await resolveOwner();
3284
3408
  if (!owner) return;
3285
- await Promise.all(urls.map(async (url) => await recordPreviewOrigin({
3409
+ const limit = pLimit(8);
3410
+ await Promise.all(urls.map((url) => limit(() => recordPreviewOrigin({
3286
3411
  ownerEmail: owner.email,
3287
3412
  url
3288
- })));
3413
+ }))));
3289
3414
  }, "sandbox.preview_origin.renew.failed");
3290
3415
  }
3291
3416
  /** Return true when Junior made the Preview at `origin` for this person. */
@@ -3337,7 +3462,7 @@ const imageGenerateOutputSchema = juniorToolOutputSchema.extend({
3337
3462
  prompt: z.string(),
3338
3463
  enriched_prompt: z.string(),
3339
3464
  image_count: z.number().int().nonnegative(),
3340
- images: z.array(generatedArtifactFileRefSchema),
3465
+ images: z.array(generatedFileRefSchema),
3341
3466
  delivery: z.string(),
3342
3467
  resized_images: z.array(resizedImageSchema).optional(),
3343
3468
  resize_notice: z.string().optional()
@@ -3439,7 +3564,7 @@ function extensionForMediaType(mediaType) {
3439
3564
  return "bin";
3440
3565
  }
3441
3566
  /**
3442
- * 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.
3443
3568
  *
3444
3569
  * @runBuilt imageGenerate
3445
3570
  */
@@ -3489,13 +3614,13 @@ function createImageGenerateTool(hooks, options, deps = {}) {
3489
3614
  mimeType: image.mediaType
3490
3615
  }));
3491
3616
  if (uploads.length > 0) {
3492
- const artifactRefs = await hooks.writeGeneratedArtifacts(uploads);
3617
+ const fileRefs = await hooks.writeGeneratedFiles(uploads);
3493
3618
  return {
3494
3619
  model,
3495
3620
  prompt,
3496
3621
  enriched_prompt: enrichedPrompt,
3497
- image_count: artifactRefs.length,
3498
- images: artifactRefs,
3622
+ image_count: fileRefs.length,
3623
+ images: fileRefs,
3499
3624
  ...resizeResult,
3500
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."
3501
3626
  };
@@ -3944,18 +4069,16 @@ function parseMcpProviderFromToolName(toolName) {
3944
4069
  const delimiterIndex = afterPrefix.indexOf("__");
3945
4070
  return delimiterIndex > 0 ? afterPrefix.slice(0, delimiterIndex) : void 0;
3946
4071
  }
3947
- // src/chat/tools/skill/call-mcp-tool.ts
3948
- function resolveMcpArguments(input) {
3949
- const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments" && key !== "intent");
3950
- if (extraKeys.length > 0) throw new ToolInputError(`callMcpTool MCP arguments must be nested under arguments, not top-level fields: ${extraKeys.join(", ")}`);
3951
- if ("arguments" in input) {
3952
- const args = input["arguments"];
3953
- if (args === void 0) return {};
3954
- if (!args || typeof args !== "object" || Array.isArray(args)) throw new ToolInputError("callMcpTool arguments must be an object when provided");
3955
- return args;
3956
- }
3957
- return {};
4072
+ // src/chat/tool-support/dispatcher-envelope.ts
4073
+ /**
4074
+ * Error map for a dispatcher envelope schema. It tells the model to nest the
4075
+ * target tool's fields under `arguments` when it sends them at the top level.
4076
+ */
4077
+ function nestedArgumentsErrorMap(label) {
4078
+ return (issue) => issue.code === "unrecognized_keys" ? `${label} arguments must be nested under arguments, not top-level fields: ${issue.keys.join(", ")}` : void 0;
3958
4079
  }
4080
+ // src/chat/tools/skill/call-mcp-tool.ts
4081
+ const MISSING_TOOL_NAME_ERROR$1 = "callMcpTool requires an MCP tool_name";
3959
4082
  function activeProviderNames(tools) {
3960
4083
  return [...new Set(tools.map((toolDef) => toolDef.provider))].sort((a, b) => a.localeCompare(b));
3961
4084
  }
@@ -3978,10 +4101,10 @@ function createCallMcpToolTool(mcpToolManager) {
3978
4101
  },
3979
4102
  description: "Call an active MCP tool by its exact name. Use searchMcpTools to discover tool names and schemas; copy required provider fields into arguments. Authorization is handled by the runtime when required.",
3980
4103
  inputSchema: z.object({
3981
- tool_name: z.string().min(1).describe("Exact MCP tool_name from searchMcpTools."),
3982
- arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the disclosed MCP tool schema, for example { \"query\": \"...\" } when searchMcpTools shows query is required. Omit only when the discovered tool has no arguments.").optional(),
4104
+ tool_name: z.string({ error: MISSING_TOOL_NAME_ERROR$1 }).min(1, { error: MISSING_TOOL_NAME_ERROR$1 }).describe("Exact MCP tool_name from searchMcpTools."),
4105
+ arguments: z.record(z.string(), z.unknown(), { error: "callMcpTool arguments must be an object when provided" }).describe("Arguments matching the disclosed MCP tool schema, for example { \"query\": \"...\" } when searchMcpTools shows query is required. Omit only when the discovered tool has no arguments.").optional(),
3983
4106
  intent: z.string().min(1).describe("Optional short purpose to show the user if this call needs them to connect their account, for example \"search Notion for the Q3 offsite doc\".").optional()
3984
- }).passthrough(),
4107
+ }, { error: nestedArgumentsErrorMap("callMcpTool MCP") }).strict(),
3985
4108
  resolveApprovalMetadata: ({ tool_name }) => {
3986
4109
  const activeTool = mcpToolManager.getResolvedActiveTools().find((candidate) => candidate.name === tool_name);
3987
4110
  if (!activeTool) return;
@@ -4018,7 +4141,7 @@ function createCallMcpToolTool(mcpToolManager) {
4018
4141
  });
4019
4142
  throw new McpToolError(missingToolMessage(tool_name, provider));
4020
4143
  }
4021
- const result = await mcpTool.execute(resolveMcpArguments(input), {
4144
+ const result = await mcpTool.execute(input.arguments ?? {}, {
4022
4145
  ...intent ? { authorizationIntent: intent } : void 0,
4023
4146
  conversationPrivacy: options?.conversationPrivacy ?? "private",
4024
4147
  ...options?.signal ? { signal: options.signal } : void 0,
@@ -4346,6 +4469,38 @@ function createSlackMessageAddReactionTool(context, state) {
4346
4469
  }
4347
4470
  });
4348
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
+ }
4349
4504
  // src/chat/slack/user-input.ts
4350
4505
  const FIELD_BLOCK_ID_PREFIX = "field:";
4351
4506
  const OTHER_BLOCK_ID = "other";
@@ -4769,7 +4924,8 @@ function createSlackReviewItemShow(getSlackAdapter) {
4769
4924
  }
4770
4925
  /**
4771
4926
  * Show the current state of a Review item in its linked Slack threads. An
4772
- * 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
4773
4929
  * card changes in place. A card in a thread that can no longer show the item
4774
4930
  * loses its content. A closed item posts no new cards. Syncs of one item run
4775
4931
  * one at a time under a state lock, so two syncs cannot post two cards in
@@ -4790,7 +4946,9 @@ async function syncReviewItemSlackCards(args) {
4790
4946
  const linkedThreads = /* @__PURE__ */ new Map();
4791
4947
  for (const thread of linked) if (thread && !linkedThreads.has(threadKey(thread))) linkedThreads.set(threadKey(thread), thread);
4792
4948
  const cardedKeys = new Set(carded.flatMap((thread) => thread ? [threadKey(thread)] : []));
4793
- 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();
4794
4952
  const failed = (await Promise.allSettled([...rows.map((row, index) => {
4795
4953
  const thread = carded[index];
4796
4954
  const shown = !!thread && linkedThreads.has(threadKey(thread));
@@ -5562,7 +5720,7 @@ function createPublishImageTool(args) {
5562
5720
  inputSchema: z.object({ path: z.string().min(1).describe("Exact sandbox path of an existing image file.") }).strict(),
5563
5721
  outputSchema: outputSchema$1,
5564
5722
  async execute({ path }) {
5565
- const publicBaseUrl = (args.publicBaseUrl ?? resolveBaseUrl)()?.trim();
5723
+ const publicBaseUrl = resolveBaseUrl()?.trim();
5566
5724
  if (!publicBaseUrl) throw new Error("publishImage requires JUNIOR_BASE_URL or a Vercel deployment URL.");
5567
5725
  const targetPath = normalizeSandboxPath(path);
5568
5726
  const body = await args.workspace.readFileToBuffer({ path: targetPath });
@@ -5645,7 +5803,7 @@ function isPublic(run) {
5645
5803
  return run.context.conversationPrivacy === "public";
5646
5804
  }
5647
5805
  const STATIC_TOOL_BINDERS = {
5648
- updatePlan: () => createUpdatePlanTool(),
5806
+ updatePlan: (run) => createUpdatePlanTool(run.context, run.reviewItemServices().findMentionedUserId),
5649
5807
  reportProgress: () => createReportProgressTool(),
5650
5808
  systemTime: () => createSystemTimeTool(),
5651
5809
  submitFeedback: (run) => createSubmitFeedbackTool(run.context),
@@ -5671,7 +5829,13 @@ const STATIC_TOOL_BINDERS = {
5671
5829
  runOperatorSql: (run) => isPublic(run) ? void 0 : createRunOperatorSqlTool(),
5672
5830
  updateUserCustomization: (run) => createUpdateUserCustomizationTool(run.context),
5673
5831
  setConversationSubscription: (run) => createSetConversationSubscriptionTool(run.context),
5674
- 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),
5675
5839
  readConversationEvent: (run) => createReadConversationEventTool(run.context),
5676
5840
  searchConversations: (run) => createSearchConversationsTool({
5677
5841
  ...run.slack ? { channels: createSlackConversationSearchChannelPort(run.slack.teamId) } : void 0,
@@ -5692,8 +5856,8 @@ const STATIC_TOOL_BINDERS = {
5692
5856
  parentConversationId: run.context.parentConversationId
5693
5857
  }) : void 0,
5694
5858
  messageAgent: (run) => run.context.messageAgent ? createMessageAgentTool(run.context.messageAgent) : void 0,
5695
- [REPLY_TOOL_NAME]: (run) => createReplyTool(enabledMode(run.context.turnTools.reply)),
5696
- [REPORT_BLOCKED_TOOL_NAME]: (run) => createReportBlockedTool(enabledMode(run.context.turnTools.reportBlocked)),
5859
+ [REPLY_TOOL_NAME]: (run) => createReplyTool(enabledMode(run.listedTools.reply)),
5860
+ [REPORT_BLOCKED_TOOL_NAME]: (run) => createReportBlockedTool(enabledMode(run.listedTools.reportBlocked)),
5697
5861
  [NO_REPLY_TOOL_NAME]: () => createNoReplyTool(),
5698
5862
  slackCanvasRead: () => createSlackCanvasReadTool(),
5699
5863
  slackCanvasEdit: (run) => createSlackCanvasEditTool(run.state),
@@ -5711,13 +5875,26 @@ const STATIC_TOOL_BINDERS = {
5711
5875
  slackListGetItems: () => createSlackListGetItemsTool(),
5712
5876
  slackListUpdateItem: (run) => createSlackListUpdateItemTool(run.state),
5713
5877
  slackChannelListMessages: (run) => createSlackChannelListMessagesTool(slackOf(run)),
5714
- addReviewItem: (run) => withDisabledReason(createAddReviewItemTool(run.context, run.reviewItemServices()), reviewDeskDisabledReason(run)),
5715
- searchReviewItems: (run) => withDisabledReason(createSearchReviewItemsTool(run.context, run.reviewItemServices()), reviewDeskDisabledReason(run)),
5716
- updateReviewItem: (run) => withDisabledReason(createUpdateReviewItemTool(run.context, run.reviewItemServices()), reviewDeskDisabledReason(run))
5878
+ addReviewItem: (run) => createAddReviewItemTool(run.context, run.reviewItemServices()),
5879
+ searchReviewItems: (run) => createSearchReviewItemsTool(run.context, run.reviewItemServices()),
5880
+ updateReviewItem: (run) => createUpdateReviewItemTool(run.context, run.reviewItemServices())
5881
+ };
5882
+ const AGENT_TOOL_LIMIT = (turnTools) => turnTools.agents === "none" ? "A person's Turn in a Thread cannot use agent tools." : void 0;
5883
+ const REVIEW_DESK_LIMIT = (turnTools) => turnTools.reviewDesk ? void 0 : `A child agent cannot use the review desk. Use ${REPORT_BLOCKED_TOOL_NAME} to tell the parent agent what needs a person.`;
5884
+ const TURN_TOOL_LIMITS = {
5885
+ spawnAgent: AGENT_TOOL_LIMIT,
5886
+ stopAgent: AGENT_TOOL_LIMIT,
5887
+ archiveAgent: AGENT_TOOL_LIMIT,
5888
+ listAgents: AGENT_TOOL_LIMIT,
5889
+ messageAgent: AGENT_TOOL_LIMIT,
5890
+ [REPLY_TOOL_NAME]: (turnTools) => turnTools.reply === "none" ? `This Turn cannot send a \`${REPLY_TOOL_NAME}\`.` : void 0,
5891
+ [REPORT_BLOCKED_TOOL_NAME]: (turnTools) => turnTools.reportBlocked === "none" ? "This Turn cannot send a blocked report." : void 0,
5892
+ updateUserCustomization: (turnTools) => turnTools.userCustomization ? void 0 : "Only a person's Turn can change user customization.",
5893
+ setConversationSubscription: (turnTools) => turnTools.subscriptions ? void 0 : "Only a person's Turn can change subscriptions.",
5894
+ addReviewItem: REVIEW_DESK_LIMIT,
5895
+ searchReviewItems: REVIEW_DESK_LIMIT,
5896
+ updateReviewItem: REVIEW_DESK_LIMIT
5717
5897
  };
5718
- function reviewDeskDisabledReason(run) {
5719
- return run.context.turnTools.reviewDesk ? void 0 : `A child agent cannot use the review desk. Use ${REPORT_BLOCKED_TOOL_NAME} to tell the parent agent what needs a person.`;
5720
- }
5721
5898
  function attachmentStore(run) {
5722
5899
  const storage = run.context.attachmentStorage;
5723
5900
  return storage ? {
@@ -5747,7 +5924,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
5747
5924
  });
5748
5925
  },
5749
5926
  viewImage: (run) => run.context.supportsImageInput ? createViewImageTool(run.context.workspace, run.context.supportsImageInput, run.hooks.toolOverrides?.viewImage) : void 0,
5750
- imageGenerate: (run) => run.hooks.writeGeneratedArtifacts ? createImageGenerateTool({ writeGeneratedArtifacts: run.hooks.writeGeneratedArtifacts }, {
5927
+ imageGenerate: (run) => run.hooks.writeGeneratedFiles ? createImageGenerateTool({ writeGeneratedFiles: run.hooks.writeGeneratedFiles }, {
5751
5928
  modelId: botConfig.imageGenerationModelId,
5752
5929
  canSendFilesToActiveConversation: run.canSendFilesToActiveConversation,
5753
5930
  modelCost: run.modelCost,
@@ -5824,10 +6001,12 @@ function once(build) {
5824
6001
  */
5825
6002
  function createTools(availableSkills, hooks = {}, context, options = {}) {
5826
6003
  const slack = getSlackToolContext(context);
6004
+ const listedTools = context.listedTools ?? context.turnTools;
5827
6005
  const run = {
5828
6006
  availableSkills,
5829
6007
  hooks,
5830
6008
  context,
6009
+ listedTools,
5831
6010
  options,
5832
6011
  state: createToolState(),
5833
6012
  slack,
@@ -5845,10 +6024,11 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
5845
6024
  const tools = {};
5846
6025
  for (const slot of coreToolSlots({
5847
6026
  platform: slack ? "slack" : "local",
5848
- turnTools: context.turnTools
6027
+ listedTools
5849
6028
  })) {
5850
6029
  const tool = slot.kind === "static" ? STATIC_TOOL_BINDERS[slot.name](run) : RUN_BUILT_TOOL_BUILDERS[slot.slot](run);
5851
- if (tool) tools[slot.name] = tool;
6030
+ if (!tool) continue;
6031
+ tools[slot.name] = slot.kind === "static" ? withDisabledReason(tool, TURN_TOOL_LIMITS[slot.name]?.(context.turnTools)) : tool;
5852
6032
  }
5853
6033
  for (const [name, pluginTool] of Object.entries(getPluginTools(context, options.pluginSandbox))) {
5854
6034
  if (tools[name]) throw new Error(`Plugin tool "${name}" conflicts with a core tool`);
@@ -5857,11 +6037,6 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
5857
6037
  return tools;
5858
6038
  }
5859
6039
  // src/chat/runtime/report-progress.ts
5860
- function isActivePlanItem(value) {
5861
- if (!value || typeof value !== "object") return false;
5862
- const item = value;
5863
- return item.status === "in_progress" && typeof item.step === "string" && item.step.trim().length > 0;
5864
- }
5865
6040
  /** Convert a `reportProgress` tool payload into assistant status text. */
5866
6041
  function buildReportedProgressStatus(input) {
5867
6042
  if (!input || typeof input !== "object") return;
@@ -5871,14 +6046,6 @@ function buildReportedProgressStatus(input) {
5871
6046
  if (!text) return;
5872
6047
  return { text };
5873
6048
  }
5874
- /** Convert an `updatePlan` payload into the active assistant status. */
5875
- function buildPlanStatus(input) {
5876
- if (!input || typeof input !== "object") return;
5877
- const plan = input.plan;
5878
- if (!Array.isArray(plan)) return;
5879
- const active = plan.find(isActivePlanItem);
5880
- return active ? { text: active.step.trim() } : void 0;
5881
- }
5882
6049
  /** Recover the latest progress status from a resumable Pi transcript. */
5883
6050
  function latestProgressStatus(messages) {
5884
6051
  for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
@@ -5889,7 +6056,6 @@ function latestProgressStatus(messages) {
5889
6056
  if (!part || typeof part !== "object") continue;
5890
6057
  const toolCall = part;
5891
6058
  if (toolCall.type !== "toolCall") continue;
5892
- if (toolCall.name === "updatePlan") return buildPlanStatus(toolCall.arguments);
5893
6059
  if (toolCall.name === "reportProgress") {
5894
6060
  const status = buildReportedProgressStatus(toolCall.arguments);
5895
6061
  if (status) return status;
@@ -5906,6 +6072,37 @@ function isTypeBoxInputSchema(schema) {
5906
6072
  function disabledToolMessage(toolName, reason) {
5907
6073
  return `${toolName} is disabled in this Turn. ${reason} Do not call it again in this Turn.`;
5908
6074
  }
6075
+ // src/chat/tools/execute-tool.ts
6076
+ const EXECUTE_TOOL_NAME = "executeTool";
6077
+ const MISSING_TOOL_NAME_ERROR = "executeTool requires a catalog tool_name";
6078
+ /** Input envelope of `executeTool`, which the dispatcher parses before it runs the catalog tool. */
6079
+ const executeToolInputSchema = z.object({
6080
+ tool_name: z.string({ error: MISSING_TOOL_NAME_ERROR }).min(1, { error: MISSING_TOOL_NAME_ERROR }).describe("Exact catalog tool_name, from searchTools or as named by a skill, tool result, or error."),
6081
+ arguments: z.record(z.string(), z.unknown(), { error: "executeTool arguments must be an object when provided" }).describe("Arguments matching the selected catalog tool schema, for example { \"query\": \"...\" }.").optional(),
6082
+ intent: z.string().min(1).describe("Optional short purpose of this call. It is not passed to the catalog tool.").optional()
6083
+ }, { error: nestedArgumentsErrorMap(EXECUTE_TOOL_NAME) }).strict();
6084
+ const executeToolDefinition = zodToolDefinition({
6085
+ annotations: {
6086
+ destructiveHint: true,
6087
+ idempotentHint: false,
6088
+ openWorldHint: true,
6089
+ readOnlyHint: false
6090
+ },
6091
+ description: "Execute a catalog tool by its exact name. Use it for a tool that is not in your tool list: one that searchTools returned, or one that a skill, tool result, or error names. Put tool-specific parameters inside arguments.",
6092
+ executionMode: "sequential",
6093
+ exposure: "modelOnly",
6094
+ inputSchema: executeToolInputSchema,
6095
+ outputSchema: juniorToolOutputSchema
6096
+ });
6097
+ /** Create the model-visible dispatcher schema for catalog tools. */
6098
+ function createExecuteToolTool() {
6099
+ return zodTool({
6100
+ ...executeToolDefinition,
6101
+ execute: async () => {
6102
+ throw new ToolInputError("executeTool can only run through the agent tool dispatcher.");
6103
+ }
6104
+ });
6105
+ }
5909
6106
  // src/chat/tool-support/tool-name-suggestions.ts
5910
6107
  const MAX_SUGGESTIONS = 3;
5911
6108
  const MAX_SOURCE_TOOLS = 10;
@@ -6046,21 +6243,11 @@ function schemaErrorText(schema, value) {
6046
6243
  if (!firstError) return "invalid arguments";
6047
6244
  return `${firstError.path || "/"} ${firstError.message}`;
6048
6245
  }
6049
- /** Resolve and validate a catalog executeTool request at runtime. */
6246
+ /** Parse an executeTool envelope and resolve the catalog tool that it names. */
6050
6247
  function resolveCatalogToolCall(input, catalogTools) {
6051
- const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments" && key !== "intent");
6052
- if (extraKeys.length > 0) throw new ToolInputError(`executeTool arguments must be nested under arguments, not top-level fields: ${extraKeys.join(", ")}`);
6053
- const toolName = input["tool_name"];
6054
- if (typeof toolName !== "string" || toolName.length === 0) throw new ToolInputError("executeTool requires a catalog tool_name.");
6248
+ const { tool_name: toolName, arguments: args = {} } = parseToolInput(executeToolInputSchema, input);
6055
6249
  const definition = catalogTools[toolName];
6056
6250
  if (!definition) throw new ToolNameMissError(`executeTool can only call catalog tools returned by searchTools: ${toolName}.`, findToolNameHint(toolName, catalogTools));
6057
- const args = input["arguments"];
6058
- if (args === void 0) return {
6059
- arguments: {},
6060
- definition,
6061
- toolName
6062
- };
6063
- if (!args || typeof args !== "object" || Array.isArray(args)) throw new ToolInputError("executeTool arguments must be an object when provided.");
6064
6251
  return {
6065
6252
  arguments: args,
6066
6253
  definition,
@@ -6392,16 +6579,16 @@ function createToolActionReview(options) {
6392
6579
  }
6393
6580
  return state;
6394
6581
  });
6395
- states.forEach((state, index) => {
6582
+ for (const [index, state] of states.entries()) {
6396
6583
  const step = steps[index];
6397
- if (step.kind !== "reviewed" || state.rejected) return;
6584
+ if (step.kind !== "reviewed" || state.rejected) continue;
6398
6585
  if (step.decision.decision === "allow") {
6399
6586
  consecutiveRejections = 0;
6400
- return;
6587
+ continue;
6401
6588
  }
6402
6589
  state.rejected = true;
6403
6590
  consecutiveRejections = state.before + 1;
6404
- if (consecutiveRejections < MAX_CONSECUTIVE_REJECTIONS) return;
6591
+ if (consecutiveRejections < MAX_CONSECUTIVE_REJECTIONS) continue;
6405
6592
  state.exhausted = true;
6406
6593
  logException(new ToolActionReviewLimitError(), "guardian.action_review.exhausted", {
6407
6594
  "app.guardian.decision": step.decision.decision,
@@ -6410,7 +6597,7 @@ function createToolActionReview(options) {
6410
6597
  "gen_ai.tool.name": step.proposal.tool.name,
6411
6598
  "gen_ai.tool.call.id": actions[index].toolCallId
6412
6599
  });
6413
- });
6600
+ }
6414
6601
  return states;
6415
6602
  };
6416
6603
  /** Apply one review step to gate state and return the action's result. */
@@ -6544,34 +6731,6 @@ function handleToolExecutionError(error, toolName, toolCallId, shouldTrace, conv
6544
6731
  });
6545
6732
  throw error;
6546
6733
  }
6547
- // src/chat/tools/execute-tool.ts
6548
- const EXECUTE_TOOL_NAME = "executeTool";
6549
- const executeToolDefinition = zodToolDefinition({
6550
- annotations: {
6551
- destructiveHint: true,
6552
- idempotentHint: false,
6553
- openWorldHint: true,
6554
- readOnlyHint: false
6555
- },
6556
- description: "Execute a catalog tool by its exact name. Use it for a tool that is not in your tool list: one that searchTools returned, or one that a skill, tool result, or error names. Put tool-specific parameters inside arguments.",
6557
- executionMode: "sequential",
6558
- exposure: "modelOnly",
6559
- inputSchema: z.object({
6560
- tool_name: z.string().min(1).describe("Exact catalog tool_name, from searchTools or as named by a skill, tool result, or error."),
6561
- arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the selected catalog tool schema, for example { \"query\": \"...\" }.").optional(),
6562
- intent: z.string().min(1).describe("Optional short purpose of this call. It is not passed to the catalog tool.").optional()
6563
- }).strict(),
6564
- outputSchema: juniorToolOutputSchema
6565
- });
6566
- /** Create the model-visible dispatcher schema for catalog tools. */
6567
- function createExecuteToolTool() {
6568
- return zodTool({
6569
- ...executeToolDefinition,
6570
- execute: async () => {
6571
- throw new ToolInputError("executeTool can only run through the agent tool dispatcher.");
6572
- }
6573
- });
6574
- }
6575
6734
  // src/chat/tool-exposure.ts
6576
6735
  /** Return the runtime exposure for a tool, preserving direct compatibility. */
6577
6736
  function effectiveToolExposure(definition) {
@@ -6682,7 +6841,10 @@ function asSchema(value) {
6682
6841
  function propertyList(schema) {
6683
6842
  const properties = asSchema(schema["properties"]);
6684
6843
  const required = new Set(Array.isArray(schema["required"]) ? schema["required"] : []);
6685
- 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(", ");
6686
6848
  }
6687
6849
  function schemaType(schema) {
6688
6850
  if ("const" in schema) return JSON.stringify(schema["const"]);
@@ -6707,6 +6869,7 @@ function schemaType(schema) {
6707
6869
  * schema.
6708
6870
  */
6709
6871
  function summarizeInputSchema(schema) {
6872
+ if (!schema["properties"] && (schema["anyOf"] ?? schema["oneOf"])) return schemaType(schema);
6710
6873
  return propertyList(schema) || "No arguments.";
6711
6874
  }
6712
6875
  // src/chat/tools/search-tools.ts
@@ -6720,7 +6883,6 @@ const SEARCH_FIELD_WEIGHTS = [
6720
6883
  1
6721
6884
  ];
6722
6885
  const MIN_RELATIVE_SCORE = .3;
6723
- const BM25_K1 = 1.2;
6724
6886
  const BM25_B = [
6725
6887
  .75,
6726
6888
  .3,
@@ -6981,7 +7143,7 @@ function scoreQueryTerms(query, documents) {
6981
7143
  const documentFrequency = documentTerms.filter((terms) => [...weights.keys()].some((term) => terms.has(term))).length;
6982
7144
  return {
6983
7145
  weights,
6984
- inverseDocumentFrequency: Math.log(1 + (documents.length - documentFrequency + .5) / (documentFrequency + .5))
7146
+ inverseDocumentFrequency: bm25InverseDocumentFrequency(documents.length, documentFrequency)
6985
7147
  };
6986
7148
  });
6987
7149
  }
@@ -6989,9 +7151,7 @@ function weightedTermFrequency(document, term, averageLengths) {
6989
7151
  return document.fields.reduce((weighted, field, fieldIndex) => {
6990
7152
  const termFrequency = field.filter((candidate) => candidate === term).length;
6991
7153
  if (termFrequency === 0) return weighted;
6992
- const averageLength = averageLengths[fieldIndex] ?? 0;
6993
- const lengthRatio = averageLength === 0 ? 1 : field.length / averageLength;
6994
- 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]);
6995
7155
  }, 0);
6996
7156
  }
6997
7157
  function scoreSearchDocument(document, query, averageLengths) {
@@ -6999,7 +7159,7 @@ function scoreSearchDocument(document, query, averageLengths) {
6999
7159
  let best = 0;
7000
7160
  for (const [term, weight] of weights) {
7001
7161
  const frequency = weightedTermFrequency(document, term, averageLengths);
7002
- best = Math.max(best, weight * frequency * 2.2 / (frequency + BM25_K1));
7162
+ best = Math.max(best, weight * bm25Saturation(frequency));
7003
7163
  }
7004
7164
  return score + inverseDocumentFrequency * best;
7005
7165
  }, 0);
@@ -7008,12 +7168,12 @@ function nameMatch(document, query) {
7008
7168
  const { action, objects } = document;
7009
7169
  if (!action || objects.length === 0) return 0;
7010
7170
  let best = 0;
7011
- query.forEach((term, actionIndex) => {
7171
+ for (const [actionIndex, term] of query.entries()) {
7012
7172
  const actionWeight = term.get(action) ?? 0;
7013
- if (actionWeight === 0) return;
7173
+ if (actionWeight === 0) continue;
7014
7174
  const covered = objects.filter((object) => query.some((other, index) => index !== actionIndex && other.has(object))).length;
7015
7175
  best = Math.max(best, actionWeight * covered / objects.length);
7016
- });
7176
+ }
7017
7177
  return best;
7018
7178
  }
7019
7179
  function namesActionAndObject(documents, query) {
@@ -7075,8 +7235,13 @@ function selectedSourceSummaries(tools, matches, requestedSource, knownSources)
7075
7235
  const matchedSourceIds = new Set(matches.map((name) => tools[name]?.source?.id).filter((source) => Boolean(source)));
7076
7236
  return knownSources.filter((source) => matchedSourceIds.has(source.id));
7077
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.";
7078
7243
  function renderSearchToolsDescription(knownSources) {
7079
- 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.`;
7080
7245
  if (knownSources.length === 0) return intro;
7081
7246
  return [
7082
7247
  intro,
@@ -7505,13 +7670,13 @@ async function runCodeModeScript(run) {
7505
7670
  })), controller.signal);
7506
7671
  })();
7507
7672
  reviews.catch(() => void 0);
7508
- accepted.forEach(({ call, host, tool }, index) => {
7673
+ for (const [index, { call, host, tool }] of accepted.entries()) {
7509
7674
  const submission = submissions[index];
7510
7675
  track(runCall(host, call, tool, async (action) => {
7511
7676
  submission.resolve(action);
7512
7677
  return (await reviews).get(action.toolCallId);
7513
7678
  }).finally(() => submission.resolve(void 0)));
7514
- });
7679
+ }
7515
7680
  };
7516
7681
  const sandbox = new CodemodeSandbox();
7517
7682
  const startedAt = performance.now();
@@ -7665,7 +7830,7 @@ function renderScriptTools(tools) {
7665
7830
  ...shown.map((entry) => entry.text),
7666
7831
  "};"
7667
7832
  ] : [],
7668
- ...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}.`] : [],
7669
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."] : []
7670
7835
  ].join("\n");
7671
7836
  }
@@ -7928,7 +8093,7 @@ function createToolPipeline(options) {
7928
8093
  }), nudges);
7929
8094
  };
7930
8095
  const reportStatus = async (executionToolName, params) => {
7931
- const status = executionToolName === "updatePlan" ? buildPlanStatus(params) : executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
8096
+ const status = executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
7932
8097
  if (status) await onStatus?.(status);
7933
8098
  };
7934
8099
  /**
@@ -8765,6 +8930,22 @@ ${renderRules("deny")}
8765
8930
  - Rate risk and user authorization first.
8766
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.
8767
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
+ }
8768
8949
  // src/chat/guardian/reviewer.ts
8769
8950
  const guardianAssessmentSchema = z.object({
8770
8951
  riskLevel: z.enum(RISK_LEVELS),
@@ -8773,7 +8954,7 @@ const guardianAssessmentSchema = z.object({
8773
8954
  reason: z.string().trim().min(1).max(500)
8774
8955
  }).strict();
8775
8956
  const GUARDIAN_REVIEW_TIMEOUT_MS = 6e4;
8776
- const GUARDIAN_REVIEW_MAX_TOKENS = 8e3;
8957
+ const GUARDIAN_REVIEW_MAX_TOKENS = 2e3;
8777
8958
  const MAX_PROPOSAL_CHARS = 192e3;
8778
8959
  const RUN_RULES = [
8779
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.",
@@ -8851,13 +9032,14 @@ function guardianDecision(assessment, proposal) {
8851
9032
  }
8852
9033
  /** Create the structured Guardian reviewer used for permissioned tool actions. */
8853
9034
  function createGuardianActionReviewer(options) {
9035
+ const system = guardianSystemPrompt(options.destinationFacts);
8854
9036
  return { async review(proposal, reviewOptions) {
8855
9037
  const timeoutSignal = AbortSignal.timeout(GUARDIAN_REVIEW_TIMEOUT_MS);
8856
9038
  const signal = reviewOptions?.signal ? AbortSignal.any([reviewOptions.signal, timeoutSignal]) : timeoutSignal;
8857
9039
  const completeReview = () => options.completeObject({
8858
9040
  modelId: options.modelId,
8859
9041
  schema: guardianAssessmentSchema,
8860
- system: GUARDIAN_ACTION_POLICY,
9042
+ system,
8861
9043
  prompt: guardianPrompt(proposal),
8862
9044
  maxTokens: GUARDIAN_REVIEW_MAX_TOKENS,
8863
9045
  operation: "guardian_action_review",
@@ -9414,10 +9596,6 @@ async function wireAgentTools(args) {
9414
9596
  const commonToolRuntimeContext = {
9415
9597
  conversationId: args.run.conversationId,
9416
9598
  turnId: args.run.turnId,
9417
- turnTools: {
9418
- ...args.behavior.tools,
9419
- reply: args.run.dispatch?.outcomes?.length === 0 ? "none" : args.behavior.tools.reply
9420
- },
9421
9599
  ...args.run.parentConversationId ? { parentConversationId: args.run.parentConversationId } : void 0,
9422
9600
  ...args.run.location ? {
9423
9601
  location: args.run.location,
@@ -9445,7 +9623,7 @@ async function wireAgentTools(args) {
9445
9623
  supportsImageInput: args.supportsImageInput,
9446
9624
  surface: args.surface,
9447
9625
  ...args.currentActor ? { resolveActorIdentity: async () => await readActorIdentity(args.currentActor) } : void 0,
9448
- ...bindAgentTools(args.run, args.behavior.tools.agents)
9626
+ ...bindTurnTools(args.run, args.behavior)
9449
9627
  };
9450
9628
  const toolRoute = resolveToolRuntimeRoute({
9451
9629
  actor: args.currentActor,
@@ -9489,12 +9667,17 @@ async function wireAgentTools(args) {
9489
9667
  priorRejections: restoreToolActionRejections(args.currentTurnMessages),
9490
9668
  reviewer: createGuardianActionReviewer({
9491
9669
  completeObject,
9670
+ destinationFacts: pluginCatalogRuntime.getProviders().flatMap(({ manifest }) => manifest.reviewContext ? [{
9671
+ plugin: manifest.name,
9672
+ text: manifest.reviewContext
9673
+ }] : []),
9492
9674
  modelId: botConfig.guardianModelId
9493
9675
  })
9494
9676
  });
9495
- const tools = createTools(loadableSkills(args.availableSkills, args.invokedSkill?.name), {
9496
- writeGeneratedArtifacts: async (files) => {
9497
- 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);
9498
9681
  args.generatedFiles.push(...files);
9499
9682
  return refs;
9500
9683
  },
@@ -9502,6 +9685,7 @@ async function wireAgentTools(args) {
9502
9685
  onSkillLoaded: async (loadedSkill) => {
9503
9686
  const effective = await args.skillSandbox.loadSkill(loadedSkill.name) ?? loadedSkill;
9504
9687
  upsertActiveSkill(args.activeSkills, effective);
9688
+ skills.splice(0, skills.length, ...loadableSkills(args.availableSkills, args.invokedSkill?.name, args.activeSkills));
9505
9689
  await tryRecordSkillLoadStat(effective);
9506
9690
  }
9507
9691
  }, toolRuntimeContext, {
@@ -9607,7 +9791,24 @@ async function wireAgentTools(args) {
9607
9791
  toolRuntimeContext
9608
9792
  };
9609
9793
  }
9610
- /** Bind the agent tools that the Turn's behavior gives it. */
9794
+ /**
9795
+ * Bind the tools that one Turn lists and the tools that it can use. Every
9796
+ * Turn of a Prompt mode lists the same tools, so a Conversation keeps one
9797
+ * tool list. `createTools` disables each listed tool that the Turn cannot
9798
+ * use.
9799
+ */
9800
+ function bindTurnTools(run, behavior) {
9801
+ const listedTools = promptModeTurnTools(behavior.promptMode);
9802
+ return {
9803
+ turnTools: run.dispatch?.outcomes?.length === 0 ? {
9804
+ ...behavior.tools,
9805
+ reply: "none"
9806
+ } : behavior.tools,
9807
+ listedTools,
9808
+ ...bindAgentTools(run, listedTools.agents)
9809
+ };
9810
+ }
9811
+ /** Bind the agent tools that the Turn lists. */
9611
9812
  function bindAgentTools(run, agents) {
9612
9813
  const { bindSpawnAgent, bindMessageAgent } = run.environment ?? {};
9613
9814
  if (agents === "none" || !bindSpawnAgent) return {};
@@ -9793,7 +9994,7 @@ function createResumeState(args) {
9793
9994
  },
9794
9995
  async translateSuspension(ending) {
9795
9996
  const { error } = ending;
9796
- const reason = error instanceof CooperativeTurnYieldError ? "yield" : error instanceof RetryableDeliveryError ? "retry" : timedOut ? "timeout" : void 0;
9997
+ const reason = error instanceof CooperativeTurnYieldError ? "yield" : ending.retryable || error instanceof RetryableDeliveryError ? "retry" : timedOut ? "timeout" : void 0;
9797
9998
  if (!reason) return;
9798
9999
  if (reason === "retry") resumeMessages = [...latestSafeBoundaryMessages];
9799
10000
  const parkMessages = reason === "yield" ? [...resumeMessages] : continuableMessages(resumeMessages, latestSafeBoundaryMessages);
@@ -10323,69 +10524,15 @@ async function prepareSummary(message, streamFn) {
10323
10524
  });
10324
10525
  return outcome;
10325
10526
  }
10326
- // src/chat/services/plan-continuation.ts
10327
- const OPEN_PLAN_TAG = "open-plan";
10328
- function openItems(input) {
10329
- const plan = input && typeof input === "object" ? input.plan : void 0;
10330
- if (!Array.isArray(plan)) return [];
10331
- return plan.flatMap((value) => {
10332
- const item = value;
10333
- if (typeof item?.step !== "string" || item.status !== "pending" && item.status !== "in_progress") return [];
10334
- return [{
10335
- step: item.step,
10336
- status: item.status
10337
- }];
10338
- });
10339
- }
10340
- function messageText$1(message) {
10341
- const content = message.content;
10342
- if (!Array.isArray(content)) return typeof content === "string" ? content : "";
10343
- return content.flatMap((part) => {
10344
- const text = part?.text;
10345
- return typeof text === "string" ? [text] : [];
10346
- }).join("\n");
10347
- }
10348
- function retainedOpenItems(message) {
10349
- const text = messageText$1(message);
10350
- if (!isCompactionSummaryText(text)) return;
10351
- const continuation = unwrapCurrentInstruction(text) ?? text;
10352
- const open = `<${OPEN_PLAN_TAG}>\n`;
10353
- const close = `\n</${OPEN_PLAN_TAG}>`;
10354
- const closeIndex = continuation.lastIndexOf(close);
10355
- const openIndex = continuation.lastIndexOf(open, closeIndex);
10356
- if (openIndex < 0 || closeIndex < 0) return;
10357
- const payload = continuation.slice(openIndex + open.length, closeIndex);
10358
- try {
10359
- return openItems({ plan: JSON.parse(payload) });
10360
- } catch {
10361
- return;
10362
- }
10363
- }
10364
- /** Read open items from the latest successful plan state. */
10365
- function latestOpenPlanItems(messages) {
10366
- const successfulCalls = /* @__PURE__ */ new Set();
10367
- for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
10368
- const message = messages[messageIndex];
10369
- if (message.role === "toolResult" && message.toolName === "updatePlan" && typeof message.toolCallId === "string" && message.isError !== true) {
10370
- successfulCalls.add(message.toolCallId);
10371
- continue;
10372
- }
10373
- if (message.role === "user") {
10374
- const retained = retainedOpenItems(messages[messageIndex]);
10375
- if (retained) return retained;
10376
- }
10377
- if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
10378
- for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {
10379
- const call = message.content[partIndex];
10380
- if (call?.type === "toolCall" && call.name === "updatePlan" && typeof call.id === "string" && successfulCalls.has(call.id)) return openItems(call.arguments);
10381
- }
10382
- }
10383
- return [];
10384
- }
10385
- /** Append exact open plan state to continuation text. */
10386
- function appendOpenPlan(continuation, messages) {
10387
- const plan = latestOpenPlanItems(messages);
10388
- return plan.length === 0 ? continuation : `${continuation}\n\n<${OPEN_PLAN_TAG}>\n${JSON.stringify(plan)}\n</${OPEN_PLAN_TAG}>`;
10527
+ // src/chat/plan/snapshot.ts
10528
+ /**
10529
+ * Append one `<plan>` snapshot of the open items, read from the database, to
10530
+ * a compaction summary, so the plan and its version survive the history
10531
+ * replacement.
10532
+ */
10533
+ async function appendPlanSnapshot(summaryText, conversationId) {
10534
+ const snapshot = renderPlanSnapshot(await listPlanItems(getSqlExecutor(), conversationId));
10535
+ return snapshot ? `${summaryText}\n\n${snapshot}` : summaryText;
10389
10536
  }
10390
10537
  // src/chat/services/context-compaction.ts
10391
10538
  /**
@@ -10459,9 +10606,12 @@ function isSessionTurnContext(text) {
10459
10606
  function withoutSections(text, tags) {
10460
10607
  return tags.reduce((result, tag) => result.replace(new RegExp(`\\n\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g"), ""), text);
10461
10608
  }
10462
- /** Remove the sections that only the Turn that received them can use. */
10609
+ /**
10610
+ * Remove the sections that only the Turn that received them can use, and
10611
+ * plan deltas, which the `<plan>` snapshot of the summary replaces.
10612
+ */
10463
10613
  function withoutRequestContext(text) {
10464
- return withoutSections(text, Object.values(REQUEST_CONTEXT_SECTION_TAG));
10614
+ return withoutSections(text, [...Object.values(REQUEST_CONTEXT_SECTION_TAG), PLAN_DELTA_TAG]);
10465
10615
  }
10466
10616
  /**
10467
10617
  * Remove the copies of capability sections that the Turn context of older
@@ -10613,11 +10763,12 @@ async function loadRetainedUserMessages(conversationId, pendingMessages) {
10613
10763
  };
10614
10764
  });
10615
10765
  }
10616
- 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.";
10617
10767
  /**
10618
10768
  * Keep generated text inside the existing evidence-only prompt boundary. The
10619
10769
  * last line says where replaced detail stays readable: without it, the model
10620
- * 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.
10621
10772
  */
10622
10773
  function renderCompactionSummary(summary) {
10623
10774
  return [
@@ -10818,7 +10969,7 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
10818
10969
  };
10819
10970
  }
10820
10971
  const summaryEntry = {
10821
- message: userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages)),
10972
+ message: userMessage(await appendPlanSnapshot(renderCompactionSummary(summary), args.conversationId)),
10822
10973
  provenance: contextProvenance
10823
10974
  };
10824
10975
  const replacement = retainUserMessages ? [
@@ -10943,9 +11094,7 @@ function trimResult(message, seq) {
10943
11094
  */
10944
11095
  function trimToolResults(entries) {
10945
11096
  let latestInstructionIndex = -1;
10946
- entries.forEach((entry, index) => {
10947
- if (hasTurnInput(entry.message)) latestInstructionIndex = index;
10948
- });
11097
+ for (const [index, entry] of entries.entries()) if (hasTurnInput(entry.message)) latestInstructionIndex = index;
10949
11098
  const trimming = {
10950
11099
  trimmedResults: 0,
10951
11100
  removedChars: 0
@@ -11115,7 +11264,7 @@ async function applyPreparedSummary(args, prepared, budget) {
11115
11264
  }] : [],
11116
11265
  ...retained,
11117
11266
  {
11118
- message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
11267
+ message: userMessage(await appendPlanSnapshot(renderCompactionSummary(prepared.summary), args.conversationId)),
11119
11268
  provenance: contextProvenance
11120
11269
  },
11121
11270
  ...systemMessage ? [{
@@ -11293,7 +11442,14 @@ async function executeAgentRun(run, streamFn) {
11293
11442
  runId: run.runId,
11294
11443
  assistantUserName: botConfig.userName
11295
11444
  };
11296
- return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, run.dispatch?.declaresResult ? "automation" : conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn)));
11445
+ return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, async () => reportFailedRun(await executeAgentRunInPrivacyContext(run, run.dispatch?.declaresResult ? "automation" : conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn), run.signal)));
11446
+ }
11447
+ function reportFailedRun(outcome, signal) {
11448
+ if (outcome.status !== "completed" || outcome.result.diagnostics.outcome === "success" || signal?.aborted) return outcome;
11449
+ return {
11450
+ ...outcome,
11451
+ result: captureTurnFailure(outcome.result, logException)
11452
+ };
11297
11453
  }
11298
11454
  async function executeAgentRunInPrivacyContext(run, conversationKind, conversationPrivacy, runLogContext, streamFn) {
11299
11455
  const conversationId = run.conversationId;
@@ -11607,6 +11763,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11607
11763
  const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, sectionsMessage, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
11608
11764
  activeMcpCatalogs: wiring.activeMcpCatalogs,
11609
11765
  promptMode: behavior.promptMode,
11766
+ sender: behavior.sender,
11610
11767
  currentActor: actor,
11611
11768
  availableSkills,
11612
11769
  configurationValues,
@@ -11738,7 +11895,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11738
11895
  }
11739
11896
  return acceptedMessages;
11740
11897
  };
11741
- const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task", {
11898
+ const cacheWarming = createCacheWarmingRecorder(conversationId, {
11899
+ userActor: isUserActor(actor) && conversationKind !== "task",
11900
+ idleNeedsPendingWork: behavior.idleNeedsPendingWork
11901
+ }, {
11742
11902
  platform: promptPlatform,
11743
11903
  mode: behavior.promptMode
11744
11904
  });
@@ -12170,7 +12330,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
12170
12330
  if (resume) {
12171
12331
  const outcome = await resume.translateSuspension({
12172
12332
  currentUsage: turnUsage,
12173
- error: runError
12333
+ error: runError,
12334
+ retryable: resume.inputCommitted && !acceptedToolFreeAssistant && !findInErrorChain(runError, (candidate) => candidate instanceof ProviderError) && isRetryableSandboxFailure(runError)
12174
12335
  });
12175
12336
  if (outcome) return outcome;
12176
12337
  }
@@ -12179,10 +12340,6 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
12179
12340
  if (isTurnInputCommitLostError(error)) throw error;
12180
12341
  if (error instanceof AuthorizationFlowDisabledError) throw error;
12181
12342
  if (durability.onInputCommitted && !resume?.inputCommitted) throw error;
12182
- if (!signal?.aborted || error !== signal.reason) {
12183
- const providerError = findProviderError(error);
12184
- logException(error, "assistant.reply.generation.failed", providerError ? getProviderErrorAttributes(providerError) : {});
12185
- }
12186
12343
  const message = error instanceof Error ? error.message : String(error);
12187
12344
  return {
12188
12345
  status: "completed",
@@ -12233,7 +12390,7 @@ function createAgentRunner(execute, options) {
12233
12390
  }
12234
12391
  };
12235
12392
  const loadStoredAttachments = async (attachments) => {
12236
- const { loadInputAttachments } = await import("./model-input-DoM9Ht-d.js").then((n) => n.r);
12393
+ const { loadInputAttachments } = await import("./model-input-Xluiy-1W.js").then((n) => n.r);
12237
12394
  const storage = nextRun.environment?.attachmentStorage;
12238
12395
  if (!storage) throw new Error("Attachment storage is unavailable.");
12239
12396
  return await loadInputAttachments({
@@ -12247,14 +12404,17 @@ function createAgentRunner(execute, options) {
12247
12404
  attachments: await loadStoredAttachments(run.instruction.storedAttachments)
12248
12405
  };
12249
12406
  const drainSteeringMessages = nextRun.durability?.drainSteeringMessages;
12250
- if (drainSteeringMessages) nextRun.durability = {
12251
- ...nextRun.durability,
12252
- drainSteeringMessages: (accept) => drainSteeringMessages(async (messages) => accept(await Promise.all(messages.map(async ({ storedAttachments, ...message }) => storedAttachments?.length ? {
12253
- ...message,
12254
- attachments: await loadStoredAttachments(storedAttachments)
12255
- } : message))))
12256
- };
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
+ }
12257
12417
  return await execute(nextRun, streamFn);
12258
12418
  } };
12259
12419
  }
12260
- export { RetryableDeliveryError as A, parseSlackReviewItemClick as C, AttachmentDownloadError as D, parseSlackUserInputSubmission as E, toolInvocationDestination as M, shouldEmitDevAgentTrace as N, readAttachmentContent as O, 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 };