@sentry/junior 0.287.0 → 0.288.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 (72) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-Cikcqdty.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BcSxHuTB.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-9MXyWUL8.js} +173 -89
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +8 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +403 -40
  8. package/dist/{app-DBY5TnfY.d.ts → app-BUklJVBe.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +521 -70
  11. package/dist/{assistant-reply-u_PRYzuz.js → assistant-reply-mj47jMRV.js} +1 -1
  12. package/dist/{automation-DksGNDRO.js → automation-DDXwHQs5.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-CjllSPir.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-DW9iuolG.js} +4 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-B3gfH58M.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-CLJcyYEF.js} +401 -9
  24. package/dist/{connections-BnIj0wtx.js → connections-BtdJftow.js} +9 -9
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-DhoqHtQ7.js} +23 -6
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-DHV0S4uF.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-BPirIVlX.js} +1 -1
  28. package/dist/core-model-BTt5E5b0.js +182 -0
  29. package/dist/{credential-sync-CzMar9hq.js → credential-sync-Co8Q2xRW.js} +28 -20
  30. package/dist/{db-DJ11eZqq.js → db-Co7DTYYh.js} +30 -20
  31. package/dist/{db-YDKKDxlh.d.ts → db-zIs8-Ba3.d.ts} +6 -2
  32. package/dist/{executor-BY9TB31g.js → executor-m0kIN71Q.js} +93 -12
  33. package/dist/{media-Cz1ZiV1U.js → history-IjdmO_r6.js} +6 -86
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{logging-BO5zU6Mt.js → logging-DbD-dErY.js} +3 -2
  36. package/dist/media-BAHvgkok.js +85 -0
  37. package/dist/{message-CsUbuEc8.js → message-DKTdTYm-.js} +9 -9
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +19 -41
  40. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-CpbepSbp.js} +2 -2
  41. package/dist/{projection-CL_YWeGf.js → projection-BViECfYu.js} +309 -616
  42. package/dist/{prompt-BHOEQSmf.js → prompt-KT6MaDHN.js} +2 -182
  43. package/dist/{registry-BriFLnaJ.js → registry-D-Acyjhh.js} +1 -1
  44. package/dist/{resolve-Bt6GgAiA.js → resolve-gkT2R66z.js} +3 -3
  45. package/dist/{result-Bo1TZu0Q.js → result-DHmCFEt8.js} +8 -8
  46. package/dist/{runner-D3YeCQgt.js → runner-DBKjGjH-.js} +8 -8
  47. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-9n8hqx29.js} +1 -1
  48. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  49. package/dist/{schema-C6fsEwjo.d.ts → schema-B_6aOcx5.d.ts} +114 -3
  50. package/dist/{schema-BWE3RJEB.js → schema-DxicIQbc.js} +66 -13
  51. package/dist/{service-account-r6fl0b-9.js → service-account-Bi0HsY6w.js} +3 -3
  52. package/dist/{service-account-DiQQuuw7.js → service-account-CDlC9ssy.js} +3 -3
  53. package/dist/{session-stop-B2Nut40V.js → session-stop-BWOsuo8p.js} +56 -14
  54. package/dist/{skills-CD5aJdzg.js → skills-DO5K68Rq.js} +2 -2
  55. package/dist/{spawn-CalgZQiu.js → spawn-BBqZDcPa.js} +5 -5
  56. package/dist/{stop-kujZLbi0.js → stop-WC97cmHz.js} +802 -338
  57. package/dist/{store-DdIEUL1q.js → store-ByR1Lr7e.js} +4 -16
  58. package/dist/{task-runner-D_RDr2Hu.js → task-runner-B-Ewf8TX.js} +30 -22
  59. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-CpdPoZSl.js} +18 -9
  60. package/dist/{validation-K4pqwoVZ.js → validation-B4sbIoES.js} +1 -1
  61. package/dist/{version-DBvhk1X9.js → version-D6lpuAgL.js} +1 -1
  62. package/dist/version.js +1 -1
  63. package/dist/{viewer-DrMmFUul.js → viewer-CeP27tC3.js} +4 -4
  64. package/dist/warmup-P_GJCL1c.js +767 -0
  65. package/dist/{work-ljRoODGu.js → work-DI7x1Slm.js} +14 -13
  66. package/dist/{worker-CYO1Q0Js.js → worker-CYPTOT4j.js} +6 -6
  67. package/migrations/0089_conversation_paused_status.sql +3 -0
  68. package/migrations/0090_guardian_review_time_index.sql +20 -0
  69. package/migrations/meta/0089_snapshot.json +4372 -0
  70. package/migrations/meta/0090_snapshot.json +4388 -0
  71. package/migrations/meta/_journal.json +14 -0
  72. package/package.json +5 -4
