@sentry/junior 0.305.0 → 0.306.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 (80) hide show
  1. package/dist/{adapter-context-BpvbUki8.js → adapter-context-CnY-i32r.js} +2 -2
  2. package/dist/{admin-CoDt35ny.js → admin-BLLdLnXh.js} +2 -2
  3. package/dist/{agent-runner-C5d6rY5g.js → agent-runner-BaLjEjPR.js} +261 -190
  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 +137 -40
  8. package/dist/{app-Cs157Zc5.d.ts → app-DvYbM9UD.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +487 -434
  11. package/dist/{background-compaction-queue-BTqMIfTA.js → background-compaction-queue-D2wzxtGU.js} +2 -2
  12. package/dist/{briefs-BRdznF7c.js → briefs-DvyzXfrF.js} +3 -3
  13. package/dist/{catalog-runtime-J52Tej47.js → catalog-runtime-B1R-nHd3.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +5 -5
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-CBZp0udd.js → config-DUD-zMvp.js} +111 -13
  22. package/dist/{connections-BYmuJ6Vm.js → connections-CDhsqPcC.js} +6 -6
  23. package/dist/{continue-in-slack-Cvot6S38.js → continue-in-slack-BXQizz9o.js} +5 -5
  24. package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
  25. package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
  26. package/dist/{conversation-privacy-D2pOzBNl.js → conversation-privacy-YE54gMN8.js} +1 -1
  27. package/dist/{conversation-turn-CI8WDpnK.js → conversation-turn-BzdmrHb0.js} +22 -40
  28. package/dist/{credential-sync-COqnZ1Dx.js → credential-sync-Cdm-e1vJ.js} +14 -13
  29. package/dist/{db-DU84dCVu.js → db-DV2ZUb1Y.js} +90 -11
  30. package/dist/{db-zbN5ZV_o.d.ts → db-pH357Dkt.d.ts} +1 -1
  31. package/dist/{executor-CFyrgOu1.js → executor-CjNhwwnj.js} +47 -4
  32. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  33. package/dist/{install-CQ76CfRw.js → install-DbD7C5td.js} +2 -2
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{lineage-DLd2UxVP.js → lineage-BFdIPb3o.js} +2 -2
  36. package/dist/{logging-BPNTQVFu.js → logging-oYpJYr-S.js} +1 -1
  37. package/dist/{message-BWJLeQ5e.js → message-BBPcMKJY.js} +8 -8
  38. package/dist/{model-input-DoM9Ht-d.js → model-input-DYYF3a8B.js} +3 -3
  39. package/dist/nitro.d.ts +1 -1
  40. package/dist/nitro.js +4 -4
  41. package/dist/{oauth-callback-server-DeHbnAQl.js → oauth-callback-server-C7Q987su.js} +2 -2
  42. package/dist/{projection-CcFBVFUo.js → projection-CWXDE0f6.js} +7738 -6166
  43. package/dist/{prompt-C5LREK2p.js → prompt-P3eRqO8C.js} +15 -7
  44. package/dist/{queue-B2AAL3ym.js → queue-7FSijgqG.js} +4 -4
  45. package/dist/{registry-BjZZqKqi.js → registry-1pzXmplY.js} +1 -1
  46. package/dist/{resolve-CeJgXuH1.js → resolve-n87oXY-d.js} +3 -3
  47. package/dist/{result-icDrueyB.js → result-BmF9v9bv.js} +9 -9
  48. package/dist/{runner-nVfMkMMB.js → runner-4j7ZsxP5.js} +13 -15
  49. package/dist/{sandbox-egress-signals-H9vQ5qRf.js → sandbox-egress-signals-BRQI8HvT.js} +1 -1
  50. package/dist/{automation-CuA3yEcD.js → schedule-CHPWQn-x.js} +347 -5
  51. package/dist/{schema-CKcu-IK6.d.ts → schema-CVbIjrF3.d.ts} +71 -1
  52. package/dist/{schema-Bx0Mlo32.js → schema-D7iIEh6t.js} +52 -6
  53. package/dist/{service-account-Dw06p3zm.js → service-account-BDQ9xzta.js} +3 -3
  54. package/dist/{service-account-DU5865XA.js → service-account-DzQiOmqa.js} +5 -5
  55. package/dist/{session-stop-uotLtp4g.js → session-stop-BQxgHR4X.js} +854 -160
  56. package/dist/{skills-Bex1EaO5.js → skills-CPf4vNuC.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-EPG3riWF.js → slack-conversation-unfurl-B1KEptUg.js} +10 -9
  58. package/dist/{spawn-CoD3vDuS.js → spawn-CjGddiAU.js} +6 -6
  59. package/dist/{state-nCR4Muhn.js → state-9wfj6aSD.js} +4 -4
  60. package/dist/{stop-BFVd0P0m.js → stop-CsQGuN5n.js} +62 -117
  61. package/dist/{store-Ca6G962n.js → store-Dz3YZ7gQ.js} +5 -5
  62. package/dist/{task-queue-BLPZU6kC.js → task-queue-CFlrJguF.js} +3 -3
  63. package/dist/{task-runner-xsOPIxCZ.js → task-runner-frzlUvFD.js} +8 -9
  64. package/dist/{thread-context-BOvZhsKK.js → thread-context-C4QuZlM8.js} +8 -91
  65. package/dist/turn-session-routing-BXaubz2w.js +244 -0
  66. package/dist/{turn-user-message-BrhuyYrH.js → turn-user-message-DNC0eRZ7.js} +3 -3
  67. package/dist/users-XCCKn3xW.js +181 -0
  68. package/dist/{validation-BnY9K5WB.js → validation-L5fdjmFX.js} +1 -1
  69. package/dist/{version-qROlRQGF.js → version-BFmuwgxP.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-CxUiOraX.js → viewer-DKOeHpv3.js} +3 -3
  72. package/dist/{warmup--Gkz7iB-.js → warmup-mTMIatCV.js} +267 -272
  73. package/dist/{web-message-id-lNodcCOI.js → web-message-id-CUaSiGme.js} +16 -1
  74. package/dist/{worker-DJ8d9fmD.js → worker-Bz4KNxjI.js} +7 -7
  75. package/migrations/0114_plan_items.sql +22 -0
  76. package/migrations/meta/0114_snapshot.json +5203 -0
  77. package/migrations/meta/_journal.json +7 -0
  78. package/package.json +6 -6
  79. package/dist/schedule-cP0AACm1.js +0 -344
  80. package/dist/turn-session-routing-2bW2qfeb.js +0 -1792
@@ -1,30 +1,30 @@
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 { $c as historyItemFromPiMessage, $i as wrapSandboxSetupError, Ac as ToolInputError, An as isToolResultMessage, As as createScheduledAutomation, B as PluginCredentialFailureError, Bi as isRetryableSandboxFailure, Bn as createUserTokenStore, Ca as SANDBOX_WORKSPACE_ROOT, Cr as getReviewItem, Cs as normalizeSlackReplyMarkdown, Da as buildCommandScript, Dn as isContinuablePiBoundary, Ea as sandboxSkillPathResolution, En as isAssistantMessage, F as calculateContextCompactionTargetTokens, Fn as CAPABILITY_SECTION_TAG, Fs as saveScheduledAutomation, G as AuthorizationPauseError, H as authorizationId, I as getAgentBackgroundCompactionMarkTokens, Ii as hash, In as REQUEST_CONTEXT_SECTION_TAG, Jc as credentialAuditAttributes, Ji as SandboxCallTimeoutError, Jt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, K as abandonReplacedPendingAuth, Ki as resolveBaseUrl, Kn as createPluginHookRunner, Ko as addReactionToMessage, L as getAgentContextCompactionTriggerTokens, Mn as retainRuntimeTurnContext, Nn as stripRuntimeTurnContext, Oa as buildNonInteractiveShellScript, Oc as automationRevision, On as isStandaloneRuntimeContextMessage, Pn as trimTrailingAssistantMessages, Ps as readScheduledAutomation, Qi as throwSandboxOperationError, Qo as postSlackMessage, Qs as createEventAutomation, Qt as TurnToolCallLimitExceededError, R as getAgentContextInputLimitTokens, Ri as ensureDockerDaemon, Rn as TURN_CONTEXT_TAG, Sa as SANDBOX_SKILLS_ROOT, Si as renderToolResultNudge, Sn as getUserMessageInstructionText, Ta as sandboxSkillFile, Ti as getWorkspace, U as AuthPausePersistenceError, Uc as resolveTaskTitle, Ui as deliverOAuthAuthorization, Us as getDashboardReviewItemLink, V as createPluginAuthOrchestration, W as AuthorizationFlowDisabledError, Wi as formatProviderLabel, X as continuableMessages, Xr as resolveChannelCapabilities, Xt as TurnBudgetExceededError, Yc as credentialAuditSource, Yi as findInErrorChain, Yt as TURN_LIMIT_WRAP_UP_MESSAGE, Z as loadTurnCheckpoint, Zi as isAlreadyExistsError, Zn as getPluginTools, Zr as getSlackToolContext, Zt as TurnSliceLimitExceededError, _n as readBlockedReport, _o as createConversationEmbedder, _s as sleep, aa as consumeSandboxEgressAuthRequiredSignal, an as remindMissingAnswer, as as SlackActionError, ba as SANDBOX_DATA_ROOT, bn as getPiMessageRole, c as recordAgentsInstructionsUpdated, cn as getAssistantReplyText, co as readLiveAttachment, da as resolveSandboxCommandEnvironment, el as piMessageFromHistoryItem, en as createTurnLimitGate, et as saveTurnCheckpoint, f as recordAuthorizationRequested, fn as isLegacyNoReplyMarker, fo as storeAttachments, g as recordToolExecutionStarted, ga as PluginToolDeniedError, gn as REPORT_BLOCKED_TOOL_NAME, hn as CODE_MODE_CALL_STATUS_TEXT, i as loadConversationProjection, ia as clearSandboxEgressSignals, ic as saveEventAutomation, in as readTurnAnswer, jc as isToolInputError, jn as normalizeToolNameFromResult, ka as runNonInteractiveCommand, kn as isToolResultError, l as recordAttachmentsDelivered, ln as sanitizeAssistantText, m as recordMcpProviderConnected, ma as tryWorkspaceRepoCheckoutPath, mn as CODEMODE_TOOL_NAME, mo as AttachmentSourceUnavailableError, na as isWorkspaceSnapshotNotReadyError, nl as getConfigDefaults, nn as REPLY_TOOL_NAME, ns as uploadFilesToConversation, oa as consumeSandboxEgressPermissionDeniedSignal, p as recordGuardianActionReviewed, pa as SANDBOX_RUNTIME, pn as readNoReply, po as storeDeferredAttachment, q as canReusePendingAuthLink, qo as deleteSlackMessage, r as loadConnectedMcpProviders, ra as workspaceSnapshotNotReadyUserMessage, rn as isAnswerToolName, ro as readSlackAttachmentSource, sa as createSandboxEgressCredentialToken, sn as decideReply, ta as getWorkspaceSnapshotNotReadyError, tc as getEventAutomation, tl as projectConversationEvents, tn as isTurnExecutionLimitExceededError, ts as updateSlackMessage, ua as buildSandboxEgressNetworkPolicy, un as NO_REPLY_TOOL_NAME, us as isConversationScopedChannel, wa as sandboxSkillDir, wn as hasTurnInput, wo as resolveUserTimezone, xn as getTerminalAssistantMessages, xs as escapeSlackMrkdwnText, ya as SANDBOX_COMMAND_PATH, yn as extractAssistantText, z as createPluginEgress, zi as getSandboxProvider } from "./projection-CWXDE0f6.js";
2
+ import { $ as ProviderError, B as unwrapCurrentInstruction, F as textCharsForTokens, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, J as readParentAgentTask, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, V as escapeXml, at as isProviderRefusal, b as GEN_AI_PROVIDER_NAME, et as createAssistantProviderError, it as getProviderErrorUserMessage, j as requestPrefixAttributes, k as resolveGatewayModel, lt as bufferBody, n as botConfig, nt as findProviderError, ot as isProviderRetryError, rt as getProviderErrorAttributes, st as getGatewayApiKey, tt as createProviderError, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-DUD-zMvp.js";
3
+ import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, S as setTags, T as withLogContext, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, t as buildTurnFailureResponse, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-oYpJYr-S.js";
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-YE54gMN8.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, O as promptModeTurnTools, St as sameDestination, T as isPersonInput, a as getConversationStore, at as withLock, k as turnBehavior, lt as addAgentTurnUsage, o as getDb, pt as hasAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, ut as agentTurnCostUsd } from "./db-DV2ZUb1Y.js";
8
+ import { f as juniorAutomationRuns, u as juniorReviewItemSlackCards, z as juniorArtifacts } from "./executor-CjNhwwnj.js";
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 { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-1pzXmplY.js";
12
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.js";
13
+ import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CPf4vNuC.js";
14
+ import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-DzQiOmqa.js";
15
+ import { d as completeText, g as NoAudioError, h as transcribeFromUrl, p as generateImages, u as completeObject } from "./prompt-P3eRqO8C.js";
16
+ import { A as automationTitleSchema, J as automationTaskDescription, L as ScheduleIntentError, O as automationContextToolSchema, P as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, R as compileScheduleIntent, j as taskOutcomeInputSchema, k as automationInstructionToolSchema, z as scheduleIntentFromTool } from "./schedule-CHPWQn-x.js";
17
+ import { Z as MAX_ATTACHMENT_BYTES } from "./conversation--f85g4zL.js";
18
+ import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-DKOeHpv3.js";
19
+ import { At as findVisibleAgentsInstructions, C as PLAN_DELTA_TAG, Dt as AGENTS_REMOVAL_NOTICE, Et as JUNIOR_PERSONALITY, Ft as foldSystemMessages, It as readAgentHistory, Lt as withAgentRequest, Mt as renderAgentsInstructions, Nt as showsAgentsInstructions, Ot as AGENTS_REPLACEMENT_NOTICE, Pt as foldLeadingSystemMessages, Rt as writeAgentHistory, T as renderPlanSnapshot, bt as slackChannelMessageTrigger, d as buildPromptInput, et as resolveSlackReplyTarget, f as buildSteeringPiMessage, gt as requireSlackChannelMessageScope, h as loadPromptTurnContext, jt as readRepositoryInstructions, kt as buildAgentsInstructionsMessage, mt as getEventCatalog, u as assemblePrompt, x as listPlanItems } from "./session-stop-BQxgHR4X.js";
20
+ import { $ as createStopAgentTool, $n as createSlackListGetItemsTool, $r as requireToolDestination, A as createWebSearchTool, Ar as createDeleteAutomationTool, B as createSearchEventTypesTool, Br as automationTriggerSchema, C as incrementStat, Cr as isMissingPathError, D as requireReadyWorkspaceSnapshot, Dr as createCanvas, Er as createOperationKey, F as userLookupIdentityProviders, Fr as automationIdForToolCall, G as missingFileResult, Gr as juniorToolOutputSchema, Gt as listAgentInvocationsForConversation, H as createSearchConversationsTool, Hn as createSetConversationSubscriptionTool, Hr as newAutomationTask, I as createUpdateUserCustomizationTool, Ir as automationSkillToolSchema, J as capToolResult, Jr as automationToolContext, K as sliceFileContent, Kr as makeStructuredToolOutput, L as createSubmitFeedbackTool, Lr as automationToolResult, M as createWatchTimerTool, Mr as parseToolInput, Mt as createReadConversationEventTool, N as createWatchEventsTool, Nr as zodTool, Nt as createRunOperatorSqlTool, O as prepareWorkspaceSnapshot, Or as createSearchAutomationsTool, P as createUserLookupTool, Pr as zodToolDefinition, Pt as createListWatchesTool, Q as createUpdatePlanTool, Qn as createSlackListUpdateItemTool, Qr as requireToolCreator, R as createSystemTimeTool, Rr as automationToolResultSchema, S as createWorkspaceTools, Si as missingAutomationSkillReason, Sr as SLACK_TOOL_SOURCE, T as ensureWorkspaceSnapshotBuild, Ti as resolveTaskOutcomes, Tr as resolveWorkspacePath, U as createWriteFileTool, Ur as triggerKind, V as createSearchConversationEventsTool, Vr as editedAutomationTask, W as createReadFileTool, Wr as injectContinuationToolName, X as editFile, Xr as requireToolAutomation, Y as createEditFileTool, Yr as automationToolsDisabledReason, Z as createBashTool, Zn as createSlackPublicSearchTool, Zr as requireToolCaller, _i as requireEventAutomationTrigger, a as createCacheWarmingRecorder, at as createNoReplyTool, b as coreToolSlots, bi as requireAutomationSkill, br as createSlackCanvasReadTool, cr as createSlackChannelJoinTool, dr as checkSlackChannelReadAccess, er as createSlackListCreateTool, et as createSpawnAgentTool, fr as joinPublicChannelForRead, gi as changedEventMatch, hi as editEventAutomation, ht as createUpdateReviewItemTool, ir as createSlackChannelListMessagesTool, it as createReplyTool, j as createWebFetchTool, jr as AUTOMATIONS_TOOL_SOURCE, kr as createRunAutomationNowTool, lr as resolveSlackChannelRef, mi as editScheduledAutomation, mt as createSearchReviewItemsTool, ni as changeAutomationLifecycle, nn as isParentMessageMeta, nr as createSlackConversationMessageSearchTool, nt as createReportProgressTool, ot as createMessageAgentTool, pt as createAddReviewItemTool, q as TOOL_RESULT_MAX_CHARS, qn as createSlackThreadReadTool, qr as getConversationAccess, rr as createSlackConversationSearchChannelPort, rt as createReportBlockedTool, st as createArchiveAgentTool, ti as automationEditor, tr as createSlackListAddItemsTool, tt as createListAgentsTool, ur as slackChannelRefParam, vi as requireAutomationTaskText, wi as moveTaskOutcomes, wr as positiveInteger, x as enabledMode, xr as createSlackCanvasEditTool, yr as createSlackCanvasWriteTool, z as createStopWatchingResourcesTool, zr as automationTriggerChangesSchema } from "./warmup-mTMIatCV.js";
21
+ import { a as USER_INPUT_LIMITS, i as AGENT_INVOCATION_STATUSES, m as detectImageMediaType, o as USER_INPUT_NOTE, s as buttonUserInputField, u as normalizeUserInputAnswer } from "./web-message-id-CUaSiGme.js";
22
+ import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-DNC0eRZ7.js";
23
+ import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-D2wzxtGU.js";
24
+ import { t as resolveConversationRouting } from "./turn-session-routing-BXaubz2w.js";
25
+ import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-DbD7C5td.js";
26
+ import { n as resolve$1 } from "./resolve-n87oXY-d.js";
27
+ import { t as runWithSlackInstallation } from "./adapter-context-CnY-i32r.js";
28
28
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
29
29
  import * as z from "zod";
30
30
  import { streamSimple } from "@earendil-works/pi-ai/compat";
@@ -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,
@@ -2469,6 +2569,7 @@ function createWorkspaceSnapshotNotReadyToolResult(cause) {
2469
2569
  });
2470
2570
  }
