@sentry/junior 0.294.0 → 0.296.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 (79) hide show
  1. package/dist/{admin-vt8aSiCD.js → admin-z_lgDi-z.js} +2 -2
  2. package/dist/{agent-runner-DJu7w6mI.js → agent-runner-HoQiUKLL.js} +318 -199
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +5 -5
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +321 -331
  7. package/dist/{app--a5RLOrr.d.ts → app-C75Ft-A_.d.ts} +3 -3
  8. package/dist/app.d.ts +2 -2
  9. package/dist/app.js +33 -34
  10. package/dist/{automation-BM-OBsKW.js → automation-yJX3C7i3.js} +3 -3
  11. package/dist/{background-compaction-queue-D2j-0XkH.js → background-compaction-queue-Cre1wFt9.js} +7 -9
  12. package/dist/{briefs-JOAoCb6d.js → briefs-BXECHduJ.js} +3 -3
  13. package/dist/{catalog-runtime-CLMA9AXd.js → catalog-runtime-CpCmlD9L.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +2 -0
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +2 -2
  23. package/dist/cli/upgrade.js +3 -3
  24. package/dist/{config-mIZeGEWv.js → config-CCPHvTqx.js} +59 -2
  25. package/dist/{connections-XhdVg7OR.js → connections-B5pWh8e2.js} +6 -6
  26. package/dist/{conversation-CDWejM4R.js → conversation-CMkSmi02.js} +2 -11
  27. package/dist/{conversation-pending-messages-Dh2tfbaw.js → conversation-feed-BVAOga0H.js} +27 -2
  28. package/dist/{conversation-privacy-C6h-X2cZ.js → conversation-privacy-CZD5soDW.js} +1 -1
  29. package/dist/{credential-sync-zigBlXS3.js → credential-sync-DwLkIvXI.js} +16 -15
  30. package/dist/{db-DV5AbcGM.d.ts → db-B3iyr_Or.d.ts} +6 -1
  31. package/dist/{db--xuNV7g6.js → db-C1M1y-bh.js} +64 -26
  32. package/dist/{executor-BItuRqAR.js → executor-DUSEwXaO.js} +16 -5
  33. package/dist/instrumentation.js +19 -2
  34. package/dist/{logging-Cb6MGvdt.js → logging-D0svFM8r.js} +2 -1
  35. package/dist/{message-BTGgSmaH.js → message-BFnIwKpx.js} +9 -9
  36. package/dist/nitro.d.ts +2 -2
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-Dvh1aOIi.js → oauth-callback-server-BXRtD6Fk.js} +2 -2
  39. package/dist/{oauth-relay-D6xxVywK.js → oauth-relay-CsfIazeF.js} +2 -1
  40. package/dist/{plugins-DtmjkTza.d.ts → plugins-B_0Cr0MO.d.ts} +0 -1
  41. package/dist/{projection-DLQgfO5N.js → projection-B6VS7kbo.js} +386 -108
  42. package/dist/{prompt-qp_LdxLX.js → prompt-CD11tfG8.js} +4 -4
  43. package/dist/{registry-MtwokaqW.js → registry-CHewwYEo.js} +3 -13
  44. package/dist/{resolve-BnJA0UNE.js → resolve-1owMH4qo.js} +3 -3
  45. package/dist/{result-ChL-1KyW.js → result-CEqQFrEf.js} +8 -8
  46. package/dist/{runner-BONN7Dp2.js → runner-BtWvJslp.js} +8 -8
  47. package/dist/{sandbox-egress-signals-nmlmI5Ab.js → sandbox-egress-signals-ByftwJVt.js} +1 -1
  48. package/dist/{schema-DgvcyJ1y.d.ts → schema-Ct1Zf2xy.d.ts} +66 -14
  49. package/dist/{schema-yr0ccDni.js → schema-D2iGyYIp.js} +24 -6
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-Bd0lBaGr.js → service-account-BZEuMKdo.js} +3 -3
  52. package/dist/{service-account-kio5nXSD.js → service-account-DLoeoHww.js} +42 -26
  53. package/dist/{session-stop-CeCXL3j9.js → session-stop-hYNTNpVf.js} +23 -778
  54. package/dist/{skills-e3DDNlKO.js → skills-DXgd5Inh.js} +3 -3
  55. package/dist/{spawn--cRxITWQ.js → spawn-YeqlNDv8.js} +5 -5
  56. package/dist/{adapter-DxLhJEnO.js → state-C3CbtD_m.js} +132 -2
  57. package/dist/{stop-Iai5N2PU.js → stop-Cze_pEL8.js} +351 -255
  58. package/dist/{store-C8LsaJwS.js → store-CZ9vqR4P.js} +3 -3
  59. package/dist/{task-runner-Dw7exu0-.js → task-runner-CMiNGsER.js} +275 -251
  60. package/dist/{turn-failure-response-BqTTx3XG.js → turn-failure-response-pXhZ2wMK.js} +12 -9
  61. package/dist/{validation-BrGahtnv.js → validation-Du7NdkOR.js} +1 -1
  62. package/dist/{version-Bdqhx8Qh.js → version-EN3Wnq-R.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-CjRFHR5U.js → viewer-Agxi_o5c.js} +3 -3
  65. package/dist/warmup-CY2ArYag.js +2017 -0
  66. package/dist/{work-BWBG1EGV.js → work-EA98F0ia.js} +11 -11
  67. package/dist/{worker-DAnBIVMs.js → worker-BALVdWbv.js} +6 -6
  68. package/migrations/0098_review_item_plugin_actions.sql +5 -0
  69. package/migrations/0099_conversation_last_message_at.sql +1 -0
  70. package/migrations/0100_automation_task_kind_repair.sql +48 -0
  71. package/migrations/0101_drop_legacy_columns.sql +12 -0
  72. package/migrations/meta/0098_snapshot.json +4490 -0
  73. package/migrations/meta/0099_snapshot.json +4720 -0
  74. package/migrations/meta/0100_snapshot.json +4496 -0
  75. package/migrations/meta/0101_snapshot.json +4496 -0
  76. package/migrations/meta/_journal.json +28 -0
  77. package/package.json +6 -5
  78. package/dist/assistant-reply-iTtEdDyc.js +0 -58
  79. package/dist/warmup-DuxCtzKC.js +0 -1039
