@sentry/junior 0.287.0 → 0.289.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/{adapter-CL-HUKgd.js → adapter-tE1wnl0T.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BmsPbmO_.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-bvl8U5uH.js} +489 -165
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +628 -238
  8. package/dist/{app-DBY5TnfY.d.ts → app-Cu454FXq.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +550 -71
  11. package/dist/assistant-reply-1N9oxyyb.js +58 -0
  12. package/dist/{automation-DksGNDRO.js → automation-DWbjJltM.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-D36oCldp.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-CV-1qkXa.js} +3 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-BNK4uJVZ.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-CkHcUMN7.js → config-DHAy7XlP.js} +363 -8
  24. package/dist/{connections-BnIj0wtx.js → connections-C3VmH3cf.js} +7 -129
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-CwC8K3RZ.js} +22 -5
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-Bky_veSp.js} +1 -1
  28. package/dist/{credential-sync-CzMar9hq.js → credential-sync-dY9o0YSj.js} +28 -20
  29. package/dist/{db-DJ11eZqq.js → db-BS2Kql3j.js} +81 -46
  30. package/dist/{db-YDKKDxlh.d.ts → db-BebRmhsH.d.ts} +10 -2
  31. package/dist/{executor-BY9TB31g.js → executor-cc4nH86C.js} +125 -18
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BO5zU6Mt.js → logging-CtCJmt9p.js} +3 -2
  34. package/dist/{media-Cz1ZiV1U.js → media-BepyEUNm.js} +5 -1
  35. package/dist/{message-CsUbuEc8.js → message-C5VuRcP9.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +19 -41
  38. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-KRrYUZ35.js} +2 -2
  39. package/dist/{projection-CL_YWeGf.js → projection-BFJG58TG.js} +448 -721
  40. package/dist/{prompt-BHOEQSmf.js → prompt-D15oftoL.js} +5 -5
  41. package/dist/{registry-BriFLnaJ.js → registry-C_JrgqUz.js} +1 -1
  42. package/dist/{resolve-Bt6GgAiA.js → resolve-Cn_7JfP-.js} +3 -3
  43. package/dist/{result-Bo1TZu0Q.js → result-CIbQFLp6.js} +16 -10
  44. package/dist/{runner-D3YeCQgt.js → runner-BwmaMJVO.js} +8 -8
  45. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
  46. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  47. package/dist/{schema-BWE3RJEB.js → schema-Bptz19Ja.js} +72 -14
  48. package/dist/{schema-C6fsEwjo.d.ts → schema-DQaFSkZZ.d.ts} +122 -3
  49. package/dist/{service-account-DiQQuuw7.js → service-account-AGw_pANb.js} +3 -3
  50. package/dist/{service-account-r6fl0b-9.js → service-account-CLZfF8O1.js} +3 -3
  51. package/dist/{session-stop-B2Nut40V.js → session-stop-CbzKf7UI.js} +84 -31
  52. package/dist/{skills-CD5aJdzg.js → skills-CcAJBquq.js} +2 -2
  53. package/dist/{spawn-CalgZQiu.js → spawn-BvAk2vTI.js} +5 -5
  54. package/dist/{stop-kujZLbi0.js → stop-BQU4u7la.js} +893 -519
  55. package/dist/{store-DdIEUL1q.js → store-DE7NJOvQ.js} +4 -16
  56. package/dist/{task-runner-D_RDr2Hu.js → task-runner-Q_7duP_T.js} +31 -27
  57. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-aWZLfUM8.js} +18 -9
  58. package/dist/{validation-K4pqwoVZ.js → validation-BOoPeIJR.js} +1 -1
  59. package/dist/{version-DBvhk1X9.js → version-Db0MFy61.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/{viewer-DrMmFUul.js → viewer-FFEFu9In.js} +4 -4
  62. package/dist/warmup-DDzrA9Gv.js +967 -0
  63. package/dist/{work-ljRoODGu.js → work-BBJK458E.js} +16 -15
  64. package/dist/{worker-CYO1Q0Js.js → worker-2iU5RFyq.js} +7 -31
  65. package/migrations/0089_conversation_paused_status.sql +3 -0
  66. package/migrations/0090_guardian_review_time_index.sql +20 -0
  67. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  68. package/migrations/0092_turn_metric_actor.sql +12 -0
  69. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  70. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  71. package/migrations/meta/0089_snapshot.json +4372 -0
  72. package/migrations/meta/0090_snapshot.json +4388 -0
  73. package/migrations/meta/0091_snapshot.json +4410 -0
  74. package/migrations/meta/0092_snapshot.json +4446 -0
  75. package/migrations/meta/0093_snapshot.json +4446 -0
  76. package/migrations/meta/0094_snapshot.json +4452 -0
  77. package/migrations/meta/_journal.json +42 -0
  78. package/package.json +6 -5
  79. package/dist/assistant-reply-u_PRYzuz.js +0 -65
@@ -1,32 +1,33 @@
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 { $i as postSlackMessage, $t as getUserMessageInstructionText, Ai as hash, An as estimateTextTokens, Ar as requireReviewItemAssignees, B as createPluginAuthOrchestration, Bo as projectConversationEvents, Br as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Ca as isWorkspaceSnapshotNotReadyError, Ci as updateWorkspace, Cn as buildDeterministicTurnId, Cr as updateReviewItemContent, Da as consumeSandboxEgressPermissionDeniedSignal, Di as setWorkspaceSnapshot, Do as saveObjectAnnotations, Dr as canReadReviewItem, E as resolveTaskTitle, Ea as consumeSandboxEgressAuthRequiredSignal, Ei as loadSnapshotsForProfile, Er as canAgentChangeReviewItem, Fa as sleep, Fr as automationCreatorUserId, G as abandonReplacedPendingAuth, Ga as SANDBOX_WORKSPACE_ROOT, Gi as slackMention, Gr as cancelWatch, H as AuthPausePersistenceError, Ha as SANDBOX_DATA_ROOT, Hr as RESOURCE_WATCH_TOOL_SOURCE, Ht as TurnBudgetExceededError, Ia as tryWorkspaceRepoCheckoutPath, Ii as deliverOAuthAuthorization, In as isExperimentalFeatureEnabled, Ir as resolveAssignee, Ja as sandboxSkillPathResolution, Ji as deleteSlackMessage, Jr as createWatch, Jt as CODEMODE_TOOL_NAME, K as canReusePendingAuthLink, Ka as sandboxSkillDir, Kt as createTurnLimitGate, L as upsertConversationMessage, La as workspaceRepoCheckoutPath, Li as formatProviderLabel, Lr as resolveAssignees, M as markConversationMessage, Ma as resolveSandboxCommandEnvironment, Mi as ensureDockerDaemon, Mn as getAgentContextCompactionTriggerTokens, Mo as resolveUserTimezone, N as normalizeConversationText, Ni as getSandboxProvider, Nn as getAgentContextInputLimitTokens, Oa as createSandboxEgressCredentialToken, Oi as setWorkspaceSnapshotBuild, On as calculateContextCompactionTargetTokens, Oo as createPluginAnnotations, P as recordDeliveredAssistantMessage, Pa as SANDBOX_RUNTIME, Pn as getTokenEstimateProfile, Pr as EVERYONE_ASSIGNEE, Qr as listWatches, Qt as getTerminalAssistantMessages, R as createPluginEgress, Ra as PluginToolDeniedError, Rn as createUserTokenStore, Ro as historyItemFromPiMessage, Rr as resolveChannelCapabilities, Sa as getWorkspaceSnapshotNotReadyError, So as matchSlackAttachments, T as fallbackShortTitle, Ta as clearSandboxEgressSignals, Ti as invalidateReadySnapshot, U as AuthorizationFlowDisabledError, Ua as SANDBOX_REPOS_ROOT, Ui as normalizeSlackReplyMarkdown, Ur as STOP_WATCHING_TOOL_NAME, Ut as TurnSliceLimitExceededError, V as authorizationId, Va as SANDBOX_COMMAND_PATH, Vi as escapeSlackMrkdwnText, Vn as getOAuthAccountProviders, Vo as getConfigDefaults, Vr as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, Vt as TURN_LIMIT_WRAP_UP_MESSAGE, W as AuthorizationPauseError, Wa as SANDBOX_SKILLS_ROOT, Wn as createPluginHookRunner, Wt as TurnToolCallLimitExceededError, X as continuableMessages, Xa as buildNonInteractiveShellScript, Xi as openSlackDirectMessage, Xr as findMatchingWatches, Xt as extractAssistantText, Ya as buildCommandScript, Yi as getSlackMessagePermalink, Yn as getPluginTools, Yr as deliverWatch, Yt as persistWithRetry, Z as loadTurnCheckpoint, Za as runNonInteractiveCommand, Zn as getPlugins, Zr as getWatch, Zt as getPiMessageRole, _a as isAbortError, _i as createWorkspace, _n as readParentAgentTask, _r as insertReviewItem, a as loadProjection, aa as SlackActionError, an as isStandaloneRuntimeContextMessage, b as persistConversationMessages, ba as wrapSandboxSetupError, bi as getWorkspaceByName, c as recordAgentsInstructionsUpdated, ci as getDashboardConversationLink, cn as normalizeToolNameFromResult, dn as trimTrailingAssistantMessages, eo as canAccessConversation, et as saveTurnCheckpoint, f as recordAuthorizationRequested, fa as normalizeSlackConversationId, fi as getDashboardTaskLink, fn as REQUEST_CONTEXT_SECTION_TAG, fr as closeReviewItem, g as recordToolExecutionStarted, gi as renderToolResultNudge, gr as getReviewItem, hr as getOpenReviewItemByDedupeKey, i as loadConversationProjection, in as isContinuablePiBoundary, it as getTurnRecord, j as latestConversationMessageSeq, ja as buildSandboxEgressNetworkPolicy, ji as isStale, jn as getAgentBackgroundCompactionMarkTokens, jo as defaultTimezone, jr as requireReviewItemLinks, ki as create, kn as estimateRequestOverheadTokens, kr as readReviewItemAgentScope, l as recordAttachmentsDelivered, la as getSlackClient, ln as retainRuntimeTurnContext, m as recordMcpProviderConnected, ma as withSlackRetries, mi as ToolInputError, mn as TURN_CONTEXT_TAG, mr as dismissOpenReviewItems, na as uploadFilesToConversation, no as readConversationAccessFromSql, oa as downloadPrivateSlackFile, oi as verifyTimerWatchCredentialSubject, on as isToolResultError, p as recordGuardianActionReviewed, pa as runWithSlackInstallationToken, q as clearPendingAuth, qa as sandboxSkillFile, qi as addReactionToMessage, qr as createTimerWatch, qt as isTurnExecutionLimitExceededError, r as loadConnectedMcpProviders, rn as isAssistantMessage, rt as failTurnRecord, sa as getFilePermalink, sn as isToolResultMessage, t as commitAcceptedReply, ta as updateSlackMessage, tn as hasTurnInput, tt as abandonTurnRecord, ua as isConversationScopedChannel, ui as getDashboardReviewItemLink, un as stripRuntimeTurnContext, v as hydrateConversationMessages, va as isAlreadyExistsError, vi as deleteWorkspace, wa as workspaceSnapshotNotReadyUserMessage, wi as WorkspaceValidationError, wr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, xa as WorkspaceSnapshotNotReadyError, xi as listWorkspaces, xr as searchReviewItems, ya as throwSandboxOperationError, yi as getWorkspace, z as PluginCredentialFailureError, zi as resolveBaseUrl, zn as findLegacyWebActorUserId, zo as piMessageFromHistoryItem, zr as getSlackToolContext } from "./projection-CL_YWeGf.js";
3
- import { B as getGatewayApiKey, D as COMPACTION_SUMMARY_PREFIX, E as resolveGatewayModel, F as createProviderError, I as findProviderError, L as getProviderErrorAttributes, M as escapeXml, O as hasCompactedConversationContext, P as ProviderError, V as resolveGatewayCredential, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as unwrapCurrentInstruction, k as isCompactionSummaryText, n as botConfig, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as isProviderRetryError } from "./config-CkHcUMN7.js";
4
- import { B as runWithLogAttributes, C as summarizeMessageText, E as withSpan, K as toOptionalString, S as setTags, T as withLogContext, U as normalizeIdentityEmail, W as isRecord$4, _ 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, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-BO5zU6Mt.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-DF1hW0ja.js";
2
+ import { $ as loadTurnCheckpoint, $a as readConversationAccessFromSql, $t as extractAssistantText, A as latestConversationMessageSeq, Aa as SANDBOX_RUNTIME, Ar as resolveAssignee, B as getAgentContextInputLimitTokens, Ba as SANDBOX_SKILLS_ROOT, Bi as slackMention, Ca as consumeSandboxEgressPermissionDeniedSignal, Ci as setWorkspaceSnapshotBuild, Co as saveObjectAnnotations, Da as buildSandboxEgressNetworkPolicy, Di as ensureDockerDaemon, Dn as findLegacyWebActorUserId, Do as defaultTimezone, Dr as EVERYONE_ASSIGNEE, Ei as isStale, En as createUserTokenStore, Fo as piMessageFromHistoryItem, Fr as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, G as AuthPausePersistenceError, Ga as buildCommandScript, Gi as openSlackDirectMessage, Gr as getWatch, Gt as TurnBudgetExceededError, H as PluginCredentialFailureError, Ha as sandboxSkillDir, Hi as addReactionToMessage, Hr as createWatch, I as upsertConversationMessage, Ii as escapeSlackMrkdwnText, Io as projectConversationEvents, Ir as RESOURCE_WATCH_TOOL_SOURCE, J as abandonReplacedPendingAuth, Ji as postSlackMessage, K as AuthorizationFlowDisabledError, Ka as buildNonInteractiveShellScript, Kr as listWatches, Kt as TurnSliceLimitExceededError, L as calculateContextCompactionTargetTokens, La as SANDBOX_COMMAND_PATH, Ln as getPluginTools, Lo as getConfigDefaults, Lr as STOP_WATCHING_TOOL_NAME, M as normalizeConversationText, Ma as tryWorkspaceRepoCheckoutPath, Mi as formatProviderLabel, Mn as createPluginHookRunner, Mr as resolveChannelCapabilities, N as recordDeliveredAssistantMessage, Na as workspaceRepoCheckoutPath, Nr as getSlackToolContext, Oa as resolveSandboxCommandEnvironment, Oi as getSandboxProvider, Oo as resolveUserTimezone, Or as activeParticipantUserIds, Pa as PluginToolDeniedError, Pi as resolveBaseUrl, Po as historyItemFromPiMessage, Pr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Q as continuableMessages, Qi as uploadFilesToConversation, Qt as persistWithRetry, R as getAgentBackgroundCompactionMarkTokens, Ra as SANDBOX_DATA_ROOT, Ri as normalizeSlackReplyMarkdown, Sa as consumeSandboxEgressAuthRequiredSignal, Si as setWorkspaceSnapshot, Sr as requireReviewItemLinks, T as resolveTaskTitle, Ti as hash, U as createPluginAuthOrchestration, Ua as sandboxSkillFile, Ui as deleteSlackMessage, Ur as deliverWatch, V as createPluginEgress, Va as SANDBOX_WORKSPACE_ROOT, Vr as createTimerWatch, W as authorizationId, Wa as sandboxSkillPathResolution, Wi as getSlackMessagePermalink, Wr as findMatchingWatches, Wt as TURN_LIMIT_WRAP_UP_MESSAGE, X as clearPendingAuth, Xa as canAccessConversation, Xt as isTurnExecutionLimitExceededError, Y as canReusePendingAuthLink, Yt as createTurnLimitGate, Zi as updateSlackMessage, Zt as CODEMODE_TOOL_NAME, _a as WorkspaceSnapshotNotReadyError, _n as TURN_CONTEXT_TAG, _r as canReadReviewItem, a as loadProjection, aa as getSlackClient, ar as getOpenReviewItemByDedupeKey, at as failTurnRecord, b as persistConversationMessages, ba as workspaceSnapshotNotReadyUserMessage, bi as invalidateReadySnapshot, bn as readParentAgentTask, br as readReviewItemAgentScope, c as recordAgentsInstructionsUpdated, ca as normalizeSlackConversationId, cn as isStandaloneRuntimeContextMessage, di as renderToolResultNudge, dn as normalizeToolNameFromResult, dr as searchReviewItems, ei as verifyTimerWatchCredentialSubject, en as getPiMessageRole, f as recordAuthorizationRequested, fi as createWorkspace, fn as retainRuntimeTurnContext, g as recordToolExecutionStarted, ga as wrapSandboxSetupError, gi as listWorkspaces, gr as canAgentChangeReviewItem, ha as throwSandboxOperationError, hi as getWorkspaceByName, hn as REQUEST_CONTEXT_SECTION_TAG, i as loadConversationProjection, ii as getDashboardReviewItemLink, in as hasTurnInput, ir as dismissOpenReviewItems, j as markConversationMessage, ja as sleep, ji as deliverOAuthAuthorization, jr as resolveAssignees, kn as getOAuthAccountProviders, kr as automationCreatorUserId, l as recordAttachmentsDelivered, la as runWithSlackInstallationToken, li as ToolInputError, ln as isToolResultError, m as recordMcpProviderConnected, ma as isAlreadyExistsError, mi as getWorkspace, mn as trimTrailingAssistantMessages, mr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, na as downloadPrivateSlackFile, ni as getDashboardConversationLink, nn as getUserMessageInstructionText, nr as closeReviewItem, nt as saveTurnCheckpoint, oa as isConversationScopedChannel, oi as getDashboardTaskLink, on as isAssistantMessage, or as getReviewItem, ot as getTurnRecord, p as recordGuardianActionReviewed, pa as isAbortError, pi as deleteWorkspace, pn as stripRuntimeTurnContext, pr as updateReviewItemContent, q as AuthorizationPauseError, qa as runNonInteractiveCommand, qt as TurnToolCallLimitExceededError, r as loadConnectedMcpProviders, ra as getFilePermalink, rt as abandonTurnRecord, sn as isContinuablePiBoundary, sr as insertReviewItem, t as commitAcceptedReply, ta as SlackActionError, tn as getTerminalAssistantMessages, ua as withSlackRetries, un as isToolResultMessage, v as hydrateConversationMessages, va as getWorkspaceSnapshotNotReadyError, vi as updateWorkspace, vo as matchSlackAttachments, w as fallbackShortTitle, wa as createSandboxEgressCredentialToken, wi as create, wo as createPluginAnnotations, xa as clearSandboxEgressSignals, xi as loadSnapshotsForProfile, xr as requireReviewItemAssignees, ya as isWorkspaceSnapshotNotReadyError, yi as WorkspaceValidationError, z as getAgentContextCompactionTriggerTokens, za as SANDBOX_REPOS_ROOT, zn as getPlugins, zr as cancelWatch } from "./projection-BFJG58TG.js";
3
+ import { A as estimateTextTokens, B as createProviderError, D as requestPrefixAttributes, E as resolveGatewayModel, G as getGatewayApiKey, H as getProviderErrorAttributes, I as unwrapCurrentInstruction, K as resolveGatewayCredential, L as escapeXml, M as COMPACTION_SUMMARY_PREFIX, N as hasCompactedConversationContext, O as estimateMessagesTokens, P as isCompactionSummaryText, V as findProviderError, W as isProviderRetryError, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as textCharsForTokens, k as estimateRequestOverheadTokens, n as botConfig, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME, z as ProviderError } from "./config-DHAy7XlP.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-CtCJmt9p.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-Bky_veSp.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 { B as touchConversationDetail, D as resolveActorIdentityId, G as hasAgentTurnUsage, H as agentTurnCostUsd, J as parseDestination, K as resolveRootConversationId$1, R as conversationDetailTouch, T as SYSTEM_IDENTITY_ID, V as addAgentTurnUsage, X as sameDestination, _ as setArchivedAt, a as getConversationStore, c as conversationIdsWithAnnotation, g as readConversationTrees, h as conversationDescendants, i as getConversationMessageSearchStore, l as hasAnnotationKey, m as conversationAncestors, o as getDb, r as getConversationEventStore, s as getSqlExecutor, u as treeHasAnnotationKey, x as conversationKindFromRow, z as nextDetailVersion } from "./db-DJ11eZqq.js";
8
- import { A as juniorConversations, C as isUserInstruction, 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-BY9TB31g.js";
9
- import { _ as instructionProvenanceFor, a as KNOWN_CONVERSATION_EVENT_TYPES, g as instructionActors, h as contextProvenance, r as detectImageMediaType, v as sameActorIdentity } from "./media-Cz1ZiV1U.js";
7
+ import { $ as sameDestination, B as addAgentTurnUsage, D as resolveActorIdentityId, G as resolveRootConversationId$1, J as nextDetailVersion, T as SYSTEM_IDENTITY_ID, V as agentTurnCostUsd, W as hasAgentTurnUsage, Y as touchConversationDetail, Z as parseDestination, _ as setArchivedAt, a as getConversationStore, c as conversationIdsWithAnnotation, g as readConversationTrees, h as conversationDescendants, i as getConversationMessageSearchStore, l as hasAnnotationKey, m as conversationAncestors, o as getDb, q as conversationDetailTouch, r as getConversationEventStore, s as getSqlExecutor, u as treeHasAnnotationKey, x as conversationKindFromRow } from "./db-BS2Kql3j.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-cc4nH86C.js";
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-BriFLnaJ.js";
12
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BCIuBe4d.js";
13
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CD5aJdzg.js";
14
- import { l as completeObject, o as isEventConversationMessage, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-BHOEQSmf.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-C_JrgqUz.js";
12
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BNK4uJVZ.js";
13
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CcAJBquq.js";
14
+ import { l as completeObject, o as isEventConversationMessage, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-D15oftoL.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-DrMmFUul.js";
17
- import { r as getStateAdapter } from "./adapter-CL-HUKgd.js";
18
- import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-BTp__wrw.js";
19
- import { B as readMessageAttachments, F as removedCardSchema, H as briefLinkSchema, U as briefOutcomeStatusSchema, q as parseStoredBrief } from "./conversation-E7ZPJx2H.js";
20
- 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, 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-B5nV1Er-.js";
21
- import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-u_PRYzuz.js";
22
- 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 readBlockedReport, b as conversationSubtree, c as loadReviewItemInput, d as getAuthPausedConversationTurnId, dt as readAutomationResult, f as getEventBatchDelayMs, ft as remindMissingAutomationResult, it as REPORT_BLOCKED_TOOL_NAME, nt as addConversationNote, ot as FINISH_AUTOMATION_RUN_TOOL_NAME, p as listActiveMailboxTurns, r as markConversationsStopped, rt as JUNIOR_PERSONALITY, s as eventReviewItemInputs, st as automationResultSchema$1, t as getConversationStoppedAtMs, tt as saveUserCustomization, v as turnInputFactsFromConversationMessage, w as eventBatchMessageMeta, x as conversationSubtreeColumns, y as legacyWebMailboxMetadataSchema } from "./session-stop-B2Nut40V.js";
16
+ import { a as readActorIdentityFromSql, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity } from "./viewer-FFEFu9In.js";
17
+ import { r as getStateAdapter } from "./adapter-tE1wnl0T.js";
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-CwC8K3RZ.js";
20
+ import { i as createCacheWarmingRecorder, l as readLastUserMessageAtByConversation } from "./warmup-DDzrA9Gv.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-D36oCldp.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-aWZLfUM8.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-1N9oxyyb.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, ht as remindMissingAutomationResult, lt as FINISH_AUTOMATION_RUN_TOOL_NAME, mt as readAutomationResult, ot as JUNIOR_PERSONALITY, p as listActiveMailboxTurns, 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-CbzKf7UI.js";
23
25
  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";
24
- import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-Bt6GgAiA.js";
25
- import { S as getTurnRequestDeadline, _ as getVercelConversationWorkQueue, b as QUEUE_SIGNATURE_MAX_AGE_MS, h as sendWorkspaceSnapshotJob, m as sendNextWorkspaceSnapshotJob, n as backgroundCompactionId } from "./background-compaction-queue-CYI909P5.js";
26
- import { O as stopConversationWork, _ as getConversationWorkState, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-DdIEUL1q.js";
27
- import { $ as readAutomationExecutionByConversationId, At as registeredEventTriggerProblems, B as setEventAutomationStatus, C as deleteScheduledAutomation, Ct as describeRegisteredEventTrigger, D as saveScheduledAutomation, Dt as eventWatchUnavailable, E as readScheduledAutomation, Et as eventNamespaceSchema, G as listAutomationVersions, I as getEventAutomation, K as readAutomationVersion, L as listDeletedEventAutomationsCreatedBy, Mt as registeredResourceTypeSchema, N as createEventAutomation, Nt as requireEventIdentifier, Ot as hasEventCatalogEntries, P as deleteEventAutomation, Pt as requireValidEventTrigger, R as parseEventAutomationRow, S as createScheduledAutomation, St as automationEventCatalog, T as parseScheduledAutomationRow, U as automationDefinition, X as requireAutomationRevision, Y as automationRevision, Z as emptyAutomationRunWindows, _t as getPersistedThreadState, at as readAutomationExecutions, bt as coerceThreadConversationState, d as getDispatchRecord, et as readAutomationExecutionDays, gt as getPersistedSandboxState, it as readAutomationExecutionSummaries, jt as registeredEventTypeSchema, kt as registeredEventMatchSchema, l as getDispatchIdForConversation, n as scheduleSessionCompletedPluginTasks, nt as readAutomationExecutionStatusDays, ot as readAutomationRuns, pt as resolveConversationRouting, q as sameDefinitionValue, rt as readAutomationExecutionStatusHours, t as processPluginTask, tt as readAutomationExecutionHours, u as getDispatchInputMessageId, yt as persistThreadStateById, z as saveEventAutomation } from "./task-runner-D_RDr2Hu.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-DiQQuuw7.js";
29
- import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-DksGNDRO.js";
26
+ import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-Cn_7JfP-.js";
27
+ import { S as requestConversationWork, T as stopConversationWork, g as getConversationWorkState, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-DE7NJOvQ.js";
28
+ import { $ as readAutomationExecutionByConversationId, At as registeredResourceTypeSchema, B as setEventAutomationStatus, C as deleteScheduledAutomation, D as saveScheduledAutomation, Dt as registeredEventMatchSchema, E as readScheduledAutomation, Et as hasEventCatalogEntries, G as listAutomationVersions, I as getEventAutomation, K as readAutomationVersion, L as listDeletedEventAutomationsCreatedBy, Mt as requireValidEventTrigger, N as createEventAutomation, Ot as registeredEventTriggerProblems, P as deleteEventAutomation, R as parseEventAutomationRow, S as createScheduledAutomation, T as parseScheduledAutomationRow, Tt as eventWatchUnavailable, U as automationDefinition, X as requireAutomationRevision, Y as automationRevision, Z as emptyAutomationRunWindows, _t as persistThreadStateById, at as readAutomationExecutions, bt as automationEventCatalog, d as getDispatchRecord, dt as resolveConversationRouting, et as readAutomationExecutionDays, ft as resolveTurnSessionRouting, ht as getPersistedThreadState, it as readAutomationExecutionSummaries, jt as requireEventIdentifier, kt as registeredEventTypeSchema, l as getDispatchIdForConversation, mt as getPersistedSandboxState, n as scheduleSessionCompletedPluginTasks, nt as readAutomationExecutionStatusDays, ot as readAutomationRuns, q as sameDefinitionValue, rt as readAutomationExecutionStatusHours, t as processPluginTask, tt as readAutomationExecutionHours, u as getDispatchInputMessageId, vt as coerceThreadConversationState, wt as eventNamespaceSchema, xt as describeRegisteredEventTrigger, z as saveEventAutomation } from "./task-runner-Q_7duP_T.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-AGw_pANb.js";
30
+ import { A as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, D as taskOutcomeInputSchema, E as automationTitleSchema, F as scheduleIntentFromTool, I as toolScheduleIntentSchema, L as weekdaySchema, N as ScheduleIntentError, P as compileScheduleIntent, T as automationInstructionToolSchema, k as eventAutomationTriggerSchema, l as automationListQuerySchema } from "./automation-DWbjJltM.js";
30
31
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
31
32
  import { streamSimple } from "@earendil-works/pi-ai/compat";
32
33
  import { createGatewayProvider } from "@ai-sdk/gateway";
@@ -39,7 +40,7 @@ import * as z from "zod";
39
40
  import { and, asc, count, desc, eq, exists, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, notExists, notInArray, or, sql } from "drizzle-orm";
40
41
  import { PluginToolInputError, agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, eventMatchFieldSchema, eventSchema, eventTriggerText, localDestinationSchema, missingToolAnnotationKeys, ownedObjectAnnotationSchema, sourceSchema, stableEventMatchKey, watchResultSchema } from "@sentry/junior-plugin-api";
41
42
  import { alias } from "drizzle-orm/pg-core";
42
- import { Agent, estimateContextTokens, estimateTokens } from "@earendil-works/pi-agent-core";
43
+ import { Agent, estimateContextTokens } from "@earendil-works/pi-agent-core";
43
44
  import fs from "node:fs/promises";
44
45
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
45
46
  import http from "node:http";
@@ -698,6 +699,7 @@ function buildChatEndAttributes(message, mode) {
698
699
  if (outputMessages) attributes["gen_ai.output.messages"] = outputMessages;
699
700
  }
700
701
  Object.assign(attributes, extractGenAiUsageAttributes(message));
702
+ if (message.usage.cacheWrite1h !== void 0) attributes["app.ai.usage.cache_write_1h"] = message.usage.cacheWrite1h;
701
703
  if (message.stopReason) attributes["gen_ai.response.finish_reasons"] = [normalizeGenAiFinishReason(message.stopReason)];
702
704
  if (message.model) attributes["gen_ai.response.model"] = message.model;
703
705
  if (message.responseId) attributes["gen_ai.response.id"] = message.responseId;
@@ -753,6 +755,17 @@ function traceResponseHeaders(span, options) {
753
755
  }
754
756
  };
755
757
  }
758
+ function traceRequestPayload(span, options) {
759
+ const onPayload = options?.onPayload;
760
+ return {
761
+ ...options,
762
+ onPayload: async (payload, model) => {
763
+ const nextPayload = await onPayload?.(payload, model);
764
+ span.setAttributes(requestPrefixAttributes(nextPayload ?? payload));
765
+ return nextPayload;
766
+ }
767
+ };
768
+ }
756
769
  function relayStream(source, onEvent) {
757
770
  const relayed = createAssistantMessageEventStream();
758
771
  const finished = (async () => {
@@ -796,7 +809,7 @@ function createTracedStreamFn(baseOrOptions = streamSimple) {
796
809
  });
797
810
  try {
798
811
  const requestStartedAtMs = Date.now();
799
- const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, traceResponseHeaders(span, options))));
812
+ const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, traceRequestPayload(span, traceResponseHeaders(span, options)))));
800
813
  const responseTiming = createResponseTiming(requestStartedAtMs);
801
814
  const relay = relayStream(stream, responseTiming.observe);
802
815
  relay.finished.then(() => stream.result()).then((finalMessage) => {
@@ -853,7 +866,9 @@ function buildTurnResult(input) {
853
866
  const rawPrimaryText = sanitizeAssistantText(terminalAssistantMessages.map((message) => extractAssistantText(message)).join("\n\n")).trim();
854
867
  const primaryText = terminalAssistantMessages.map((message) => decideReply(message)).filter((output) => output.kind === "deliver").map((output) => output.text).join("\n\n");
855
868
  const terminalTexts = terminalAssistantMessages.map((message) => sanitizeAssistantText(extractAssistantText(message)));
856
- const noReplyRequested = !primaryText && terminalTexts.some((text) => isNoReplyMarker(text)) && terminalTexts.every((text) => !text || isNoReplyMarker(text));
869
+ const legacyMarkerOnly = terminalTexts.some((text) => isLegacyNoReplyMarker(text)) && terminalTexts.every((text) => !text || isLegacyNoReplyMarker(text));
870
+ const noReply = primaryText ? void 0 : readNoReply(newMessages) ?? (legacyMarkerOnly ? {} : void 0);
871
+ const noReplyRequested = Boolean(noReply);
857
872
  const toolErrorCount = toolResults.filter((result) => result.isError).length;
858
873
  const reactionPerformed = toolResults.some((result) => !isToolResultError(result) && normalizeToolNameFromResult(result) === "addReaction");
859
874
  const completedWithoutTerminalText = noReplyRequested;
@@ -861,14 +876,10 @@ function buildTurnResult(input) {
861
876
  const stopReason = typeof lastAssistant?.stopReason === "string" ? lastAssistant.stopReason : void 0;
862
877
  const errorMessage = typeof lastAssistant?.errorMessage === "string" ? lastAssistant.errorMessage : void 0;
863
878
  const isProviderError = stopReason === "error";
864
- if (noReplyRequested) {
865
- const markerAttributes = {
866
- "app.ai.no_reply_marker": true,
867
- "app.ai.no_reply_marker_category": reactionPerformed ? "reaction" : "none",
868
- "app.ai.no_reply_marker_accepted": !isProviderError
869
- };
870
- if (!isProviderError) logInfo("ai.no_reply_marker.accepted", markerAttributes);
871
- }
879
+ if (noReplyRequested && !isProviderError) logInfo("ai.no_reply.accepted", {
880
+ "app.ai.no_reply.category": reactionPerformed ? "reaction" : "none",
881
+ "app.ai.no_reply.legacy_marker": legacyMarkerOnly
882
+ });
872
883
  if (!primaryText && !completedWithoutTerminalText && !blocked && !isProviderError) logWarn("ai.model_response.empty", {
873
884
  "app.ai.tool_results": toolResults.length,
874
885
  "app.ai.tool_error_results": toolErrorCount,
@@ -892,6 +903,7 @@ function buildTurnResult(input) {
892
903
  return {
893
904
  text: primaryText,
894
905
  ...blocked ? { blocked } : void 0,
906
+ ...noReply ? { noReply } : void 0,
895
907
  sandboxRef,
896
908
  piMessages: input.piMessages,
897
909
  diagnostics: buildDiagnostics(input, {
@@ -3715,13 +3727,18 @@ function createSandbox(options) {
3715
3727
  const timeoutMs = positiveInteger$1(rawInput.timeoutMs);
3716
3728
  logSandboxBootRequest("tool.bash", { "app.sandbox.command_length": command.length });
3717
3729
  let tools = await runtime.tools(context.signal);
3730
+ const waitStartedAtMs = Date.now();
3718
3731
  const bashTurn = await takeBashTurn();
3732
+ const waitMs = Date.now() - waitStartedAtMs;
3719
3733
  try {
3720
3734
  context.signal?.throwIfAborted();
3721
3735
  if (bashTurn.waited) tools = await runtime.tools(context.signal);
3722
3736
  const { bash: executeBash, sessionId: activeSessionId } = tools;
3723
3737
  await clearEgressSignals(activeSessionId);
3724
- const result = await withSandboxToolSpan("bash", "process.exec", { "process.executable.name": "bash" }, async () => {
3738
+ const result = await withSandboxToolSpan("bash", "process.exec", {
3739
+ "process.executable.name": "bash",
3740
+ "app.sandbox.bash.wait_ms": waitMs
3741
+ }, async () => {
3725
3742
  const response = await executeBash({
3726
3743
  command,
3727
3744
  cwd,
@@ -3740,6 +3757,7 @@ function createSandbox(options) {
3740
3757
  return response;
3741
3758
  });
3742
3759
  const { authRequired, permissionDenied } = await consumeEgressSignals(activeSessionId);
3760
+ if (!authRequired && `${result.stdout ?? ""}${result.stderr ?? ""}`.includes(`junior-auth-required provider=`)) logWarn("sandbox.egress.auth_signal.missing", { "app.sandbox.egress_id": activeSessionId });
3743
3761
  return formatSandboxCommandResult({
3744
3762
  ok: result.exitCode === 0,
3745
3763
  command,
@@ -4320,7 +4338,6 @@ function createAgentSandbox(options) {
4320
4338
  // src/chat/mcp/tool-manager.ts
4321
4339
  const MAX_TOOL_RESULT_TOKENS = 1e4;
4322
4340
  const MAX_TOOL_RESULT_BYTES = 32768;
4323
- const CHARS_PER_ESTIMATED_TOKEN = 4;
4324
4341
  function normalizeMcpToolName(provider, toolName) {
4325
4342
  return `mcp__${provider}__${toolName}`;
4326
4343
  }
@@ -4416,10 +4433,10 @@ function suffixWithin(value, maxChars, maxBytes) {
4416
4433
  function boundMcpContent(content) {
4417
4434
  const text = content.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
4418
4435
  const originalBytes = utf8Bytes(text);
4419
- const originalTokens = Math.ceil(text.length / CHARS_PER_ESTIMATED_TOKEN);
4436
+ const originalTokens = estimateTextTokens(text);
4420
4437
  if (originalTokens <= MAX_TOOL_RESULT_TOKENS && originalBytes <= MAX_TOOL_RESULT_BYTES) return content;
4421
4438
  const warning = `\n\nWarning: truncated output (original token count: ${originalTokens}; original bytes: ${originalBytes})\n\n`;
4422
- const remainingChars = MAX_TOOL_RESULT_TOKENS * CHARS_PER_ESTIMATED_TOKEN - warning.length;
4439
+ const remainingChars = textCharsForTokens(MAX_TOOL_RESULT_TOKENS) - warning.length;
4423
4440
  const remainingBytes = MAX_TOOL_RESULT_BYTES - utf8Bytes(warning);
4424
4441
  const head = prefixWithin(text, Math.ceil(remainingChars / 2), Math.ceil(remainingBytes / 2));
4425
4442
  return [{
@@ -5879,9 +5896,9 @@ const spawnAgentOutputSchema = juniorToolOutputSchema.extend({
5879
5896
  function createSpawnAgentTool(spawnAgent, titleCost) {
5880
5897
  return zodTool({
5881
5898
  description: [
5882
- "Start a new asynchronous child agent on a delegated task. A child agent has its own sandbox and tool budget, runs at the same time as you, and sends back only its result. Use child agents to run independent work in parallel and to keep long investigations out of your context.",
5883
- "Delegate 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).",
5884
- "Do it yourself 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.",
5899
+ "Start a new asynchronous child agent. A child agent has its own sandbox and tool budget, runs at the same time as you, and sends back only its result. Its kind is a Thread for one discrete work item that people will own and talk to, or a Task for work that you delegate. Use Tasks to run independent work in parallel and to keep long investigations out of your context.",
5900
+ "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).",
5901
+ "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.",
5885
5902
  `Pick agent_type when one fits; omit it for a fresh general-purpose child with your tools:\n${formatAgentTypes()}`,
5886
5903
  "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.",
5887
5904
  "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.",
@@ -5898,9 +5915,9 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
5898
5915
  },
5899
5916
  inputSchema: z.object({
5900
5917
  task: z.string().trim().min(1).describe("Self-contained brief. Unless its agent type starts with this conversation's history, the child has not seen this thread, so this is its only context. Brief it like a capable peer who just joined: the goal and why it matters; target repos, refs, paths, and URLs; facts you already verified and what you ruled out; constraints, including which remote side effects are allowed (scratch work in its sandbox is always fine); what counts as done; and the shape and length of the result to return. Do the synthesis yourself: name the exact question, files, or change instead of writing 'based on your findings, fix it'. If you cannot write a clear brief, you do not understand the task well enough to delegate it. Summarize thread facts instead of pasting the thread."),
5901
- title: z.string().trim().min(1).max(60).nullable().optional().describe("Optional short display title for the task. Omit to generate one from the task."),
5918
+ title: z.string().trim().min(1).max(60).nullable().optional().describe("Optional short display title of the child and its Conversation. Pass one to skip title generation; omit it to generate one from the task."),
5902
5919
  name: agentNameSchema.refine((name) => name !== PARENT_AGENT_TARGET, { message: `"${PARENT_AGENT_TARGET}" is reserved` }).nullable().optional().describe("New child-agent name that messageAgent can address, or omit for a one-off agent"),
5903
- kind: z.enum(CHILD_AGENT_KINDS).nullable().optional().describe("thread: people can open and message the child directly, like a conversation of its own. Pick it for long-lived work that people will want to follow, steer, or talk to. task (default; omit or pass null): background work that only you message."),
5920
+ kind: z.enum(CHILD_AGENT_KINDS).nullable().optional().describe("thread: one discrete work item, about the size of one issue or code change, that people can open, message, and steer directly, like a conversation of its own. A request to create or start a thread means this kind, not a Slack thread. Also pick it for long-lived work that people will follow or steer. Share its dashboard_url so people can find it. task (default; omit or pass null): background work that only you message."),
5904
5921
  agent_type: z.enum(AGENT_TYPES).nullable().optional().describe("Child agent type from the list in this tool's description. Omit or pass null for a fresh general-purpose child."),
5905
5922
  reasoning_level: z.enum(TURN_REASONING_LEVELS).nullable().optional().describe("Optional reasoning level for this delegated task only")
5906
5923
  }).strict(),
@@ -5941,10 +5958,38 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
5941
5958
  }
5942
5959
  });
5943
5960
  }
5961
+ // src/chat/conversations/delivery-pause.ts
5962
+ /** True when the Conversation is a root that delivers to a Location. */
5963
+ function canPauseConversationDelivery(conversation) {
5964
+ return conversation.kind === "root" && conversation.location !== void 0;
5965
+ }
5966
+ const rootConversation = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId));
5967
+ /**
5968
+ * Stop Delivery of a root's Event Turn replies to its Location. Returns false
5969
+ * when Delivery was already paused or the root does not exist.
5970
+ */
5971
+ async function pauseConversationDelivery(conversationId) {
5972
+ return (await getSqlExecutor().db().update(juniorConversations).set({
5973
+ deliveryPausedAt: /* @__PURE__ */ new Date(),
5974
+ detailVersion: nextDetailVersion
5975
+ }).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
5976
+ }
5977
+ /** Deliver a root's Event Turn replies to its Location again. */
5978
+ async function resumeConversationDelivery(conversationId) {
5979
+ await getSqlExecutor().db().update(juniorConversations).set({
5980
+ deliveryPausedAt: null,
5981
+ detailVersion: nextDetailVersion
5982
+ }).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
5983
+ }
5984
+ /** True while a root's Event Turn replies stay out of its Location. */
5985
+ async function isConversationDeliveryPaused(conversationId) {
5986
+ const [row] = await getSqlExecutor().db().select({ pausedAt: juniorConversations.deliveryPausedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
5987
+ return Boolean(row?.pausedAt);
5988
+ }
5944
5989
  // src/chat/conversations/web-authorization.ts
5945
5990
  const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
5946
5991
  const WEB_AUTHORIZATION_TTL_MS = 864e5;
5947
- function authorizationKey(conversationId, actorId) {
5992
+ function authorizationKey$1(conversationId, actorId) {
5948
5993
  return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
5949
5994
  }
5950
5995
  /** Build authorization delivery for one web turn. */
@@ -5952,7 +5997,7 @@ function createWebAuthorization(args) {
5952
5997
  return {
5953
5998
  createState: async () => randomUUID(),
5954
5999
  deliver: async (request) => {
5955
- await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
6000
+ await getStateAdapter().set(authorizationKey$1(args.conversationId, args.actorId), JSON.stringify({
5956
6001
  ...request,
5957
6002
  ...args
5958
6003
  }), WEB_AUTHORIZATION_TTL_MS);
@@ -5961,7 +6006,7 @@ function createWebAuthorization(args) {
5961
6006
  }
5962
6007
  /** Read the pending authorization request for one web actor. */
5963
6008
  async function getWebAuthorization(args) {
5964
- const value = await getStateAdapter().get(authorizationKey(args.conversationId, args.actorId));
6009
+ const value = await getStateAdapter().get(authorizationKey$1(args.conversationId, args.actorId));
5965
6010
  if (typeof value !== "string") return void 0;
5966
6011
  try {
5967
6012
  const parsed = JSON.parse(value);
@@ -5973,7 +6018,7 @@ async function getWebAuthorization(args) {
5973
6018
  }
5974
6019
  /** Remove a web authorization request after the parked turn continues. */
5975
6020
  async function deleteWebAuthorization(args) {
5976
- await getStateAdapter().delete(authorizationKey(args.conversationId, args.actorId));
6021
+ await getStateAdapter().delete(authorizationKey$1(args.conversationId, args.actorId));
5977
6022
  }
5978
6023
  // src/chat/task-execution/assistant-message.ts
5979
6024
  /** Store one assistant Message and its Agent history. */
@@ -6152,6 +6197,183 @@ async function finishTurn(conversationId, turnId, saved) {
6152
6197
  outcome: saved.outcome
6153
6198
  });
6154
6199
  }
6200
+ // src/chat/task-execution/attempt-selection.ts
6201
+ function inputOwner(message) {
6202
+ return {
6203
+ authorId: message.input.authorId,
6204
+ identityId: message.input.authorIdentityId,
6205
+ source: message.source
6206
+ };
6207
+ }
6208
+ function turnOwner(turn) {
6209
+ return {
6210
+ authorId: isUserActor(turn.actor) ? turn.actor.userId : void 0,
6211
+ identityId: turn.actorIdentityId,
6212
+ source: turn.source?.kind
6213
+ };
6214
+ }
6215
+ /**
6216
+ * One Turn has one Actor and one Source: it runs with that Actor's
6217
+ * credentials, so input from anyone else must not join it. Every value that
6218
+ * both sides know must match, and they must share an Identity id or an author
6219
+ * id. Input with no known author matches nothing.
6220
+ */
6221
+ function hasSameOwner(a, b) {
6222
+ if (a.source && b.source && a.source !== b.source) return false;
6223
+ const sameIdentity = a.identityId && b.identityId ? a.identityId === b.identityId : void 0;
6224
+ const sameAuthor = a.authorId && b.authorId ? a.authorId === b.authorId : void 0;
6225
+ return sameIdentity !== false && sameAuthor !== false && (sameIdentity ?? sameAuthor) === true;
6226
+ }
6227
+ /** True when two Inbound messages may share one Turn. */
6228
+ function canShareTurn(a, b) {
6229
+ return hasSameOwner(inputOwner(a), inputOwner(b));
6230
+ }
6231
+ /** True when an Inbound message may join `turn`. */
6232
+ function canJoinTurn(turn, message) {
6233
+ return hasSameOwner(turnOwner(turn), inputOwner(message));
6234
+ }
6235
+ function selectContiguousTurnBatch(messages) {
6236
+ const first = messages[0];
6237
+ if (!first) return [];
6238
+ const nextTurnIndex = messages.findIndex((message, index) => index > 0 && !canShareTurn(first, message));
6239
+ return messages.slice(0, nextTurnIndex === -1 ? messages.length : nextTurnIndex);
6240
+ }
6241
+ /**
6242
+ * True when an interrupt can start its own attempt.
6243
+ *
6244
+ * A steered web message must not start a second Turn while a yielded Turn
6245
+ * waits to resume. It stays pending for that Turn's drain or the next attempt.
6246
+ */
6247
+ function isAttemptInterrupt(message, work) {
6248
+ return message.delivery === "interrupt" && !(work.execution.status === "paused" && message.source === "web");
6249
+ }
6250
+ /** Prioritize interrupts while keeping each attempt to one Actor and Source. */
6251
+ function selectAttemptMessages(work) {
6252
+ const messages = work.messages;
6253
+ const interrupts = messages.filter((message) => isAttemptInterrupt(message, work));
6254
+ if (interrupts.length > 0) return selectContiguousTurnBatch(interrupts);
6255
+ if (work.execution.status === "paused") return [];
6256
+ const nonEventMessages = messages.filter((message) => message.source !== "event");
6257
+ return selectContiguousTurnBatch(nonEventMessages.length > 0 ? nonEventMessages : messages);
6258
+ }
6259
+ // src/chat/task-execution/authorized-turn.ts
6260
+ /**
6261
+ * OAuth callbacks save readiness, not agent history. The conversation worker
6262
+ * consumes this event under its lease before it resumes the paused Turn.
6263
+ */
6264
+ const authorizationSchema = z.object({
6265
+ kind: z.enum(["mcp", "plugin"]),
6266
+ provider: z.string().min(1),
6267
+ actorId: z.string().min(1),
6268
+ authorizationId: z.string().min(1),
6269
+ authSessionId: z.string().optional(),
6270
+ scope: z.string().optional(),
6271
+ configuration: z.record(z.string(), z.unknown()).optional(),
6272
+ toolChannelId: z.string().optional()
6273
+ });
6274
+ function authorizationKey(turn) {
6275
+ return `turn:${turn.turnId}:authorization:${turn.version}`;
6276
+ }
6277
+ /** Save authorization for this parked boundary without changing model history. */
6278
+ async function recordTurnAuthorization(args) {
6279
+ const turn = await getTurnRecord(args.conversationId, args.turnId);
6280
+ if (!turn || turn.state !== "paused" || turn.resumeReason !== "auth") return;
6281
+ await getConversationEventStore().append(args.conversationId, [{
6282
+ idempotencyKey: authorizationKey(turn),
6283
+ createdAtMs: Date.now(),
6284
+ data: {
6285
+ type: "structured_event",
6286
+ namespace: "junior",
6287
+ name: "turn_authorized",
6288
+ version: 1,
6289
+ turnId: turn.turnId,
6290
+ content: authorizationSchema.parse(args)
6291
+ }
6292
+ }], { activity: "preserve" });
6293
+ return {
6294
+ conversationId: args.conversationId,
6295
+ destination: args.destination,
6296
+ turnId: turn.turnId,
6297
+ expectedVersion: turn.version
6298
+ };
6299
+ }
6300
+ /** Read authorization for the exact pause; a later auth pause needs its own callback. */
6301
+ async function getTurnAuthorization(turn) {
6302
+ const event = await getConversationEventStore().loadByIdempotencyKey(turn.conversationId, authorizationKey(turn));
6303
+ if (event?.data.type !== "structured_event") return void 0;
6304
+ return authorizationSchema.parse(event.data.content);
6305
+ }
6306
+ // src/chat/task-execution/turn-wake.ts
6307
+ /** Build the worker input for a paused turn. */
6308
+ async function getPausedTurnRequest(args) {
6309
+ const turn = (await loadTurnCheckpoint({
6310
+ conversationId: args.conversationId,
6311
+ turnId: args.turnId
6312
+ })).record;
6313
+ if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
6314
+ let routing;
6315
+ try {
6316
+ routing = await resolveTurnSessionRouting({
6317
+ conversationId: args.conversationId,
6318
+ conversationStore: args.conversationStore
6319
+ });
6320
+ } catch (error) {
6321
+ await failTurnRecord({
6322
+ conversationId: args.conversationId,
6323
+ expectedVersion: turn.version,
6324
+ turnId: args.turnId,
6325
+ errorMessage: error instanceof Error ? error.message : String(error)
6326
+ });
6327
+ return;
6328
+ }
6329
+ return {
6330
+ conversationId: args.conversationId,
6331
+ destination: routing.destination,
6332
+ turnId: args.turnId,
6333
+ expectedVersion: turn.version,
6334
+ traceContext: turn.traceContext
6335
+ };
6336
+ }
6337
+ /** Wake the conversation worker for a paused turn. */
6338
+ async function wakePausedTurn(request, options = {}) {
6339
+ const nowMs = options.nowMs ?? Date.now();
6340
+ const conversation = await (options.conversationStore ?? getConversationStore()).get({ conversationId: request.conversationId });
6341
+ await requestConversationWork({
6342
+ conversationId: request.conversationId,
6343
+ destination: conversation && conversation.kind !== "root" ? void 0 : request.destination,
6344
+ nowMs,
6345
+ state: options.state
6346
+ });
6347
+ const queue = options.queue ?? getVercelConversationWorkQueue();
6348
+ await ensureConversationWake({
6349
+ conversationId: request.conversationId,
6350
+ idempotencyKey: [
6351
+ "agent-continue",
6352
+ request.conversationId,
6353
+ request.turnId,
6354
+ request.expectedVersion,
6355
+ nowMs
6356
+ ].join(":"),
6357
+ nowMs,
6358
+ queue,
6359
+ state: options.state
6360
+ });
6361
+ }
6362
+ /** Create paused Turn operations for one app. */
6363
+ function createPausedTurns(options = {}) {
6364
+ return {
6365
+ get: (args) => getPausedTurnRequest({
6366
+ ...args,
6367
+ conversationStore: options.conversationStore
6368
+ }),
6369
+ wake: (request) => wakePausedTurn(request, options)
6370
+ };
6371
+ }
6372
+ /** Record completed authorization and wake the sole execution owner. */
6373
+ async function wakeAuthorizedTurn(args, queue) {
6374
+ const request = await recordTurnAuthorization(args);
6375
+ if (request) await wakePausedTurn(request, { queue });
6376
+ }
6155
6377
  // src/chat/task-execution/supersede-turns.ts
6156
6378
  /**
6157
6379
  * End every open mailbox Turn other than `keepTurnId`, so new input runs in
@@ -6161,27 +6383,68 @@ async function finishTurn(conversationId, turnId, saved) {
6161
6383
  * true first.
6162
6384
  */
6163
6385
  async function supersedeOpenMailboxTurns(args) {
6386
+ return await supersedeTurns({
6387
+ ...args,
6388
+ turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
6389
+ });
6390
+ }
6391
+ /**
6392
+ * End open Turns that new input replaces. A late resume or OAuth callback
6393
+ * for an ended Turn is a no-op. The caller persists `conversation`. Returns
6394
+ * false when `isStopped` turns true first.
6395
+ */
6396
+ async function supersedeTurns(args) {
6164
6397
  const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
6165
- const superseded = (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId);
6166
- for (const stale of superseded) {
6398
+ for (const stale of args.turns) {
6167
6399
  if (args.isStopped?.()) return false;
6168
6400
  await abandonTurnRecord({
6169
6401
  conversationId: args.conversationId,
6170
6402
  turnId: stale.turnId,
6171
6403
  errorMessage: "Turn superseded by new input"
6172
6404
  });
6405
+ await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
6406
+ conversationId: args.conversationId,
6407
+ createdAtMs: Date.now(),
6408
+ outcome: "cancelled",
6409
+ turnId: stale.turnId
6410
+ });
6173
6411
  markTurnClosed({
6174
6412
  conversation: args.conversation,
6175
6413
  nowMs: Date.now(),
6176
6414
  sessionId: stale.turnId
6177
6415
  });
6178
6416
  }
6179
- if (superseded.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
6417
+ if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
6180
6418
  actorId: pendingAuthorizationActorId,
6181
6419
  conversationId: args.conversationId
6182
6420
  });
6183
6421
  return true;
6184
6422
  }
6423
+ /**
6424
+ * End the Turn that waits for its next Run when `message` cannot join it, so
6425
+ * the message starts its own Turn instead of running with that Turn's Actor.
6426
+ * A stored legacy Turn without an Actor keeps taking the input.
6427
+ */
6428
+ async function supersedeTurnForInput(args) {
6429
+ const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
6430
+ const turnId = conversation.processing.activeTurnId;
6431
+ if (!turnId || !await getPausedTurnRequest({
6432
+ conversationId: args.conversationId,
6433
+ turnId
6434
+ })) return;
6435
+ const turn = await getTurnRecord(args.conversationId, turnId);
6436
+ if (!turn?.actor || canJoinTurn(turn, args.message)) return;
6437
+ await hydrateConversationMessages({
6438
+ conversation,
6439
+ conversationId: args.conversationId
6440
+ });
6441
+ await supersedeTurns({
6442
+ conversation,
6443
+ conversationId: args.conversationId,
6444
+ turns: [turn]
6445
+ });
6446
+ await persistThreadStateById(args.conversationId, { conversation });
6447
+ }
6185
6448
  // src/chat/task-execution/mailbox-input.ts
6186
6449
  /**
6187
6450
  * Return the Turn inputs of web Messages, one per non-empty Message, in
@@ -6365,9 +6628,22 @@ async function completeCancelledConversationTurn(args) {
6365
6628
  await args.acknowledge();
6366
6629
  }
6367
6630
  /**
6631
+ * End the Turn of a stopped Conversation that waits for sign-in, so a later
6632
+ * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
6633
+ * Slack request waits as the thread's pending sign-in. Every stop path calls
6634
+ * this, because no worker holds a waiting Turn and the stop wake can go to
6635
+ * queued input first.
6636
+ */
6637
+ async function cancelSignInWait(conversationId) {
6638
+ const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
6639
+ if (turnId) await cancelSignInPausedTurn({
6640
+ conversationId,
6641
+ turnId
6642
+ });
6643
+ }
6644
+ /**
6368
6645
  * Cancel a Turn that waits for sign-in outside its worker, with the same
6369
- * cleanup as a stopped resume. A tree stop calls this, because its stop wake
6370
- * can go to queued input before the paused Turn.
6646
+ * cleanup as a stopped resume.
6371
6647
  */
6372
6648
  async function cancelSignInPausedTurn(args) {
6373
6649
  if (!await abandonTurnRecord({
@@ -6588,16 +6864,15 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6588
6864
  let modelFailureEventId;
6589
6865
  let modelFailureCaptureAttempted = false;
6590
6866
  let completedSuccessfully = false;
6591
- const deliverAssistantMessage = async (value) => {
6867
+ const deliverAssistantMessage = async (value, options) => {
6592
6868
  const agentMessage = typeof value === "string" ? void 0 : value;
6593
- const decision = agentMessage ? decideReply(agentMessage) : void 0;
6594
- const replyText = typeof value === "string" ? value : decision?.kind === "deliver" ? decision.text : void 0;
6869
+ const replyText = typeof value === "string" ? value : getAssistantReplyText(value);
6595
6870
  if (!replyText?.trim()) return;
6596
6871
  failureCode = "delivery_failed";
6597
6872
  const cards = await loadPendingMessageCards(context.conversationId);
6598
- const quiet = decision?.kind === "deliver" && decision.quiet === true && isEventTurn && cards.length === 0;
6873
+ const quiet = options?.quiet === true && isEventTurn && cards.length === 0;
6599
6874
  let deliveryResult;
6600
- if (deliverToProvider && !quiet) {
6875
+ if (deliverToProvider && !quiet && !await isConversationDeliveryPaused(context.conversationId)) {
6601
6876
  if (!conversationLocation || !deliverMessage) throw new Error(`Conversation ${context.conversationId} cannot deliver to its Location`);
6602
6877
  deliveryResult = await deliverMessage({
6603
6878
  cards,
@@ -6705,6 +6980,7 @@ function createConversationTurnWorker(agentRunner, deliverMessage) {
6705
6980
  const reply = finalized.reply;
6706
6981
  modelFailureEventId = finalized.eventId;
6707
6982
  if (reply.diagnostics.outcome !== "success") await deliverAssistantMessage(reply.text);
6983
+ else if (reply.noReply?.note && isEventTurn) await deliverAssistantMessage(reply.noReply.note, { quiet: true });
6708
6984
  const completedState = buildDeliveredTurnStatePatch({
6709
6985
  conversation,
6710
6986
  reply,
@@ -6865,9 +7141,11 @@ const SUBAGENT_KIND = "agent";
6865
7141
  * pairs the parent event with `subagent_ended` to show the child and its
6866
7142
  * status. It must be written before the child mailbox append, so the child
6867
7143
  * cannot end first. An agent wrote the input, not a person, so the message
6868
- * names its agent invocation instead of an author.
7144
+ * names its agent invocation instead of an author. Input from Events, such as
7145
+ * the child's own Watch Events, passes their Event fields, so the dashboard
7146
+ * shows it as an Event, as on a root.
6869
7147
  */
6870
- async function recordSubagentStarted(invocation) {
7148
+ async function recordSubagentStarted(invocation, eventMeta) {
6871
7149
  const eventStore = getConversationEventStore();
6872
7150
  const messageId = getAgentInvocationMessageId(invocation.invocationId);
6873
7151
  await eventStore.append(invocation.childConversationId, [{
@@ -6877,7 +7155,10 @@ async function recordSubagentStarted(invocation) {
6877
7155
  messageId,
6878
7156
  role: "user",
6879
7157
  text: invocation.input,
6880
- meta: { agentInvocationId: invocation.invocationId }
7158
+ meta: {
7159
+ ...eventMeta,
7160
+ agentInvocationId: invocation.invocationId
7161
+ }
6881
7162
  },
6882
7163
  createdAtMs: invocation.createdAtMs
6883
7164
  }]);
@@ -7018,9 +7299,9 @@ async function stopChildAgentsBelow(conversationId, options) {
7018
7299
  * stopped each child agent, so no result becomes `appended` after this read.
7019
7300
  *
7020
7301
  * The mailbox read is not atomic with the parent worker. A worker that takes
7021
- * a result before this update holds the work lease, so the
7022
- * `stopConversationTurn` that each caller runs next stops its Turn. A result
7023
- * that such a Turn took but did not ack yet is marked `skipped`.
7302
+ * a result before this update holds the work lease, so the stop request of
7303
+ * the Conversation stops its Turn. A result that such a Turn took but did not
7304
+ * ack yet is marked `skipped`.
7024
7305
  */
7025
7306
  async function skipUnreadResults(conversationId, nowMs, state) {
7026
7307
  const invocationIds = ((await getConversationWorkState({
@@ -7045,11 +7326,7 @@ async function finishStoppedTree(tree, conversationIdsToStop, options) {
7045
7326
  for (const invocation of tree.stopped) await recordSubagentEnded(invocation);
7046
7327
  await markConversationsStopped(conversationIdsToStop, options);
7047
7328
  for (const conversationId of conversationIdsToStop) {
7048
- const pausedTurnId = await getAuthPausedConversationTurnId(conversationId);
7049
- if (pausedTurnId) await cancelSignInPausedTurn({
7050
- conversationId,
7051
- turnId: pausedTurnId
7052
- });
7329
+ await cancelSignInWait(conversationId);
7053
7330
  await stopConversationWork({
7054
7331
  conversationId,
7055
7332
  state: options.state
@@ -7341,35 +7618,6 @@ async function archiveConversation(viewer, conversationId, body) {
7341
7618
  case "archived_ancestor": throwApiError(409, `Conversation ${result.archivedAncestorId} above this one is archived. Restore it first.`);
7342
7619
  }
7343
7620
  }
7344
- // src/api/conversations/user-message-activity.ts
7345
- /**
7346
- * The newest event of one type in the outer Conversation that matches the
7347
- * filter. It walks the message role or user message time index from the
7348
- * newest event. The user message index has only matching entries, so that
7349
- * read stops at the first one.
7350
- */
7351
- function latestEventAt(db, type, filter) {
7352
- return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1).as(`latest_${type}`);
7353
- }
7354
- /** Read the latest true user message time for each selected conversation. */
7355
- async function readLastUserMessageAtByConversation(db, conversationIds) {
7356
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
7357
- const payload = juniorConversationEvents.payload;
7358
- const instruction = latestEventAt(db, "user_message", isUserInstruction(payload));
7359
- const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
7360
- const message = latestEventAt(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`);
7361
- const rows = await db.select({
7362
- conversationId: juniorConversations.conversationId,
7363
- instructionAt: instruction.createdAt,
7364
- messageAt: message.createdAt
7365
- }).from(juniorConversations).leftJoinLateral(instruction, sql`true`).leftJoinLateral(message, sql`true`).where(inArray(juniorConversations.conversationId, conversationIds));
7366
- const result = /* @__PURE__ */ new Map();
7367
- for (const { conversationId, instructionAt, messageAt } of rows) {
7368
- const times = [instructionAt, messageAt].flatMap((at) => at ? [at.getTime()] : []);
7369
- if (times.length > 0) result.set(conversationId, new Date(Math.max(...times)).toISOString());
7370
- }
7371
- return result;
7372
- }
7373
7621
  // src/chat/tools/runtime/archive-agent.ts
7374
7622
  const archiveAgentOutputSchema = juniorToolOutputSchema.extend({
7375
7623
  conversation_id: z.string().min(1).describe("Archived Thread ID"),
@@ -7461,13 +7709,30 @@ function createFinishAutomationRunTool(options) {
7461
7709
  execute: async (input) => {
7462
7710
  const parsed = automationResultSchema$1.safeParse(input);
7463
7711
  if (!parsed.success) throw new ToolInputError(input.result === "send_message" ? "send_message requires a non-empty message." : `${input.result} requires a non-empty reason.`);
7464
- return parsed.data.result === "send_message" && isNoReplyMarker(parsed.data.message) ? {
7712
+ return parsed.data.result === "send_message" && isLegacyNoReplyMarker(parsed.data.message) ? {
7465
7713
  result: "no_action",
7466
7714
  reason: "The message was the no-reply marker."
7467
7715
  } : parsed.data;
7468
7716
  }
7469
7717
  });
7470
7718
  }
7719
+ // src/chat/tools/runtime/no-reply.ts
7720
+ /** Create the tool that ends a Turn with no reply. */
7721
+ function createNoReplyTool() {
7722
+ return zodTool({
7723
+ annotations: {
7724
+ destructiveHint: false,
7725
+ idempotentHint: true,
7726
+ openWorldHint: false,
7727
+ readOnlyHint: true
7728
+ },
7729
+ description: "End the Turn without a reply. Nothing is posted and nobody is notified.",
7730
+ exposure: "modelOnly",
7731
+ inputSchema: z.object({ note: z.string().trim().min(1).nullable().optional().describe("Outcome to keep in the conversation without notifying anyone, such as a routine fix that worked. Omit it when a person asked for no reply. Null is the same as omitted.") }).strict(),
7732
+ outputSchema: juniorToolOutputSchema.extend({ note: z.string().optional() }),
7733
+ execute: async (input) => input.note ? { note: input.note } : {}
7734
+ });
7735
+ }
7471
7736
  // src/chat/tools/runtime/report-blocked.ts
7472
7737
  /** Create the tool that ends a child agent run as blocked. */
7473
7738
  function createReportBlockedTool() {
@@ -7948,6 +8213,7 @@ async function recordWebConversationActivity(args) {
7948
8213
  actor: storedActorFromWeb(args.actor),
7949
8214
  ...isNewRoot ? { source: "web" } : void 0,
7950
8215
  ...source ? { sessionSource: source } : void 0,
8216
+ ...isNewRoot && args.rootTitle ? { title: args.rootTitle } : void 0,
7951
8217
  ...isNewRoot ? { visibility } : void 0
7952
8218
  });
7953
8219
  return existing && existing.kind !== "root" ? void 0 : destination;
@@ -7965,6 +8231,7 @@ async function createAndEnqueueConversation(input, options) {
7965
8231
  idempotencyKey: input.idempotencyKey,
7966
8232
  message: input.message,
7967
8233
  images: input.images,
8234
+ ...input.title ? { rootTitle: input.title } : void 0,
7968
8235
  rootVisibility: input.visibility === "private" ? "private" : "public"
7969
8236
  }, options);
7970
8237
  }
@@ -7982,6 +8249,7 @@ async function appendAndEnqueueWebMessage(input, options) {
7982
8249
  conversationId: input.conversationId,
7983
8250
  conversationStore: options.conversationStore,
7984
8251
  nowMs,
8252
+ ...input.rootTitle && { rootTitle: input.rootTitle },
7985
8253
  ...input.rootVisibility && { rootVisibility: input.rootVisibility }
7986
8254
  });
7987
8255
  let attachments = [];
@@ -8254,15 +8522,21 @@ const titleSchema = z.string().trim().min(1).max(200);
8254
8522
  const bodySchema = z.string().trim().min(1).max(4e3).describe("Markdown details for the person.");
8255
8523
  /**
8256
8524
  * Pick the assignees of a new item when the agent names none: the User of
8257
- * the Actor, or else the creator of the Automation of this run. A Slack
8258
- * Actor without a Junior User gets an item with no assignees, so that the
8259
- * agent can still ask; any person in the thread can then answer it.
8525
+ * the Actor, or else the creator of the Automation of this run. A Turn with
8526
+ * a system Actor, such as an event Turn, falls back to the active
8527
+ * Participants of the Conversation. A Slack Actor without a Junior User gets
8528
+ * an item with no assignees, so that the agent can still ask; any person in
8529
+ * the thread can then answer it.
8260
8530
  */
8261
- async function defaultAssignees(scope) {
8531
+ async function defaultAssignees(scope, conversationId) {
8262
8532
  const userId = scope.user?.id ?? (scope.reader.automationId ? await automationCreatorUserId(getDb(), scope.reader.automationId) : void 0);
8533
+ if (userId) return {
8534
+ everyone: false,
8535
+ userIds: [userId]
8536
+ };
8263
8537
  return {
8264
8538
  everyone: false,
8265
- userIds: userId ? [userId] : []
8539
+ userIds: scope.actorIsPerson ? [] : await activeParticipantUserIds(getDb(), conversationId)
8266
8540
  };
8267
8541
  }
8268
8542
  function delivery(services) {
@@ -8315,7 +8589,7 @@ function subjectInput(subject) {
8315
8589
  /** Create the tool that adds a Review item or updates the open one. */
8316
8590
  function createAddReviewItemTool(context, services) {
8317
8591
  return zodTool({
8318
- 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, or to the Automation creator in an Automation run. 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 end with exactly ${NO_REPLY_MARKER}, 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.`,
8592
+ 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.`,
8319
8593
  annotations: {
8320
8594
  destructiveHint: false,
8321
8595
  idempotentHint: true,
@@ -8357,7 +8631,8 @@ function createAddReviewItemTool(context, services) {
8357
8631
  const assignees = input.assignees ? await resolveAssignees(db, input.assignees, existing ? existing.tenant : scope.tenant, services.findMentionedUserId) : existing ? {
8358
8632
  everyone: existing.assignedToEveryone,
8359
8633
  userIds: existing.assignees.map((assignee) => assignee.userId)
8360
- } : await defaultAssignees(scope);
8634
+ } : await defaultAssignees(scope, context.conversationId);
8635
+ if (!assignees.everyone && assignees.userIds.length === 0 && !scope.actorIsPerson) throw new ToolInputError("No person would see this item: no default assignee has a Junior user, and this Turn has no person. Set `assignees`.");
8361
8636
  await requireReviewItemAssignees({
8362
8637
  assignees,
8363
8638
  automationId: existing ? existing.automationId : scope.reader.automationId,
@@ -9914,7 +10189,7 @@ async function readConversationSourceTask(args) {
9914
10189
  * Web edits and lifecycle actions. Anyone who can read an Automation can
9915
10190
  * manage it. Creator credential rules still apply.
9916
10191
  */
9917
- /** Owners and public Destination readers can manage. Others get not found. */
10192
+ /** Creators and public Destination readers can manage. Others get not found. */
9918
10193
  async function requireEditableAutomation(user, id) {
9919
10194
  const candidate = await resolveViewerTaskCandidate(user, id);
9920
10195
  if (!candidate) throw new ViewerTaskNotFoundError();
@@ -12036,7 +12311,7 @@ function createSlackMessageAddReactionTool(context, state) {
12036
12311
  openWorldHint: true,
12037
12312
  readOnlyHint: false
12038
12313
  },
12039
- description: `Add an emoji reaction to the current inbound Slack message. The person sees the reaction on their message. When the reaction is the whole reply, do not report it in text: end the Turn with exactly ${NO_REPLY_MARKER}.`,
12314
+ description: `Add an emoji reaction to the current inbound Slack message. The person sees the reaction on their message. When the reaction is the whole reply, do not report it in text: end the Turn with \`${NO_REPLY_TOOL_NAME}\`.`,
12040
12315
  inputSchema: z.object({ emoji: z.string().min(1).max(64).describe("Slack emoji alias name to react with (for example `thumbsup`, `white_check_mark`, or `thumbsup::skin-tone-6`). Optional surrounding colons are allowed.") }),
12041
12316
  outputSchema: juniorToolOutputSchema,
12042
12317
  execute: async ({ emoji }) => {
@@ -14558,15 +14833,10 @@ async function updateConversationSubscription(person, conversationId, subscribed
14558
14833
  };
14559
14834
  });
14560
14835
  }
14561
- /**
14562
- * True when someone still has the root in their feed: a participant who did
14563
- * not unsubscribe, or the root actor before they have a participant row.
14564
- */
14836
+ /** True when an active Participant still has the root in their feed. */
14565
14837
  async function hasSubscriber(db, rootConversationId) {
14566
14838
  const [subscriber] = await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.rootConversationId, rootConversationId), isNull(juniorConversationParticipants.unsubscribedAt))).limit(1);
14567
- if (subscriber) return true;
14568
- const [rowlessActor] = await db.select({ userId: juniorIdentities.userId }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).where(and(eq(juniorConversations.conversationId, rootConversationId), isNotNull(juniorIdentities.userId), notExists(db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.rootConversationId, rootConversationId), eq(juniorConversationParticipants.userId, juniorIdentities.userId)))))).limit(1);
14569
- return Boolean(rowlessActor);
14839
+ return Boolean(subscriber);
14570
14840
  }
14571
14841
  /**
14572
14842
  * Archive the root and each descendant that is not archived. Descendants
@@ -16081,6 +16351,7 @@ function createWorkspaceTools(context) {
16081
16351
  }),
16082
16352
  switchWorkspace: zodTool({
16083
16353
  executionMode: "sequential",
16354
+ exposure: "modelOnly",
16084
16355
  annotations: {
16085
16356
  destructiveHint: true,
16086
16357
  idempotentHint: true,
@@ -16241,6 +16512,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
16241
16512
  if (context.messageAgent) tools.messageAgent = createMessageAgentTool(context.messageAgent);
16242
16513
  if (context.agentInvocationId) tools[REPORT_BLOCKED_TOOL_NAME] = createReportBlockedTool();
16243
16514
  if (context.automation) tools[FINISH_AUTOMATION_RUN_TOOL_NAME] = createFinishAutomationRunTool(context.automation);
16515
+ else tools[NO_REPLY_TOOL_NAME] = createNoReplyTool();
16244
16516
  if (context.mcpToolManager) {
16245
16517
  tools.searchMcpTools = createSearchMcpToolsTool(context.mcpToolManager);
16246
16518
  tools.callMcpTool = createCallMcpToolTool(context.mcpToolManager);
@@ -17685,7 +17957,6 @@ async function runCodeModeScript(run) {
17685
17957
  * Pi's coding agent uses the same default.
17686
17958
  */
17687
17959
  const DECLARATION_BUDGET_TOKENS = 3e3;
17688
- const CHARS_PER_TOKEN = 4;
17689
17960
  /** Fields of the shared tool result envelope. They say nothing about one tool. */
17690
17961
  const ENVELOPE_FIELDS = new Set(juniorToolOutputSchema.keyof().options);
17691
17962
  /**
@@ -17715,17 +17986,19 @@ function renderDeclaration(name, tool) {
17715
17986
  }).trim().replace(/\n/g, "\n ")}`;
17716
17987
  }
17717
17988
  /**
17718
- * Declare the script tools that fit the token budget, cheapest first, so
17719
- * that the most tools fit. The others stay callable. The model finds their
17720
- * input with `searchTools`. Script-only tools come first, because
17721
- * `searchTools` does not find them. The same tools give the same text, so
17722
- * the description does not change between Turns.
17989
+ * Tell the script which tools it may call. Direct tools are only named: the
17990
+ * model already has their input schemas. The other tools are declared within
17991
+ * the token budget, cheapest first, so that the most tools fit. The others
17992
+ * stay callable. The model finds their input with `searchTools`. Script-only
17993
+ * tools come first, because `searchTools` does not find them. The same tools
17994
+ * give the same text, so the description does not change between Turns.
17723
17995
  */
17724
17996
  function renderScriptTools(tools) {
17725
- const entries = Object.entries(tools).map(([name, tool]) => {
17997
+ const directNames = Object.entries(tools).filter(([, tool]) => effectiveToolExposure(tool) === "direct").map(([name]) => name).sort((a, b) => a.localeCompare(b));
17998
+ const entries = Object.entries(tools).filter(([, tool]) => effectiveToolExposure(tool) !== "direct").map(([name, tool]) => {
17726
17999
  const text = renderDeclaration(name, tool);
17727
18000
  return {
17728
- cost: Math.ceil(text.length / CHARS_PER_TOKEN),
18001
+ cost: estimateTextTokens(text),
17729
18002
  name,
17730
18003
  scriptOnly: effectiveToolExposure(tool) === "codemode",
17731
18004
  text
@@ -17741,9 +18014,12 @@ function renderScriptTools(tools) {
17741
18014
  shown.sort((a, b) => a.name.localeCompare(b.name));
17742
18015
  const omitted = entries.length - shown.length;
17743
18016
  return [
17744
- "declare const tools: {",
17745
- ...shown.map((entry) => entry.text),
17746
- "};",
18017
+ ...directNames.length > 0 ? [`These tools from your tool list can also be called as \`tools.<name>(args)\`, with the same input: ${directNames.join(", ")}.`] : [],
18018
+ ...shown.length > 0 ? [
18019
+ "declare const tools: {",
18020
+ ...shown.map((entry) => entry.text),
18021
+ "};"
18022
+ ] : [],
17747
18023
  ...omitted > 0 ? [`${omitted} more tools are not declared here. To find one, call ${SEARCH_TOOLS_NAME} directly before the script. Then call each result as \`tools.<tool_name>(args)\`, with its input_schema. A script cannot call ${SEARCH_TOOLS_NAME} or ${EXECUTE_TOOL_NAME}.`] : [],
17748
18024
  ...Object.hasOwn(tools, "callMcpTool") ? ["Call an MCP tool as `tools.callMcpTool({ tool_name, arguments })`. Its `result` field holds the structured content of the MCP tool, or its text. `tools.mcp__<provider>__<tool>` does not exist."] : []
17749
18025
  ].join("\n");
@@ -19142,7 +19418,7 @@ function isToolEntry(entry) {
19142
19418
  function truncateText(text, maxTokens) {
19143
19419
  const tokenCount = estimateTextTokens(text);
19144
19420
  if (tokenCount <= maxTokens) return text;
19145
- const maxChars = maxTokens * 4;
19421
+ const maxChars = textCharsForTokens(maxTokens);
19146
19422
  const marker = `<truncated omitted_approx_tokens="${Math.max(1, tokenCount - maxTokens)}" />`;
19147
19423
  if (maxChars <= marker.length) return marker;
19148
19424
  const availableChars = maxChars - marker.length;
@@ -20067,10 +20343,13 @@ const SUMMARY_NUDGE = "Do not call tools. Keep the summary short. Return only th
20067
20343
  /** Raised when the model returns no usable summary after one nudge. */
20068
20344
  var ContextSummaryError = class extends Error {
20069
20345
  failure;
20070
- constructor(failure) {
20071
- super(`Context summary failed: ${failure}`);
20346
+ /** Estimated cost of the summary requests that did not succeed. */
20347
+ costUsd;
20348
+ constructor(failure, costUsd, options) {
20349
+ super(`Context summary failed: ${failure}`, options);
20072
20350
  this.failure = failure;
20073
20351
  this.name = "ContextSummaryError";
20352
+ if (costUsd !== void 0) this.costUsd = costUsd;
20074
20353
  }
20075
20354
  };
20076
20355
  /**
@@ -20141,16 +20420,34 @@ function readSummary(message) {
20141
20420
  *
20142
20421
  * A tool call, a stop at the output limit, empty output, or output without
20143
20422
  * `<summary>` tags gets one nudge. A second failure throws
20144
- * `ContextSummaryError`, so the caller keeps the full history.
20423
+ * `ContextSummaryError`, so the caller keeps the full history. The cost
20424
+ * covers each summary request, including a nudged one.
20145
20425
  */
20146
20426
  async function requestContextSummary(request, streamFn) {
20147
20427
  const instruction = userText(SUMMARY_INSTRUCTION);
20148
- const first = readSummary(await complete(request, streamFn, [instruction]));
20149
- if ("summary" in first) return first.summary;
20428
+ const firstMessage = await complete(request, streamFn, [instruction]);
20429
+ const first = readSummary(firstMessage);
20430
+ if ("summary" in first) return withCost(first.summary, firstMessage);
20150
20431
  logWarn("context_compaction.summary.nudged", { "app.compaction.summary_failure": first.failure });
20151
- const second = readSummary(await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]));
20152
- if ("summary" in second) return second.summary;
20153
- throw new ContextSummaryError(second.failure);
20432
+ let secondMessage;
20433
+ try {
20434
+ secondMessage = await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]);
20435
+ } catch (error) {
20436
+ throw new ContextSummaryError("request_failed", summaryCostUsd(firstMessage), { cause: error });
20437
+ }
20438
+ const second = readSummary(secondMessage);
20439
+ if ("summary" in second) return withCost(second.summary, firstMessage, secondMessage);
20440
+ throw new ContextSummaryError(second.failure, summaryCostUsd(firstMessage, secondMessage));
20441
+ }
20442
+ function summaryCostUsd(...messages) {
20443
+ return agentTurnCostUsd(extractGenAiUsageSummary(...messages));
20444
+ }
20445
+ function withCost(summary, ...messages) {
20446
+ const costUsd = summaryCostUsd(...messages);
20447
+ return costUsd === void 0 ? { summary } : {
20448
+ summary,
20449
+ costUsd
20450
+ };
20154
20451
  }
20155
20452
  // src/chat/services/background-compaction.ts
20156
20453
  /**
@@ -20227,7 +20524,7 @@ async function loadLatestBackgroundCompaction(conversationId) {
20227
20524
  }
20228
20525
  /**
20229
20526
  * Return whether the newest fact is a pending request or a ready summary.
20230
- * Then `mayRequest` is false too, so a Turn can skip the full history load.
20527
+ * Then `mayRequest` is false too, so a Turn can skip the other reads.
20231
20528
  * Only one request is pending at a time, so the newest fact decides it.
20232
20529
  */
20233
20530
  function waitsForUse(event, nowMs) {
@@ -20260,9 +20557,12 @@ async function requestBackgroundCompaction(args) {
20260
20557
  }
20261
20558
  async function requestAboveMark(args) {
20262
20559
  const nowMs = Date.now();
20263
- const latest = await loadLatestBackgroundCompaction(args.conversationId);
20264
- if (latest && waitsForUse(latest.event, nowMs)) return;
20265
20560
  const eventStore = getConversationEventStore();
20561
+ const latest = await loadLatestBackgroundCompaction(args.conversationId);
20562
+ if (latest) {
20563
+ if (waitsForUse(latest.event, nowMs)) return;
20564
+ if (!mayRequest((await Promise.all([eventStore.loadEventsOfType(args.conversationId, "compaction_requested"), eventStore.loadEventsOfType(args.conversationId, "compaction_prepared")])).flat(), latest.historyVersion, nowMs)) return;
20565
+ }
20266
20566
  const events = await eventStore.loadCurrentHistory(args.conversationId);
20267
20567
  const historyVersion = events[0]?.historyVersion;
20268
20568
  if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs)) return;
@@ -20310,7 +20610,7 @@ async function requestAboveMark(args) {
20310
20610
  /** A fixed label for a failed summary. Never raw exception text. */
20311
20611
  function failureLabel(error, signal) {
20312
20612
  if (signal.aborted) return "timeout";
20313
- if (error instanceof ContextSummaryError) return error.failure;
20613
+ if (error instanceof ContextSummaryError && error.failure !== "request_failed") return error.failure;
20314
20614
  const providerError = findProviderError(error);
20315
20615
  return providerError ? `provider_${providerError.kind}` : "summary_error";
20316
20616
  }
@@ -20407,15 +20707,16 @@ async function prepareSummary(message, streamFn) {
20407
20707
  } catch (error) {
20408
20708
  return await writePrepared({
20409
20709
  outcome: "failed",
20410
- errorType: failureLabel(error, signal)
20710
+ errorType: failureLabel(error, signal),
20711
+ ...error instanceof ContextSummaryError && error.costUsd !== void 0 ? { costUsd: error.costUsd } : void 0
20411
20712
  });
20412
20713
  }
20413
20714
  const outcome = await writePrepared({
20414
20715
  outcome: "ready",
20415
- summary
20716
+ ...summary
20416
20717
  });
20417
20718
  if (outcome === "ready") setSpanAttributes({
20418
- "app.compaction.summary_chars": summary.length,
20719
+ "app.compaction.summary_chars": summary.summary.length,
20419
20720
  "app.compaction.ready_ms": Date.now() - request.createdAtMs
20420
20721
  });
20421
20722
  return outcome;
@@ -20522,7 +20823,7 @@ function sanitizeText(text) {
20522
20823
  return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
20523
20824
  }
20524
20825
  function truncateToTokenBudget(text, maxTokens) {
20525
- const maxChars = Math.max(0, maxTokens * 4);
20826
+ const maxChars = Math.max(0, textCharsForTokens(maxTokens));
20526
20827
  if (text.length <= maxChars) return text;
20527
20828
  return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
20528
20829
  }
@@ -20774,15 +21075,6 @@ function measuredReplacementTokens(messages) {
20774
21075
  function estimateReplacementTokens(messages, modelId, requestOverheadTokens = 0) {
20775
21076
  return requestOverheadTokens + estimateMessagesTokens(messages, modelId);
20776
21077
  }
20777
- /** Estimate messages from their size at the model's characters per token. */
20778
- function estimateMessagesTokens(messages, modelId) {
20779
- const profile = getTokenEstimateProfile(modelId);
20780
- return messages.reduce((total, message) => {
20781
- const tokens = Math.ceil(estimateTokens(message) * 4 / profile.charsPerToken);
20782
- const overhead = message.role === "toolResult" ? profile.toolResultOverheadTokens : 0;
20783
- return total + tokens + overhead;
20784
- }, 0);
20785
- }
20786
21078
  async function loadLastInstruction(conversationId) {
20787
21079
  const event = await getConversationEventStore().loadLatestInstruction(conversationId);
20788
21080
  if (!event) return void 0;
@@ -20866,8 +21158,9 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
20866
21158
  if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
20867
21159
  await args.onCompactionStart?.();
20868
21160
  let summary;
21161
+ let costUsd;
20869
21162
  try {
20870
- summary = await summarize(args.piMessages, args.signal);
21163
+ ({summary, costUsd} = await summarize(args.piMessages, args.signal));
20871
21164
  } catch (error) {
20872
21165
  if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
20873
21166
  logWarn("context_compaction.active.summary.failed", {
@@ -20915,6 +21208,7 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
20915
21208
  retainedMessageCount,
20916
21209
  summaryChars: summary.length
20917
21210
  },
21211
+ ...costUsd === void 0 ? void 0 : { costUsd },
20918
21212
  summary,
20919
21213
  replacementHistory: replacement.map((entry) => ({
20920
21214
  item: historyItemFromPiMessage(entry.message, entry.provenance),
@@ -21230,16 +21524,36 @@ async function applyPreparedSummary(args, prepared, budget) {
21230
21524
  };
21231
21525
  }
21232
21526
  // src/chat/agent/exclusive-tools.ts
21233
- /** Tools that must be the only tool call in their assistant message. */
21527
+ /**
21528
+ * Tools that must be the only tool call in their assistant message. Each one
21529
+ * must be `modelOnly`: this check does not see script or `executeTool` calls.
21530
+ */
21234
21531
  const EXCLUSIVE_TOOL_NAMES = [
21235
21532
  "switchWorkspace",
21236
21533
  FINISH_AUTOMATION_RUN_TOOL_NAME,
21237
- REPORT_BLOCKED_TOOL_NAME
21534
+ REPORT_BLOCKED_TOOL_NAME,
21535
+ NO_REPLY_TOOL_NAME
21238
21536
  ];
21239
21537
  /** Return the exclusive tool name when one is present among the calls. */
21240
21538
  function exclusiveToolName(toolCalls) {
21241
21539
  for (const name of EXCLUSIVE_TOOL_NAMES) if (toolCalls.some((call) => call.name === name)) return name;
21242
21540
  }
21541
+ // src/chat/agent/tool-batch.ts
21542
+ /**
21543
+ * Record how Pi runs the tool calls of one assistant message. Pi runs them
21544
+ * in parallel unless one of their tools is `sequential`; then it runs all of
21545
+ * them one at a time.
21546
+ */
21547
+ function logToolBatch(toolCalls, tools) {
21548
+ const names = toolCalls.map((call) => call.name);
21549
+ const sequentialTools = [...new Set(names)].filter((name) => tools.find((tool) => tool.name === name)?.executionMode === "sequential").sort();
21550
+ logInfo("agent.tool_batch.started", {
21551
+ "app.tool_batch.size": toolCalls.length,
21552
+ "app.tool_batch.execution": sequentialTools.length > 0 ? "sequential" : "parallel",
21553
+ "app.tool_batch.tool_names": names,
21554
+ "app.tool_batch.sequential_tool_names": sequentialTools
21555
+ });
21556
+ }
21243
21557
  // src/chat/agent/index.ts
21244
21558
  /**
21245
21559
  * Agent executor.
@@ -21758,16 +22072,18 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21758
22072
  }
21759
22073
  return acceptedMessages;
21760
22074
  };
22075
+ const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task");
21761
22076
  agent = new Agent({
21762
22077
  getApiKey: getGatewayApiKey,
21763
22078
  sessionId: conversationId,
21764
22079
  streamFn: createTracedStreamFn({
21765
22080
  conversationPrivacy,
21766
- ...streamFn ? { base: streamFn } : void 0
22081
+ base: cacheWarming.wrap(streamFn)
21767
22082
  }),
21768
22083
  steeringMode: "all",
21769
- beforeToolCall: async ({ assistantMessage }) => {
22084
+ beforeToolCall: async ({ assistantMessage, context, toolCall }) => {
21770
22085
  const toolCalls = assistantMessage.content.filter((part) => part.type === "toolCall");
22086
+ if (toolCalls.length > 1 && toolCall.id === toolCalls[0].id) logToolBatch(toolCalls, context.tools ?? []);
21771
22087
  const exclusiveTool = exclusiveToolName(toolCalls);
21772
22088
  if (exclusiveTool && toolCalls.length !== 1) return {
21773
22089
  block: true,
@@ -21805,7 +22121,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21805
22121
  const sourceResult = timedOutResult ?? result;
21806
22122
  const projectedResult = wiring.projectActionReviewResult(toolCall.id, sourceResult);
21807
22123
  const override = timedOutResult || projectedResult !== result ? projectedResult : void 0;
21808
- if ((toolCall.name === "finishAutomationRun" || toolCall.name === "reportBlocked") && !isError && !override) return { terminate: true };
22124
+ if ((toolCall.name === "finishAutomationRun" || toolCall.name === "reportBlocked" || toolCall.name === "noReply") && !isError && !override) return { terminate: true };
21809
22125
  return override;
21810
22126
  },
21811
22127
  prepareNextTurnWithContext: async (nextTurn, hookSignal) => {
@@ -21843,13 +22159,20 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21843
22159
  });
21844
22160
  const unsubscribe = agent.subscribe((event) => {
21845
22161
  if (event.type === "tool_execution_start") return recordParentToolExecutionStart(event);
21846
- if (event.type === "turn_end" && event.toolResults.length > 0) return requireConversationLease("save").then(() => runResume.persistSafeBoundary([...agent.state.messages])).then(() => void 0, (error) => {
21847
- pendingPiHookError ??= error instanceof Error ? error : new Error(String(error));
21848
- throw error;
21849
- });
22162
+ if (event.type === "turn_end" && event.toolResults.length > 0) {
22163
+ cacheWarming.toolsReturned();
22164
+ return requireConversationLease("save").then(() => runResume.persistSafeBoundary([...agent.state.messages])).then(() => void 0, (error) => {
22165
+ pendingPiHookError ??= error instanceof Error ? error : new Error(String(error));
22166
+ throw error;
22167
+ });
22168
+ }
21850
22169
  if (event.type === "message_end" && isAssistantMessage(event.message)) {
21851
- if (event.message.stopReason === "error" || event.message.stopReason === "aborted") return;
21852
- return deliverAssistantMessage(event.message);
22170
+ const message = event.message;
22171
+ const delivery = message.stopReason === "error" || message.stopReason === "aborted" ? void 0 : deliverAssistantMessage(message);
22172
+ return Promise.resolve(delivery).then(() => cacheWarming.record(message), async (error) => {
22173
+ await cacheWarming.record(message);
22174
+ throw error;
22175
+ });
21853
22176
  }
21854
22177
  });
21855
22178
  let newMessages = [];
@@ -22063,6 +22386,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22063
22386
  if (authPauseOutcome) return authPauseOutcome;
22064
22387
  } finally {
22065
22388
  unsubscribe();
22389
+ await cacheWarming.stop();
22066
22390
  }
22067
22391
  await requireConversationLease("save");
22068
22392
  await recordActiveMcpProviders();
@@ -22205,4 +22529,4 @@ function createAgentRunner(execute, options) {
22205
22529
  return await execute(nextRun, streamFn);
22206
22530
  } };
22207
22531
  }
22208
- export { readViewerAutomationSummary as $, toolInvocationDestination as $t, runWithSlackInstallation as A, recordSubagentStarted as At, listThreadReplies as B, getWebAuthorization as Bt, readSlackReviewItemCardConversationId as C, markConversationRead as Ct, parseSlackReviewItemClick as D, stopChildAgentsBelow as Dt, buildSlackReviewItemModal as E, throwApiError as Et, resolveSlackChannelIdFromThreadId as F, finishTurn as Ft, changeViewerAutomationLifecycle as G, AgentMessageTargetError as Gt, logScheduledAutomationRunSkipped as H, AgentInvocationLimitError as Ht, checkSlackChannelReadAccess as I, getTurnInputSpanAttributes as It, updateViewerAutomation as J, listUnreportedSiblingAgents as Jt, deleteViewerTask as K, AgentNameInUseError as Kt, joinPublicChannelForRead as L, turnInputTelemetry as Lt, parseSlackThreadId as M, supersedeOpenMailboxTurns as Mt, readSlackRawMessageContext as N, AgentRunError as Nt, parseSlackReviewItemFormTarget as O, stopChildAgentsOf as Ot, resolveSlackChannelIdFromMessage as P, executeTurn as Pt, readViewerAutomationRuns as Q, actorFromRun as Qt, getConversationInfo as R, withTurnSpan as Rt, createSlackReviewItemShow as S, conversationReadPositionQuery as St, SLACK_REVIEW_ITEM_VIEW_ID as T, jsonResponse as Tt, scheduledAutomationRunAttributes as U, AgentMessagePausedError as Ut, resolveDestinationVisibility as V, AgentDepthLimitError as Vt, activateViewerAutomationVersion as W, AgentMessageQueueFullError as Wt, readConversationSourceTask as X, ingestEvent as Xt, ViewerTaskNotFoundError as Y, processWorkspaceSnapshotJob as Yt, readViewerAutomationExecutions as Z, RetryableDeliveryError as Zt, unpublishedArtifactHeaders as _, readLiveAttachment as _t, finalizeMcpAuthorization as a, deliverReviewItemChange as at, renderAttachmentText as b, readLastUserMessageAtByConversation as bt, deleteMcpServerSessionId as c, acceptsWebMessages as ct, getMcpStoredOAuthCredentials as d, createAndEnqueueConversation as dt, shouldEmitDevAgentTrace as en, readViewerAutomationVersions as et, putMcpStoredOAuthCredentials as f, createConversationId as ft, readPublicArtifact as g, collectAttachmentGarbage as gt, publicArtifactHeaders as h, decodeInputImages as ht, buildAuthPauseResponse as i, listOwnedWatches as it, verifySlackSignature as j, createConversationTurnWorker as jt, parseSlackUserInputSubmission as k, recordSubagentEnded as kt, deleteMcpStoredOAuthCredentials as l, appendAndEnqueueWebMessage as lt, readStats as m, webActorFromUser as mt, executeAgentRun as n, AutomationEditError as nt, deleteMcpAuthSession as o, renderReviewItemMessage as ot, latestProgressStatus as p, recordWebConversationActivity as pt, readViewerAutomationEdit as q, listChildAgents as qt, processBackgroundCompaction as r, effectiveTaskOutcomes as rt, deleteMcpAuthSessionsForUserProvider as s, reviewItemChangeRecord as st, createAgentRunner as t, readViewerAutomations as tt, getMcpAuthSession as u, conversationTurnIdForMessage as ut, setConversationSubscription as v, requestAttachmentDeletion as vt, syncReviewItemSlackCards as w, emptyResponse as wt, renderBlockText as x, archiveConversation as xt, lookupSlackUserProfile as y, storeAttachment as yt, joinPublicChannel as z, deleteWebAuthorization as zt };
22532
+ export { readViewerAutomationSummary as $, resumeConversationDelivery as $t, runWithSlackInstallation as A, cancelSignInWait as At, listThreadReplies as B, canShareTurn as Bt, readSlackReviewItemCardConversationId as C, emptyResponse as Ct, parseSlackReviewItemClick as D, stopChildAgentsOf as Dt, buildSlackReviewItemModal as E, stopChildAgentsBelow as Et, resolveSlackChannelIdFromThreadId as F, getPausedTurnRequest as Ft, changeViewerAutomationLifecycle as G, finishTurn as Gt, logScheduledAutomationRunSkipped as H, selectAttemptMessages as Ht, checkSlackChannelReadAccess as I, wakeAuthorizedTurn as It, updateViewerAutomation as J, withTurnSpan as Jt, deleteViewerTask as K, getTurnInputSpanAttributes as Kt, joinPublicChannelForRead as L, wakePausedTurn as Lt, parseSlackThreadId as M, supersedeOpenMailboxTurns as Mt, readSlackRawMessageContext as N, supersedeTurnForInput as Nt, parseSlackReviewItemFormTarget as O, recordSubagentEnded as Ot, resolveSlackChannelIdFromMessage as P, createPausedTurns as Pt, readViewerAutomationRuns as Q, pauseConversationDelivery as Qt, getConversationInfo as R, getTurnAuthorization as Rt, createSlackReviewItemShow as S, markConversationRead as St, SLACK_REVIEW_ITEM_VIEW_ID as T, throwApiError as Tt, scheduledAutomationRunAttributes as U, AgentRunError as Ut, resolveDestinationVisibility as V, isAttemptInterrupt as Vt, activateViewerAutomationVersion as W, executeTurn as Wt, readConversationSourceTask as X, getWebAuthorization as Xt, ViewerTaskNotFoundError as Y, deleteWebAuthorization as Yt, readViewerAutomationExecutions as Z, canPauseConversationDelivery as Zt, unpublishedArtifactHeaders as _, readLiveAttachment as _t, finalizeMcpAuthorization as a, AgentNameInUseError as an, deliverReviewItemChange as at, renderAttachmentText as b, archiveConversation as bt, deleteMcpServerSessionId as c, processWorkspaceSnapshotJob as cn, acceptsWebMessages as ct, getMcpStoredOAuthCredentials as d, actorFromRun as dn, createAndEnqueueConversation as dt, AgentDepthLimitError as en, readViewerAutomationVersions as et, putMcpStoredOAuthCredentials as f, toolInvocationDestination as fn, createConversationId as ft, readPublicArtifact as g, collectAttachmentGarbage as gt, publicArtifactHeaders as h, decodeInputImages as ht, buildAuthPauseResponse as i, AgentMessageTargetError as in, listOwnedWatches as it, verifySlackSignature as j, createConversationTurnWorker as jt, parseSlackUserInputSubmission as k, recordSubagentStarted as kt, deleteMcpStoredOAuthCredentials as l, ingestEvent as ln, appendAndEnqueueWebMessage as lt, readStats as m, webActorFromUser as mt, executeAgentRun as n, AgentMessagePausedError as nn, AutomationEditError as nt, deleteMcpAuthSession as o, listChildAgents as on, renderReviewItemMessage as ot, latestProgressStatus as p, shouldEmitDevAgentTrace as pn, recordWebConversationActivity as pt, readViewerAutomationEdit as q, turnInputTelemetry as qt, processBackgroundCompaction as r, AgentMessageQueueFullError as rn, effectiveTaskOutcomes as rt, deleteMcpAuthSessionsForUserProvider as s, listUnreportedSiblingAgents as sn, reviewItemChangeRecord as st, createAgentRunner as t, AgentInvocationLimitError as tn, readViewerAutomations as tt, getMcpAuthSession as u, RetryableDeliveryError as un, conversationTurnIdForMessage as ut, setConversationSubscription as v, requestAttachmentDeletion as vt, syncReviewItemSlackCards as w, jsonResponse as wt, renderBlockText as x, conversationReadPositionQuery as xt, lookupSlackUserProfile as y, storeAttachment as yt, joinPublicChannel as z, canJoinTurn as zt };