2471
2571
  const VERCEL_FIREWALL_CHALLENGE_MARKER = "Vercel Security Checkpoint";
2572
+ const REPOSITORY_INSTRUCTIONS_READ_TIMEOUT_MS = 3e4;
2472
2573
  const SANDBOX_TOOL_NAMES = /* @__PURE__ */ new Set([
2473
2574
  "bash",
2474
2575
  "readFile",
@@ -2780,9 +2881,16 @@ function createSandbox(options) {
2780
2881
  const { runCommand } = await runtime.tools();
2781
2882
  const workspaceDirectories = activeWorkspace?.repos.map((repo) => tryWorkspaceRepoCheckoutPath(repo.repo)).filter((checkoutPath) => Boolean(checkoutPath)).map((checkoutPath) => `${SANDBOX_WORKSPACE_ROOT}/${checkoutPath}`) ?? [];
2782
2883
  return await withSandboxSpan("sandbox.repository_instructions.read", "sandbox.repository_instructions.read", {}, async (setSpanAttributes) => {
2884
+ const timeout = AbortSignal.timeout(REPOSITORY_INSTRUCTIONS_READ_TIMEOUT_MS);
2783
2885
  const { directories, instructions } = await readRepositoryInstructions({
2784
2886
  ...workspaceDirectories.length > 0 ? { directories: workspaceDirectories } : void 0,
2785
- runCommand
2887
+ runCommand: (input) => runCommand({
2888
+ ...input,
2889
+ signal: timeout
2890
+ })
2891
+ }).catch((error) => {
2892
+ if (!timeout.aborted) throw error;
2893
+ throw new SandboxCallTimeoutError("sandbox.repository_instructions.read", REPOSITORY_INSTRUCTIONS_READ_TIMEOUT_MS, { cause: error });
2786
2894
  });
2787
2895
  setSpanAttributes({
2788
2896
  "app.repository_instructions.repo_count": directories.length,
@@ -3944,18 +4052,16 @@ function parseMcpProviderFromToolName(toolName) {
3944
4052
  const delimiterIndex = afterPrefix.indexOf("__");
3945
4053
  return delimiterIndex > 0 ? afterPrefix.slice(0, delimiterIndex) : void 0;
3946
4054
  }
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 {};
4055
+ // src/chat/tool-support/dispatcher-envelope.ts
4056
+ /**
4057
+ * Error map for a dispatcher envelope schema. It tells the model to nest the
4058
+ * target tool's fields under `arguments` when it sends them at the top level.
4059
+ */
4060
+ function nestedArgumentsErrorMap(label) {
4061
+ return (issue) => issue.code === "unrecognized_keys" ? `${label} arguments must be nested under arguments, not top-level fields: ${issue.keys.join(", ")}` : void 0;
3958
4062
  }
4063
+ // src/chat/tools/skill/call-mcp-tool.ts
4064
+ const MISSING_TOOL_NAME_ERROR$1 = "callMcpTool requires an MCP tool_name";
3959
4065
  function activeProviderNames(tools) {
3960
4066
  return [...new Set(tools.map((toolDef) => toolDef.provider))].sort((a, b) => a.localeCompare(b));
3961
4067
  }
@@ -3978,10 +4084,10 @@ function createCallMcpToolTool(mcpToolManager) {
3978
4084
  },
3979
4085
  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
4086
  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(),
4087
+ 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."),
4088
+ 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
4089
  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(),
4090
+ }, { error: nestedArgumentsErrorMap("callMcpTool MCP") }).strict(),
3985
4091
  resolveApprovalMetadata: ({ tool_name }) => {
3986
4092
  const activeTool = mcpToolManager.getResolvedActiveTools().find((candidate) => candidate.name === tool_name);
3987
4093
  if (!activeTool) return;
@@ -4018,7 +4124,7 @@ function createCallMcpToolTool(mcpToolManager) {
4018
4124
  });
4019
4125
  throw new McpToolError(missingToolMessage(tool_name, provider));
4020
4126
  }
4021
- const result = await mcpTool.execute(resolveMcpArguments(input), {
4127
+ const result = await mcpTool.execute(input.arguments ?? {}, {
4022
4128
  ...intent ? { authorizationIntent: intent } : void 0,
4023
4129
  conversationPrivacy: options?.conversationPrivacy ?? "private",
4024
4130
  ...options?.signal ? { signal: options.signal } : void 0,
@@ -5562,7 +5668,7 @@ function createPublishImageTool(args) {
5562
5668
  inputSchema: z.object({ path: z.string().min(1).describe("Exact sandbox path of an existing image file.") }).strict(),
5563
5669
  outputSchema: outputSchema$1,
5564
5670
  async execute({ path }) {
5565
- const publicBaseUrl = (args.publicBaseUrl ?? resolveBaseUrl)()?.trim();
5671
+ const publicBaseUrl = resolveBaseUrl()?.trim();
5566
5672
  if (!publicBaseUrl) throw new Error("publishImage requires JUNIOR_BASE_URL or a Vercel deployment URL.");
5567
5673
  const targetPath = normalizeSandboxPath(path);
5568
5674
  const body = await args.workspace.readFileToBuffer({ path: targetPath });
@@ -5645,7 +5751,7 @@ function isPublic(run) {
5645
5751
  return run.context.conversationPrivacy === "public";
5646
5752
  }
5647
5753
  const STATIC_TOOL_BINDERS = {
5648
- updatePlan: () => createUpdatePlanTool(),
5754
+ updatePlan: (run) => createUpdatePlanTool(run.context, run.reviewItemServices().findMentionedUserId),
5649
5755
  reportProgress: () => createReportProgressTool(),
5650
5756
  systemTime: () => createSystemTimeTool(),
5651
5757
  submitFeedback: (run) => createSubmitFeedbackTool(run.context),
@@ -5692,8 +5798,8 @@ const STATIC_TOOL_BINDERS = {
5692
5798
  parentConversationId: run.context.parentConversationId
5693
5799
  }) : void 0,
5694
5800
  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)),
5801
+ [REPLY_TOOL_NAME]: (run) => createReplyTool(enabledMode(run.listedTools.reply)),
5802
+ [REPORT_BLOCKED_TOOL_NAME]: (run) => createReportBlockedTool(enabledMode(run.listedTools.reportBlocked)),
5697
5803
  [NO_REPLY_TOOL_NAME]: () => createNoReplyTool(),
5698
5804
  slackCanvasRead: () => createSlackCanvasReadTool(),
5699
5805
  slackCanvasEdit: (run) => createSlackCanvasEditTool(run.state),
@@ -5711,13 +5817,26 @@ const STATIC_TOOL_BINDERS = {
5711
5817
  slackListGetItems: () => createSlackListGetItemsTool(),
5712
5818
  slackListUpdateItem: (run) => createSlackListUpdateItemTool(run.state),
5713
5819
  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))
5820
+ addReviewItem: (run) => createAddReviewItemTool(run.context, run.reviewItemServices()),
5821
+ searchReviewItems: (run) => createSearchReviewItemsTool(run.context, run.reviewItemServices()),
5822
+ updateReviewItem: (run) => createUpdateReviewItemTool(run.context, run.reviewItemServices())
5823
+ };
5824
+ const AGENT_TOOL_LIMIT = (turnTools) => turnTools.agents === "none" ? "A person's Turn in a Thread cannot use agent tools." : void 0;
5825
+ 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.`;
5826
+ const TURN_TOOL_LIMITS = {
5827
+ spawnAgent: AGENT_TOOL_LIMIT,
5828
+ stopAgent: AGENT_TOOL_LIMIT,
5829
+ archiveAgent: AGENT_TOOL_LIMIT,
5830
+ listAgents: AGENT_TOOL_LIMIT,
5831
+ messageAgent: AGENT_TOOL_LIMIT,
5832
+ [REPLY_TOOL_NAME]: (turnTools) => turnTools.reply === "none" ? `This Turn cannot send a \`${REPLY_TOOL_NAME}\`.` : void 0,
5833
+ [REPORT_BLOCKED_TOOL_NAME]: (turnTools) => turnTools.reportBlocked === "none" ? "This Turn cannot send a blocked report." : void 0,
5834
+ updateUserCustomization: (turnTools) => turnTools.userCustomization ? void 0 : "Only a person's Turn can change user customization.",
5835
+ setConversationSubscription: (turnTools) => turnTools.subscriptions ? void 0 : "Only a person's Turn can change subscriptions.",
5836
+ addReviewItem: REVIEW_DESK_LIMIT,
5837
+ searchReviewItems: REVIEW_DESK_LIMIT,
5838
+ updateReviewItem: REVIEW_DESK_LIMIT
5717
5839
  };
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
5840
  function attachmentStore(run) {
5722
5841
  const storage = run.context.attachmentStorage;
5723
5842
  return storage ? {
@@ -5824,10 +5943,12 @@ function once(build) {
5824
5943
  */
5825
5944
  function createTools(availableSkills, hooks = {}, context, options = {}) {
5826
5945
  const slack = getSlackToolContext(context);
5946
+ const listedTools = context.listedTools ?? context.turnTools;
5827
5947
  const run = {
5828
5948
  availableSkills,
5829
5949
  hooks,
5830
5950
  context,
5951
+ listedTools,
5831
5952
  options,
5832
5953
  state: createToolState(),
5833
5954
  slack,
@@ -5845,10 +5966,11 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
5845
5966
  const tools = {};
5846
5967
  for (const slot of coreToolSlots({
5847
5968
  platform: slack ? "slack" : "local",
5848
- turnTools: context.turnTools
5969
+ listedTools
5849
5970
  })) {
5850
5971
  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;
5972
+ if (!tool) continue;
5973
+ tools[slot.name] = slot.kind === "static" ? withDisabledReason(tool, TURN_TOOL_LIMITS[slot.name]?.(context.turnTools)) : tool;
5852
5974
  }
5853
5975
  for (const [name, pluginTool] of Object.entries(getPluginTools(context, options.pluginSandbox))) {
5854
5976
  if (tools[name]) throw new Error(`Plugin tool "${name}" conflicts with a core tool`);
@@ -5857,11 +5979,6 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
5857
5979
  return tools;
5858
5980
  }
5859
5981
  // 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
5982
  /** Convert a `reportProgress` tool payload into assistant status text. */
5866
5983
  function buildReportedProgressStatus(input) {
5867
5984
  if (!input || typeof input !== "object") return;
@@ -5871,14 +5988,6 @@ function buildReportedProgressStatus(input) {
5871
5988
  if (!text) return;
5872
5989
  return { text };
5873
5990
  }
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
5991
  /** Recover the latest progress status from a resumable Pi transcript. */
5883
5992
  function latestProgressStatus(messages) {
5884
5993
  for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
@@ -5889,7 +5998,6 @@ function latestProgressStatus(messages) {
5889
5998
  if (!part || typeof part !== "object") continue;
5890
5999
  const toolCall = part;
5891
6000
  if (toolCall.type !== "toolCall") continue;
5892
- if (toolCall.name === "updatePlan") return buildPlanStatus(toolCall.arguments);
5893
6001
  if (toolCall.name === "reportProgress") {
5894
6002
  const status = buildReportedProgressStatus(toolCall.arguments);
5895
6003
  if (status) return status;
@@ -5906,6 +6014,37 @@ function isTypeBoxInputSchema(schema) {
5906
6014
  function disabledToolMessage(toolName, reason) {
5907
6015
  return `${toolName} is disabled in this Turn. ${reason} Do not call it again in this Turn.`;
5908
6016
  }
6017
+ // src/chat/tools/execute-tool.ts
6018
+ const EXECUTE_TOOL_NAME = "executeTool";
6019
+ const MISSING_TOOL_NAME_ERROR = "executeTool requires a catalog tool_name";
6020
+ /** Input envelope of `executeTool`, which the dispatcher parses before it runs the catalog tool. */
6021
+ const executeToolInputSchema = z.object({
6022
+ 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."),
6023
+ 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(),
6024
+ intent: z.string().min(1).describe("Optional short purpose of this call. It is not passed to the catalog tool.").optional()
6025
+ }, { error: nestedArgumentsErrorMap(EXECUTE_TOOL_NAME) }).strict();
6026
+ const executeToolDefinition = zodToolDefinition({
6027
+ annotations: {
6028
+ destructiveHint: true,
6029
+ idempotentHint: false,
6030
+ openWorldHint: true,
6031
+ readOnlyHint: false
6032
+ },
6033
+ 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.",
6034
+ executionMode: "sequential",
6035
+ exposure: "modelOnly",
6036
+ inputSchema: executeToolInputSchema,
6037
+ outputSchema: juniorToolOutputSchema
6038
+ });
6039
+ /** Create the model-visible dispatcher schema for catalog tools. */
6040
+ function createExecuteToolTool() {
6041
+ return zodTool({
6042
+ ...executeToolDefinition,
6043
+ execute: async () => {
6044
+ throw new ToolInputError("executeTool can only run through the agent tool dispatcher.");
6045
+ }
6046
+ });
6047
+ }
5909
6048
  // src/chat/tool-support/tool-name-suggestions.ts
5910
6049
  const MAX_SUGGESTIONS = 3;
5911
6050
  const MAX_SOURCE_TOOLS = 10;
@@ -6046,21 +6185,11 @@ function schemaErrorText(schema, value) {
6046
6185
  if (!firstError) return "invalid arguments";
6047
6186
  return `${firstError.path || "/"} ${firstError.message}`;
6048
6187
  }
6049
- /** Resolve and validate a catalog executeTool request at runtime. */
6188
+ /** Parse an executeTool envelope and resolve the catalog tool that it names. */
6050
6189
  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.");
6190
+ const { tool_name: toolName, arguments: args = {} } = parseToolInput(executeToolInputSchema, input);
6055
6191
  const definition = catalogTools[toolName];
6056
6192
  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
6193
  return {
6065
6194
  arguments: args,
6066
6195
  definition,
@@ -6544,34 +6673,6 @@ function handleToolExecutionError(error, toolName, toolCallId, shouldTrace, conv
6544
6673
  });
6545
6674
  throw error;
6546
6675
  }
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
6676
  // src/chat/tool-exposure.ts
6576
6677
  /** Return the runtime exposure for a tool, preserving direct compatibility. */
6577
6678
  function effectiveToolExposure(definition) {
@@ -7928,7 +8029,7 @@ function createToolPipeline(options) {
7928
8029
  }), nudges);
7929
8030
  };
7930
8031
  const reportStatus = async (executionToolName, params) => {
7931
- const status = executionToolName === "updatePlan" ? buildPlanStatus(params) : executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
8032
+ const status = executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
7932
8033
  if (status) await onStatus?.(status);
7933
8034
  };
7934
8035
  /**
@@ -9414,10 +9515,6 @@ async function wireAgentTools(args) {
9414
9515
  const commonToolRuntimeContext = {
9415
9516
  conversationId: args.run.conversationId,
9416
9517
  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
9518
  ...args.run.parentConversationId ? { parentConversationId: args.run.parentConversationId } : void 0,
9422
9519
  ...args.run.location ? {
9423
9520
  location: args.run.location,
@@ -9445,7 +9542,7 @@ async function wireAgentTools(args) {
9445
9542
  supportsImageInput: args.supportsImageInput,
9446
9543
  surface: args.surface,
9447
9544
  ...args.currentActor ? { resolveActorIdentity: async () => await readActorIdentity(args.currentActor) } : void 0,
9448
- ...bindAgentTools(args.run, args.behavior.tools.agents)
9545
+ ...bindTurnTools(args.run, args.behavior)
9449
9546
  };
9450
9547
  const toolRoute = resolveToolRuntimeRoute({
9451
9548
  actor: args.currentActor,
@@ -9607,7 +9704,24 @@ async function wireAgentTools(args) {
9607
9704
  toolRuntimeContext
9608
9705
  };
9609
9706
  }
9610
- /** Bind the agent tools that the Turn's behavior gives it. */
9707
+ /**
9708
+ * Bind the tools that one Turn lists and the tools that it can use. Every
9709
+ * Turn of a Prompt mode lists the same tools, so a Conversation keeps one
9710
+ * tool list. `createTools` disables each listed tool that the Turn cannot
9711
+ * use.
9712
+ */
9713
+ function bindTurnTools(run, behavior) {
9714
+ const listedTools = promptModeTurnTools(behavior.promptMode);
9715
+ return {
9716
+ turnTools: run.dispatch?.outcomes?.length === 0 ? {
9717
+ ...behavior.tools,
9718
+ reply: "none"
9719
+ } : behavior.tools,
9720
+ listedTools,
9721
+ ...bindAgentTools(run, listedTools.agents)
9722
+ };
9723
+ }
9724
+ /** Bind the agent tools that the Turn lists. */
9611
9725
  function bindAgentTools(run, agents) {
9612
9726
  const { bindSpawnAgent, bindMessageAgent } = run.environment ?? {};
9613
9727
  if (agents === "none" || !bindSpawnAgent) return {};
@@ -9793,7 +9907,7 @@ function createResumeState(args) {
9793
9907
  },
9794
9908
  async translateSuspension(ending) {
9795
9909
  const { error } = ending;
9796
- const reason = error instanceof CooperativeTurnYieldError ? "yield" : error instanceof RetryableDeliveryError ? "retry" : timedOut ? "timeout" : void 0;
9910
+ const reason = error instanceof CooperativeTurnYieldError ? "yield" : ending.retryable || error instanceof RetryableDeliveryError ? "retry" : timedOut ? "timeout" : void 0;
9797
9911
  if (!reason) return;
9798
9912
  if (reason === "retry") resumeMessages = [...latestSafeBoundaryMessages];
9799
9913
  const parkMessages = reason === "yield" ? [...resumeMessages] : continuableMessages(resumeMessages, latestSafeBoundaryMessages);
@@ -10323,69 +10437,15 @@ async function prepareSummary(message, streamFn) {
10323
10437
  });
10324
10438
  return outcome;
10325
10439
  }
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}>`;
10440
+ // src/chat/plan/snapshot.ts
10441
+ /**
10442
+ * Append one `<plan>` snapshot of the open items, read from the database, to
10443
+ * a compaction summary, so the plan and its version survive the history
10444
+ * replacement.
10445
+ */
10446
+ async function appendPlanSnapshot(summaryText, conversationId) {
10447
+ const snapshot = renderPlanSnapshot(await listPlanItems(getSqlExecutor(), conversationId));
10448
+ return snapshot ? `${summaryText}\n\n${snapshot}` : summaryText;
10389
10449
  }
10390
10450
  // src/chat/services/context-compaction.ts
10391
10451
  /**
@@ -10459,9 +10519,12 @@ function isSessionTurnContext(text) {
10459
10519
  function withoutSections(text, tags) {
10460
10520
  return tags.reduce((result, tag) => result.replace(new RegExp(`\\n\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g"), ""), text);
10461
10521
  }
10462
- /** Remove the sections that only the Turn that received them can use. */
10522
+ /**
10523
+ * Remove the sections that only the Turn that received them can use, and
10524
+ * plan deltas, which the `<plan>` snapshot of the summary replaces.
10525
+ */
10463
10526
  function withoutRequestContext(text) {
10464
- return withoutSections(text, Object.values(REQUEST_CONTEXT_SECTION_TAG));
10527
+ return withoutSections(text, [...Object.values(REQUEST_CONTEXT_SECTION_TAG), PLAN_DELTA_TAG]);
10465
10528
  }
10466
10529
  /**
10467
10530
  * Remove the copies of capability sections that the Turn context of older
@@ -10818,7 +10881,7 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
10818
10881
  };
10819
10882
  }
10820
10883
  const summaryEntry = {
10821
- message: userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages)),
10884
+ message: userMessage(await appendPlanSnapshot(renderCompactionSummary(summary), args.conversationId)),
10822
10885
  provenance: contextProvenance
10823
10886
  };
10824
10887
  const replacement = retainUserMessages ? [
@@ -11115,7 +11178,7 @@ async function applyPreparedSummary(args, prepared, budget) {
11115
11178
  }] : [],
11116
11179
  ...retained,
11117
11180
  {
11118
- message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
11181
+ message: userMessage(await appendPlanSnapshot(renderCompactionSummary(prepared.summary), args.conversationId)),
11119
11182
  provenance: contextProvenance
11120
11183
  },
11121
11184
  ...systemMessage ? [{
@@ -11293,7 +11356,14 @@ async function executeAgentRun(run, streamFn) {
11293
11356
  runId: run.runId,
11294
11357
  assistantUserName: botConfig.userName
11295
11358
  };
11296
- return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, run.dispatch?.declaresResult ? "automation" : conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn)));
11359
+ return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, async () => reportFailedRun(await executeAgentRunInPrivacyContext(run, run.dispatch?.declaresResult ? "automation" : conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn), run.signal)));
11360
+ }
11361
+ function reportFailedRun(outcome, signal) {
11362
+ if (outcome.status !== "completed" || outcome.result.diagnostics.outcome === "success" || signal?.aborted) return outcome;
11363
+ return {
11364
+ ...outcome,
11365
+ result: captureTurnFailure(outcome.result, logException)
11366
+ };
11297
11367
  }
11298
11368
  async function executeAgentRunInPrivacyContext(run, conversationKind, conversationPrivacy, runLogContext, streamFn) {
11299
11369
  const conversationId = run.conversationId;
@@ -11607,6 +11677,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11607
11677
  const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, sectionsMessage, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
11608
11678
  activeMcpCatalogs: wiring.activeMcpCatalogs,
11609
11679
  promptMode: behavior.promptMode,
11680
+ sender: behavior.sender,
11610
11681
  currentActor: actor,
11611
11682
  availableSkills,
11612
11683
  configurationValues,
@@ -11738,7 +11809,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11738
11809
  }
11739
11810
  return acceptedMessages;
11740
11811
  };
11741
- const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task", {
11812
+ const cacheWarming = createCacheWarmingRecorder(conversationId, {
11813
+ userActor: isUserActor(actor) && conversationKind !== "task",
11814
+ idleNeedsPendingWork: behavior.idleNeedsPendingWork
11815
+ }, {
11742
11816
  platform: promptPlatform,
11743
11817
  mode: behavior.promptMode
11744
11818
  });
@@ -12170,7 +12244,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
12170
12244
  if (resume) {
12171
12245
  const outcome = await resume.translateSuspension({
12172
12246
  currentUsage: turnUsage,
12173
- error: runError
12247
+ error: runError,
12248
+ retryable: resume.inputCommitted && !acceptedToolFreeAssistant && !findInErrorChain(runError, (candidate) => candidate instanceof ProviderError) && isRetryableSandboxFailure(runError)
12174
12249
  });
12175
12250
  if (outcome) return outcome;
12176
12251
  }
@@ -12179,10 +12254,6 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
12179
12254
  if (isTurnInputCommitLostError(error)) throw error;
12180
12255
  if (error instanceof AuthorizationFlowDisabledError) throw error;
12181
12256
  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
12257
  const message = error instanceof Error ? error.message : String(error);
12187
12258
  return {
12188
12259
  status: "completed",
@@ -12233,7 +12304,7 @@ function createAgentRunner(execute, options) {
12233
12304
  }
12234
12305
  };
12235
12306
  const loadStoredAttachments = async (attachments) => {
12236
- const { loadInputAttachments } = await import("./model-input-DoM9Ht-d.js").then((n) => n.r);
12307
+ const { loadInputAttachments } = await import("./model-input-DYYF3a8B.js").then((n) => n.r);
12237
12308
  const storage = nextRun.environment?.attachmentStorage;
12238
12309
  if (!storage) throw new Error("Attachment storage is unavailable.");
12239
12310
  return await loadInputAttachments({
@@ -12257,4 +12328,4 @@ function createAgentRunner(execute, options) {
12257
12328
  return await execute(nextRun, streamFn);
12258
12329
  } };
12259
12330
  }
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 };
12331
+ export { RetryableDeliveryError as A, parseSlackReviewItemClick as C, AttachmentDownloadError as D, parseSlackUserInputSubmission as E, requireTurnFailureEventId as F, shouldEmitDevAgentTrace as I, toolInvocationDestination as M, finalizeFailedTurnReplyWithEvent as N, readAttachmentContent as O, getAgentTurnDiagnosticsAttributes as P, buildSlackReviewItemModal as S, safeLinkUrl as T, createSlackReviewItemShow as _, buildAuthPauseResponse as a, findSlackThreadOwnerId as b, createClientMetadata as c, publicArtifactHeaders as d, readPublicArtifact as f, scheduledAutomationRunAttributes as g, logScheduledAutomationRunSkipped as h, measureTurnCompactionWait as i, actorFromRun as j, previewOriginBelongsTo as k, readMcpClientInformation as l, resolveDestinationVisibility as m, executeAgentRun as n, finalizeMcpAuthorization as o, unpublishedArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, resolveSlackReviewItemCardConversationId as v, parseSlackReviewItemFormTarget as w, SLACK_REVIEW_ITEM_VIEW_ID as x, syncReviewItemSlackCards as y };