@sentry/junior 0.304.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-B1IpoELr.js → adapter-context-CnY-i32r.js} +2 -2
  2. package/dist/{admin-BnVFGo_z.js → admin-BLLdLnXh.js} +2 -2
  3. package/dist/{agent-runner-CoEeZSRh.js → agent-runner-BaLjEjPR.js} +312 -204
  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 +489 -445
  11. package/dist/{background-compaction-queue-WLPNSF_b.js → background-compaction-queue-D2wzxtGU.js} +7 -3
  12. package/dist/{briefs-CagVVefw.js → briefs-DvyzXfrF.js} +3 -3
  13. package/dist/{catalog-runtime-B8ZXvXWm.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-DdO1BNcw.js → config-DUD-zMvp.js} +111 -13
  22. package/dist/{connections-D20kp0j5.js → connections-CDhsqPcC.js} +6 -6
  23. package/dist/{continue-in-slack-BKEVMBj1.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-L1SK_v0V.js → conversation-privacy-YE54gMN8.js} +1 -1
  27. package/dist/{conversation-turn-BptVJylj.js → conversation-turn-BzdmrHb0.js} +22 -40
  28. package/dist/{credential-sync-D1J1CGzL.js → credential-sync-Cdm-e1vJ.js} +14 -13
  29. package/dist/{db-EKJnkrIb.js → db-DV2ZUb1Y.js} +90 -11
  30. package/dist/{db-zbN5ZV_o.d.ts → db-pH357Dkt.d.ts} +1 -1
  31. package/dist/{executor-CoIZmFK8.js → executor-CjNhwwnj.js} +47 -4
  32. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  33. package/dist/{install-BT2Pf6HP.js → install-DbD7C5td.js} +2 -2
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{lineage-C5DGQCS_.js → lineage-BFdIPb3o.js} +2 -2
  36. package/dist/{logging-QSZuMcvo.js → logging-oYpJYr-S.js} +1 -1
  37. package/dist/{message-TtxftRHj.js → message-BBPcMKJY.js} +8 -8
  38. package/dist/{model-input-BHXfA29g.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-B0enqHtZ.js → oauth-callback-server-C7Q987su.js} +2 -2
  42. package/dist/{projection-CNKK7doO.js → projection-CWXDE0f6.js} +7740 -6165
  43. package/dist/{prompt-DSjhoKu5.js → prompt-P3eRqO8C.js} +15 -7
  44. package/dist/{queue-CDxkit82.js → queue-7FSijgqG.js} +4 -4
  45. package/dist/{registry-DBDNUUmz.js → registry-1pzXmplY.js} +1 -1
  46. package/dist/{resolve-CQLhMWSu.js → resolve-n87oXY-d.js} +3 -3
  47. package/dist/{result-B-pauj42.js → result-BmF9v9bv.js} +9 -9
  48. package/dist/{runner-B3KxKks5.js → runner-4j7ZsxP5.js} +13 -15
  49. package/dist/{sandbox-egress-signals-DJJX9ClG.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-DQLqkSVv.js → service-account-BDQ9xzta.js} +3 -3
  54. package/dist/{service-account-2HmlNPvy.js → service-account-DzQiOmqa.js} +5 -5
  55. package/dist/{session-stop-DEeZKqbX.js → session-stop-BQxgHR4X.js} +919 -168
  56. package/dist/{skills-2UrD7JkN.js → skills-CPf4vNuC.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-Dd129Uov.js → slack-conversation-unfurl-B1KEptUg.js} +10 -9
  58. package/dist/{spawn-eMho9HDJ.js → spawn-CjGddiAU.js} +6 -6
  59. package/dist/{state-Bveuc4Zh.js → state-9wfj6aSD.js} +4 -4
  60. package/dist/{stop-D_ltJLDS.js → stop-CsQGuN5n.js} +62 -118
  61. package/dist/{store-COeYnPL_.js → store-Dz3YZ7gQ.js} +5 -5
  62. package/dist/{task-queue-CBIDXZpV.js → task-queue-CFlrJguF.js} +3 -3
  63. package/dist/{task-runner-CJF7zIJL.js → task-runner-frzlUvFD.js} +8 -9
  64. package/dist/{thread-context-Cg0jt0aE.js → thread-context-C4QuZlM8.js} +8 -91
  65. package/dist/turn-session-routing-BXaubz2w.js +244 -0
  66. package/dist/{turn-user-message-tcom1RYd.js → turn-user-message-DNC0eRZ7.js} +3 -3
  67. package/dist/users-XCCKn3xW.js +181 -0
  68. package/dist/{validation-EU91JwIT.js → validation-L5fdjmFX.js} +1 -1
  69. package/dist/{version-BYRPhY5G.js → version-BFmuwgxP.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-Cf8ISkAc.js → viewer-DKOeHpv3.js} +3 -3
  72. package/dist/{warmup-TgY4S1vx.js → warmup-mTMIatCV.js} +271 -279
  73. package/dist/{web-message-id-lNodcCOI.js → web-message-id-CUaSiGme.js} +16 -1
  74. package/dist/{worker-C6Uq4OKD.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-CaY3Tp8m.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-CNKK7doO.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-DdO1BNcw.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-QSZuMcvo.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-L1SK_v0V.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-EKJnkrIb.js";
8
- import { L as juniorArtifacts, c as juniorReviewItemSlackCards, u as juniorAutomationRuns } from "./executor-CoIZmFK8.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-DBDNUUmz.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B8ZXvXWm.js";
13
- import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-2UrD7JkN.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-2HmlNPvy.js";
15
- import { f as generateImages, h as NoAudioError, l as completeObject, m as transcribeFromUrl, u as completeText } from "./prompt-DSjhoKu5.js";
16
- import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-Cf8ISkAc.js";
17
- import { W as MAX_ATTACHMENT_BYTES } from "./conversation-BOqdRtUx.js";
18
- import { Q as requireSlackChannelMessageScope, R as resolveSlackReplyTarget, X as getEventCatalog, _t as foldSystemMessages, bt as writeAgentHistory, ct as JUNIOR_PERSONALITY, d as buildPromptInput, dt as buildAgentsInstructionsMessage, f as buildSteeringPiMessage, ft as findVisibleAgentsInstructions, gt as foldLeadingSystemMessages, h as loadPromptTurnContext, ht as showsAgentsInstructions, lt as AGENTS_REMOVAL_NOTICE, mt as renderAgentsInstructions, nt as slackChannelMessageTrigger, pt as readRepositoryInstructions, u as assemblePrompt, ut as AGENTS_REPLACEMENT_NOTICE, vt as readAgentHistory, yt as withAgentRequest } from "./session-stop-DEeZKqbX.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-TgY4S1vx.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-CaY3Tp8m.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-tcom1RYd.js";
24
- import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-WLPNSF_b.js";
25
- import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-BT2Pf6HP.js";
26
- import { n as resolve$1 } from "./resolve-CQLhMWSu.js";
27
- import { t as runWithSlackInstallation } from "./adapter-context-B1IpoELr.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");
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,33 +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
- }).strict(),
6563
- outputSchema: juniorToolOutputSchema
6564
- });
6565
- /** Create the model-visible dispatcher schema for catalog tools. */
6566
- function createExecuteToolTool() {
6567
- return zodTool({
6568
- ...executeToolDefinition,
6569
- execute: async () => {
6570
- throw new ToolInputError("executeTool can only run through the agent tool dispatcher.");
6571
- }
6572
- });
6573
- }
6574
6676
  // src/chat/tool-exposure.ts