@@ -1,32 +1,35 @@
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 continuableMessages, $i as downloadPrivateSlackFile, $r as getDashboardConversationLink, $t as persistWithRetry, Aa as workspaceRepoCheckoutPath, An as getOAuthAccountProviders, Ar as getSlackToolContext, B as getAgentContextCompactionTriggerTokens, Ba as sandboxSkillFile, Bi as deleteSlackMessage, Bn as getPlugins, Br as deliverWatch, Ci as isStale, Da as SANDBOX_RUNTIME, Dn as createUserTokenStore, Dr as resolveAssignee, E as resolveTaskTitle, Er as automationCreatorUserId, Fa as SANDBOX_DATA_ROOT, Fi as normalizeSlackReplyMarkdown, G as authorizationId, Gi as postSlackMessage, Gt as TURN_LIMIT_WRAP_UP_MESSAGE, H as createPluginEgress, Ha as buildCommandScript, Hi as openSlackDirectMessage, Hr as getWatch, Ia as SANDBOX_REPOS_ROOT, Ir as cancelWatch, J as AuthorizationPauseError, Ji as updateSlackMessage, Jt as TurnToolCallLimitExceededError, K as AuthPausePersistenceError, Kt as TurnBudgetExceededError, L as upsertConversationMessage, La as SANDBOX_SKILLS_ROOT, Li as slackMention, M as markConversationMessage, Mo as piMessageFromHistoryItem, Mr as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, N as normalizeConversationText, Ni as escapeSlackMrkdwnText, Nn as createPluginHookRunner, No as projectConversationEvents, Nr as RESOURCE_WATCH_TOOL_SOURCE, Oa as sleep, Oi as deliverOAuthAuthorization, On as findLegacyWebActorUserId, Or as resolveAssignees, P as recordDeliveredAssistantMessage, Pa as SANDBOX_COMMAND_PATH, Po as getConfigDefaults, Pr as STOP_WATCHING_TOOL_NAME, Qi as SlackActionError, Qt as CODEMODE_TOOL_NAME, R as calculateContextCompactionTargetTokens, Ra as SANDBOX_WORKSPACE_ROOT, Rn as getPluginTools, Rr as createTimerWatch, Si as hash, T as fallbackShortTitle, Ta as resolveSandboxCommandEnvironment, Ti as getSandboxProvider, To as resolveUserTimezone, Tr as EVERYONE_ASSIGNEE, U as PluginCredentialFailureError, Ua as buildNonInteractiveShellScript, Ur as listWatches, V as getAgentContextInputLimitTokens, Va as sandboxSkillPathResolution, Vi as getSlackMessagePermalink, Vr as findMatchingWatches, W as createPluginAuthOrchestration, Wa as runNonInteractiveCommand, X as canReusePendingAuthLink, Xt as createTurnLimitGate, Y as abandonReplacedPendingAuth, Ya as readConversationAccessFromSql, Yi as uploadFilesToConversation, Z as clearPendingAuth, Zr as verifyTimerWatchCredentialSubject, Zt as isTurnExecutionLimitExceededError, _a as workspaceSnapshotNotReadyUserMessage, _i as invalidateReadySnapshot, _r as canReadReviewItem, a as loadProjection, aa as normalizeSlackConversationId, an as hasTurnInput, ar as getOpenReviewItemByDedupeKey, b as persistConversationMessages, ba as consumeSandboxEgressPermissionDeniedSignal, bi as setWorkspaceSnapshotBuild, bo as saveObjectAnnotations, br as requireReviewItemAssignees, c as recordAgentsInstructionsUpdated, ci as renderToolResultNudge, cn as isContinuablePiBoundary, da as isAlreadyExistsError, di as getWorkspace, dn as isToolResultMessage, dr as searchReviewItems, ea as getFilePermalink, en as extractAssistantText, et as loadTurnCheckpoint, f as recordAuthorizationRequested, fa as throwSandboxOperationError, fi as getWorkspaceByName, fn as normalizeToolNameFromResult, g as recordToolExecutionStarted, ga as isWorkspaceSnapshotNotReadyError, gi as WorkspaceValidationError, gn as REQUEST_CONTEXT_SECTION_TAG, gr as canAgentChangeReviewItem, ha as getWorkspaceSnapshotNotReadyError, hi as updateWorkspace, hn as trimTrailingAssistantMessages, ho as matchSlackAttachments, i as loadConversationProjection, ir as dismissOpenReviewItems, it as abandonTurnRecord, j as latestConversationMessageSeq, ja as PluginToolDeniedError, ji as resolveBaseUrl, jo as historyItemFromPiMessage, jr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, ka as tryWorkspaceRepoCheckoutPath, ki as formatProviderLabel, kr as resolveChannelCapabilities, l as recordAttachmentsDelivered, li as createWorkspace, ln as isStandaloneRuntimeContextMessage, m as recordMcpProviderConnected, ma as WorkspaceSnapshotNotReadyError, mn as stripRuntimeTurnContext, mr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, na as getSlackClient, nn as getTerminalAssistantMessages, nr as closeReviewItem, oa as runWithSlackInstallationToken, oi as ToolInputError, or as getReviewItem, ot as failTurnRecord, p as recordGuardianActionReviewed, pa as wrapSandboxSetupError, pi as listWorkspaces, pn as retainRuntimeTurnContext, pr as updateReviewItemContent, q as AuthorizationFlowDisabledError, qa as canAccessConversation, qt as TurnSliceLimitExceededError, r as loadConnectedMcpProviders, ra as isConversationScopedChannel, ri as getDashboardTaskLink, rn as getUserMessageInstructionText, rt as saveTurnCheckpoint, sa as withSlackRetries, sn as isAssistantMessage, sr as insertReviewItem, st as getTurnRecord, t as commitAcceptedReply, ti as getDashboardReviewItemLink, tn as getPiMessageRole, ua as isAbortError, ui as deleteWorkspace, un as isToolResultError, v as hydrateConversationMessages, va as clearSandboxEgressSignals, vi as loadSnapshotsForProfile, vn as TURN_CONTEXT_TAG, wa as buildSandboxEgressNetworkPolicy, wi as ensureDockerDaemon, wo as defaultTimezone, xa as createSandboxEgressCredentialToken, xi as create, xn as readParentAgentTask, xo as createPluginAnnotations, xr as requireReviewItemLinks, ya as consumeSandboxEgressAuthRequiredSignal, yi as setWorkspaceSnapshot, yr as readReviewItemAgentScope, z as getAgentBackgroundCompactionMarkTokens, za as sandboxSkillDir, zi as addReactionToMessage, zr as createWatch } from "./projection-BViECfYu.js";
3
+ import { A as estimateRequestOverheadTokens, B as ProviderError, E as resolveGatewayModel, F as isCompactionSummaryText, G as isProviderRetryError, H as findProviderError, K as getGatewayApiKey, L as unwrapCurrentInstruction, M as textCharsForTokens, N as COMPACTION_SUMMARY_PREFIX, O as requestPrefixAttributes, P as hasCompactedConversationContext, R as escapeXml, U as getProviderErrorAttributes, V as createProviderError, _ as toPiReasoningLevel, b as GEN_AI_SERVER_ADDRESS, g as TURN_REASONING_LEVELS, j as estimateTextTokens, k as estimateMessagesTokens, n as botConfig, q as resolveGatewayCredential, v as normalizeSlackEmojiName, y as GEN_AI_PROVIDER_NAME } from "./config-CLJcyYEF.js";
4
+ import { C as summarizeMessageText, E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, K as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, _ 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-DbD-dErY.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-BPirIVlX.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 { B as conversationDetailTouch, D as resolveActorIdentityId, H as touchConversationDetail, J as resolveRootConversationId$1, Q as sameDestination, T as SYSTEM_IDENTITY_ID, U as addAgentTurnUsage, V as nextDetailVersion, W as agentTurnCostUsd, X 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 hasAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, u as treeHasAnnotationKey, x as conversationKindFromRow } from "./db-Co7DTYYh.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-m0kIN71Q.js";
9
+ import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-IjdmO_r6.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-D-Acyjhh.js";
12
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B3gfH58M.js";
13
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-DO5K68Rq.js";
14
+ import { n as completeObject, r as completeText } from "./core-model-BTt5E5b0.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-CeP27tC3.js";
17
+ import { r as getStateAdapter } from "./adapter-Cikcqdty.js";
18
+ import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-cP0AACm1.js";
19
+ import { r as detectImageMediaType } from "./media-BAHvgkok.js";
20
+ import { G as readMessageAttachments, J as briefOutcomeStatusSchema, Q as parseStoredBrief, q as briefLinkSchema, z as removedCardSchema } from "./conversation-DhoqHtQ7.js";
21
+ import { o as isEventConversationMessage, r as EVENT_AUTHOR_ID } from "./prompt-KT6MaDHN.js";
22
+ import { i as createCacheWarmingRecorder } from "./warmup-P_GJCL1c.js";
23
+ 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-CjllSPir.js";
24
+ 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-CpdPoZSl.js";
25
+ import { i as NO_REPLY_MARKER, n as getAssistantReplyText, o as isNoReplyMarker, r as sanitizeAssistantText, t as decideReply } from "./assistant-reply-mj47jMRV.js";
26
+ 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-BWOsuo8p.js";
23
27
  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";
28
+ import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-gkT2R66z.js";
29
+ import { T as stopConversationWork, g as getConversationWorkState, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-ByR1Lr7e.js";
30
+ 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-B-Ewf8TX.js";
31
+ 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-CDlC9ssy.js";
32
+ 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-DDXwHQs5.js";
30
33
  import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
31
34
  import { streamSimple } from "@earendil-works/pi-ai/compat";
32
35
  import { createGatewayProvider } from "@ai-sdk/gateway";
@@ -39,7 +42,7 @@ import * as z from "zod";
39
42
  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
43
  import { PluginToolInputError, agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, eventMatchFieldSchema, eventSchema, eventTriggerText, localDestinationSchema, missingToolAnnotationKeys, ownedObjectAnnotationSchema, sourceSchema, stableEventMatchKey, watchResultSchema } from "@sentry/junior-plugin-api";
41
44
  import { alias } from "drizzle-orm/pg-core";
42
- import { Agent, estimateContextTokens, estimateTokens } from "@earendil-works/pi-agent-core";
45
+ import { Agent, estimateContextTokens } from "@earendil-works/pi-agent-core";
43
46
  import fs from "node:fs/promises";
44
47
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
45
48
  import http from "node:http";
@@ -698,6 +701,7 @@ function buildChatEndAttributes(message, mode) {
698
701
  if (outputMessages) attributes["gen_ai.output.messages"] = outputMessages;
699
702
  }
700
703
  Object.assign(attributes, extractGenAiUsageAttributes(message));
704
+ if (message.usage.cacheWrite1h !== void 0) attributes["app.ai.usage.cache_write_1h"] = message.usage.cacheWrite1h;
701
705
  if (message.stopReason) attributes["gen_ai.response.finish_reasons"] = [normalizeGenAiFinishReason(message.stopReason)];
702
706
  if (message.model) attributes["gen_ai.response.model"] = message.model;
703
707
  if (message.responseId) attributes["gen_ai.response.id"] = message.responseId;
@@ -753,6 +757,17 @@ function traceResponseHeaders(span, options) {
753
757
  }
754
758
  };
755
759
  }