@@ -1,33 +1,32 @@
1
1
  import { g as withActiveSpan, h as startSpan, i as getActiveSpan, m as startInactiveSpan, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { $ as loadTurnCheckpoint, $i as uploadFilesToConversation, $t as extractAssistantText, A as latestConversationMessageSeq, Ar as automationCreatorUserId, B as getAgentContextInputLimitTokens, Ba as SANDBOX_REPOS_ROOT, Bn as getPlugins, Br as cancelWatch, Ca as consumeSandboxEgressAuthRequiredSignal, Ci as setWorkspaceSnapshot, Cr as requireReviewItemLinks, Di as isStale, Dn as findLegacyWebActorUserId, Ei as hash, En as createUserTokenStore, Fa as PluginToolDeniedError, Fi as resolveBaseUrl, Fo as historyItemFromPiMessage, Fr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, G as AuthPausePersistenceError, Ga as sandboxSkillPathResolution, Gi as getSlackMessagePermalink, Gr as findMatchingWatches, Gt as TurnBudgetExceededError, H as PluginCredentialFailureError, Ha as SANDBOX_WORKSPACE_ROOT, Hr as createTimerWatch, I as upsertConversationMessage, Io as piMessageFromHistoryItem, Ir as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, J as abandonReplacedPendingAuth, Ja as runNonInteractiveCommand, K as AuthorizationFlowDisabledError, Ka as buildCommandScript, Ki as openSlackDirectMessage, Kr as getWatch, Kt as TurnSliceLimitExceededError, L as calculateContextCompactionTargetTokens, Li as escapeSlackMrkdwnText, Lo as projectConversationEvents, Lr as RESOURCE_WATCH_TOOL_SOURCE, M as normalizeConversationText, Ma as sleep, Mi as deliverOAuthAuthorization, Mr as resolveAssignees, N as recordDeliveredAssistantMessage, Na as tryWorkspaceRepoCheckoutPath, Ni as formatProviderLabel, Nn as createPluginHookRunner, Nr as resolveChannelCapabilities, Oa as buildSandboxEgressNetworkPolicy, Oi as ensureDockerDaemon, Oo as defaultTimezone, Or as EVERYONE_ASSIGNEE, Pa as workspaceRepoCheckoutPath, Pr as getSlackToolContext, Q as continuableMessages, Qi as updateSlackMessage, Qt as persistWithRetry, R as getAgentBackgroundCompactionMarkTokens, Ra as SANDBOX_COMMAND_PATH, Rn as getPluginTools, Ro as getConfigDefaults, Rr as STOP_WATCHING_TOOL_NAME, Sa as clearSandboxEgressSignals, Si as loadSnapshotsForProfile, Sr as requireReviewItemAssignees, T as resolveTaskTitle, Ta as createSandboxEgressCredentialToken, Ti as create, To as createPluginAnnotations, U as createPluginAuthOrchestration, Ua as sandboxSkillDir, Ui as addReactionToMessage, Ur as createWatch, V as createPluginEgress, Va as SANDBOX_SKILLS_ROOT, Vi as slackMention, W as authorizationId, Wa as sandboxSkillFile, Wi as deleteSlackMessage, Wr as deliverWatch, Wt as TURN_LIMIT_WRAP_UP_MESSAGE, X as clearPendingAuth, Xt as isTurnExecutionLimitExceededError, Y as canReusePendingAuthLink, Yi as postSlackMessage, Yt as createTurnLimitGate, Za as canAccessConversation, Zt as CODEMODE_TOOL_NAME, _a as wrapSandboxSetupError, _i as listWorkspaces, _n as TURN_CONTEXT_TAG, _r as canAgentChangeReviewItem, a as loadProjection, ai as getDashboardReviewItemLink, ar as dismissOpenReviewItems, at as failTurnRecord, b as persistConversationMessages, ba as isWorkspaceSnapshotNotReadyError, bi as WorkspaceValidationError, bn as readParentAgentTask, c as recordAgentsInstructionsUpdated, cn as isStandaloneRuntimeContextMessage, cr as insertReviewItem, da as withSlackRetries, dn as normalizeToolNameFromResult, en as getPiMessageRole, eo as readConversationAccessFromSql, f as recordAuthorizationRequested, fi as renderToolResultNudge, fn as retainRuntimeTurnContext, fr as searchReviewItems, g as recordToolExecutionStarted, ga as throwSandboxOperationError, gi as getWorkspaceByName, ha as isAlreadyExistsError, hi as getWorkspace, hn as REQUEST_CONTEXT_SECTION_TAG, hr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, i as loadConversationProjection, ia as getFilePermalink, in as hasTurnInput, j as markConversationMessage, ja as SANDBOX_RUNTIME, jr as resolveAssignee, ka as resolveSandboxCommandEnvironment, ki as getSandboxProvider, kn as getOAuthAccountProviders, ko as resolveUserTimezone, kr as activeParticipantUserIds, l as recordAttachmentsDelivered, la as normalizeSlackConversationId, ln as isToolResultError, m as recordMcpProviderConnected, ma as isAbortError, mi as deleteWorkspace, mn as trimTrailingAssistantMessages, mr as updateReviewItemContent, na as SlackActionError, nn as getUserMessageInstructionText, nt as saveTurnCheckpoint, oa as getSlackClient, on as isAssistantMessage, or as getOpenReviewItemByDedupeKey, ot as getTurnRecord, p as recordGuardianActionReviewed, pi as createWorkspace, pn as stripRuntimeTurnContext, q as AuthorizationPauseError, qa as buildNonInteractiveShellScript, qr as listWatches, qt as TurnToolCallLimitExceededError, r as loadConnectedMcpProviders, ra as downloadPrivateSlackFile, ri as getDashboardConversationLink, rr as closeReviewItem, rt as abandonTurnRecord, sa as isConversationScopedChannel, si as getDashboardTaskLink, sn as isContinuablePiBoundary, sr as getReviewItem, t as commitAcceptedReply, ti as verifyTimerWatchCredentialSubject, tn as getTerminalAssistantMessages, ua as runWithSlackInstallationToken, ui as ToolInputError, un as isToolResultMessage, v as hydrateConversationMessages, va as WorkspaceSnapshotNotReadyError, vr as canReadReviewItem, w as fallbackShortTitle, wa as consumeSandboxEgressPermissionDeniedSignal, wi as setWorkspaceSnapshotBuild, wo as saveObjectAnnotations, xa as workspaceSnapshotNotReadyUserMessage, xi as invalidateReadySnapshot, xr as readReviewItemAgentScope, ya as getWorkspaceSnapshotNotReadyError, yi as updateWorkspace, yo as matchSlackAttachments, z as getAgentContextCompactionTriggerTokens, za as SANDBOX_DATA_ROOT, zi as normalizeSlackReplyMarkdown } from "./projection-DLQgfO5N.js";
3
- import { A as estimateTextTokens, B as createAssistantProviderError, D as requestPrefixAttributes, E as resolveGatewayModel, G as isProviderRefusal, H as findProviderError, I as unwrapCurrentInstruction, J as resolveGatewayCredential, K as isProviderRetryError, L as escapeXml, M as COMPACTION_SUMMARY_PREFIX, N as hasCompactedConversationContext, O as estimateMessagesTokens, P as isCompactionSummaryText, U as getProviderErrorAttributes, V as createProviderError, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as textCharsForTokens, k as estimateRequestOverheadTokens, n as botConfig, q as getGatewayApiKey, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as ProviderError } from "./config-mIZeGEWv.js";
4
- import { C as summarizeMessageText, E as withSpan, G as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, W as normalizeIdentityEmail, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-Cb6MGvdt.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-C6h-X2cZ.js";
2
+ import { $ as loadTurnCheckpoint, $i as uploadFilesToConversation, $t as extractAssistantText, A as latestConversationMessageSeq, Ar as automationCreatorUserId, B as getAgentContextInputLimitTokens, Ba as SANDBOX_REPOS_ROOT, Bn as getPlugins, Bo as getConfigDefaults, Br as cancelWatch, Ca as consumeSandboxEgressAuthRequiredSignal, Ci as setWorkspaceSnapshot, Cr as requireReviewItemLinks, Di as isStale, Dn as findLegacyWebActorUserId, Ei as hash, En as createUserTokenStore, Fa as PluginToolDeniedError, Fi as resolveBaseUrl, Fr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, G as AuthPausePersistenceError, Ga as sandboxSkillPathResolution, Gi as getSlackMessagePermalink, Gr as findMatchingWatches, Gt as TurnBudgetExceededError, H as PluginCredentialFailureError, Ha as SANDBOX_WORKSPACE_ROOT, Hr as createTimerWatch, I as upsertConversationMessage, Ir as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, J as abandonReplacedPendingAuth, Ja as runNonInteractiveCommand, K as AuthorizationFlowDisabledError, Ka as buildCommandScript, Ki as openSlackDirectMessage, Kr as getWatch, Kt as TurnSliceLimitExceededError, L as calculateContextCompactionTargetTokens, Li as escapeSlackMrkdwnText, Lo as historyItemFromPiMessage, Lr as RESOURCE_WATCH_TOOL_SOURCE, M as normalizeConversationText, Ma as sleep, Mi as deliverOAuthAuthorization, Mo as credentialAuditAttributes, Mr as resolveAssignees, N as recordDeliveredAssistantMessage, Na as tryWorkspaceRepoCheckoutPath, Ni as formatProviderLabel, Nn as createPluginHookRunner, No as credentialAuditSource, Nr as resolveChannelCapabilities, Oa as buildSandboxEgressNetworkPolicy, Oi as ensureDockerDaemon, Oo as defaultTimezone, Or as EVERYONE_ASSIGNEE, Pa as workspaceRepoCheckoutPath, Pr as getSlackToolContext, Q as continuableMessages, Qi as updateSlackMessage, Qt as persistWithRetry, R as getAgentBackgroundCompactionMarkTokens, Ra as SANDBOX_COMMAND_PATH, Rn as getPluginTools, Ro as piMessageFromHistoryItem, Rr as STOP_WATCHING_TOOL_NAME, Sa as clearSandboxEgressSignals, Si as loadSnapshotsForProfile, Sr as requireReviewItemAssignees, T as resolveTaskTitle, Ta as createSandboxEgressCredentialToken, Ti as create, To as createPluginAnnotations, U as createPluginAuthOrchestration, Ua as sandboxSkillDir, Ui as addReactionToMessage, Ur as createWatch, V as createPluginEgress, Va as SANDBOX_SKILLS_ROOT, Vi as slackMention, W as authorizationId, Wa as sandboxSkillFile, Wi as deleteSlackMessage, Wr as deliverWatch, Wt as TURN_LIMIT_WRAP_UP_MESSAGE, X as clearPendingAuth, Xt as isTurnExecutionLimitExceededError, Y as canReusePendingAuthLink, Yi as postSlackMessage, Yt as createTurnLimitGate, Za as canAccessConversation, Zt as CODEMODE_TOOL_NAME, _a as wrapSandboxSetupError, _i as listWorkspaces, _n as TURN_CONTEXT_TAG, _r as canAgentChangeReviewItem, a as loadProjection, ai as getDashboardReviewItemLink, ar as dismissOpenReviewItems, at as failTurnRecord, b as persistConversationMessages, ba as isWorkspaceSnapshotNotReadyError, bi as WorkspaceValidationError, bn as readParentAgentTask, c as recordAgentsInstructionsUpdated, cn as isStandaloneRuntimeContextMessage, cr as insertReviewItem, da as withSlackRetries, dn as normalizeToolNameFromResult, en as getPiMessageRole, eo as readConversationAccessFromSql, f as recordAuthorizationRequested, fi as renderToolResultNudge, fn as retainRuntimeTurnContext, fr as searchReviewItems, g as recordToolExecutionStarted, ga as throwSandboxOperationError, gi as getWorkspaceByName, ha as isAlreadyExistsError, hi as getWorkspace, hn as REQUEST_CONTEXT_SECTION_TAG, hr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, i as loadConversationProjection, ia as getFilePermalink, in as hasTurnInput, j as markConversationMessage, ja as SANDBOX_RUNTIME, jr as resolveAssignee, ka as resolveSandboxCommandEnvironment, ki as getSandboxProvider, kn as getOAuthAccountProviders, ko as resolveUserTimezone, kr as activeParticipantUserIds, l as recordAttachmentsDelivered, la as normalizeSlackConversationId, ln as isToolResultError, m as recordMcpProviderConnected, ma as isAbortError, mi as deleteWorkspace, mn as trimTrailingAssistantMessages, mr as updateReviewItemContent, na as SlackActionError, nn as getUserMessageInstructionText, nt as saveTurnCheckpoint, oa as getSlackClient, on as isAssistantMessage, or as getOpenReviewItemByDedupeKey, ot as getTurnRecord, p as recordGuardianActionReviewed, pi as createWorkspace, pn as stripRuntimeTurnContext, q as AuthorizationPauseError, qa as buildNonInteractiveShellScript, qr as listWatches, qt as TurnToolCallLimitExceededError, r as loadConnectedMcpProviders, ra as downloadPrivateSlackFile, ri as getDashboardConversationLink, rr as closeReviewItem, rt as abandonTurnRecord, sa as isConversationScopedChannel, si as getDashboardTaskLink, sn as isContinuablePiBoundary, sr as getReviewItem, t as commitAcceptedReply, ti as verifyTimerWatchCredentialSubject, tn as getTerminalAssistantMessages, ua as runWithSlackInstallationToken, ui as ToolInputError, un as isToolResultMessage, v as hydrateConversationMessages, va as WorkspaceSnapshotNotReadyError, vr as canReadReviewItem, w as fallbackShortTitle, wa as consumeSandboxEgressPermissionDeniedSignal, wi as setWorkspaceSnapshotBuild, wo as saveObjectAnnotations, xa as workspaceSnapshotNotReadyUserMessage, xi as invalidateReadySnapshot, xr as readReviewItemAgentScope, ya as getWorkspaceSnapshotNotReadyError, yi as updateWorkspace, yo as matchSlackAttachments, z as getAgentContextCompactionTriggerTokens, za as SANDBOX_DATA_ROOT, zi as normalizeSlackReplyMarkdown, zo as projectConversationEvents } from "./projection-B6VS7kbo.js";
3
+ import { A as estimateTextTokens, B as createAssistantProviderError, D as requestPrefixAttributes, E as resolveGatewayModel, G as isProviderRefusal, H as findProviderError, I as unwrapCurrentInstruction, J as resolveGatewayCredential, K as isProviderRetryError, L as escapeXml, M as COMPACTION_SUMMARY_PREFIX, N as hasCompactedConversationContext, O as estimateMessagesTokens, P as isCompactionSummaryText, U as getProviderErrorAttributes, V as createProviderError, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as textCharsForTokens, k as estimateRequestOverheadTokens, n as botConfig, q as getGatewayApiKey, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as ProviderError } from "./config-CCPHvTqx.js";
4
+ import { C as summarizeMessageText, E as withSpan, G as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, W as normalizeIdentityEmail, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-D0svFM8r.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-CZD5soDW.js";
6
6
  import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, n as createSlackActor, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
7
- import { $ as nextDetailVersion, A as SYSTEM_IDENTITY_ID, C as isTopLevelKind, E as conversationKindFromRow, G as addAgentTurnUsage, K as agentTurnCostUsd, M as resolveActorIdentityId, Q as conversationDetailTouch, S as isPersonInput, T as turnBehavior, X as resolveRootConversationId$1, Y as hasAgentTurnUsage, _ as setArchivedAt, a as getConversationStore, c as conversationIdsWithAnnotation, et as touchConversationDetail, g as readConversationTrees, h as conversationDescendants, i as getConversationMessageSearchStore, it as sameDestination, l as hasAnnotationKey, m as conversationAncestors, nt as parseDestination, o as getDb, r as getConversationEventStore, s as getSqlExecutor, u as treeHasAnnotationKey } from "./db--xuNV7g6.js";
8
- import { A as juniorConversations, M as juniorUsers, N as juniorDestinations, P as juniorArtifacts, _ as juniorConversationReadPositions, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorIdentities, k as juniorAttachments, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-BItuRqAR.js";
7
+ import { D as turnBehavior, J as agentTurnCostUsd, M as SYSTEM_IDENTITY_ID, O as conversationKindFromRow, P as resolveActorIdentityId, Q as resolveRootConversationId$1, T as isTopLevelKind, Z as hasAgentTurnUsage, _ as setArchivedAt, a as getConversationStore, c as conversationIdsWithAnnotation, et as conversationDetailTouch, g as readConversationTrees, h as conversationDescendants, i as getConversationMessageSearchStore, it as parseDestination, l as hasAnnotationKey, m as conversationAncestors, nt as touchConversationDetail, o as getDb, ot as sameDestination, q as addAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, tt as nextDetailVersion, u as treeHasAnnotationKey, w as isPersonInput } from "./db-C1M1y-bh.js";
8
+ import { A as juniorConversations, M as juniorUsers, N as juniorDestinations, P as juniorArtifacts, _ as juniorConversationReadPositions, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorIdentities, k as juniorAttachments, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-DUSEwXaO.js";
9
9
  import { _ as instructionProvenanceFor, a as KNOWN_CONVERSATION_EVENT_TYPES, g as instructionActors, h as contextProvenance, r as detectImageMediaType, v as sameActorIdentity } from "./media-BepyEUNm.js";
10
10
  import { a as listReferenceFiles } from "./package-discovery-DJhGdS4c.js";
11
- import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-MtwokaqW.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-CLMA9AXd.js";
13
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-e3DDNlKO.js";
14
- import { l as completeObject, o as isEventConversationMessage, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-qp_LdxLX.js";
11
+ import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-CHewwYEo.js";
12
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-CpCmlD9L.js";
13
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DXgd5Inh.js";
14
+ import { l as completeObject, o as isEventConversationMessage, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-CD11tfG8.js";
15
15
  import { a as withLock, i as fenceLock } from "./locks-D-0h111u.js";
16
- import { a as readActorIdentityFromSql, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity } from "./viewer-CjRFHR5U.js";
17
- import { r as getStateAdapter } from "./adapter-DxLhJEnO.js";
16
+ import { a as readActorIdentityFromSql, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity } from "./viewer-Agxi_o5c.js";
17
+ import { a as getStateAdapter, n as readEncryptedState, t as createEncryptedState } from "./state-C3CbtD_m.js";
18
18
  import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-cP0AACm1.js";
19
- import { K as briefLinkSchema, W as readMessageAttachments, Z as parseStoredBrief, q as briefOutcomeStatusSchema, z as removedCardSchema } from "./conversation-CDWejM4R.js";
20
- import { i as createCacheWarmingRecorder, l as readLastUserMessageAtByConversation } from "./warmup-DuxCtzKC.js";
21
- import { D as QUEUE_SIGNATURE_MAX_AGE_MS, g as getVercelConversationWorkQueue, k as getTurnRequestDeadline, m as sendWorkspaceSnapshotJob, n as backgroundCompactionId, p as sendNextWorkspaceSnapshotJob } from "./background-compaction-queue-D2j-0XkH.js";
22
- import { B as AGENT_TYPES, C as isTerminalAgentInvocation, F as CHILD_AGENT_RESULTS, I as PARENT_AGENT_TARGET, J as getAgentInvocationMessageId, P as CHILD_AGENT_KINDS, R as agentNameSchema, S as invocationFromRow, T as listOpenAgentInvocations, U as formatAgentTypes, Z as getChildAgentLockName, at as getConversationTurnBoundaryError, dt as markTurnFailed, et as parseAgentInvocationResultMessageId, f as ConversationTurnLifecycleService, ft as startActiveTurn, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, mt as buildDeterministicTurnId, nt as CooperativeTurnYieldError, o as getTurnUserMessage, q as getAgentInvocationIdForResult, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, u as buildTurnThreadContext, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation } from "./turn-failure-response-BqTTx3XG.js";
23
- import { a as isLegacyNoReplyMarker, i as NO_REPLY_TOOL_NAME, n as getAssistantReplyText, o as readNoReply, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-iTtEdDyc.js";
24
- import { $ as withoutSavedSteeringMessages, A as requireSlackChannelMessageScope, B as maybePostAutomatedTurnLimitNotice, C as enqueueEventNotification, D as timerWatchCredentialSubject, E as renderEventBatchInputs, F as WORKSPACE_SNAPSHOT_FAILED_EVENT, H as resolveSlackReplyTarget, I as WORKSPACE_SNAPSHOT_READY_EVENT, J as assemblePrompt, K as recordFinishedTurnForAutomatedLimit, L as workspaceSnapshotFinishedEvent, O as getEventCatalog, P as slackChannelMessageTrigger, Q as loadPromptTurnContext, R as workspaceSnapshotWatch, S as EVENT_WAIT_MS, T as isEventMailboxMetadata, X as buildSteeringPiMessage, Y as buildPromptInput, Z as instructionForInputs, _ as sourceFromTurnInput, at as addConversationNote, b as conversationSubtree, c as loadReviewItemInput, ct as readBlockedReport, d as getAuthPausedConversationTurnId, f as getEventBatchDelayMs, ft as readAutomationResult, lt as FINISH_AUTOMATION_RUN_TOOL_NAME, ot as JUNIOR_PERSONALITY, p as listActiveMailboxTurns, pt as remindMissingAutomationResult, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, s as eventReviewItemInputs, st as REPORT_BLOCKED_TOOL_NAME, t as getConversationStoppedAtMs, tt as saveUserCustomization, ut as automationResultSchema$1, v as turnInputFactsFromConversationMessage, w as eventBatchMessageMeta, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-CeCXL3j9.js";
19
+ import { G as briefLinkSchema, K as briefOutcomeStatusSchema, R as removedCardSchema, U as readMessageAttachments, X as parseStoredBrief } from "./conversation-CMkSmi02.js";
20
+ import { A as readNoReply, C as replyTextSchema, D as NO_REPLY_TOOL_NAME, E as sanitizeAssistantText, M as readBlockedReport, O as findLegacyNoReplyMarker, S as remindMissingAnswer, T as getAssistantReplyText, b as REPLY_TOOL_NAME, i as createCacheWarmingRecorder, j as REPORT_BLOCKED_TOOL_NAME, k as isLegacyNoReplyMarker, l as readLastUserMessageAtByConversation, v as JUNIOR_PERSONALITY, w as decideReply, x as readTurnAnswer } from "./warmup-CY2ArYag.js";
21
+ import { D as QUEUE_SIGNATURE_MAX_AGE_MS, g as getVercelConversationWorkQueue, k as getTurnRequestDeadline, m as sendWorkspaceSnapshotJob, n as backgroundCompactionId, p as sendNextWorkspaceSnapshotJob } from "./background-compaction-queue-Cre1wFt9.js";
22
+ import { B as AGENT_TYPES, C as isTerminalAgentInvocation, F as CHILD_AGENT_RESULTS, I as PARENT_AGENT_TARGET, J as getAgentInvocationMessageId, P as CHILD_AGENT_KINDS, R as agentNameSchema, S as invocationFromRow, T as listOpenAgentInvocations, U as formatAgentTypes, Z as getChildAgentLockName, at as getConversationTurnBoundaryError, dt as markTurnFailed, et as parseAgentInvocationResultMessageId, f as ConversationTurnLifecycleService, ft as startActiveTurn, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, lt as markTurnClosed, m as loadPendingMessageCards, mt as buildDeterministicTurnId, nt as CooperativeTurnYieldError, o as getTurnUserMessage, q as getAgentInvocationIdForResult, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, t as finalizeFailedTurnReplyWithEvent, u as buildTurnThreadContext, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation } from "./turn-failure-response-pXhZ2wMK.js";
23
+ import { $ as withoutSavedSteeringMessages, A as requireSlackChannelMessageScope, B as maybePostAutomatedTurnLimitNotice, C as enqueueEventNotification, D as timerWatchCredentialSubject, E as renderEventBatchInputs, F as WORKSPACE_SNAPSHOT_FAILED_EVENT, H as resolveSlackReplyTarget, I as WORKSPACE_SNAPSHOT_READY_EVENT, J as assemblePrompt, K as recordFinishedTurnForAutomatedLimit, L as workspaceSnapshotFinishedEvent, O as getEventCatalog, P as slackChannelMessageTrigger, Q as loadPromptTurnContext, R as workspaceSnapshotWatch, S as EVENT_WAIT_MS, T as isEventMailboxMetadata, X as buildSteeringPiMessage, Y as buildPromptInput, Z as instructionForInputs, _ as sourceFromTurnInput, at as addConversationNote, b as conversationSubtree, c as loadReviewItemInput, d as getAuthPausedConversationTurnId, f as getEventBatchDelayMs, p as listActiveMailboxTurns, r as markConversationsStopped, rt as isExperimentalFeatureEnabled, s as eventReviewItemInputs, t as getConversationStoppedAtMs, tt as saveUserCustomization, v as turnInputFactsFromConversationMessage, w as eventBatchMessageMeta, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-hYNTNpVf.js";
25
24
  import { D as userCustomizationTextSchema, T as USER_CUSTOMIZATION_MAX_CHARS, _ as buttonUserInputField, b as normalizeUserInputAnswer, g as USER_INPUT_NOTE, h as USER_INPUT_LIMITS, m as apiErrorSchema, p as webMessageId, s as sumUtcHoursIntoSixHours, v as formatUserInputAnswer, w as AGENT_INVOCATION_STATUSES, x as userInputRequestSchema } from "./reporting-window-B3Ze-Qnt.js";
26
- import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-BnJA0UNE.js";
27
- import { S as requestConversationWork, T as stopConversationWork, g as getConversationWorkState, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-C8LsaJwS.js";
28
- import { $ as readAutomationExecutionByConversationId, At as requireValidEventTrigger, B as setEventAutomationStatus, C as deleteScheduledAutomation, Ct as eventWatchUnavailable, D as saveScheduledAutomation, Dt as registeredEventTypeSchema, E as readScheduledAutomation, Et as registeredEventTriggerProblems, G as listAutomationVersions, I as getEventAutomation, K as readAutomationVersion, L as listDeletedEventAutomationsCreatedBy, N as createEventAutomation, Ot as registeredResourceTypeSchema, P as deleteEventAutomation, R as parseEventAutomationRow, S as createScheduledAutomation, St as eventNamespaceSchema, T as parseScheduledAutomationRow, Tt as registeredEventMatchSchema, U as automationDefinition, X as requireAutomationRevision, Y as automationRevision, Z as emptyAutomationRunWindows, d as getDispatchRecord, et as readAutomationExecutionStatusDays, ft as getPersistedSandboxState, gt as coerceThreadConversationState, ht as persistThreadStateById, it as readAutomationRuns, kt as requireEventIdentifier, l as getDispatchIdForConversation, lt as resolveConversationRouting, n as scheduleSessionCompletedPluginTasks, nt as readAutomationExecutionSummaries, pt as getPersistedThreadState, q as sameDefinitionValue, rt as readAutomationExecutions, t as processPluginTask, tt as readAutomationExecutionStatusHours, u as getDispatchInputMessageId, ut as resolveTurnSessionRouting, vt as automationEventCatalog, wt as hasEventCatalogEntries, yt as describeRegisteredEventTrigger, z as saveEventAutomation } from "./task-runner-Dw7exu0-.js";
29
- import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-kio5nXSD.js";
30
- import { A as eventAutomationTriggerSchema, D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, H as automationTaskSchema, I as scheduleIntentFromTool, L as toolScheduleIntentSchema, O as taskOutcomeInputSchema, P as ScheduleIntentError, R as weekdaySchema, T as automationContextToolSchema, U as automationTaskText, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, l as automationListQuerySchema, z as automationSkillNameSchema } from "./automation-BM-OBsKW.js";
25
+ import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-1owMH4qo.js";
26
+ import { S as requestConversationWork, T as stopConversationWork, g as getConversationWorkState, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-CZ9vqR4P.js";
27
+ import { A as blockScheduledAutomation, At as registeredResourceTypeSchema, B as blockEventAutomation, Dt as registeredEventMatchSchema, Et as hasEventCatalogEntries, F as readScheduledAutomation, G as getEventAutomation, H as createEventAutomation, I as saveScheduledAutomation, J as saveEventAutomation, K as listDeletedEventAutomationsCreatedBy, M as deleteScheduledAutomation, Mt as requireValidEventTrigger, Ot as registeredEventTriggerProblems, P as parseScheduledAutomationRow, Q as automationDefinition, Tt as eventWatchUnavailable, U as deleteEventAutomation, Y as setEventAutomationStatus, _ as getDispatchIdForConversation, a as resolveTurnSessionRouting, at as requireAutomationRevision, bt as automationEventCatalog, c as getPersistedThreadState, ct as readAutomationExecutionByConversationId, d as coerceThreadConversationState, dt as readAutomationExecutionSummaries, et as listAutomationVersions, ft as readAutomationExecutions, i as resolveConversationRouting, it as automationRevision, j as createScheduledAutomation, jt as requireEventIdentifier, k as notifyAutomationBlocked, kt as registeredEventTypeSchema, lt as readAutomationExecutionStatusDays, n as scheduleSessionCompletedPluginTasks, nt as sameDefinitionValue, ot as emptyAutomationRunWindows, pt as readAutomationRuns, q as parseEventAutomationRow, s as getPersistedSandboxState, t as processPluginTask, tt as readAutomationVersion, u as persistThreadStateById, ut as readAutomationExecutionStatusHours, v as getDispatchInputMessageId, wt as eventNamespaceSchema, xt as describeRegisteredEventTrigger, y as getDispatchRecord } from "./task-runner-CMiNGsER.js";
28
+ import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-DLoeoHww.js";
29
+ import { A as eventAutomationTriggerSchema, D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, H as automationTaskSchema, I as scheduleIntentFromTool, L as toolScheduleIntentSchema, O as taskOutcomeInputSchema, P as ScheduleIntentError, R as weekdaySchema, T as automationContextToolSchema, U as automationTaskText, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, l as automationListQuerySchema, z as automationSkillNameSchema } from "./automation-yJX3C7i3.js";
31
30
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
32
31
  import { streamSimple } from "@earendil-works/pi-ai/compat";
33
32
  import { createGatewayProvider } from "@ai-sdk/gateway";
@@ -791,13 +790,15 @@ function relayStream(source, onEvent) {
791
790
  *
792
791
  * The base argument exists so tests can inject a stub stream function.
793
792
  * `promptName` names a request that is not an agent loop call, such as a
794
- * context summary.
793
+ * context summary. `endAttributes` adds caller attributes from the final
794
+ * message.
795
795
  */
796
796
  function createTracedStreamFn(baseOrOptions = streamSimple) {
797
797
  const base = typeof baseOrOptions === "function" ? baseOrOptions : baseOrOptions.base ?? streamSimple;
798
798
  const mode = attributeModeForPrivacy(typeof baseOrOptions === "function" ? void 0 : baseOrOptions.conversationPrivacy);
799
799
  const effectivePrivacy = (typeof baseOrOptions === "function" ? void 0 : baseOrOptions.conversationPrivacy) ?? "private";
800
800
  const promptName = typeof baseOrOptions === "function" ? void 0 : baseOrOptions.promptName;
801
+ const callerEndAttributes = typeof baseOrOptions === "function" ? void 0 : baseOrOptions.endAttributes;
801
802
  return async (model, context, options) => {
802
803
  const span = startInactiveSpan({
803
804
  name: `chat ${model.id}`,
@@ -816,7 +817,8 @@ function createTracedStreamFn(baseOrOptions = streamSimple) {
816
817
  try {
817
818
  const endAttributes = {
818
819
  ...buildChatEndAttributes(finalMessage, mode),
819
- ...responseTiming.attributes()
820
+ ...responseTiming.attributes(),
821
+ ...callerEndAttributes?.(finalMessage)
820
822
  };
821
823
  for (const [key, value] of Object.entries(endAttributes)) span.setAttribute(key, value);
822
824
  if (finalMessage.stopReason === "error") {
@@ -857,7 +859,7 @@ function shouldEmitDevAgentTrace() {
857
859
  // src/chat/services/turn-result.ts
858
860
  /** Process raw agent messages into a structured AgentRunResult. */
859
861
  function buildTurnResult(input) {
860
- if (input.requireAutomationResult) return buildAutomationTurnResult(input);
862
+ if (input.answer) return buildGatedTurnResult(input, input.answer);
861
863
  const { newMessages, sandboxRef, shouldTrace } = input;
862
864
  const toolResults = newMessages.filter(isToolResultMessage);
863
865
  const assistantMessages = newMessages.filter(isAssistantMessage);
@@ -941,29 +943,40 @@ function buildDiagnostics(input, result) {
941
943
  }) : void 0
942
944
  };
943
945
  }
946
+ /** Name of a Turn answer in telemetry. */
947
+ function answerName(answer) {
948
+ if (answer === "missing") return "missing";
949
+ if ("reply" in answer) return "reply";
950
+ if ("noReply" in answer) return "noReply";
951
+ return "reportBlocked";
952
+ }
944
953
  /**
945
- * Build the result of an Automation run from its declared result. Final
946
- * assistant text is not used. A run without a declared result fails.
954
+ * Build the result of a gated Turn from its answer. Final assistant text is
955
+ * not used. A Turn without an answer posts nothing.
947
956
  */
948
- function buildAutomationTurnResult(input) {
957
+ function buildGatedTurnResult(input, answer) {
949
958
  const lastAssistant = input.newMessages.filter(isAssistantMessage).at(-1);
950
959
  const stopReason = lastAssistant?.stopReason;
951
- const automation = readAutomationResult(input.piMessages ?? input.newMessages);
952
- const outcome = automation ? "success" : stopReason === "error" ? "provider_error" : "execution_failure";
953
- const errorMessage = outcome === "provider_error" ? lastAssistant?.errorMessage : outcome === "execution_failure" ? "Automation run ended without a declared result." : void 0;
960
+ const answered = answer !== "missing";
961
+ const outcome = answered ? "success" : stopReason === "error" ? "provider_error" : input.missingAnswerFails ? "execution_failure" : "success";
962
+ const errorMessage = outcome === "provider_error" ? lastAssistant?.errorMessage : outcome === "execution_failure" ? "Automation run ended without an answer." : void 0;
963
+ const reply = answered && "reply" in answer ? answer.reply : void 0;
964
+ if (!answered && stopReason !== "error") logWarn("agent.turn.answer.missing", {});
954
965
  if (input.shouldTrace) logInfo("agent.message.generated", {
955
- "app.message.kind": "automation_result",
966
+ "app.message.kind": "turn_answer",
956
967
  "app.ai.outcome": outcome,
957
- "app.automation.result": automation?.result ?? "missing"
968
+ "app.turn.answer": answerName(answer)
958
969
  });
959
970
  return {
960
- text: automation?.result === "send_message" ? automation.message : "",
961
- ...automation ? { automation } : void 0,
971
+ text: reply?.text ?? "",
972
+ ...reply ? { reply } : void 0,
973
+ ...answered && "noReply" in answer ? { noReply: answer.noReply } : void 0,
974
+ ...answered && "blocked" in answer ? { blocked: answer.blocked } : void 0,
962
975
  sandboxRef: input.sandboxRef,
963
976
  piMessages: input.piMessages,
964
977
  diagnostics: buildDiagnostics(input, {
965
978
  outcome,
966
- usedPrimaryText: automation?.result === "send_message",
979
+ usedPrimaryText: Boolean(reply),
967
980
  stopReason,
968
981
  errorMessage,
969
982
  lastAssistant
@@ -1303,14 +1316,14 @@ function restoreToolActionRejections(messages) {
1303
1316
  return priorRejections;
1304
1317
  }
1305
1318
  // src/chat/agent/action-confirmation-retry.ts
1306
- const RUN_ENDING_TOOL_NAMES = /* @__PURE__ */ new Set([FINISH_AUTOMATION_RUN_TOOL_NAME, REPORT_BLOCKED_TOOL_NAME]);
1319
+ const RUN_ENDING_TOOL_NAMES = /* @__PURE__ */ new Set([REPLY_TOOL_NAME, REPORT_BLOCKED_TOOL_NAME]);
1307
1320
  function endsRun(message) {
1308
1321
  return isToolResultMessage(message) && !isToolResultError(message) && RUN_ENDING_TOOL_NAMES.has(normalizeToolNameFromResult(message) ?? "");
1309
1322
  }
1310
1323
  /**
1311
1324
  * Return the durable tool-result boundary for one additional agent
1312
1325
  * continuation when an ask rejection has no destination-visible reply. A run
1313
- * that a blocked report or an Automation result ended gets none.
1326
+ * that a blocked report or a `reply` call ended gets none.
1314
1327
  */
1315
1328
  function actionConfirmationRetryMessages(messages) {
1316
1329
  let rejectionIndex = -1;
@@ -3662,6 +3675,7 @@ function createSandbox(options) {
3662
3675
  conversationId: options.conversationId,
3663
3676
  credentials: credentialEgress,
3664
3677
  egressId,
3678
+ source: options.credentialAuditSource,
3665
3679
  ttlMs: sandboxEgressTokenTtlMs
3666
3680
  });
3667
3681
  sandboxEgressCredentialTokens.set(egressId, {
@@ -4181,9 +4195,29 @@ function accountText(value) {
4181
4195
  if (!label) return;
4182
4196
  return id && id !== label ? `${label} (${id})` : label;
4183
4197
  }
4184
- function upstreamPermissionDeniedText(value) {
4198
+ function policyDeniedText(value, signal) {
4199
+ const message = stringField(signal, "message");
4200
+ const method = stringField(signal, "method");
4201
+ const upstreamHost = stringField(signal, "upstreamHost");
4202
+ const upstreamPath = stringField(signal, "upstreamPath");
4203
+ if (!message || !method || !upstreamHost || !upstreamPath) return;
4204
+ const command = stringField(value, "command");
4205
+ const stderr = stringField(value, "stderr").trim();
4206
+ return [
4207
+ "The runtime egress policy denied the request. It did not reach the provider.",
4208
+ message,
4209
+ "",
4210
+ `Request: ${method} ${upstreamHost}${upstreamPath}`,
4211
+ ...command ? [`Command: ${command}`] : [],
4212
+ "",
4213
+ "Do not retry the same request, and do not ask for more permissions or a new credential. Follow the policy message.",
4214
+ ...stderr ? ["", `stderr:\n${stderr}`] : []
4215
+ ].join("\n");
4216
+ }
4217
+ function permissionDeniedText(value) {
4185
4218
  if (!isRecord$1(value) || !isRecord$1(value.permission_denied)) return;
4186
4219
  const signal = value.permission_denied;
4220
+ if (signal.source === "policy") return policyDeniedText(value, signal);
4187
4221
  if (signal.source !== "upstream") return;
4188
4222
  const provider = stringField(signal, "provider");
4189
4223
  const message = stringField(signal, "message");
@@ -4234,7 +4268,7 @@ function normalizeToolResult(result, options = {}) {
4234
4268
  const unwrapped = result;
4235
4269
  if (isStructuredToolExecutionResult(unwrapped)) {
4236
4270
  const normalized = normalizeDetails(unwrapped.details, options);
4237
- const permissionText = upstreamPermissionDeniedText(normalized.details);
4271
+ const permissionText = permissionDeniedText(normalized.details);
4238
4272
  if (!permissionText && normalized.details === unwrapped.details) return unwrapped;
4239
4273
  return {
4240
4274
  content: permissionText || normalized.replaceEnvelopeText ? replaceGeneratedTextContent(unwrapped.content, permissionText ?? toToolContentText(normalized.details)) : unwrapped.content,
@@ -4252,7 +4286,7 @@ function normalizeToolResult(result, options = {}) {
4252
4286
  return {
4253
4287
  content: [{
4254
4288
  type: "text",
4255
- text: upstreamPermissionDeniedText(normalized.details) ?? toToolContentText(normalized.details)
4289
+ text: permissionDeniedText(normalized.details) ?? toToolContentText(normalized.details)
4256
4290
  }],
4257
4291
  details: normalized.details
4258
4292
  };
@@ -4326,6 +4360,7 @@ function createAgentSandbox(options) {
4326
4360
  egressSignals: options.egressSignals,
4327
4361
  conversationId: options.conversationId,
4328
4362
  credentialEgress: options.credentialEgress,
4363
+ credentialAuditSource: options.credentialAuditSource,
4329
4364
  prepare: options.prepareSandbox,
4330
4365
  prepareWorkspace: options.prepareWorkspace,
4331
4366
  onSandboxRefChanged: async (sandboxRef) => {
@@ -4630,12 +4665,13 @@ var McpToolManager = class {
4630
4665
  return actorClient;
4631
4666
  }
4632
4667
  /**
4633
- * Record a completed call to an audit tool, with the account that made it.
4668
+ * Record a completed tool call, with the account that made it.
4634
4669
  * Arguments stay out: the conversation history keeps them.
4635
4670
  */
4636
4671
  logToolCallAudit(plugin, toolName, attributes) {
4637
4672
  const usedServiceAccount = this.serviceAccountProviders.has(plugin.manifest.name) && serviceAccountAllows(plugin.manifest, { tool: toolName });
4638
4673
  logAudit("mcp.tool_call.completed", {
4674
+ ...this.options.auditAttributes,
4639
4675
  ...attributes,
4640
4676
  "mcp.method.name": "tools/call",
4641
4677
  "app.plugin.name": plugin.manifest.name,
@@ -4678,7 +4714,7 @@ var McpToolManager = class {
4678
4714
  try {
4679
4715
  const result = await (await this.clientForTool(plugin, client, tool.name)).callTool(tool.name, resolvedArgs, options?.signal);
4680
4716
  if ("isError" in result && result.isError) throw new McpToolError(extractMcpErrorMessage(result));
4681
- if (plugin.manifest.mcp?.auditTools?.includes(tool.name)) this.logToolCallAudit(plugin, tool.name, {
4717
+ this.logToolCallAudit(plugin, tool.name, {
4682
4718
  "gen_ai.tool.name": managedToolName,
4683
4719
  ...options?.toolCallId ? { "gen_ai.tool.call.id": options.toolCallId } : void 0
4684
4720
  });
@@ -4723,7 +4759,10 @@ var McpToolManager = class {
4723
4759
  "exception.message": getMcpAwareTelemetryMessage(error, conversationPrivacy)
4724
4760
  };
4725
4761
  setSpanAttributes(errorAttributes);
4726
- if (error instanceof McpToolError) logWarn("mcp.tool_call.failed", errorAttributes);
4762
+ if (error instanceof McpToolError) logWarn("mcp.tool_call.failed", {
4763
+ ...this.options.auditAttributes,
4764
+ ...errorAttributes
4765
+ });
4727
4766
  throw error;
4728
4767
  }
4729
4768
  }, {
@@ -5939,7 +5978,8 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
5939
5978
  "Delegate a Task when: the request splits into independent tracks that each need real investigation, such as several repos, services, sources, or items (start every track in the same message); an answer needs reading across many files, logs, or sources and you need the conclusion, not the raw output; a side task does not block your main answer; or you want a second opinion that is not anchored on your analysis (give it the evidence, not your conclusion).",
5940
5979
  "Do it yourself instead of a Task when: the work fits in a handful of tool calls; you already know the file, symbol, or value to look up; or the job is one modest task that you would only split into pieces. Each child rebuilds its context and its result arrives in a later turn, so when in doubt, do not spawn a Task.",
5941
5980
  `Pick agent_type when one fits; omit it for a fresh general-purpose child with your tools:\n${formatAgentTypes()}`,
5942
- "After you delegate, do not do the same work yourself. End your turn with a short status. You know nothing about a child's findings until its result arrives: do not predict them, do not wait or poll, and if the user asks before then, give status.",
5981
+ `After you delegate, do not do the same work yourself. When your reply posts to people, do not post a status that only says the work started or repeats the task: call ${NO_REPLY_TOOL_NAME} instead, because the child's result posts when it arrives. Reply only with something people need now, such as an answer, a question, or a Thread's dashboard_url.`,
5982
+ "You know nothing about a child's findings until its result arrives: do not predict them, do not wait or poll, and if the user asks before then, give status.",
5943
5983
  "Give a child a name when you may send it more work later. To give more work to a child agent that already exists, use messageAgent instead.",
5944
5984
  "A child keeps its type and kind when it receives more work through messageAgent.",
5945
5985
  "Your task text is the child's instruction. Its action review judges the child's actions against that text, so name only actions that your own conversation backs, with the exact target."
@@ -5997,6 +6037,42 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
5997
6037
  }
5998
6038
  });
5999
6039
  }
6040
+ // src/chat/automations/block-run.ts
6041
+ /**
6042
+ * Find the Automation of a run. The SQL run row lasts as long as the
6043
+ * Automation, but a Watch can outlive the dispatch record. The dispatch record
6044
+ * covers a run whose row does not link its Conversation yet.
6045
+ */
6046
+ async function findRunAutomation(conversationId, dispatchId) {
6047
+ const run = await readAutomationExecutionByConversationId({ conversationId });
6048
+ if (run) return run;
6049
+ const source = dispatchId ? (await getDispatchRecord(dispatchId))?.source : void 0;
6050
+ if (!source || !("automationId" in source) || !source.automationId) return;
6051
+ return {
6052
+ automationId: source.automationId,
6053
+ kind: source.kind === "scheduled_automation" ? "scheduled" : "event"
6054
+ };
6055
+ }
6056
+ /**
6057
+ * Block the Automation of a run from a later Turn of the run, such as a Watch
6058
+ * Event or child result Turn. The dispatch Turn blocks through its dispatch
6059
+ * outcome. Its creator is told when the block is first stored.
6060
+ */
6061
+ async function blockRunAutomation(conversationId, blocked) {
6062
+ const dispatchId = getDispatchIdForConversation(conversationId);
6063
+ const automation = await findRunAutomation(conversationId, dispatchId);
6064
+ if (!automation) {
6065
+ logWarn("automation.block.unresolved", { "gen_ai.conversation.id": conversationId });
6066
+ return;
6067
+ }
6068
+ const { automationId, kind } = automation;
6069
+ if (kind === "scheduled" ? await blockScheduledAutomation(getDb(), automationId, blocked.missing) : await blockEventAutomation(getDb(), automationId, blocked.missing)) await notifyAutomationBlocked({
6070
+ automationId,
6071
+ ...dispatchId ? { dispatchId } : void 0,
6072
+ kind,
6073
+ reason: blocked.missing
6074
+ });
6075
+ }
6000
6076
  // src/chat/conversations/delivery-pause.ts
6001
6077
  /** True when the Conversation is a root that delivers to a Location. */
6002
6078
  function canPauseConversationDelivery(conversation) {
@@ -6123,16 +6199,32 @@ async function measureTurnCompactionWait(setTurnAttributes, callback) {
6123
6199
  }
6124
6200
  }
6125
6201
  /**
6126
- * Log the provider-reported input of the first model request after a
6127
- * replacement. It shows when the replacement was still above the threshold.
6202
+ * Track the replacement that waits for the provider-reported input of the
6203
+ * next model request. That request's `gen_ai.chat` span shows whether the
6204
+ * replacement got the history below the threshold. Production drops info
6205
+ * logs, so this is a span attribute.
6128
6206
  */
6129
- function logInputAfterCompaction(args) {
6130
- logInfo("context_compaction.next_request.completed", {
6131
- "app.compaction.mode": args.mode,
6132
- "app.compaction.next_input.size": args.inputSize,
6133
- "app.compaction.next_input.over_threshold": args.inputSize > args.threshold,
6134
- "app.compaction.threshold": args.threshold
6135
- });
6207
+ function createNextInputTracker() {
6208
+ let pending;
6209
+ return {
6210
+ replaced(mode, threshold) {
6211
+ pending = {
6212
+ mode,
6213
+ threshold
6214
+ };
6215
+ },
6216
+ attributes(inputSize) {
6217
+ if (!pending || !inputSize) return;
6218
+ const { mode, threshold } = pending;
6219
+ pending = void 0;
6220
+ return {
6221
+ "app.compaction.mode": mode,
6222
+ "app.compaction.next_input.size": inputSize,
6223
+ "app.compaction.next_input.over_threshold": inputSize > threshold,
6224
+ "app.compaction.threshold": threshold
6225
+ };
6226
+ }
6227
+ };
6136
6228
  }
6137
6229
  // src/chat/task-execution/turn-telemetry.ts
6138
6230
  /** Read the turn input timing facts from a mailbox batch, oldest first. */
@@ -6813,12 +6905,12 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6813
6905
  const disabledFeatures = webActor ? [] : ["interactive-auth"];
6814
6906
  const conversationLocation = storedConversation?.location;
6815
6907
  const isEventTurn = source.kind === "event" || savedMessageIsEvent;
6816
- const deliverToProvider = Boolean(conversationLocation) && isEventTurn && turnBehavior({
6908
+ const postsToProvider = Boolean(conversationLocation) && isEventTurn;
6909
+ const deliverToProvider = postsToProvider && turnBehavior({
6817
6910
  kind: storedConversation?.kind ?? "root",
6818
- personInput: false,
6819
- automationRun: false
6911
+ personInput: false
6820
6912
  }).delivery === "location";
6821
- const surface = deliverToProvider ? "slack" : "api";
6913
+ const surface = postsToProvider ? "slack" : "api";
6822
6914
  const inputTelemetry = resolved.kind === "mailbox" ? turnInputTelemetry(resolved.batch.map((entry) => entry.message)) : void 0;
6823
6915
  const turnTrace = inputTelemetry ?? (savedTurn?.traceContext ? { traceContexts: [savedTurn.traceContext] } : void 0);
6824
6916
  return await withTurnSpan({
@@ -6915,7 +7007,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6915
7007
  const cards = await loadPendingMessageCards(context.conversationId);
6916
7008
  const quiet = options?.quiet === true && isEventTurn && cards.length === 0;
6917
7009
  let deliveryResult;
6918
- if (deliverToProvider && !quiet && !await isConversationDeliveryPaused(context.conversationId)) {
7010
+ if ((options?.reply ? postsToProvider : deliverToProvider) && !quiet && !await isConversationDeliveryPaused(context.conversationId)) {
6919
7011
  if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
6920
7012
  deliveryResult = await deliverMessage({
6921
7013
  cards,
@@ -7023,6 +7115,8 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
7023
7115
  const reply = finalized.reply;
7024
7116
  modelFailureEventId = finalized.eventId;
7025
7117
  if (reply.diagnostics.outcome !== "success") await deliverAssistantMessage(reply.text);
7118
+ else if (reply.reply) await deliverAssistantMessage(reply.reply.text, { reply: true });
7119
+ else if (reply.blocked) await blockRunAutomation(context.conversationId, reply.blocked);
7026
7120
  else if (reply.noReply?.note && isEventTurn) await deliverAssistantMessage(reply.noReply.note, { quiet: true });
7027
7121
  const completedState = buildDeliveredTurnStatePatch({
7028
7122
  conversation,
@@ -7721,41 +7815,28 @@ function createArchiveAgentTool(conversationId) {
7721
7815
  }
7722
7816
  });
7723
7817
  }
7724
- // src/chat/tools/runtime/finish-automation-run.ts
7725
- const RESULT_GUIDANCE = ["Use `no_action` when the run worked and nothing should be posted, such as when a condition in the instruction is not met, or when a temporary failure stopped the work.", "Use `misconfigured` when the run cannot do its job until its creator changes the automation: a provider, tool, account, or access that the job needs is missing, a target no longer exists, or the instruction cannot be done. Do not use it for a temporary failure or a condition that is not met."].join(" ");
7726
- /** Create the tool that ends one Automation run with a declared result. */
7727
- function createFinishAutomationRunTool(options) {
7728
- const results = options.sendsMessage ? [
7729
- "send_message",
7730
- "no_action",
7731
- "misconfigured"
7732
- ] : ["no_action", "misconfigured"];
7818
+ // src/chat/tools/runtime/reply.ts
7819
+ /**
7820
+ * Create the tool that sets the reply of one gated Turn. The runtime posts the
7821
+ * reply after the Turn ends.
7822
+ */
7823
+ function createReplyTool() {
7733
7824
  return zodTool({
7734
7825
  annotations: {
7735
7826
  destructiveHint: false,
7736
- idempotentHint: true,
7737
- openWorldHint: false,
7827
+ idempotentHint: false,
7828
+ openWorldHint: true,
7738
7829
  readOnlyHint: false
7739
7830
  },
7740
- description: options.sendsMessage ? `End this automation run. Use \`send_message\` with the finished reminder, digest, alert, or answer; the runtime posts it to the stored destinations. This is the only way that the run posts, so a missing Slack posting tool does not make the run \`misconfigured\`. ${RESULT_GUIDANCE}` : `End this automation run. This automation posts nothing. ${RESULT_GUIDANCE}`,
7831
+ description: "Post the reply of this Turn when the Turn ends. When the run starts, the reply goes to its stored destinations. After the run posts, a reply goes to the run's Slack thread.",
7741
7832
  exposure: "modelOnly",
7742
- inputSchema: z.object({
7743
- result: z.enum(results),
7744
- ...options.sendsMessage ? { message: z.string().optional().describe("Required for send_message. The text to post.") } : void 0,
7745
- reason: z.string().optional().describe("Required for no_action and misconfigured. One sentence for the creator.")
7746
- }),
7747
- outputSchema: juniorToolOutputSchema.extend({ result: z.enum([
7748
- "send_message",
7749
- "no_action",
7750
- "misconfigured"
7751
- ]) }),
7833
+ inputSchema: z.object({ text: z.string().describe("The finished message, such as a reminder, digest, or alert.") }).strict(),
7834
+ outputSchema: juniorToolOutputSchema.extend({ text: z.string() }),
7752
7835
  execute: async (input) => {
7753
- const parsed = automationResultSchema$1.safeParse(input);
7754
- if (!parsed.success) throw new ToolInputError(input.result === "send_message" ? "send_message requires a non-empty message." : `${input.result} requires a non-empty reason.`);
7755
- return parsed.data.result === "send_message" && isLegacyNoReplyMarker(parsed.data.message) ? {
7756
- result: "no_action",
7757
- reason: "The message was the no-reply marker."
7758
- } : parsed.data;
7836
+ if (isLegacyNoReplyMarker(input.text)) throw new ToolInputError(`To post nothing, call \`${NO_REPLY_TOOL_NAME}\` instead.`);
7837
+ const text = replyTextSchema.safeParse(input.text);
7838
+ if (!text.success) throw new ToolInputError("The reply text must not be empty.");
7839
+ return { text: text.data };
7759
7840
  }
7760
7841
  });
7761
7842
  }
@@ -7777,8 +7858,22 @@ function createNoReplyTool() {
7777
7858
  });
7778
7859
  }
7779
7860
  // src/chat/tools/runtime/report-blocked.ts
7780
- /** Create the tool that ends a child agent run as blocked. */
7781
- function createReportBlockedTool() {
7861
+ const DESCRIPTIONS = {
7862
+ parent: {
7863
+ tool: "End this delegated task as blocked. Call this when missing access, credentials, input, or a decision stops the task, also when a search for the missing part found nothing. Do not guess, mock, or fake results to work around it.",
7864
+ missing: "What the task needs and who can give it. Add the work you already did, so the parent does not repeat it."
7865
+ },
7866
+ automation: {
7867
+ tool: "End this Turn and block the Automation until someone fixes it. Call this when a provider, tool, account, or access that the job needs is missing, a target no longer exists, or the instruction cannot be done. Do not call it for a temporary failure or a condition that is not met.",
7868
+ missing: "What the Automation needs and who can give it. One sentence for the creator."
7869
+ }
7870
+ };
7871
+ /**
7872
+ * Create the tool that ends a Turn as blocked. `parent`: a child agent reports
7873
+ * to its parent. `automation`: the Automation is blocked.
7874
+ */
7875
+ function createReportBlockedTool(target) {
7876
+ const descriptions = DESCRIPTIONS[target];
7782
7877
  return zodTool({
7783
7878
  annotations: {
7784
7879
  destructiveHint: false,
@@ -7786,9 +7881,9 @@ function createReportBlockedTool() {
7786
7881
  openWorldHint: false,
7787
7882
  readOnlyHint: false
7788
7883
  },
7789
- description: "End this delegated task as blocked. Call this when missing access, credentials, input, or a decision stops the task, also when a search for the missing part found nothing. Do not guess, mock, or fake results to work around it.",
7884
+ description: descriptions.tool,
7790
7885
  exposure: "modelOnly",
7791
- inputSchema: z.object({ missing: z.string().trim().min(1).describe("What the task needs and who can give it. Add the work you already did, so the parent does not repeat it.") }).strict(),
7886
+ inputSchema: z.object({ missing: z.string().trim().min(1).describe(descriptions.missing) }).strict(),
7792
7887
  outputSchema: juniorToolOutputSchema.extend({ missing: z.string() }),
7793
7888
  execute: async (input) => ({ missing: input.missing })
7794
7889
  });
@@ -8632,7 +8727,7 @@ function subjectInput(subject) {
8632
8727
  /** Create the tool that adds a Review item or updates the open one. */
8633
8728
  function createAddReviewItemTool(context, services) {
8634
8729
  return zodTool({
8635
- description: `Ask a person for input, or tell them about work that needs them. This is how you ask a person anything: the item goes on the review desk, and in a Slack thread it also shows as a card with buttons. Write the question so it stands alone: a person who sees only the card must understand it. Put the option that you recommend first, set \`recommended: true\` on it, and say why in its description. Use kind \`action\` with a \`request\` to ask: a question and 1-4 fields. Each field is \`choice\` (pick one), \`multi_choice\` (pick any), or \`text\` (a short answer). For a simple decision, use one \`choice\` field. Ask for related input in one item. Use kind \`notice\` only to tell a person something. Assignees default to the person in this Turn, to the Automation creator in an Automation run, or else to the people still subscribed to the Conversation. The current Conversation is always linked. The answer arrives later as a \`<review-item-answer>\` with the item id, or a \`<review-item-dismissed>\` when the person dismisses it. A reply that the assignee types in the thread also closes the item when the reply answers it. If your next step needs the answer, end the Turn now: the card is your reply, so do not write text: call \`${NO_REPLY_TOOL_NAME}\`, or finish the Automation run. If other work does not need the answer, continue with it. If an open item has the same \`dedupe_key\`, this updates that item instead of adding another.`,
8730
+ description: `Ask a person for input, or tell them about work that needs them. This is how you ask a person anything: the item goes on the review desk, and in a Slack thread it also shows as a card with buttons. Write the question so it stands alone: a person who sees only the card must understand it. Put the option that you recommend first, set \`recommended: true\` on it, and say why in its description. Use kind \`action\` with a \`request\` to ask: a question and 1-4 fields. Each field is \`choice\` (pick one), \`multi_choice\` (pick any), or \`text\` (a short answer). For a simple decision, use one \`choice\` field. Ask for related input in one item. Use kind \`notice\` only to tell a person something. Assignees default to the person in this Turn, to the Automation creator in an Automation run, or else to the people still subscribed to the Conversation. The current Conversation is always linked. The answer arrives later as a \`<review-item-answer>\` with the item id, or a \`<review-item-dismissed>\` when the person dismisses it. A reply that the assignee types in the thread also closes the item when the reply answers it. If your next step needs the answer, end the Turn now: the card is your reply, so do not write text: call \`${NO_REPLY_TOOL_NAME}\`. If other work does not need the answer, continue with it. If an open item has the same \`dedupe_key\`, this updates that item instead of adding another.`,
8636
8731
  annotations: {
8637
8732
  destructiveHint: false,
8638
8733
  idempotentHint: true,
@@ -9555,6 +9650,59 @@ async function editAutomationFields(current, input, isCreator, changesExecution)
9555
9650
  outcomes
9556
9651
  };
9557
9652
  }
9653
+ // src/chat/automations/instruction-references.ts
9654
+ function namesPerson(text, name) {
9655
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9656
+ return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu").test(text);
9657
+ }
9658
+ const CONVERSATION_REFERENCE = /\bthis (?:channel|conversation|thread)\b/i;
9659
+ function refersTo(text, person) {
9660
+ return text.includes(slackMention(person.slackUserId)) || !!person.fullName && namesPerson(text, person.fullName);
9661
+ }
9662
+ /**
9663
+ * Return why the text cannot run later, or undefined.
9664
+ *
9665
+ * An Automation runs later without the request. So "this channel" means
9666
+ * nothing to the run. Its outcomes already say where it posts, so the text
9667
+ * names the channel only where the run reads or acts on it. Each run reads
9668
+ * "the Automation creator" as its creator, so the text calls the creator
9669
+ * that. Every other requester needs their Slack mention, because a display
9670
+ * name does not notify the person and it can match another person. A run
9671
+ * ends with `reply`, `noReply`, or `reportBlocked`, so a legacy no-reply
9672
+ * marker does nothing. A problem that the previous text already had stays
9673
+ * allowed, so an edit does not have to rewrite text that the requester did
9674
+ * not change.
9675
+ */
9676
+ function taskTextProblem(text, references) {
9677
+ const { creator, requester, previousText, label } = references;
9678
+ const conversationReference = CONVERSATION_REFERENCE.exec(text)?.[0];
9679
+ if (conversationReference && !CONVERSATION_REFERENCE.test(previousText)) return `The run does not see this conversation, and its outcomes already set where it posts. Remove "${conversationReference}" and do not say where to post. Where the run reads or changes a channel, name it with a channel mention.`;
9680
+ const marker = findLegacyNoReplyMarker(text);
9681
+ if (marker && !previousText.includes(marker)) return `Remove "${marker}". Say when the run posts nothing; it then ends without a message.`;
9682
+ if (refersTo(text, creator) && !refersTo(previousText, creator)) return `The ${label} names ${creator.fullName ?? slackMention(creator.slackUserId)}, the Automation creator. Write "the Automation creator" for this person; each run knows who that is.`;
9683
+ if (!requester?.fullName || requester.slackUserId === creator.slackUserId) return;
9684
+ const mention = slackMention(requester.slackUserId);
9685
+ if (text.includes(mention) || !namesPerson(text, requester.fullName)) return;
9686
+ return `The ${label} names ${requester.fullName} without a Slack mention. Write ${mention} for this person.`;
9687
+ }
9688
+ /**
9689
+ * Reject task text that a later run cannot use. The Automation tools and the
9690
+ * dashboard edit API call this. Restoring a saved version does not, because
9691
+ * that text was accepted when it was saved. Text that the current task
9692
+ * already had is not checked again.
9693
+ */
9694
+ function requireAutomationTaskText(task, references) {
9695
+ const text = automationTaskText(task);
9696
+ const previousText = (references.current && automationTaskText(references.current)) ?? "";
9697
+ if (text === void 0 || text === previousText) return;
9698
+ const label = task.kind === "instruction" ? "instruction" : "context";
9699
+ const problem = taskTextProblem(text, {
9700
+ ...references,
9701
+ previousText,
9702
+ label
9703
+ });
9704
+ if (problem) throw new AutomationEditError(problem, `task.${label}`);
9705
+ }
9558
9706
  // src/chat/event-automations/tool-support.ts
9559
9707
  /** Model-facing shape of one event automation. */
9560
9708
  const compactEventAutomationResultSchema = z.object({
@@ -10291,6 +10439,11 @@ async function updateViewerAutomation(user, id, input) {
10291
10439
  const current = await requireEditableAutomation(user, id);
10292
10440
  if (input.kind !== current.kind) throw new AutomationEditError("The trigger type cannot change.", "kind");
10293
10441
  requireAutomationRevision(current.task, input.revision);
10442
+ if (input.task) requireAutomationTaskText(input.task, {
10443
+ creator: current.task.createdBy,
10444
+ requester: automationEditor(user, current),
10445
+ current: current.task.task
10446
+ });
10294
10447
  return saveViewerEdit(user, current, input);
10295
10448
  }
10296
10449
  /** `restored` carries version values that edit input cannot express, such as a cleared title. */
@@ -10647,39 +10800,6 @@ async function searchToolAutomations(context, caller, input) {
10647
10800
  truncated: total > rows.length
10648
10801
  };
10649
10802
  }
10650
- // src/chat/automations/instruction-references.ts
10651
- function namesPerson(text, name) {
10652
- const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10653
- return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu").test(text);
10654
- }
10655
- const CONVERSATION_REFERENCE = /\bthis (?:channel|conversation|thread)\b/i;
10656
- function refersTo(text, person) {
10657
- return text.includes(slackMention(person.slackUserId)) || !!person.fullName && namesPerson(text, person.fullName);
10658
- }
10659
- /**
10660
- * Reject an instruction with a reference that the run cannot use.
10661
- *
10662
- * An Automation runs later without the request. So "this channel" means
10663
- * nothing to the run; the instruction names the channel instead. Each run
10664
- * reads "the Automation creator" as its creator, so the instruction calls the
10665
- * creator that. Every other requester needs their Slack mention, because a
10666
- * display name does not notify the person and it can match another person. A
10667
- * reference that the previous instruction already had stays allowed, so an
10668
- * edit does not have to rewrite text that the requester did not change.
10669
- */
10670
- function requireInstructionReferences(instruction, references) {
10671
- const { creator, destinationChannelId, requester, previousInstruction = "" } = references;
10672
- const conversationReference = CONVERSATION_REFERENCE.exec(instruction)?.[0];
10673
- if (conversationReference && !CONVERSATION_REFERENCE.test(previousInstruction)) throw new ToolInputError(`The run does not see this conversation. Write <#${destinationChannelId}> instead of "${conversationReference}".`);
10674
- if (refersTo(instruction, creator) && !refersTo(previousInstruction, creator)) {
10675
- const reference = creator.fullName ?? slackMention(creator.slackUserId);
10676
- throw new ToolInputError(`The instruction names ${reference}, the Automation creator. Write "the Automation creator" for this person; each run knows who that is.`);
10677
- }
10678
- if (!requester?.fullName || requester.slackUserId === creator.slackUserId) return;
10679
- const mention = slackMention(requester.slackUserId);
10680
- if (instruction.includes(mention)) return;
10681
- if (namesPerson(instruction, requester.fullName)) throw new ToolInputError(`The instruction names ${requester.fullName} without a Slack mention. Write ${mention} for this person.`);
10682
- }
10683
10803
  // src/chat/scheduled-automations/tool-support.ts
10684
10804
  /** Model-facing shape of one scheduled automation. */
10685
10805
  const compactTaskResultSchema = z.object({
@@ -11074,7 +11194,7 @@ function createAutomationTool(context, catalog, skills = []) {
11074
11194
  readOnlyHint: false
11075
11195
  },
11076
11196
  executionMode: "sequential",
11077
- description: "Create a durable automation. It belongs to the channel or DM of this conversation, never a thread. Its outcomes set where its messages go. Use trigger type \"schedule\" for one-time or recurring work. Use trigger type \"event\" only when the user explicitly asks for an event automation or durable whenever-this-happens-do-X work; it runs for every matching event. Set instruction for written work, or skill to run an installed skill, with context only when the skill needs more. Ordinary watch, notify, or tell-me-when requests use watchEvents instead. Store the requested future work; do not perform it or check its service access now unless the user also asks for that. When the trigger is known, create it without redundant confirmation.",
11197
+ description: "Create a durable automation. It belongs to the channel or DM of this conversation, never a thread. Its outcomes set where its messages go. Use trigger type \"schedule\" for one-time or recurring work. Use trigger type \"event\" only when the user explicitly asks for an event automation or durable whenever-this-happens-do-X work; it runs for every matching event. Set instruction for written work, or skill to run an installed skill, with context only when the skill needs more. When an installed skill does the work, set skill; do not write an instruction that names the skill. Ordinary watch, notify, or tell-me-when requests use watchEvents instead. Store the requested future work; do not perform it or check its service access now unless the user also asks for that. When the trigger is known, create it without redundant confirmation.",
11078
11198
  inputSchema: z.object({
11079
11199
  instruction: automationInstructionToolSchema.nullable().optional(),
11080
11200
  skill: automationSkillToolSchema(skills).nullable().optional(),
@@ -11082,7 +11202,7 @@ function createAutomationTool(context, catalog, skills = []) {
11082
11202
  title: z.string().trim().min(1).max(60).nullable().describe("Optional short display title. Omit or use null to generate one from the instruction or skill.").optional(),
11083
11203
  trigger,
11084
11204
  outcomes: z.array(taskOutcomeInputSchema).max(5).describe("Successful work is silent by default. Omit this field or use an empty list when the Automation should act through tools without a status message. Add send_message only when the user asks for a reminder, notification, post, digest, summary, or other visible result.").optional(),
11085
- credential_mode: z.enum(["creator", "system"]).nullable().describe("Use creator to make the creator's connected credentials available, or system when the creator says not to use them. Omit or use null for the creator default.").optional()
11205
+ credential_mode: z.enum(["creator", "system"]).nullable().describe("Omit or use null for the system default: runs use your own credentials. Use creator only when the creator asks for their connected credentials to be available to the runs.").optional()
11086
11206
  }).strict(),
11087
11207
  prepareArguments(args) {
11088
11208
  const prepared = { ...args };
@@ -11090,7 +11210,7 @@ function createAutomationTool(context, catalog, skills = []) {
11090
11210
  if (prepared.instruction == null) delete prepared.instruction;
11091
11211
  if (prepared.skill == null) delete prepared.skill;
11092
11212
  if (prepared.context == null) delete prepared.context;
11093
- if (prepared.credential_mode === "creator" || prepared.credential_mode === null) delete prepared.credential_mode;
11213
+ if (prepared.credential_mode === null) delete prepared.credential_mode;
11094
11214
  return prepared;
11095
11215
  },
11096
11216
  outputSchema: automationToolResultSchema,
@@ -11106,11 +11226,7 @@ function createAutomationTool(context, catalog, skills = []) {
11106
11226
  context: input.context ?? void 0
11107
11227
  });
11108
11228
  await requireAutomationSkill(task, void 0);
11109
- const text = automationTaskText(task);
11110
- if (text) requireInstructionReferences(text, {
11111
- creator: createdBy,
11112
- destinationChannelId: destination.channelId
11113
- });
11229
+ requireAutomationTaskText(task, { creator: createdBy });
11114
11230
  const eventTrigger = input.trigger.type === "event" ? requireEventAutomationTrigger(catalog, slackChannelMessageTrigger({
11115
11231
  ...input.trigger,
11116
11232
  match: input.trigger.match ? declaredEventKeys(input.trigger.match) : void 0
@@ -11137,7 +11253,7 @@ function createAutomationTool(context, catalog, skills = []) {
11137
11253
  id,
11138
11254
  nowMs,
11139
11255
  task,
11140
- credentialMode: input.credential_mode ?? "creator",
11256
+ credentialMode: input.credential_mode ?? "system",
11141
11257
  outcomes: await resolveTaskOutcomes(input.outcomes, destination, createdBy.slackUserId),
11142
11258
  title: await resolveTaskTitle({
11143
11259
  signal: options.signal,
@@ -11624,13 +11740,10 @@ function createUpdateAutomationTool(context, catalog, skills = []) {
11624
11740
  if (input.destination && !current.ownedByViewer && await resolveDestinationVisibility({ destination: current.task.destination }) !== "public") throw new ToolInputError("Only the creator can move an automation out of a private channel or DM.");
11625
11741
  const editor = automationEditor(caller.viewer, current);
11626
11742
  const editedTask = editedAutomationTask(current.task.task, input);
11627
- const previousText = automationTaskText(current.task.task);
11628
- const text = editedTask && automationTaskText(editedTask);
11629
- if (text !== void 0 && text !== previousText) requireInstructionReferences(text, {
11743
+ if (editedTask) requireAutomationTaskText(editedTask, {
11630
11744
  creator: current.task.createdBy,
11631
- destinationChannelId: current.task.destination.channelId,
11632
11745
  requester: editor,
11633
- previousInstruction: previousText ?? ""
11746
+ current: current.task.task
11634
11747
  });
11635
11748
  let saved = current;
11636
11749
  if (Object.keys(input).length > 0) saved = current.kind === "scheduled" ? await updateScheduled(context, current, input, editedTask, editor) : await updateEvent(current, input, editedTask, editor, catalog);
@@ -16617,8 +16730,8 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
16617
16730
  parentConversationId: context.parentConversationId
16618
16731
  });
16619
16732
  if (context.messageAgent) tools.messageAgent = createMessageAgentTool(context.messageAgent);
16620
- if (turnTools.reportBlocked) tools[REPORT_BLOCKED_TOOL_NAME] = createReportBlockedTool();
16621
- if (context.automation) tools[FINISH_AUTOMATION_RUN_TOOL_NAME] = createFinishAutomationRunTool(context.automation);
16733
+ if (turnTools.reply) tools[REPLY_TOOL_NAME] = createReplyTool();
16734
+ if (turnTools.reportBlocked !== "none") tools[REPORT_BLOCKED_TOOL_NAME] = createReportBlockedTool(turnTools.reportBlocked);
16622
16735
  if (turnTools.noReply) tools[NO_REPLY_TOOL_NAME] = createNoReplyTool();
16623
16736
  if (context.mcpToolManager) {
16624
16737
  tools.searchMcpTools = createSearchMcpToolsTool(context.mcpToolManager);
@@ -18730,10 +18843,9 @@ function parseSessionIndex(value) {
18730
18843
  }
18731
18844
  }
18732
18845
  function parseMcpAuthSession(value) {
18733
- if (typeof value !== "string") return;
18846
+ if (!isRecord$4(value)) return;
18734
18847
  try {
18735
- const parsed = JSON.parse(value);
18736
- if (!isRecord$4(parsed)) return;
18848
+ const parsed = value;
18737
18849
  if (parsed.schemaVersion !== 2 || typeof parsed.authSessionId !== "string" || typeof parsed.provider !== "string" || typeof parsed.userId !== "string" || typeof parsed.conversationId !== "string" || typeof parsed.sessionId !== "string" || typeof parsed.userMessage !== "string" || typeof parsed.createdAtMs !== "number" || typeof parsed.updatedAtMs !== "number") return;
18738
18850
  const destination = parsed.destination === void 0 ? void 0 : parseDestination(parsed.destination);
18739
18851
  if (parsed.destination !== void 0 && !destination) return;
@@ -18776,9 +18888,8 @@ function parseServerSession(value) {
18776
18888
  }
18777
18889
  }
18778
18890
  function parseStoredCredentials(value) {
18779
- if (typeof value !== "string") return;
18780
18891
  try {
18781
- const parsed = JSON.parse(value);
18892
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
18782
18893
  if (!isRecord$4(parsed)) return;
18783
18894
  return {
18784
18895
  ...isRecord$4(parsed.clientInformation) ? { clientInformation: parsed.clientInformation } : void 0,
@@ -18789,17 +18900,26 @@ function parseStoredCredentials(value) {
18789
18900
  return;
18790
18901
  }
18791
18902
  }
18903
+ async function readMcpAuthSession(stateAdapter, authSessionId) {
18904
+ const stored = await readEncryptedState(stateAdapter, sessionKey(authSessionId));
18905
+ if (stored?.stale && typeof stored.value === "string") try {
18906
+ return JSON.parse(stored.value);
18907
+ } catch {
18908
+ return;
18909
+ }
18910
+ return stored?.value;
18911
+ }
18792
18912
  async function getConnectedStateAdapter() {
18793
18913
  const stateAdapter = getStateAdapter();
18794
18914
  await stateAdapter.connect();
18795
18915
  return stateAdapter;
18796
18916
  }
18797
18917
  async function getMcpAuthSession(authSessionId) {
18798
- return parseMcpAuthSession(await (await getConnectedStateAdapter()).get(sessionKey(authSessionId)));
18918
+ return parseMcpAuthSession(await readMcpAuthSession(await getConnectedStateAdapter(), authSessionId));
18799
18919
  }
18800
18920
  async function putMcpAuthSession(session, ttlMs = MCP_AUTH_SESSION_TTL_MS) {
18801
18921
  const stateAdapter = await getConnectedStateAdapter();
18802
- await stateAdapter.set(sessionKey(session.authSessionId), JSON.stringify(session), ttlMs);
18922
+ await createEncryptedState(stateAdapter).set(sessionKey(session.authSessionId), session, ttlMs);
18803
18923
  const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(session.userId, session.provider)));
18804
18924
  if (!nextIndex.includes(session.authSessionId)) nextIndex.push(session.authSessionId);
18805
18925
  await stateAdapter.set(sessionIndexKey(session.userId, session.provider), JSON.stringify(nextIndex), ttlMs);
@@ -18826,7 +18946,7 @@ async function patchMcpAuthSession(authSessionId, patch) {
18826
18946
  }
18827
18947
  async function deleteMcpAuthSession(authSessionId) {
18828
18948
  const stateAdapter = await getConnectedStateAdapter();
18829
- const current = parseMcpAuthSession(await stateAdapter.get(sessionKey(authSessionId)));
18949
+ const current = parseMcpAuthSession(await readMcpAuthSession(stateAdapter, authSessionId));
18830
18950
  await stateAdapter.delete(sessionKey(authSessionId));
18831
18951
  if (!current) return;
18832
18952
  const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(current.userId, current.provider))).filter((id) => id !== authSessionId);
@@ -18845,19 +18965,20 @@ async function deleteMcpAuthSessionsForUserProvider(userId, provider) {
18845
18965
  }
18846
18966
  async function getMcpStoredOAuthCredentials(userId, provider) {
18847
18967
  const stateAdapter = await getConnectedStateAdapter();
18848
- const stored = parseStoredCredentials(await stateAdapter.get(credentialsKey(userId, provider)));
18968
+ const stored = parseStoredCredentials((await readEncryptedState(stateAdapter, credentialsKey(userId, provider)))?.value);
18849
18969
  if (stored) return stored;
18850
18970
  const legacyUserId = await findLegacyWebActorUserId(userId);
18851
18971
  if (!legacyUserId) return void 0;
18852
18972
  const legacyKey = credentialsKey(legacyUserId, provider);
18853
- const legacy = parseStoredCredentials(await stateAdapter.get(legacyKey));
18973
+ const legacy = parseStoredCredentials((await readEncryptedState(stateAdapter, legacyKey))?.value);
18854
18974
  if (!legacy) return void 0;
18855
18975
  await putMcpStoredOAuthCredentials(userId, provider, legacy);
18856
18976
  await stateAdapter.delete(legacyKey);
18857
18977
  return legacy;
18858
18978
  }
18859
18979
  async function putMcpStoredOAuthCredentials(userId, provider, value, ttlMs = MCP_AUTH_CREDENTIALS_TTL_MS) {
18860
- await (await getConnectedStateAdapter()).set(credentialsKey(userId, provider), JSON.stringify(value), ttlMs);
18980
+ const stateAdapter = await getConnectedStateAdapter();
18981
+ await createEncryptedState(stateAdapter).set(credentialsKey(userId, provider), value, ttlMs);
18861
18982
  }
18862
18983
  async function deleteMcpStoredOAuthCredentials(userId, provider) {
18863
18984
  const stateAdapter = await getConnectedStateAdapter();
@@ -19381,7 +19502,7 @@ ${renderRules("deny")}
19381
19502
  - A user-requested read, query, or upload to a trusted destination is not data exposure. Using an existing credential to authenticate a user-requested action is not credential probing.
19382
19503
  - A tool that is external, multi-field, open-world, uses connected credentials, has plugin or catalog identity, or carries a destructive annotation does not match a rule by those facts alone. Judge actual side effects, not tool names or annotations.
19383
19504
  - For a scheduled automation or event automation, a request by the current actor for scoped work that needs their connected service access authorizes routine service-native reads and posting the requested result to the task's stored Slack destination. It does not authorize exposing credential values, broad data dumps, or delivery to another destination.
19384
- - A current actor's request for scoped work that needs their connected service access authorizes routine creator credential use required for that work; tools enforce whether they are the original creator. Creator mode that the current actor denied matches \`withheld_step\`. System mode does not delegate personal credentials, so it needs no credential confirmation. An automation's credential mode applies to its later runs. The credential-authority fields describe only the current action, so a difference between the two is expected.
19505
+ - A new automation uses system mode unless the creator asks for creator mode. System mode does not delegate personal credentials, so it needs no credential confirmation. A current actor's request to make their connected service access available for scoped work authorizes routine creator credential use required for that work; tools enforce whether they are the original creator. Creator mode that the current actor denied matches \`withheld_step\`. An automation's credential mode applies to its later runs. The credential-authority fields describe only the current action, so a difference between the two is expected.
19385
19506
 
19386
19507
  # Output
19387
19508
  - Rate risk and user authorization first.
@@ -19891,6 +20012,7 @@ async function createRunSandbox(args) {
19891
20012
  egressSignals: args.run.environment?.sandboxEgressSignals,
19892
20013
  conversationId: args.run.conversationId,
19893
20014
  credentialEgress: args.run.credentialContext,
20015
+ credentialAuditSource: credentialAuditSource(args.run.source),
19894
20016
  actor: args.currentActor,
19895
20017
  locationConfiguration: args.run.environment?.locationConfiguration,
19896
20018
  configurationValues: args.configurationValues,
@@ -19974,6 +20096,7 @@ function resolveToolRuntimeRoute(args) {
19974
20096
  /** Wire sandbox tools, auth orchestration, MCP restoration, and Pi tool surfaces for one slice. */
19975
20097
  async function wireAgentTools(args) {
19976
20098
  const runSource = args.run.source;
20099
+ const auditSource = credentialAuditSource(runSource);
19977
20100
  const credentialUserId = args.run.credentialContext ? credentialUserSubjectId(args.run.credentialContext) : void 0;
19978
20101
  const userTokenStore = createUserTokenStore();
19979
20102
  const { agentSandbox, pluginHooks } = args.sandbox;
@@ -20013,6 +20136,7 @@ async function wireAgentTools(args) {
20013
20136
  authorization: args.authorization
20014
20137
  });
20015
20138
  const mcpToolManager = new McpToolManager(pluginCatalogRuntime.getMcpProviders(), {
20139
+ auditAttributes: credentialAuditAttributes(auditSource),
20016
20140
  authProviderFactory: mcpAuth.authProviderFactory,
20017
20141
  serviceAccountProviderFactory: mcpAuth.serviceAccountProviderFactory,
20018
20142
  onAuthorizationRequired: (provider, _error, context) => mcpAuth.onAuthorizationRequired(provider, context),
@@ -20027,7 +20151,10 @@ async function wireAgentTools(args) {
20027
20151
  const commonToolRuntimeContext = {
20028
20152
  conversationId: args.run.conversationId,
20029
20153
  turnId: args.run.turnId,
20030
- turnTools: args.behavior.tools,
20154
+ turnTools: {
20155
+ ...args.behavior.tools,
20156
+ reply: args.behavior.tools.reply && args.run.dispatch?.outcomes?.length !== 0
20157
+ },
20031
20158
  ...args.run.parentConversationId ? { parentConversationId: args.run.parentConversationId } : void 0,
20032
20159
  ...args.run.location ? {
20033
20160
  location: args.run.location,
@@ -20037,6 +20164,7 @@ async function wireAgentTools(args) {
20037
20164
  userText: args.userInput,
20038
20165
  configuration: args.configurationValues,
20039
20166
  egress: createPluginEgress({
20167
+ credentialAuditSource: auditSource,
20040
20168
  credentialContext: args.run.credentialContext,
20041
20169
  pluginAuth: { async handleAuthRequired(signal) {
20042
20170
  await pluginAuth.maybeHandleAuthSignal({ auth_required: {
@@ -20054,8 +20182,7 @@ async function wireAgentTools(args) {
20054
20182
  supportsImageInput: args.supportsImageInput,
20055
20183
  surface: args.surface,
20056
20184
  ...args.currentActor ? { resolveActorIdentity: async () => await readActorIdentity(args.currentActor) } : void 0,
20057
- ...bindAgentTools(args.run, args.behavior.tools.agents),
20058
- ...args.behavior.tools.finishAutomationRun ? { automation: { sendsMessage: args.run.dispatch?.outcomes?.length !== 0 } } : void 0
20185
+ ...bindAgentTools(args.run, args.behavior.tools.agents)
20059
20186
  };
20060
20187
  const toolRoute = resolveToolRuntimeRoute({
20061
20188
  actor: args.currentActor,
@@ -20720,11 +20847,6 @@ async function requestAboveMark(args) {
20720
20847
  }
20721
20848
  }], { activity: "preserve" })).length === 0) return;
20722
20849
  await args.queue.send(message);
20723
- logInfo("context_compaction.background.requested", {
20724
- "app.compaction.mark_seq": markSeq,
20725
- "app.compaction.history_version": historyVersion,
20726
- "app.compaction.input.size": args.inputSize
20727
- });
20728
20850
  }
20729
20851
  /** A fixed label for a failed summary. Never raw exception text. */
20730
20852
  function failureLabel(error, signal) {
@@ -21649,7 +21771,7 @@ async function applyPreparedSummary(args, prepared, budget) {
21649
21771
  */
21650
21772
  const EXCLUSIVE_TOOL_NAMES = [
21651
21773
  "switchWorkspace",
21652
- FINISH_AUTOMATION_RUN_TOOL_NAME,
21774
+ REPLY_TOOL_NAME,
21653
21775
  REPORT_BLOCKED_TOOL_NAME,
21654
21776
  NO_REPLY_TOOL_NAME
21655
21777
  ];
@@ -21679,7 +21801,10 @@ function recordToolBatch(stats, toolCalls, tools) {
21679
21801
  stats.sequentialCallCount += toolCalls.length;
21680
21802
  for (const name of sequentialTools) stats.sequentialToolNames.add(name);
21681
21803
  }
21682
- /** Span attributes for the batch counts of one Run. */
21804
+ /**
21805
+ * Span attributes for the batch counts of one Run, set on its
21806
+ * `gen_ai.invoke_agent` span because production drops info logs.
21807
+ */
21683
21808
  function toolBatchSpanAttributes(stats) {
21684
21809
  return {
21685
21810
  "app.tool_batch.count": stats.count,
@@ -21758,17 +21883,15 @@ async function executeAgentRun(run, streamFn) {
21758
21883
  runId: run.runId,
21759
21884
  assistantUserName: botConfig.userName
21760
21885
  };
21761
- return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn)));
21886
+ return withLogContext(runLogContext, () => runWithConversationPrivacy(conversationPrivacy, () => executeAgentRunInPrivacyContext(run, run.dispatch?.declaresResult ? "automation" : conversation?.kind ?? "root", conversationPrivacy, runLogContext, streamFn)));
21762
21887
  }
21763
21888
  async function executeAgentRunInPrivacyContext(run, conversationKind, conversationPrivacy, runLogContext, streamFn) {
21764
21889
  const conversationId = run.conversationId;
21765
21890
  const turnId = run.turnId;
21766
21891
  const behavior = turnBehavior({
21767
21892
  kind: conversationKind,
21768
- personInput: isPersonInput(run.source.kind),
21769
- automationRun: run.dispatch?.declaresResult === true
21893
+ personInput: isPersonInput(run.source.kind)
21770
21894
  });
21771
- const requireAutomationResult = behavior.gated;
21772
21895
  const input = {
21773
21896
  actor: run.instruction.actor,
21774
21897
  messageText: run.instruction.text,
@@ -22065,7 +22188,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22065
22188
  };
22066
22189
  if (initialRepositoryInstructions) await recordAgentsTransition(initialRepositoryInstructions);
22067
22190
  const getPendingAuthPause = wiring.getPendingAuthPause;
22068
- const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
22191
+ const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
22069
22192
  activeMcpCatalogs: wiring.activeMcpCatalogs,
22070
22193
  promptMode: behavior.promptMode,
22071
22194
  currentActor: actor,
@@ -22111,19 +22234,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22111
22234
  promptName: CONTEXT_COMPACTION_PROMPT_NAME,
22112
22235
  ...streamFn ? { base: streamFn } : void 0
22113
22236
  });
22114
- let replacementAwaitingInput;
22115
- /** Log the first provider-reported input after a replacement. */
22116
- const logFirstInputAfterReplacement = () => {
22117
- if (!replacementAwaitingInput) return;
22118
- const inputSize = lastRequestInputSize(agent.state.messages.slice(replacementAwaitingInput.messageCount));
22119
- if (!inputSize) return;
22120
- logInputAfterCompaction({
22121
- inputSize,
22122
- mode: replacementAwaitingInput.mode,
22123
- threshold: getAgentContextCompactionTriggerTokens(activeModelId)
22124
- });
22125
- replacementAwaitingInput = void 0;
22126
- };
22237
+ const nextInputAfterReplacement = createNextInputTracker();
22127
22238
  /** Commit and adopt an active capacity replacement before another model call. */
22128
22239
  const applyActiveContextCompaction = async (messages, hookSignal, pendingMessages, clearSteeringQueueOnCommit = false, pairPendingRuntimeContext = false, mode = "active") => {
22129
22240
  const compaction = await compactWithPreparedSummary({
@@ -22150,10 +22261,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22150
22261
  throw error;
22151
22262
  }
22152
22263
  agent.state.messages = replacement;
22153
- replacementAwaitingInput = {
22154
- messageCount: replacement.length,
22155
- mode
22156
- };
22264
+ nextInputAfterReplacement.replaced(mode, getAgentContextCompactionTriggerTokens(activeModelId));
22157
22265
  runResume.setBeforeMessageCount(replacement.length);
22158
22266
  runResume.adoptCommittedBoundary(replacement);
22159
22267
  if (clearSteeringQueueOnCommit && pendingMessages?.length) agent.clearSteeringQueue();
@@ -22216,7 +22324,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22216
22324
  }
22217
22325
  return acceptedMessages;
22218
22326
  };
22219
- const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task");
22327
+ const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task", {
22328
+ platform: promptPlatform,
22329
+ mode: behavior.promptMode
22330
+ });
22220
22331
  const toolBatchStats = createToolBatchStats();
22221
22332
  let setAgentSpanAttributes;
22222
22333
  agent = new Agent({
@@ -22224,7 +22335,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22224
22335
  sessionId: conversationId,
22225
22336
  streamFn: createTracedStreamFn({
22226
22337
  conversationPrivacy,
22227
- base: cacheWarming.wrap(streamFn)
22338
+ base: cacheWarming.wrap(streamFn),
22339
+ endAttributes: (message) => nextInputAfterReplacement.attributes(lastRequestInputSize([message]))
22228
22340
  }),
22229
22341
  steeringMode: "all",
22230
22342
  beforeToolCall: async ({ assistantMessage, context, toolCall }) => {
@@ -22270,12 +22382,14 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22270
22382
  const sourceResult = timedOutResult ?? result;
22271
22383
  const projectedResult = wiring.projectActionReviewResult(toolCall.id, sourceResult);
22272
22384
  const override = timedOutResult || projectedResult !== result ? projectedResult : void 0;
22273
- if ((toolCall.name === "finishAutomationRun" || toolCall.name === "reportBlocked" || toolCall.name === "noReply") && !isError && !override) return { terminate: true };
22385
+ if ((toolCall.name === "reply" || toolCall.name === "reportBlocked" || toolCall.name === "noReply") && !isError && !override) {
22386
+ if (toolCall.name === "noReply" && !behavior.gated) cacheWarming.noReplyEnded();
22387
+ return { terminate: true };
22388
+ }
22274
22389
  return override;
22275
22390
  },
22276
22391
  prepareNextTurnWithContext: async (nextTurn, hookSignal) => {
22277
22392
  try {
22278
- logFirstInputAfterReplacement();
22279
22393
  if (hookSignal?.aborted) return;
22280
22394
  const stepUpdate = await withSpan("agent.step.prepare", "agent.step.prepare", {}, async () => {
22281
22395
  const contextUpdate = await repositoryInstructionsContext.applyUpdate(nextTurn.context);
@@ -22325,6 +22439,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22325
22439
  }
22326
22440
  });
22327
22441
  let newMessages = [];
22442
+ const turnStartIndex = () => existingSessionRecord?.turnStartMessageIndex ?? runResume.turnStartMessageIndex ?? runResume.beforeMessageCount;
22443
+ const turnMessages = () => agent.state.messages.slice(turnStartIndex());
22328
22444
  try {
22329
22445
  if (resumedFromSessionRecord) {
22330
22446
  agent.state.messages = shouldPromptAgent ? promptHistoryMessages : existingSessionRecord.piMessages;
@@ -22335,7 +22451,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22335
22451
  if (shouldPromptAgent) runResume.setTurnStartMessageIndex(agent.state.messages.length);
22336
22452
  const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async (setInvokeAgentSpanAttributes) => {
22337
22453
  setAgentSpanAttributes = setInvokeAgentSpanAttributes;
22338
- if (requireAutomationResult && readAutomationResult(agent.state.messages)) return;
22454
+ if (behavior.gated && readTurnAnswer(turnMessages())) return;
22339
22455
  const promptTimestamp = restoredPromptTimestamp ?? Date.now();
22340
22456
  const contextMessage = shouldPromptAgent && promptContextContentParts.length > 0 ? {
22341
22457
  role: "user",
@@ -22440,7 +22556,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22440
22556
  run = shouldPromptAgent && !capacityUpdate ? agent.prompt(freshPromptMessage) : agent.continue();
22441
22557
  discardedRetryUsage = void 0;
22442
22558
  let actionConfirmationRetryUsed = false;
22443
- let automationResultReminderUsed = !requireAutomationResult;
22559
+ let answerReminderUsed = !behavior.gated;
22444
22560
  let providerRetryAttempt = 0;
22445
22561
  let refusalFallbackUsed = false;
22446
22562
  let emptyOutputAttempt = 0;
@@ -22481,12 +22597,12 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22481
22597
  run = agent.continue();
22482
22598
  continue;
22483
22599
  }
22484
- const automationResultReminder = automationResultReminderUsed ? void 0 : remindMissingAutomationResult(agent.state.messages);
22485
- if (automationResultReminder) {
22486
- automationResultReminderUsed = true;
22487
- agent.state.messages = automationResultReminder;
22488
- await runResume.persistSafeBoundary(automationResultReminder);
22489
- logWarn("agent.turn.automation_result.reminded", {});
22600
+ const answerReminder = answerReminderUsed ? void 0 : remindMissingAnswer(agent.state.messages, turnStartIndex());
22601
+ if (answerReminder) {
22602
+ answerReminderUsed = true;
22603
+ agent.state.messages = answerReminder;
22604
+ await runResume.persistSafeBoundary(answerReminder);
22605
+ logWarn("agent.turn.answer.reminded", {});
22490
22606
  run = agent.continue();
22491
22607
  continue;
22492
22608
  }
@@ -22573,7 +22689,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22573
22689
  reasoningLevel,
22574
22690
  assistantUserName: botConfig.userName,
22575
22691
  modelId: activeModelId,
22576
- requireAutomationResult
22692
+ ...behavior.gated ? {
22693
+ answer: readTurnAnswer(turnMessages()) ?? "missing",
22694
+ missingAnswerFails: Boolean(run.dispatch)
22695
+ } : void 0
22577
22696
  })
22578
22697
  };
22579
22698
  } catch (error) {