6575
6677
  /** Return the runtime exposure for a tool, preserving direct compatibility. */
6576
6678
  function effectiveToolExposure(definition) {
@@ -6674,6 +6776,40 @@ async function rerankSearchCandidates(args) {
6674
6776
  telemetry(picked.length > 0 ? "picked" : "none");
6675
6777
  return picked;
6676
6778
  }
6779
+ // src/chat/tool-support/schema-summary.ts
6780
+ function asSchema(value) {
6781
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
6782
+ }
6783
+ function propertyList(schema) {
6784
+ const properties = asSchema(schema["properties"]);
6785
+ const required = new Set(Array.isArray(schema["required"]) ? schema["required"] : []);
6786
+ return Object.entries(properties).map(([name, property]) => `${name}${required.has(name) ? "" : "?"}: ${schemaType(asSchema(property))}`).join(", ");
6787
+ }
6788
+ function schemaType(schema) {
6789
+ if ("const" in schema) return JSON.stringify(schema["const"]);
6790
+ if (Array.isArray(schema["enum"])) return schema["enum"].map((value) => JSON.stringify(value)).join(" | ");
6791
+ const variants = schema["anyOf"] ?? schema["oneOf"];
6792
+ if (Array.isArray(variants)) return variants.map((variant) => schemaType(asSchema(variant))).join(" | ");
6793
+ return (Array.isArray(schema["type"]) ? schema["type"] : [schema["type"] ?? (schema["properties"] ? "object" : void 0)]).map((type) => {
6794
+ if (type === "array") {
6795
+ const item = schemaType(asSchema(schema["items"]));
6796
+ return item.includes(" | ") ? `(${item})[]` : `${item}[]`;
6797
+ }
6798
+ if (type === "object") {
6799
+ const properties = propertyList(schema);
6800
+ return properties ? `{ ${properties} }` : "object";
6801
+ }
6802
+ return typeof type === "string" ? type : "unknown";
6803
+ }).join(" | ");
6804
+ }
6805
+ /**
6806
+ * Summarize a tool input schema as `name: type` pairs, with `?` on optional
6807
+ * params, so a search result can show how to call a tool without its full
6808
+ * schema.
6809
+ */
6810
+ function summarizeInputSchema(schema) {
6811
+ return propertyList(schema) || "No arguments.";
6812
+ }
6677
6813
  // src/chat/tools/search-tools.ts
6678
6814
  const SEARCH_TOOLS_NAME = "searchTools";
6679
6815
  const DEFAULT_MAX_RESULTS = 5;
@@ -6817,9 +6953,9 @@ const searchToolsToolSchema = z.object({
6817
6953
  tool_name: z.string(),
6818
6954
  description: z.string(),
6819
6955
  source: z.string().optional(),
6820
- input_schema: z.unknown(),
6821
- call_notes: z.array(z.string()),
6822
- annotations: z.record(z.string(), z.unknown())
6956
+ input_schema: z.unknown().optional(),
6957
+ params: z.string().optional(),
6958
+ call_notes: z.array(z.string()).optional()
6823
6959
  }).strict();
6824
6960
  const searchToolsOutputSchema = juniorToolOutputSchema.extend({
6825
6961
  query: z.string().nullable(),
@@ -7041,7 +7177,7 @@ function selectedSourceSummaries(tools, matches, requestedSource, knownSources)
7041
7177
  return knownSources.filter((source) => matchedSourceIds.has(source.id));
7042
7178
  }
7043
7179
  function renderSearchToolsDescription(knownSources) {
7044
- 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.";
7180
+ const intro = "Search the executable tool catalog. Deferred tools are grouped by source; use searchTools with source to inspect one source, then executeTool with the exact returned tool_name. The best match has its full input_schema. Other results have params, a preview for choosing a tool: before you call one, search its exact name to get its input_schema.";
7045
7181
  if (knownSources.length === 0) return intro;
7046
7182
  return [
7047
7183
  intro,
@@ -7050,14 +7186,14 @@ function renderSearchToolsDescription(knownSources) {
7050
7186
  ].join("\n");
7051
7187
  }
7052
7188
  /** Build the agent-visible catalog tool summary returned by searchTools. */
7053
- function toolMetadata(name, definition, includeSource) {
7189
+ function toolMetadata(name, definition, includeSource, includeSchema) {
7190
+ const notes = callNotes(definition);
7054
7191
  return {
7055
7192
  tool_name: name,
7056
7193
  description: summarizeModelVisibleDescription(definition.description),
7057
7194
  ...includeSource && definition.source ? { source: definition.source.id } : void 0,
7058
- input_schema: definition.inputSchema,
7059
- call_notes: callNotes(definition),
7060
- annotations: definition.annotations ?? {}
7195
+ ...includeSchema ? { input_schema: definition.inputSchema } : { params: summarizeInputSchema(definition.inputSchema) },
7196
+ ...notes.length > 0 ? { call_notes: notes } : void 0
7061
7197
  };
7062
7198
  }
7063
7199
  /**
@@ -7084,10 +7220,11 @@ function createSearchToolsTool(allCatalogTools, rerankCost) {
7084
7220
  max_results: z.number().int().min(1).max(MAX_RESULTS).nullable().describe("Maximum matching catalog tool descriptors to return.").optional()
7085
7221
  }).strict(),
7086
7222
  outputSchema: searchToolsOutputSchema,
7087
- privateTraceResult: (result) => ({ tools: result.tools.map(({ tool_name, description, input_schema }) => ({
7223
+ privateTraceResult: (result) => ({ tools: result.tools.map(({ tool_name, description, input_schema, params }) => ({
7088
7224
  tool_name,
7089
7225
  description,
7090
- input_schema
7226
+ input_schema,
7227
+ params
7091
7228
  })) }),
7092
7229
  execute: async ({ query, source, max_results }, { signal }) => {
7093
7230
  const maxResults = max_results ?? DEFAULT_MAX_RESULTS;
@@ -7117,7 +7254,7 @@ function createSearchToolsTool(allCatalogTools, rerankCost) {
7117
7254
  const sources = !sourceExists ? knownSources : (query ?? "").trim() ? selectedSourceSummaries(catalogTools, matches, requestedSource, knownSources) : requestedSource ? knownSources.filter((candidate) => candidate.id === requestedSource) : knownSources;
7118
7255
  const totalEligibleTools = sourceExists ? listCatalogTools(catalogTools, requestedSource).length : 0;
7119
7256
  const includePerToolSource = requestedSource === null;
7120
- const renderedTools = matches.map((name) => toolMetadata(name, catalogTools[name], includePerToolSource));
7257
+ const renderedTools = matches.map((name, index) => toolMetadata(name, catalogTools[name], includePerToolSource, hasQuery && index === 0));
7121
7258
  const result = {
7122
7259
  query: query ?? null,
7123
7260
  source: requestedSource,
@@ -7629,7 +7766,7 @@ function renderScriptTools(tools) {
7629
7766
  ...shown.map((entry) => entry.text),
7630
7767
  "};"
7631
7768
  ] : [],
7632
- ...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 script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
7769
+ ...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. A result with only params is a preview: search its exact name to get its input_schema before you call it. A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
7633
7770
  ...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."] : []
7634
7771
  ].join("\n");
7635
7772
  }
@@ -7892,7 +8029,7 @@ function createToolPipeline(options) {
7892
8029
  }), nudges);
7893
8030
  };
7894
8031
  const reportStatus = async (executionToolName, params) => {
7895
- const status = executionToolName === "updatePlan" ? buildPlanStatus(params) : executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
8032
+ const status = executionToolName === "reportProgress" ? buildReportedProgressStatus(params) : void 0;
7896
8033
  if (status) await onStatus?.(status);
7897
8034
  };
7898
8035
  /**
@@ -9378,10 +9515,6 @@ async function wireAgentTools(args) {
9378
9515
  const commonToolRuntimeContext = {
9379
9516
  conversationId: args.run.conversationId,
9380
9517
  turnId: args.run.turnId,
9381
- turnTools: {
9382
- ...args.behavior.tools,
9383
- reply: args.run.dispatch?.outcomes?.length === 0 ? "none" : args.behavior.tools.reply
9384
- },
9385
9518
  ...args.run.parentConversationId ? { parentConversationId: args.run.parentConversationId } : void 0,
9386
9519
  ...args.run.location ? {
9387
9520
  location: args.run.location,
@@ -9409,7 +9542,7 @@ async function wireAgentTools(args) {
9409
9542
  supportsImageInput: args.supportsImageInput,
9410
9543
  surface: args.surface,
9411
9544
  ...args.currentActor ? { resolveActorIdentity: async () => await readActorIdentity(args.currentActor) } : void 0,
9412
- ...bindAgentTools(args.run, args.behavior.tools.agents)
9545
+ ...bindTurnTools(args.run, args.behavior)
9413
9546
  };
9414
9547
  const toolRoute = resolveToolRuntimeRoute({
9415
9548
  actor: args.currentActor,
@@ -9571,11 +9704,28 @@ async function wireAgentTools(args) {
9571
9704
  toolRuntimeContext
9572
9705
  };
9573
9706
  }
9574
- /** 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. */
9575
9725
  function bindAgentTools(run, agents) {
9576
9726
  const { bindSpawnAgent, bindMessageAgent } = run.environment ?? {};
9577
9727
  if (agents === "none" || !bindSpawnAgent) return {};
9578
- const spawnAgent = isAgentRunFeatureDisabled(run.disabledFeatures, "subagents") ? void 0 : bindSpawnAgent(run);
9728
+ const spawnAgent = agents === "children" || agents === "children_and_parent" && botConfig.maxAgentDepth > 0 ? bindSpawnAgent(run) : void 0;
9579
9729
  const messageAgent = spawnAgent || agents === "children_and_parent" ? bindMessageAgent?.(run, agents) : void 0;
9580
9730
  return {
9581
9731
  ...spawnAgent ? { spawnAgent } : void 0,
@@ -9757,7 +9907,7 @@ function createResumeState(args) {
9757
9907
  },
9758
9908
  async translateSuspension(ending) {
9759
9909
  const { error } = ending;
9760
- 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;
9761
9911
  if (!reason) return;
9762
9912
  if (reason === "retry") resumeMessages = [...latestSafeBoundaryMessages];
9763
9913
  const parkMessages = reason === "yield" ? [...resumeMessages] : continuableMessages(resumeMessages, latestSafeBoundaryMessages);
@@ -10140,12 +10290,13 @@ async function requestAboveMark(args) {
10140
10290
  historyVersion,
10141
10291
  markSeq
10142
10292
  };
10143
- const { systemPrompt, thinkingLevel, tools } = args.agent.state;
10293
+ const { messages, thinkingLevel, tools } = args.agent.state;
10294
+ const leading = getInitialSystemMessage(messages);
10144
10295
  const snapshot = {
10145
10296
  conversationPrivacy: args.conversationPrivacy ?? "private",
10146
10297
  inputSize: args.inputSize,
10147
10298
  modelId: args.modelId,
10148
- systemPrompt,
10299
+ systemPrompt: leading ? getSystemMessageText$1(leading) : "",
10149
10300
  thinkingLevel,
10150
10301
  tools: tools.map((tool) => ({
10151
10302
  name: tool.name,
@@ -10286,69 +10437,15 @@ async function prepareSummary(message, streamFn) {
10286
10437
  });
10287
10438
  return outcome;
10288
10439
  }
10289
- // src/chat/services/plan-continuation.ts
10290
- const OPEN_PLAN_TAG = "open-plan";
10291
- function openItems(input) {
10292
- const plan = input && typeof input === "object" ? input.plan : void 0;
10293
- if (!Array.isArray(plan)) return [];
10294
- return plan.flatMap((value) => {
10295
- const item = value;
10296
- if (typeof item?.step !== "string" || item.status !== "pending" && item.status !== "in_progress") return [];
10297
- return [{
10298
- step: item.step,
10299
- status: item.status
10300
- }];
10301
- });
10302
- }
10303
- function messageText$1(message) {
10304
- const content = message.content;
10305
- if (!Array.isArray(content)) return typeof content === "string" ? content : "";
10306
- return content.flatMap((part) => {
10307
- const text = part?.text;
10308
- return typeof text === "string" ? [text] : [];
10309
- }).join("\n");
10310
- }
10311
- function retainedOpenItems(message) {
10312
- const text = messageText$1(message);
10313
- if (!isCompactionSummaryText(text)) return;
10314
- const continuation = unwrapCurrentInstruction(text) ?? text;
10315
- const open = `<${OPEN_PLAN_TAG}>\n`;
10316
- const close = `\n</${OPEN_PLAN_TAG}>`;
10317
- const closeIndex = continuation.lastIndexOf(close);
10318
- const openIndex = continuation.lastIndexOf(open, closeIndex);
10319
- if (openIndex < 0 || closeIndex < 0) return;
10320
- const payload = continuation.slice(openIndex + open.length, closeIndex);
10321
- try {
10322
- return openItems({ plan: JSON.parse(payload) });
10323
- } catch {
10324
- return;
10325
- }
10326
- }
10327
- /** Read open items from the latest successful plan state. */
10328
- function latestOpenPlanItems(messages) {
10329
- const successfulCalls = /* @__PURE__ */ new Set();
10330
- for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
10331
- const message = messages[messageIndex];
10332
- if (message.role === "toolResult" && message.toolName === "updatePlan" && typeof message.toolCallId === "string" && message.isError !== true) {
10333
- successfulCalls.add(message.toolCallId);
10334
- continue;
10335
- }
10336
- if (message.role === "user") {
10337
- const retained = retainedOpenItems(messages[messageIndex]);
10338
- if (retained) return retained;
10339
- }
10340
- if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
10341
- for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {
10342
- const call = message.content[partIndex];
10343
- if (call?.type === "toolCall" && call.name === "updatePlan" && typeof call.id === "string" && successfulCalls.has(call.id)) return openItems(call.arguments);
10344
- }
10345
- }
10346
- return [];
10347
- }
10348
- /** Append exact open plan state to continuation text. */
10349
- function appendOpenPlan(continuation, messages) {
10350
- const plan = latestOpenPlanItems(messages);
10351
- 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;
10352
10449
  }
10353
10450
  // src/chat/services/context-compaction.ts
10354
10451
  /**
@@ -10422,9 +10519,12 @@ function isSessionTurnContext(text) {
10422
10519
  function withoutSections(text, tags) {
10423
10520
  return tags.reduce((result, tag) => result.replace(new RegExp(`\\n\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g"), ""), text);
10424
10521
  }
10425
- /** 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
+ */
10426
10526
  function withoutRequestContext(text) {
10427
- return withoutSections(text, Object.values(REQUEST_CONTEXT_SECTION_TAG));
10527
+ return withoutSections(text, [...Object.values(REQUEST_CONTEXT_SECTION_TAG), PLAN_DELTA_TAG]);
10428
10528
  }
10429
10529
  /**
10430
10530
  * Remove the copies of capability sections that the Turn context of older
@@ -10781,7 +10881,7 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
10781
10881
  };
10782
10882
  }
10783
10883
  const summaryEntry = {
10784
- message: userMessage(appendOpenPlan(renderCompactionSummary(summary), source.messages)),
10884
+ message: userMessage(await appendPlanSnapshot(renderCompactionSummary(summary), args.conversationId)),
10785
10885
  provenance: contextProvenance
10786
10886
  };
10787
10887
  const replacement = retainUserMessages ? [
@@ -11078,7 +11178,7 @@ async function applyPreparedSummary(args, prepared, budget) {
11078
11178
  }] : [],
11079
11179
  ...retained,
11080
11180
  {
11081
- message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
11181
+ message: userMessage(await appendPlanSnapshot(renderCompactionSummary(prepared.summary), args.conversationId)),
11082
11182
  provenance: contextProvenance
11083
11183
  },
11084
11184
  ...systemMessage ? [{
@@ -11256,7 +11356,14 @@ async function executeAgentRun(run, streamFn) {
11256
11356
  runId: run.runId,
11257
11357
  assistantUserName: botConfig.userName
11258
11358
  };
11259
- 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
+ };
11260
11367
  }
11261
11368
  async function executeAgentRunInPrivacyContext(run, conversationKind, conversationPrivacy, runLogContext, streamFn) {
11262
11369
  const conversationId = run.conversationId;
@@ -11570,6 +11677,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11570
11677
  const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, sectionsMessage, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
11571
11678
  activeMcpCatalogs: wiring.activeMcpCatalogs,
11572
11679
  promptMode: behavior.promptMode,
11680
+ sender: behavior.sender,
11573
11681
  currentActor: actor,
11574
11682
  availableSkills,
11575
11683
  configurationValues,
@@ -11701,7 +11809,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
11701
11809
  }
11702
11810
  return acceptedMessages;
11703
11811
  };
11704
- const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task", {
11812
+ const cacheWarming = createCacheWarmingRecorder(conversationId, {
11813
+ userActor: isUserActor(actor) && conversationKind !== "task",
11814
+ idleNeedsPendingWork: behavior.idleNeedsPendingWork
11815
+ }, {
11705
11816
  platform: promptPlatform,
11706
11817
  mode: behavior.promptMode
11707
11818
  });
@@ -12133,7 +12244,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
12133
12244
  if (resume) {
12134
12245
  const outcome = await resume.translateSuspension({
12135
12246
  currentUsage: turnUsage,
12136
- error: runError
12247
+ error: runError,
12248
+ retryable: resume.inputCommitted && !acceptedToolFreeAssistant && !findInErrorChain(runError, (candidate) => candidate instanceof ProviderError) && isRetryableSandboxFailure(runError)
12137
12249
  });
12138
12250
  if (outcome) return outcome;
12139
12251
  }
@@ -12142,10 +12254,6 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
12142
12254
  if (isTurnInputCommitLostError(error)) throw error;
12143
12255
  if (error instanceof AuthorizationFlowDisabledError) throw error;
12144
12256
  if (durability.onInputCommitted && !resume?.inputCommitted) throw error;
12145
- if (!signal?.aborted || error !== signal.reason) {
12146
- const providerError = findProviderError(error);
12147
- logException(error, "assistant.reply.generation.failed", providerError ? getProviderErrorAttributes(providerError) : {});
12148
- }
12149
12257
  const message = error instanceof Error ? error.message : String(error);
12150
12258
  return {
12151
12259
  status: "completed",
@@ -12196,7 +12304,7 @@ function createAgentRunner(execute, options) {
12196
12304
  }
12197
12305
  };
12198
12306
  const loadStoredAttachments = async (attachments) => {
12199
- const { loadInputAttachments } = await import("./model-input-BHXfA29g.js").then((n) => n.r);
12307
+ const { loadInputAttachments } = await import("./model-input-DYYF3a8B.js").then((n) => n.r);
12200
12308
  const storage = nextRun.environment?.attachmentStorage;
12201
12309
  if (!storage) throw new Error("Attachment storage is unavailable.");
12202
12310
  return await loadInputAttachments({
@@ -12220,4 +12328,4 @@ function createAgentRunner(execute, options) {
12220
12328
  return await execute(nextRun, streamFn);
12221
12329
  } };
12222
12330
  }
12223
- 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 };