760
+ function traceRequestPayload(span, options) {
761
+ const onPayload = options?.onPayload;
762
+ return {
763
+ ...options,
764
+ onPayload: async (payload, model) => {
765
+ const nextPayload = await onPayload?.(payload, model);
766
+ span.setAttributes(requestPrefixAttributes(nextPayload ?? payload));
767
+ return nextPayload;
768
+ }
769
+ };
770
+ }
756
771
  function relayStream(source, onEvent) {
757
772
  const relayed = createAssistantMessageEventStream();
758
773
  const finished = (async () => {
@@ -796,7 +811,7 @@ function createTracedStreamFn(baseOrOptions = streamSimple) {
796
811
  });
797
812
  try {
798
813
  const requestStartedAtMs = Date.now();
799
- const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, traceResponseHeaders(span, options))));
814
+ const stream = await withActiveSpan(span, () => Promise.resolve(base(model, context, traceRequestPayload(span, traceResponseHeaders(span, options)))));
800
815
  const responseTiming = createResponseTiming(requestStartedAtMs);
801
816
  const relay = relayStream(stream, responseTiming.observe);
802
817
  relay.finished.then(() => stream.result()).then((finalMessage) => {
@@ -3715,13 +3730,18 @@ function createSandbox(options) {
3715
3730
  const timeoutMs = positiveInteger$1(rawInput.timeoutMs);
3716
3731
  logSandboxBootRequest("tool.bash", { "app.sandbox.command_length": command.length });
3717
3732
  let tools = await runtime.tools(context.signal);
3733
+ const waitStartedAtMs = Date.now();
3718
3734
  const bashTurn = await takeBashTurn();
3735
+ const waitMs = Date.now() - waitStartedAtMs;
3719
3736
  try {
3720
3737
  context.signal?.throwIfAborted();
3721
3738
  if (bashTurn.waited) tools = await runtime.tools(context.signal);
3722
3739
  const { bash: executeBash, sessionId: activeSessionId } = tools;
3723
3740
  await clearEgressSignals(activeSessionId);
3724
- const result = await withSandboxToolSpan("bash", "process.exec", { "process.executable.name": "bash" }, async () => {
3741
+ const result = await withSandboxToolSpan("bash", "process.exec", {
3742
+ "process.executable.name": "bash",
3743
+ "app.sandbox.bash.wait_ms": waitMs
3744
+ }, async () => {
3725
3745
  const response = await executeBash({
3726
3746
  command,
3727
3747
  cwd,
@@ -3740,6 +3760,7 @@ function createSandbox(options) {
3740
3760
  return response;
3741
3761
  });
3742
3762
  const { authRequired, permissionDenied } = await consumeEgressSignals(activeSessionId);
3763
+ if (!authRequired && `${result.stdout ?? ""}${result.stderr ?? ""}`.includes(`junior-auth-required provider=`)) logWarn("sandbox.egress.auth_signal.missing", { "app.sandbox.egress_id": activeSessionId });
3743
3764
  return formatSandboxCommandResult({
3744
3765
  ok: result.exitCode === 0,
3745
3766
  command,
@@ -4320,7 +4341,6 @@ function createAgentSandbox(options) {
4320
4341
  // src/chat/mcp/tool-manager.ts
4321
4342
  const MAX_TOOL_RESULT_TOKENS = 1e4;
4322
4343
  const MAX_TOOL_RESULT_BYTES = 32768;
4323
- const CHARS_PER_ESTIMATED_TOKEN = 4;
4324
4344
  function normalizeMcpToolName(provider, toolName) {
4325
4345
  return `mcp__${provider}__${toolName}`;
4326
4346
  }
@@ -4416,10 +4436,10 @@ function suffixWithin(value, maxChars, maxBytes) {
4416
4436
  function boundMcpContent(content) {
4417
4437
  const text = content.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
4418
4438
  const originalBytes = utf8Bytes(text);
4419
- const originalTokens = Math.ceil(text.length / CHARS_PER_ESTIMATED_TOKEN);
4439
+ const originalTokens = estimateTextTokens(text);
4420
4440
  if (originalTokens <= MAX_TOOL_RESULT_TOKENS && originalBytes <= MAX_TOOL_RESULT_BYTES) return content;
4421
4441
  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;
4442
+ const remainingChars = textCharsForTokens(MAX_TOOL_RESULT_TOKENS) - warning.length;
4423
4443
  const remainingBytes = MAX_TOOL_RESULT_BYTES - utf8Bytes(warning);
4424
4444
  const head = prefixWithin(text, Math.ceil(remainingChars / 2), Math.ceil(remainingBytes / 2));
4425
4445
  return [{
@@ -5898,7 +5918,7 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
5898
5918
  },
5899
5919
  inputSchema: z.object({
5900
5920
  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."),
5921
+ 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
5922
  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
5923
  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."),
5904
5924
  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."),
@@ -6365,9 +6385,22 @@ async function completeCancelledConversationTurn(args) {
6365
6385
  await args.acknowledge();
6366
6386
  }
6367
6387
  /**
6388
+ * End the Turn of a stopped Conversation that waits for sign-in, so a later
6389
+ * sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
6390
+ * Slack request waits as the thread's pending sign-in. Every stop path calls
6391
+ * this, because no worker holds a waiting Turn and the stop wake can go to
6392
+ * queued input first.
6393
+ */
6394
+ async function cancelSignInWait(conversationId) {
6395
+ const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
6396
+ if (turnId) await cancelSignInPausedTurn({
6397
+ conversationId,
6398
+ turnId
6399
+ });
6400
+ }
6401
+ /**
6368
6402
  * 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.
6403
+ * cleanup as a stopped resume.
6371
6404
  */
6372
6405
  async function cancelSignInPausedTurn(args) {
6373
6406
  if (!await abandonTurnRecord({
@@ -7018,9 +7051,9 @@ async function stopChildAgentsBelow(conversationId, options) {
7018
7051
  * stopped each child agent, so no result becomes `appended` after this read.
7019
7052
  *
7020
7053
  * 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`.
7054
+ * a result before this update holds the work lease, so the stop request of
7055
+ * the Conversation stops its Turn. A result that such a Turn took but did not
7056
+ * ack yet is marked `skipped`.
7024
7057
  */
7025
7058
  async function skipUnreadResults(conversationId, nowMs, state) {
7026
7059
  const invocationIds = ((await getConversationWorkState({
@@ -7045,11 +7078,7 @@ async function finishStoppedTree(tree, conversationIdsToStop, options) {
7045
7078
  for (const invocation of tree.stopped) await recordSubagentEnded(invocation);
7046
7079
  await markConversationsStopped(conversationIdsToStop, options);
7047
7080
  for (const conversationId of conversationIdsToStop) {
7048
- const pausedTurnId = await getAuthPausedConversationTurnId(conversationId);
7049
- if (pausedTurnId) await cancelSignInPausedTurn({
7050
- conversationId,
7051
- turnId: pausedTurnId
7052
- });
7081
+ await cancelSignInWait(conversationId);
7053
7082
  await stopConversationWork({
7054
7083
  conversationId,
7055
7084
  state: options.state
@@ -7948,6 +7977,7 @@ async function recordWebConversationActivity(args) {
7948
7977
  actor: storedActorFromWeb(args.actor),
7949
7978
  ...isNewRoot ? { source: "web" } : void 0,
7950
7979
  ...source ? { sessionSource: source } : void 0,
7980
+ ...isNewRoot && args.rootTitle ? { title: args.rootTitle } : void 0,
7951
7981
  ...isNewRoot ? { visibility } : void 0
7952
7982
  });
7953
7983
  return existing && existing.kind !== "root" ? void 0 : destination;
@@ -7965,6 +7995,7 @@ async function createAndEnqueueConversation(input, options) {
7965
7995
  idempotencyKey: input.idempotencyKey,
7966
7996
  message: input.message,
7967
7997
  images: input.images,
7998
+ ...input.title ? { rootTitle: input.title } : void 0,
7968
7999
  rootVisibility: input.visibility === "private" ? "private" : "public"
7969
8000
  }, options);
7970
8001
  }
@@ -7982,6 +8013,7 @@ async function appendAndEnqueueWebMessage(input, options) {
7982
8013
  conversationId: input.conversationId,
7983
8014
  conversationStore: options.conversationStore,
7984
8015
  nowMs,
8016
+ ...input.rootTitle && { rootTitle: input.rootTitle },
7985
8017
  ...input.rootVisibility && { rootVisibility: input.rootVisibility }
7986
8018
  });
7987
8019
  let attachments = [];
@@ -16081,6 +16113,7 @@ function createWorkspaceTools(context) {
16081
16113
  }),
16082
16114
  switchWorkspace: zodTool({
16083
16115
  executionMode: "sequential",
16116
+ exposure: "modelOnly",
16084
16117
  annotations: {
16085
16118
  destructiveHint: true,
16086
16119
  idempotentHint: true,
@@ -17685,7 +17718,6 @@ async function runCodeModeScript(run) {
17685
17718
  * Pi's coding agent uses the same default.
17686
17719
  */
17687
17720
  const DECLARATION_BUDGET_TOKENS = 3e3;
17688
- const CHARS_PER_TOKEN = 4;
17689
17721
  /** Fields of the shared tool result envelope. They say nothing about one tool. */
17690
17722
  const ENVELOPE_FIELDS = new Set(juniorToolOutputSchema.keyof().options);
17691
17723
  /**
@@ -17715,17 +17747,19 @@ function renderDeclaration(name, tool) {
17715
17747
  }).trim().replace(/\n/g, "\n ")}`;
17716
17748
  }
17717
17749
  /**
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.
17750
+ * Tell the script which tools it may call. Direct tools are only named: the
17751
+ * model already has their input schemas. The other tools are declared within
17752
+ * the token budget, cheapest first, so that the most tools fit. The others
17753
+ * stay callable. The model finds their input with `searchTools`. Script-only
17754
+ * tools come first, because `searchTools` does not find them. The same tools
17755
+ * give the same text, so the description does not change between Turns.
17723
17756
  */
17724
17757
  function renderScriptTools(tools) {
17725
- const entries = Object.entries(tools).map(([name, tool]) => {
17758
+ const directNames = Object.entries(tools).filter(([, tool]) => effectiveToolExposure(tool) === "direct").map(([name]) => name).sort((a, b) => a.localeCompare(b));
17759
+ const entries = Object.entries(tools).filter(([, tool]) => effectiveToolExposure(tool) !== "direct").map(([name, tool]) => {
17726
17760
  const text = renderDeclaration(name, tool);
17727
17761
  return {
17728
- cost: Math.ceil(text.length / CHARS_PER_TOKEN),
17762
+ cost: estimateTextTokens(text),
17729
17763
  name,
17730
17764
  scriptOnly: effectiveToolExposure(tool) === "codemode",
17731
17765
  text
@@ -17741,9 +17775,12 @@ function renderScriptTools(tools) {
17741
17775
  shown.sort((a, b) => a.name.localeCompare(b.name));
17742
17776
  const omitted = entries.length - shown.length;
17743
17777
  return [
17744
- "declare const tools: {",
17745
- ...shown.map((entry) => entry.text),
17746
- "};",
17778
+ ...directNames.length > 0 ? [`These tools from your tool list can also be called as \`tools.<name>(args)\`, with the same input: ${directNames.join(", ")}.`] : [],
17779
+ ...shown.length > 0 ? [
17780
+ "declare const tools: {",
17781
+ ...shown.map((entry) => entry.text),
17782
+ "};"
17783
+ ] : [],
17747
17784
  ...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
17785
  ...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
17786
  ].join("\n");
@@ -19142,7 +19179,7 @@ function isToolEntry(entry) {
19142
19179
  function truncateText(text, maxTokens) {
19143
19180
  const tokenCount = estimateTextTokens(text);
19144
19181
  if (tokenCount <= maxTokens) return text;
19145
- const maxChars = maxTokens * 4;
19182
+ const maxChars = textCharsForTokens(maxTokens);
19146
19183
  const marker = `<truncated omitted_approx_tokens="${Math.max(1, tokenCount - maxTokens)}" />`;
19147
19184
  if (maxChars <= marker.length) return marker;
19148
19185
  const availableChars = maxChars - marker.length;
@@ -20067,10 +20104,13 @@ const SUMMARY_NUDGE = "Do not call tools. Keep the summary short. Return only th
20067
20104
  /** Raised when the model returns no usable summary after one nudge. */
20068
20105
  var ContextSummaryError = class extends Error {
20069
20106
  failure;
20070
- constructor(failure) {
20071
- super(`Context summary failed: ${failure}`);
20107
+ /** Estimated cost of the summary requests that did not succeed. */
20108
+ costUsd;
20109
+ constructor(failure, costUsd, options) {
20110
+ super(`Context summary failed: ${failure}`, options);
20072
20111
  this.failure = failure;
20073
20112
  this.name = "ContextSummaryError";
20113
+ if (costUsd !== void 0) this.costUsd = costUsd;
20074
20114
  }
20075
20115
  };
20076
20116
  /**
@@ -20141,16 +20181,34 @@ function readSummary(message) {
20141
20181
  *
20142
20182
  * A tool call, a stop at the output limit, empty output, or output without
20143
20183
  * `<summary>` tags gets one nudge. A second failure throws
20144
- * `ContextSummaryError`, so the caller keeps the full history.
20184
+ * `ContextSummaryError`, so the caller keeps the full history. The cost
20185
+ * covers each summary request, including a nudged one.
20145
20186
  */
20146
20187
  async function requestContextSummary(request, streamFn) {
20147
20188
  const instruction = userText(SUMMARY_INSTRUCTION);
20148
- const first = readSummary(await complete(request, streamFn, [instruction]));
20149
- if ("summary" in first) return first.summary;
20189
+ const firstMessage = await complete(request, streamFn, [instruction]);
20190
+ const first = readSummary(firstMessage);
20191
+ if ("summary" in first) return withCost(first.summary, firstMessage);
20150
20192
  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);
20193
+ let secondMessage;
20194
+ try {
20195
+ secondMessage = await complete(request, streamFn, [instruction, userText(SUMMARY_NUDGE)]);
20196
+ } catch (error) {
20197
+ throw new ContextSummaryError("request_failed", summaryCostUsd(firstMessage), { cause: error });
20198
+ }
20199
+ const second = readSummary(secondMessage);
20200
+ if ("summary" in second) return withCost(second.summary, firstMessage, secondMessage);
20201
+ throw new ContextSummaryError(second.failure, summaryCostUsd(firstMessage, secondMessage));
20202
+ }
20203
+ function summaryCostUsd(...messages) {
20204
+ return agentTurnCostUsd(extractGenAiUsageSummary(...messages));
20205
+ }
20206
+ function withCost(summary, ...messages) {
20207
+ const costUsd = summaryCostUsd(...messages);
20208
+ return costUsd === void 0 ? { summary } : {
20209
+ summary,
20210
+ costUsd
20211
+ };
20154
20212
  }
20155
20213
  // src/chat/services/background-compaction.ts
20156
20214
  /**
@@ -20227,7 +20285,7 @@ async function loadLatestBackgroundCompaction(conversationId) {
20227
20285
  }
20228
20286
  /**
20229
20287
  * 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.
20288
+ * Then `mayRequest` is false too, so a Turn can skip the other reads.
20231
20289
  * Only one request is pending at a time, so the newest fact decides it.
20232
20290
  */
20233
20291
  function waitsForUse(event, nowMs) {
@@ -20260,9 +20318,12 @@ async function requestBackgroundCompaction(args) {
20260
20318
  }
20261
20319
  async function requestAboveMark(args) {
20262
20320
  const nowMs = Date.now();
20263
- const latest = await loadLatestBackgroundCompaction(args.conversationId);
20264
- if (latest && waitsForUse(latest.event, nowMs)) return;
20265
20321
  const eventStore = getConversationEventStore();
20322
+ const latest = await loadLatestBackgroundCompaction(args.conversationId);
20323
+ if (latest) {
20324
+ if (waitsForUse(latest.event, nowMs)) return;
20325
+ if (!mayRequest((await Promise.all([eventStore.loadEventsOfType(args.conversationId, "compaction_requested"), eventStore.loadEventsOfType(args.conversationId, "compaction_prepared")])).flat(), latest.historyVersion, nowMs)) return;
20326
+ }
20266
20327
  const events = await eventStore.loadCurrentHistory(args.conversationId);
20267
20328
  const historyVersion = events[0]?.historyVersion;
20268
20329
  if (historyVersion === void 0 || !mayRequest(events, historyVersion, nowMs)) return;
@@ -20310,7 +20371,7 @@ async function requestAboveMark(args) {
20310
20371
  /** A fixed label for a failed summary. Never raw exception text. */
20311
20372
  function failureLabel(error, signal) {
20312
20373
  if (signal.aborted) return "timeout";
20313
- if (error instanceof ContextSummaryError) return error.failure;
20374
+ if (error instanceof ContextSummaryError && error.failure !== "request_failed") return error.failure;
20314
20375
  const providerError = findProviderError(error);
20315
20376
  return providerError ? `provider_${providerError.kind}` : "summary_error";
20316
20377
  }
@@ -20407,15 +20468,16 @@ async function prepareSummary(message, streamFn) {
20407
20468
  } catch (error) {
20408
20469
  return await writePrepared({
20409
20470
  outcome: "failed",
20410
- errorType: failureLabel(error, signal)
20471
+ errorType: failureLabel(error, signal),
20472
+ ...error instanceof ContextSummaryError && error.costUsd !== void 0 ? { costUsd: error.costUsd } : void 0
20411
20473
  });
20412
20474
  }
20413
20475
  const outcome = await writePrepared({
20414
20476
  outcome: "ready",
20415
- summary
20477
+ ...summary
20416
20478
  });
20417
20479
  if (outcome === "ready") setSpanAttributes({
20418
- "app.compaction.summary_chars": summary.length,
20480
+ "app.compaction.summary_chars": summary.summary.length,
20419
20481
  "app.compaction.ready_ms": Date.now() - request.createdAtMs
20420
20482
  });
20421
20483
  return outcome;
@@ -20522,7 +20584,7 @@ function sanitizeText(text) {
20522
20584
  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
20585
  }
20524
20586
  function truncateToTokenBudget(text, maxTokens) {
20525
- const maxChars = Math.max(0, maxTokens * 4);
20587
+ const maxChars = Math.max(0, textCharsForTokens(maxTokens));
20526
20588
  if (text.length <= maxChars) return text;
20527
20589
  return `${text.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
20528
20590
  }
@@ -20774,15 +20836,6 @@ function measuredReplacementTokens(messages) {
20774
20836
  function estimateReplacementTokens(messages, modelId, requestOverheadTokens = 0) {
20775
20837
  return requestOverheadTokens + estimateMessagesTokens(messages, modelId);
20776
20838
  }
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
20839
  async function loadLastInstruction(conversationId) {
20787
20840
  const event = await getConversationEventStore().loadLatestInstruction(conversationId);
20788
20841
  if (!event) return void 0;
@@ -20866,8 +20919,9 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
20866
20919
  if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
20867
20920
  await args.onCompactionStart?.();
20868
20921
  let summary;
20922
+ let costUsd;
20869
20923
  try {
20870
- summary = await summarize(args.piMessages, args.signal);
20924
+ ({summary, costUsd} = await summarize(args.piMessages, args.signal));
20871
20925
  } catch (error) {
20872
20926
  if (source.estimatedTokens >= inputLimitTokens) throw new ContextInputLimitExceededError(source.estimatedTokens, inputLimitTokens);
20873
20927
  logWarn("context_compaction.active.summary.failed", {
@@ -20915,6 +20969,7 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
20915
20969
  retainedMessageCount,
20916
20970
  summaryChars: summary.length
20917
20971
  },
20972
+ ...costUsd === void 0 ? void 0 : { costUsd },
20918
20973
  summary,
20919
20974
  replacementHistory: replacement.map((entry) => ({
20920
20975
  item: historyItemFromPiMessage(entry.message, entry.provenance),
@@ -21230,7 +21285,10 @@ async function applyPreparedSummary(args, prepared, budget) {
21230
21285
  };
21231
21286
  }
21232
21287
  // src/chat/agent/exclusive-tools.ts
21233
- /** Tools that must be the only tool call in their assistant message. */
21288
+ /**
21289
+ * Tools that must be the only tool call in their assistant message. Each one
21290
+ * must be `modelOnly`: this check does not see script or `executeTool` calls.
21291
+ */
21234
21292
  const EXCLUSIVE_TOOL_NAMES = [
21235
21293
  "switchWorkspace",
21236
21294
  FINISH_AUTOMATION_RUN_TOOL_NAME,
@@ -21240,6 +21298,22 @@ const EXCLUSIVE_TOOL_NAMES = [
21240
21298
  function exclusiveToolName(toolCalls) {
21241
21299
  for (const name of EXCLUSIVE_TOOL_NAMES) if (toolCalls.some((call) => call.name === name)) return name;
21242
21300
  }
21301
+ // src/chat/agent/tool-batch.ts
21302
+ /**
21303
+ * Record how Pi runs the tool calls of one assistant message. Pi runs them
21304
+ * in parallel unless one of their tools is `sequential`; then it runs all of
21305
+ * them one at a time.
21306
+ */
21307
+ function logToolBatch(toolCalls, tools) {
21308
+ const names = toolCalls.map((call) => call.name);
21309
+ const sequentialTools = [...new Set(names)].filter((name) => tools.find((tool) => tool.name === name)?.executionMode === "sequential").sort();
21310
+ logInfo("agent.tool_batch.started", {
21311
+ "app.tool_batch.size": toolCalls.length,
21312
+ "app.tool_batch.execution": sequentialTools.length > 0 ? "sequential" : "parallel",
21313
+ "app.tool_batch.tool_names": names,
21314
+ "app.tool_batch.sequential_tool_names": sequentialTools
21315
+ });
21316
+ }
21243
21317
  // src/chat/agent/index.ts
21244
21318
  /**
21245
21319
  * Agent executor.
@@ -21758,16 +21832,18 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21758
21832
  }
21759
21833
  return acceptedMessages;
21760
21834
  };
21835
+ const cacheWarming = createCacheWarmingRecorder(conversationId, isUserActor(actor) && conversationKind !== "task");
21761
21836
  agent = new Agent({
21762
21837
  getApiKey: getGatewayApiKey,
21763
21838
  sessionId: conversationId,
21764
21839
  streamFn: createTracedStreamFn({
21765
21840
  conversationPrivacy,
21766
- ...streamFn ? { base: streamFn } : void 0
21841
+ base: cacheWarming.wrap(streamFn)
21767
21842
  }),
21768
21843
  steeringMode: "all",
21769
- beforeToolCall: async ({ assistantMessage }) => {
21844
+ beforeToolCall: async ({ assistantMessage, context, toolCall }) => {
21770
21845
  const toolCalls = assistantMessage.content.filter((part) => part.type === "toolCall");
21846
+ if (toolCalls.length > 1 && toolCall.id === toolCalls[0].id) logToolBatch(toolCalls, context.tools ?? []);
21771
21847
  const exclusiveTool = exclusiveToolName(toolCalls);
21772
21848
  if (exclusiveTool && toolCalls.length !== 1) return {
21773
21849
  block: true,
@@ -21843,13 +21919,20 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
21843
21919
  });
21844
21920
  const unsubscribe = agent.subscribe((event) => {
21845
21921
  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
- });
21922
+ if (event.type === "turn_end" && event.toolResults.length > 0) {
21923
+ cacheWarming.toolsReturned();
21924
+ return requireConversationLease("save").then(() => runResume.persistSafeBoundary([...agent.state.messages])).then(() => void 0, (error) => {
21925
+ pendingPiHookError ??= error instanceof Error ? error : new Error(String(error));
21926
+ throw error;
21927
+ });
21928
+ }
21850
21929
  if (event.type === "message_end" && isAssistantMessage(event.message)) {
21851
- if (event.message.stopReason === "error" || event.message.stopReason === "aborted") return;
21852
- return deliverAssistantMessage(event.message);
21930
+ const message = event.message;
21931
+ const delivery = message.stopReason === "error" || message.stopReason === "aborted" ? void 0 : deliverAssistantMessage(message);
21932
+ return Promise.resolve(delivery).then(() => cacheWarming.record(message), async (error) => {
21933
+ await cacheWarming.record(message);
21934
+ throw error;
21935
+ });
21853
21936
  }
21854
21937
  });
21855
21938
  let newMessages = [];
@@ -22063,6 +22146,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
22063
22146
  if (authPauseOutcome) return authPauseOutcome;
22064
22147
  } finally {
22065
22148
  unsubscribe();
22149
+ await cacheWarming.stop();
22066
22150
  }
22067
22151
  await requireConversationLease("save");
22068
22152
  await recordActiveMcpProviders();
@@ -22205,4 +22289,4 @@ function createAgentRunner(execute, options) {
22205
22289
  return await execute(nextRun, streamFn);
22206
22290
  } };
22207
22291
  }
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 };
22292
+ export { readViewerAutomationSummary as $, actorFromRun as $t, runWithSlackInstallation as A, recordSubagentStarted as At, listThreadReplies as B, deleteWebAuthorization as Bt, readSlackReviewItemCardConversationId as C, markConversationRead as Ct, parseSlackReviewItemClick as D, stopChildAgentsBelow as Dt, buildSlackReviewItemModal as E, throwApiError as Et, resolveSlackChannelIdFromThreadId as F, executeTurn as Ft, changeViewerAutomationLifecycle as G, AgentMessageQueueFullError as Gt, logScheduledAutomationRunSkipped as H, AgentDepthLimitError as Ht, checkSlackChannelReadAccess as I, finishTurn as It, updateViewerAutomation as J, listChildAgents as Jt, deleteViewerTask as K, AgentMessageTargetError as Kt, joinPublicChannelForRead as L, getTurnInputSpanAttributes as Lt, parseSlackThreadId as M, createConversationTurnWorker as Mt, readSlackRawMessageContext as N, supersedeOpenMailboxTurns as Nt, parseSlackReviewItemFormTarget as O, stopChildAgentsOf as Ot, resolveSlackChannelIdFromMessage as P, AgentRunError as Pt, readViewerAutomationRuns as Q, RetryableDeliveryError as Qt, getConversationInfo as R, turnInputTelemetry as Rt, createSlackReviewItemShow as S, conversationReadPositionQuery as St, SLACK_REVIEW_ITEM_VIEW_ID as T, jsonResponse as Tt, scheduledAutomationRunAttributes as U, AgentInvocationLimitError as Ut, resolveDestinationVisibility as V, getWebAuthorization as Vt, activateViewerAutomationVersion as W, AgentMessagePausedError as Wt, readConversationSourceTask as X, processWorkspaceSnapshotJob as Xt, ViewerTaskNotFoundError as Y, listUnreportedSiblingAgents as Yt, readViewerAutomationExecutions as Z, ingestEvent 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, toolInvocationDestination 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, cancelSignInWait 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, AgentNameInUseError as qt, processBackgroundCompaction as r, effectiveTaskOutcomes as rt, deleteMcpAuthSessionsForUserProvider as s, reviewItemChangeRecord as st, createAgentRunner as t, shouldEmitDevAgentTrace as tn, 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, withTurnSpan as zt };