@sentry/junior 0.306.0 → 0.307.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 (91) hide show
  1. package/dist/{adapter-context-CnY-i32r.js → adapter-context-B69WPn6b.js} +2 -2
  2. package/dist/{admin-BLLdLnXh.js → admin-nCJXMgkp.js} +2 -2
  3. package/dist/{agent-runner-BaLjEjPR.js → agent-runner-DdFcxAxG.js} +226 -137
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -4
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +328 -298
  8. package/dist/{app-DvYbM9UD.d.ts → app-EZur8cVC.d.ts} +12 -3
  9. package/dist/app.d.ts +2 -2
  10. package/dist/app.js +84 -44
  11. package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
  12. package/dist/{briefs-DvyzXfrF.js → briefs-Dl9lxi7J.js} +2 -2
  13. package/dist/{catalog-runtime-B1R-nHd3.js → catalog-runtime-OXrv2Ewn.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +17 -16
  16. package/dist/cli/check.js +58 -48
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.d.ts +1 -1
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +2 -2
  22. package/dist/cli/upgrade.js +3 -8
  23. package/dist/{config-DUD-zMvp.js → config-362yMSIz.js} +74 -38
  24. package/dist/{connections-CDhsqPcC.js → connections-BJv3EjmB.js} +10 -8
  25. package/dist/{continue-in-slack-BXQizz9o.js → continue-in-slack-CFEevC7z.js} +5 -5
  26. package/dist/{conversation-privacy-YE54gMN8.js → conversation-privacy-Tjj5P2W6.js} +1 -1
  27. package/dist/{conversation-turn-BzdmrHb0.js → conversation-turn-DU0_WDAr.js} +19 -47
  28. package/dist/{credential-sync-Cdm-e1vJ.js → credential-sync-D6aFARKE.js} +28 -28
  29. package/dist/{db-DV2ZUb1Y.js → db-Bcbd9zQc.js} +140 -11
  30. package/dist/{db-pH357Dkt.d.ts → db-C41UgdBj.d.ts} +1 -1
  31. package/dist/{executor-CjNhwwnj.js → executor-DBMBrpNV.js} +93 -32
  32. package/dist/{install-DbD7C5td.js → install-CgoAbzfF.js} +2 -2
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{lineage-BFdIPb3o.js → lineage-CsZDmz3e.js} +2 -2
  35. package/dist/{logging-oYpJYr-S.js → logging-CHCuQ5iz.js} +1 -1
  36. package/dist/{message-BBPcMKJY.js → message-B8vCbZZB.js} +8 -8
  37. package/dist/{model-input-DYYF3a8B.js → model-input-Xluiy-1W.js} +3 -3
  38. package/dist/nitro.d.ts +2 -2
  39. package/dist/nitro.js +3 -4
  40. package/dist/{oauth-callback-server-C7Q987su.js → oauth-callback-server-BUuNvfvu.js} +2 -2
  41. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
  42. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  43. package/dist/{projection-CWXDE0f6.js → projection-xPpvqexa.js} +1112 -693
  44. package/dist/{prompt-P3eRqO8C.js → prompt-D8u4jFs_.js} +3 -3
  45. package/dist/{registry-1pzXmplY.js → registry-D20hG3r6.js} +19 -9
  46. package/dist/{resolve-n87oXY-d.js → resolve-BhCySRCW.js} +3 -3
  47. package/dist/{result-BmF9v9bv.js → result-DddO63S9.js} +13 -11
  48. package/dist/{runner-4j7ZsxP5.js → runner-DQR9vYce.js} +9 -9
  49. package/dist/{sandbox-egress-signals-BRQI8HvT.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
  50. package/dist/{schedule-CHPWQn-x.js → schedule-BG1tEbRF.js} +34 -4
  51. package/dist/{schema-CVbIjrF3.d.ts → schema-CRXcj4fj.d.ts} +350 -143
  52. package/dist/{schema-D7iIEh6t.js → schema-D4jdesIu.js} +12 -4
  53. package/dist/{service-account-DzQiOmqa.js → service-account-Bv5QwrEq.js} +8 -6
  54. package/dist/{service-account-BDQ9xzta.js → service-account-CNfycv0z.js} +3 -3
  55. package/dist/{session-stop-BQxgHR4X.js → session-stop-BDdwyZaa.js} +36 -23
  56. package/dist/{skills-CPf4vNuC.js → skills-63i1Bcv1.js} +32 -28
  57. package/dist/{slack-conversation-unfurl-B1KEptUg.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -10
  58. package/dist/{spawn-CjGddiAU.js → spawn-mwimEY9_.js} +6 -6
  59. package/dist/{state-9wfj6aSD.js → state-BBn9L6gC.js} +4 -4
  60. package/dist/{stop-CsQGuN5n.js → stop-Da-Ug7tg.js} +146 -158
  61. package/dist/{store-Dz3YZ7gQ.js → store-CdWg2r2L.js} +5 -5
  62. package/dist/{background-compaction-queue-D2wzxtGU.js → task-queue-BcjAYWyB.js} +164 -180
  63. package/dist/{task-runner-frzlUvFD.js → task-runner-CoXmMlsW.js} +11 -8
  64. package/dist/{thread-context-C4QuZlM8.js → thread-context-ZPGqOjW7.js} +6 -6
  65. package/dist/{turn-session-routing-BXaubz2w.js → turn-session-routing-DFYak28Q.js} +24 -5
  66. package/dist/{turn-user-message-DNC0eRZ7.js → turn-user-message-B1S8nOnG.js} +3 -3
  67. package/dist/{users-XCCKn3xW.js → users-DDbENg-I.js} +1 -1
  68. package/dist/{validation-L5fdjmFX.js → validation-fl21ps-k.js} +1 -1
  69. package/dist/{version-BFmuwgxP.js → version-DCdMMx_0.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-DKOeHpv3.js → viewer-DN_xzVKj.js} +3 -3
  72. package/dist/{warmup-mTMIatCV.js → warmup-CxhEhm71.js} +596 -281
  73. package/dist/{web-message-id-CUaSiGme.js → web-message-id-BT8Mg8LL.js} +1 -1
  74. package/dist/{worker-Bz4KNxjI.js → worker-Btb1SB5h.js} +8 -7
  75. package/migrations/0115_automation_creator_slack_index.sql +1 -0
  76. package/migrations/0116_conversation_event_search.sql +25 -0
  77. package/migrations/0117_automation_last_run.sql +46 -0
  78. package/migrations/0118_automation_last_run_index.sql +1 -0
  79. package/migrations/0119_money_micro_usd.sql +29 -0
  80. package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
  81. package/migrations/meta/0115_snapshot.json +5225 -0
  82. package/migrations/meta/0116_snapshot.json +5388 -0
  83. package/migrations/meta/0117_snapshot.json +5413 -0
  84. package/migrations/meta/0118_snapshot.json +5428 -0
  85. package/migrations/meta/0119_snapshot.json +5441 -0
  86. package/migrations/meta/0120_snapshot.json +5441 -0
  87. package/migrations/meta/_journal.json +42 -0
  88. package/package.json +10 -9
  89. package/dist/queue-7FSijgqG.js +0 -115
  90. package/dist/secrets-DHaJ5TTn.js +0 -18
  91. package/dist/task-queue-CFlrJguF.js +0 -89
@@ -1,37 +1,38 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $ as pauseLostWorkerTurn, $n as getPlugins, $r as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, $s as deleteEventAutomation, Ac as ToolInputError, Ai as WorkspaceValidationError, Ar as updateReviewItemContent, B as PluginCredentialFailureError, Br as requireReviewItemLinks, Ca as SANDBOX_WORKSPACE_ROOT, Ci as createWorkspace, Cr as getReviewItem, Di as listWorkspaces, Ec as sameDefinitionValue, Ei as getWorkspaceByName, Fa as readConversationAccessFromSql, Fc as readAutomationExecutionStatusDays, Fi as create, Fo as getDispatchRecord, Fs as saveScheduledAutomation, Gr as activeParticipantUserIds, Gs as getDashboardTaskLink, Hc as fallbackShortTitle, Ic as readAutomationExecutionStatusHours, J as clearPendingAuth, Jo as getSlackMessagePermalink, Jr as resolveAssignees, Kn as createPluginHookRunner, Kr as automationCreatorUserId, Lc as readAutomationExecutionSummaries, Li as isStale, Ma as canAccessConversation, Mc as emptyAutomationRunWindows, Mi as loadSnapshotsForProfile, Ni as setWorkspaceSnapshot, No as getDispatchIdForConversation, Nr as canAgentChangeReviewItem, Ns as parseScheduledAutomationRow, Oc as automationRevision, Or as searchReviewItems, Pc as readAutomationExecutionByConversationId, Pi as setWorkspaceSnapshotBuild, Po as getDispatchInputMessageId, Pr as canReadReviewItem, Q as lostWorkerBeforeFirstSave, Qa as loadForkHistory, Qr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Rc as readAutomationExecutions, Rr as readReviewItemAgentScope, Sc as automationDefinition, So as defaultTimezone, Sr as getOpenReviewItemByDedupeKey, Tc as readAutomationVersion, Ti as getWorkspace, Ts as slackMention, Uc as resolveTaskTitle, Vn as getOAuthAccountProviders, W as AuthorizationFlowDisabledError, Wr as EVERYONE_ASSIGNEE, Xc as createPluginCache, Xi as isAbortError, Yo as openSlackDirectMessage, Z as loadTurnCheckpoint, Za as FORK_INSTRUCTIONS, Zr as getSlackToolContext, _c as registeredEventTriggerProblems, _s as sleep, ac as setEventAutomationStatus, ai as createTimerWatch, as as SlackActionError, at as getTurnRecord, bc as requireEventIdentifier, ci as findMatchingWatches, cn as getAssistantReplyText, co as readLiveAttachment, di as listWatches, dn as findLegacyNoReplyMarker, ea as WorkspaceSnapshotNotReadyError, ei as RESOURCE_WATCH_TOOL_SOURCE, er as getStaticPluginToolDefinitions, et as saveTurnCheckpoint, fn as isLegacyNoReplyMarker, gc as registeredEventMatchSchema, gn as REPORT_BLOCKED_TOOL_NAME, go as searchConversations, gs as withSlackRetries, ha as workspaceRepoCheckoutPath, hc as hasEventCatalogEntries, ic as saveEventAutomation, in as readTurnAnswer, ja as createPluginLogger, ji as invalidateReadySnapshot, jr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, js as deleteScheduledAutomation, k as markConversationMessage, kc as requireAutomationRevision, ki as updateWorkspace, lc as automationEventCatalog, li as getWatch, lo as recordUploadedAttachment, ls as getSlackClient, mc as eventWatchUnavailable, na as isWorkspaceSnapshotNotReadyError, nc as listDeletedEventAutomationsCreatedBy, nn as REPLY_TOOL_NAME, oi as createWatch, on as replyTextSchema, os as downloadPrivateSlackFile, pa as SANDBOX_RUNTIME, pc as eventNamespaceSchema, pi as turnEvents, ps as normalizeSlackConversationId, qr as resolveAssignee, rc as parseEventAutomationRow, ri as cancelWatch, rt as failTurnRecord, s as openConversationProjection, sa as createSandboxEgressCredentialToken, si as deliverWatch, ss as getFilePermalink, ti as STOP_WATCHING_TOOL_NAME, tn as isTurnExecutionLimitExceededError, to as matchSlackAttachments, tt as abandonTurnRecord, ua as buildSandboxEgressNetworkPolicy, uc as describeRegisteredEventTrigger, ui as isQuietEvent, un as NO_REPLY_TOOL_NAME, us as isConversationScopedChannel, v as hydrateConversationMessages, vc as registeredEventTypeSchema, vo as saveObjectAnnotations, vr as closeReviewItem, wc as listAutomationVersions, wi as deleteWorkspace, wr as insertReviewItem, xa as SANDBOX_REPOS_ROOT, xc as requireValidEventTrigger, xn as getTerminalAssistantMessages, xr as dismissOpenReviewItems, yc as registeredResourceTypeSchema, yo as createPluginAnnotations, zc as readAutomationRuns, zi as getSandboxProvider, zr as requireReviewItemAssignees, zs as getDashboardConversationLink } from "./projection-CWXDE0f6.js";
3
- import { W as escapeClosingTags, X as renderTag, _ as TURN_REASONING_LEVELS, i as getChatConfig, k as resolveGatewayModel, lt as bufferBody, n as botConfig, ot as isProviderRetryError } from "./config-DUD-zMvp.js";
4
- import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, x as setSpanStatus, z as getDeploymentId } from "./logging-oYpJYr-S.js";
2
+ import { $ as pauseLostWorkerTurn, $c as readAutomationExecutions, $n as getTerminalAssistantMessages, Ac as hasEventCatalogEntries, B as PluginCredentialFailureError, Bc as readAutomationVersion, Bi as updateWorkspace, Bs as slackMention, Ea as workspaceRepoCheckoutPath, En as createPluginHookRunner, Fa as SANDBOX_WORKSPACE_ROOT, Fc as requireEventIdentifier, Fi as deleteWorkspace, Fr as insertReviewItem, Gc as ToolInputError, Gi as setWorkspaceSnapshotBuild, Gn as seqIn, Gr as canReadReviewItem, Hi as invalidateReadySnapshot, Hr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, Ic as requireValidEventTrigger, Ii as getWorkspace, Io as defaultTimezone, J as clearPendingAuth, Ji as isStale, Jn as eventExcerpt, Jo as getDispatchInputMessageId, Js as parseScheduledAutomationRow, Ki as create, Kn as SEARCHABLE_EVENT_TYPES, Ks as deleteScheduledAutomation, Lc as automationDefinition, Li as getWorkspaceByName, Ma as SANDBOX_REPOS_ROOT, Mc as registeredEventTriggerProblems, Mo as saveObjectAnnotations, Mr as dismissOpenReviewItems, Ms as sleep, Na as SANDBOX_SCRATCH_ROOT, Nc as registeredEventTypeSchema, Nn as getPlugins, No as createPluginAnnotations, Nr as getOpenReviewItemByDedupeKey, Oc as eventNamespaceSchema, Oo as searchConversations, Os as normalizeSlackConversationId, Pc as registeredResourceTypeSchema, Pi as createWorkspace, Pn as getStaticPluginToolDefinitions, Pr as getReviewItem, Q as lostWorkerBeforeFirstSave, Qc as readAutomationExecutionSummaries, Ri as listWorkspaces, Si as listWatches, Ss as getFilePermalink, Tc as describeRegisteredEventTrigger, Ts as isConversationScopedChannel, Ua as createPluginLogger, Uc as automationRevision, Ui as loadSnapshotsForProfile, Un as lexemesSql, Vc as sameDefinitionValue, Vi as WorkspaceValidationError, Vr as updateReviewItemContent, W as AuthorizationFlowDisabledError, Wa as canAccessConversation, Wc as requireAutomationRevision, Wi as setWorkspaceSnapshot, Wn as searchedEventTextSql, Wr as canAgentChangeReviewItem, Xc as readAutomationExecutionStatusDays, Xi as getSandboxProvider, Xr as requireReviewItemAssignees, Xs as saveScheduledAutomation, Yc as readAutomationExecutionByConversationId, Yn as excerptTerms, Yo as getDispatchRecord, Yr as readReviewItemAgentScope, Z as loadTurnCheckpoint, Zc as readAutomationExecutionStatusHours, Zr as requireReviewItemLinks, _c as listDeletedEventAutomationsCreatedBy, _i as createWatch, ai as resolveAssignees, al as fallbackShortTitle, at as getTurnRecord, bc as setEventAutomationStatus, bi as getWatch, bo as readLiveAttachment, bs as SlackActionError, ci as getSlackToolContext, cn as getAssistantReplyText, cs as getSlackMessagePermalink, da as WorkspaceSnapshotNotReadyError, di as RESOURCE_WATCH_TOOL_SOURCE, dn as findLegacyNoReplyMarker, ec as getDashboardConversationLink, el as readAutomationRowStats, et as saveTurnCheckpoint, fi as STOP_WATCHING_TOOL_NAME, fn as isLegacyNoReplyMarker, gi as createTimerWatch, gn as REPORT_BLOCKED_TOOL_NAME, ii as resolveAssignee, in as readTurnAnswer, jc as registeredEventMatchSchema, jo as embedConversationQuery, js as withSlackRetries, k as markConversationMessage, kc as eventWatchUnavailable, kr as closeReviewItem, li as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, lo as FORK_INSTRUCTIONS, ls as openSlackDirectMessage, mc as deleteEventAutomation, mi as cancelWatch, ni as activeParticipantUserIds, nn as REPLY_TOOL_NAME, oc as getDashboardTaskLink, ol as resolveTaskTitle, on as replyTextSchema, pa as isWorkspaceSnapshotNotReadyError, po as matchSlackAttachments, qa as readConversationAccessFromSql, qc as emptyAutomationRunWindows, qn as callsToolSql, qo as getDispatchIdForConversation, ri as automationCreatorUserId, rt as failTurnRecord, s as openConversationProjection, sa as isAbortError, st as recordTurnSummary, ti as EVERYONE_ASSIGNEE, tl as readAutomationRuns, tn as isTurnExecutionLimitExceededError, tt as abandonTurnRecord, ui as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, ul as createPluginCache, un as NO_REPLY_TOOL_NAME, uo as loadForkHistory, v as hydrateConversationMessages, va as createSandboxEgressCredentialToken, vc as parseEventAutomationRow, vi as deliverWatch, wa as SANDBOX_RUNTIME, wc as automationEventCatalog, wi as turnEvents, ws as getSlackClient, xa as buildSandboxEgressNetworkPolicy, xi as isQuietEvent, xn as getOAuthAccountProviders, xo as recordUploadedAttachment, xs as downloadPrivateSlackFile, yc as saveEventAutomation, yi as findMatchingWatches, zc as listAutomationVersions, zr as searchReviewItems } from "./projection-xPpvqexa.js";
3
+ import { W as escapeClosingTags, X as renderTag, _ as TURN_REASONING_LEVELS, i as getChatConfig, k as resolveGatewayModel, lt as bufferBody, n as botConfig, ot as isProviderRetryError } from "./config-362yMSIz.js";
4
+ import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, b as setSpanAttributes, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, x as setSpanStatus, z as getDeploymentId } from "./logging-CHCuQ5iz.js";
5
5
  import { h as startSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
6
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.js";
7
- import { Ct as workspaceSnapshotFinishedEvent, E as getAuthPausedConversationTurnId, F as EVENT_WAIT_MS, H as addConversationNote, I as addQuietEventNote, J as resolveEventAuthor, L as enqueueEventNotification, O as listActiveMailboxTurnSources, Q as maybePostAutomatedTurnLimitNotice, St as WORKSPACE_SNAPSHOT_READY_EVENT, Tt as buildDeploymentSystemPrompt, bt as slackChannelMessageTrigger, ct as resetAutomatedTurnLimit, f as buildSteeringPiMessage, ft as isExperimentalFeatureEnabled, g as withoutSavedSteeringMessages, gt as requireSlackChannelMessageScope, i as resumeStoppedConversationTree, k as listActiveMailboxTurns, lt as conversationSubtree, m as instructionForInputs, mt as getEventCatalog, n as isSkippedAfterConversationStop, nt as resolveEventMentions, r as markConversationsStopped, st as recordFinishedTurnForAutomatedLimit, t as getConversationStoppedAtMs, ut as conversationSubtreeColumns, v as saveUserCustomization, w as renderPlanAssignee, wt as workspaceSnapshotWatch, x as listPlanItems, xt as WORKSPACE_SNAPSHOT_FAILED_EVENT, y as changePlan, z as isEventMailboxMetadata } from "./session-stop-BQxgHR4X.js";
6
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-OXrv2Ewn.js";
7
+ import { Ct as workspaceSnapshotFinishedEvent, E as getAuthPausedConversationTurnId, F as EVENT_WAIT_MS, H as addConversationNote, I as addQuietEventNote, J as resolveEventAuthor, L as enqueueEventNotification, O as listActiveMailboxTurnSources, Q as maybePostAutomatedTurnLimitNotice, St as WORKSPACE_SNAPSHOT_READY_EVENT, Tt as buildDeploymentSystemPrompt, bt as slackChannelMessageTrigger, ct as resetAutomatedTurnLimit, f as buildSteeringPiMessage, ft as isExperimentalFeatureEnabled, g as withoutSavedSteeringMessages, gt as requireSlackChannelMessageScope, i as resumeStoppedConversationTree, k as listActiveMailboxTurns, lt as conversationSubtree, m as instructionForInputs, mt as getEventCatalog, n as isSkippedAfterConversationStop, nt as resolveEventMentions, r as markConversationsStopped, st as recordFinishedTurnForAutomatedLimit, t as getConversationStoppedAtMs, ut as conversationSubtreeColumns, v as saveUserCustomization, w as renderPlanAssignee, wt as workspaceSnapshotWatch, x as listPlanItems, xt as WORKSPACE_SNAPSHOT_FAILED_EVENT, y as changePlan, z as isEventMailboxMetadata } from "./session-stop-BDdwyZaa.js";
8
8
  import { A as agentTypeSchema, N as briefLinkSchema, O as AGENT_TYPES, P as briefOutcomeStatusSchema, Y as removedCardSchema, j as formatAgentTypes, k as agentTypeInstructions } from "./conversation--f85g4zL.js";
9
- import { B as toolScheduleIntentSchema, G as isValidTimeZone, H as getFirstRunAtMs, J as automationTaskDescription, K as automationSkillNameSchema, L as ScheduleIntentError, N as eventAutomationTriggerSchema, R as compileScheduleIntent, V as weekdaySchema, W as getZonedDateTimeParts, X as automationTaskText, Y as automationTaskSchema, f as automationListQuerySchema } from "./schedule-CHPWQn-x.js";
9
+ import { B as compileScheduleIntent, F as eventAutomationTriggerSchema, H as toolScheduleIntentSchema, J as automationSkillNameSchema, K as getZonedDateTimeParts, Q as automationTaskText, U as weekdaySchema, W as getFirstRunAtMs, X as automationTaskDescription, Z as automationTaskSchema, m as automationListQuerySchema, q as isValidTimeZone, z as ScheduleIntentError } from "./schedule-BG1tEbRF.js";
10
10
  import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
11
- import { $ as getStateAdapter, A as conversationKindFromRow, E as isTopLevelKind, I as resolveActorIdentityId, O as promptModeTurnTools, P as SYSTEM_IDENTITY_ID, St as sameDestination, T as isPersonInput, _ as readConversationTrees, _t as nextDetailVersion, a as getConversationStore, at as withLock, g as conversationDescendants, h as conversationAncestors, ht as rootConversationIsArchived, i as getConversationMessageSearchStore, it as fenceLock, k as turnBehavior, mt as resolveRootConversationId, o as getDb, r as getConversationEventStore, s as getSqlExecutor, v as setArchivedAt, x as userMessageQueries } from "./db-DV2ZUb1Y.js";
12
- import { D as juniorConversationEvents, F as juniorConversations, I as juniorIdentities, L as juniorUsers, M as juniorAttachmentUploads, N as juniorAttachments, R as juniorDestinations, _ as juniorAgentBindings, b as juniorConversationParticipants, f as juniorAutomationRuns, h as juniorStats, m as juniorAutomations, v as juniorAgentInvocations, y as juniorConversationReadPositions } from "./executor-CjNhwwnj.js";
13
- import { t as discoverSkills } from "./skills-CPf4vNuC.js";
14
- import { D as isAgentInvocationResultEventType, F as sumUtcHoursIntoSixHours, O as apiErrorSchema, S as AGENT_INVOCATION_EVENT_NAMESPACE, b as SELF_PLAN_ASSIGNEE, c as formatUserInputAnswer, d as userInputRequestSchema, g as USER_CUSTOMIZATION_MAX_CHARS, h as isVisionImageMediaType, m as detectImageMediaType, n as AGENT_INVOCATION_MAILBOX_STATUSES, r as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, t as webMessageId, v as userCustomizationTextSchema, w as AGENT_PARENT_MESSAGE_EVENT_TYPE, x as isOpenPlanItemStatus, y as PLAN_ITEM_STATUSES } from "./web-message-id-CUaSiGme.js";
15
- import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-DKOeHpv3.js";
16
- import { A as getAgentInvocationResultMessageId, C as ownAgentInvocation, I as getUnnamedAgentConversationId, N as getChildAgentLockName, O as getAgentInvocationIdForResult, P as getNamedAgentConversationId, R as buildDeterministicTurnId, S as listChildMessages, T as getAgentInvocationId, _ as ConversationTurnLifecycleService, b as hasAgentInvocationReply, d as isTurnInputCommitLostError, j as getAgentInvocationTurnId, k as getAgentInvocationMessageId, l as getConversationTurnBoundaryError, p as markTurnClosed, s as TurnInputCommitLostError, t as getTurnUserMessage, w as readChildMessageSender } from "./turn-user-message-DNC0eRZ7.js";
17
- import { D as stopConversationWork, _ as getConversationWorkState, h as ensureConversationWake, m as dropPendingMessages, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage, v as getConversationWorkStates, w as requestConversationWork } from "./store-Dz3YZ7gQ.js";
11
+ import { $ as getStateAdapter, A as conversationKindFromRow, E as isTopLevelKind, I as resolveActorIdentityId, O as promptModeTurnTools, P as SYSTEM_IDENTITY_ID, St as rootConversationIsArchived, T as isPersonInput, _ as readConversationTrees, a as getConversationStore, at as withLock, d as eventFromRow, et as getStateValues, ft as usdToMicroUsd, g as conversationDescendants, h as conversationAncestors, i as getConversationMessageSearchStore, it as fenceLock, k as turnBehavior, kt as sameDestination, o as getDb, r as getConversationEventStore, s as getSqlExecutor, v as setArchivedAt, wt as nextDetailVersion, x as userMessageQueries, xt as resolveRootConversationId } from "./db-Bcbd9zQc.js";
12
+ import { A as juniorConversationEvents, B as juniorUsers, C as juniorConversationEventLexemes, F as juniorAttachmentUploads, I as juniorAttachments, R as juniorConversations, V as juniorDestinations, b as juniorConversationReadPositions, g as juniorStats, h as juniorAutomations, p as juniorAutomationRuns, v as juniorAgentBindings, w as juniorConversationEventEmbeddings, x as juniorConversationParticipants, y as juniorAgentInvocations, z as juniorIdentities } from "./executor-DBMBrpNV.js";
13
+ import { t as discoverSkills } from "./skills-63i1Bcv1.js";
14
+ import { D as isAgentInvocationResultEventType, F as sumUtcHoursIntoSixHours, O as apiErrorSchema, S as AGENT_INVOCATION_EVENT_NAMESPACE, b as SELF_PLAN_ASSIGNEE, c as formatUserInputAnswer, d as userInputRequestSchema, g as USER_CUSTOMIZATION_MAX_CHARS, h as isVisionImageMediaType, m as detectImageMediaType, n as AGENT_INVOCATION_MAILBOX_STATUSES, r as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, t as webMessageId, v as userCustomizationTextSchema, w as AGENT_PARENT_MESSAGE_EVENT_TYPE, x as isOpenPlanItemStatus, y as PLAN_ITEM_STATUSES } from "./web-message-id-BT8Mg8LL.js";
15
+ import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-DN_xzVKj.js";
16
+ import { A as getAgentInvocationResultMessageId, C as ownAgentInvocation, I as getUnnamedAgentConversationId, N as getChildAgentLockName, O as getAgentInvocationIdForResult, P as getNamedAgentConversationId, R as buildDeterministicTurnId, S as listChildMessages, T as getAgentInvocationId, _ as ConversationTurnLifecycleService, b as hasAgentInvocationReply, d as isTurnInputCommitLostError, j as getAgentInvocationTurnId, k as getAgentInvocationMessageId, l as getConversationTurnBoundaryError, p as markTurnClosed, s as TurnInputCommitLostError, t as getTurnUserMessage, w as readChildMessageSender } from "./turn-user-message-B1S8nOnG.js";
17
+ import { D as stopConversationWork, _ as getConversationWorkState, h as ensureConversationWake, m as dropPendingMessages, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage, v as getConversationWorkStates, w as requestConversationWork } from "./store-CdWg2r2L.js";
18
18
  import { d as contextProvenance, m as sameActorIdentity, t as KNOWN_CONVERSATION_EVENT_TYPES, u as agentInstructionProvenance } from "./history-N7IVbUom.js";
19
- import { f as credentialContextForActor, p as credentialContextSchema } from "./registry-1pzXmplY.js";
20
- import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, s as persistThreadStateById } from "./turn-session-routing-BXaubz2w.js";
21
- import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-D2wzxtGU.js";
22
- import { d as completeText, m as searchWeb, r as EVENT_AUTHOR_ID } from "./prompt-P3eRqO8C.js";
23
- import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-XCCKn3xW.js";
24
- import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-DbD7C5td.js";
25
- import { a as sendCacheWarmup, c as sendWorkspaceSnapshotJob, s as sendNextWorkspaceSnapshotJob } from "./queue-7FSijgqG.js";
19
+ import { m as credentialContextSchema, p as credentialContextForActor } from "./registry-D20hG3r6.js";
20
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnResumeRouting, s as persistThreadStateById } from "./turn-session-routing-DFYak28Q.js";
21
+ import { g as getTurnRequestDeadline } from "./task-queue-BcjAYWyB.js";
22
+ import { d as sendNextWorkspaceSnapshotJob, f as sendWorkspaceSnapshotJob, l as sendCacheWarmup, m as getVercelConversationWorkQueue } from "./background-compaction-queue-BhEe4UfU.js";
23
+ import { d as completeText, m as searchWeb, r as EVENT_AUTHOR_ID } from "./prompt-D8u4jFs_.js";
24
+ import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-DDbENg-I.js";
25
+ import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-CgoAbzfF.js";
26
+ import pLimit from "p-limit";
26
27
  import * as z from "zod";
27
28
  import { streamSimple } from "@earendil-works/pi-ai/compat";
28
29
  import path from "node:path";
29
30
  import { isDeepStrictEqual, promisify } from "node:util";
30
31
  import { createHash, randomUUID } from "node:crypto";
31
- import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, notExists, notInArray, or, sql } from "drizzle-orm";
32
+ import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notExists, notInArray, or, sql } from "drizzle-orm";
32
33
  import { actorSchema, agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, destinationSchema, eventMatchFieldSchema, eventSchema, eventTriggerText, localDestinationSchema, ownedObjectAnnotationSchema, sourceSchema, stableEventMatchKey, watchResultSchema } from "@sentry/junior-plugin-api";
33
- import { alias } from "drizzle-orm/pg-core";
34
- import pLimit from "p-limit";
34
+ import { alias, unionAll } from "drizzle-orm/pg-core";
35
+ import { guardedCosineDistance } from "@sentry/junior-plugin-api/embeddings";
35
36
  import http from "node:http";
36
37
  import dns from "node:dns/promises";
37
38
  import net from "node:net";
@@ -39,6 +40,7 @@ import { Readable } from "node:stream";
39
40
  import { NodeHtmlMarkdown } from "node-html-markdown";
40
41
  import { structuredPatch } from "diff";
41
42
  import { HTTPException } from "hono/http-exception";
43
+ import { bm25InverseDocumentFrequency, bm25NormalizedFrequency, bm25Saturation, fuseRankedLists } from "@sentry/junior-search";
42
44
  import https from "node:https";
43
45
  import { constants, zstdCompress as zstdCompress$1, zstdDecompress as zstdDecompress$1 } from "node:zlib";
44
46
  // src/chat/cache-warming/model.ts
@@ -358,15 +360,16 @@ function viewerAutomationCollection(viewer) {
358
360
  const owned = or(inArray(automation.creatorIdentityId, identityIds), ...slackAccounts.map((account) => and(eq(automation.teamId, account.providerTenantId), eq(automation.creatorSlackUserId, account.providerSubjectId))));
359
361
  const publicDestination = sql`coalesce(${destination.visibility} = 'public', false)`;
360
362
  const sharedToViewer = and(ne(automation.status, "completed"), or(and(inArray(automation.teamId, teamIds), publicDestination), viewer.location ? and(eq(automation.teamId, viewer.location.teamId), eq(automation.channelId, viewer.location.channelId)) : void 0));
361
- const runs = juniorAutomationRuns;
362
- const lastRunNeedsAttention = sql`coalesce((select ${runs.status} in ('failed', 'blocked') from ${runs}
363
- where ${runs.automationId} = ${automation.id} and ${runs.status} in ('blocked', 'completed', 'failed') and ${runs.completedAtMs} is not null
364
- order by ${runs.completedAtMs} desc, ${runs.id} desc limit 1), false)`;
363
+ const lastRun = juniorAutomationRuns;
364
+ const lastRunNeedsAttention = sql`coalesce(${lastRun.status} in ('failed', 'blocked'), false)`;
365
+ const activityAtMs = sql`coalesce(${lastRun.completedAtMs}, ${automation.createdAtMs})`;
365
366
  return db.select({
366
367
  kind: automation.kind,
367
368
  id: automation.id,
368
369
  title: automation.title,
369
370
  createdAtMs: automation.createdAtMs,
371
+ lastRunId: automation.lastRunId,
372
+ activityAtMs: activityAtMs.mapWith(Number).as("activity_at_ms"),
370
373
  state: sql`${automation.status}`.as("state"),
371
374
  lastRunNeedsAttention: lastRunNeedsAttention.as("last_run_needs_attention"),
372
375
  trigger: sql`${automation.record}->'trigger'`.as("trigger"),
@@ -380,7 +383,7 @@ function viewerAutomationCollection(viewer) {
380
383
  instruction: automation.instruction,
381
384
  skill: automation.skill,
382
385
  task: sql`${automation.record}->'task'`.as("task")
383
- }).from(automation).leftJoin(destination, and(eq(destination.provider, "slack"), eq(destination.providerTenantId, automation.teamId), eq(destination.providerDestinationId, automation.channelId))).where(and(ne(automation.status, "deleted"), or(owned, sharedToViewer))).as("accessible_automations");
386
+ }).from(automation).leftJoin(destination, and(eq(destination.provider, "slack"), eq(destination.providerTenantId, automation.teamId), eq(destination.providerDestinationId, automation.channelId))).leftJoin(lastRun, eq(lastRun.id, automation.lastRunId)).where(and(ne(automation.status, "deleted"), or(owned, sharedToViewer))).as("accessible_automations");
384
387
  }
385
388
  function eventTriggerAvailable(catalog, trigger) {
386
389
  const parsed = eventAutomationTriggerSchema.safeParse(trigger);
@@ -426,12 +429,71 @@ async function countOwnedAutomationsNeedingAttention(viewer) {
426
429
  const catalog = automationEventCatalog(getEventCatalog());
427
430
  return rows.filter((row) => row.state === "blocked" || row.lastRunNeedsAttention || row.kind === "event" && !eventTriggerAvailable(catalog, row.trigger)).length;
428
431
  }
429
- /** Read an SQL page and complete, access-scoped counts and filter options. */
432
+ /** Build the access-scoped collection and the filters of one list query. */
433
+ async function selectViewerAutomations(viewer, input) {
434
+ const collection = viewerAutomationCollection(viewer);
435
+ const { attention, unavailable } = input.scope === "attention" || input.state === "unavailable" ? await attentionFilters(collection) : {
436
+ attention: void 0,
437
+ unavailable: void 0
438
+ };
439
+ return {
440
+ collection,
441
+ where: and(input.scope === "mine" ? eq(collection.owned, true) : input.scope === "public" ? eq(collection.isPublic, true) : input.scope === "attention" ? attention : void 0, input.type === "all" ? void 0 : eq(collection.kind, input.type), input.state === "all" ? void 0 : input.state === "unavailable" ? unavailable : eq(collection.state, input.state), input.creator ? eq(collection.creator, input.creator) : void 0, input.owner === "me" ? eq(collection.owned, true) : void 0, input.destination ? eq(collection.destination, input.destination) : void 0, input.skill ? eq(collection.skill, input.skill) : void 0, input.q ? sql`(strpos(lower(concat_ws(' ', ${collection.title}, ${collection.instruction}, ${collection.skill}, ${collection.resource})), ${input.q.toLowerCase()}) > 0 or strpos(${input.q.toLowerCase()}, lower(${collection.id})) > 0)` : void 0)
442
+ };
443
+ }
444
+ /**
445
+ * Read one `sort=activity` page: the rows after `after`, newest activity
446
+ * first. `next` is set when more rows follow.
447
+ */
448
+ async function readAutomationActivityPage({ collection, where }, pageSize, after) {
449
+ const db = getDb();
450
+ const limit = pageSize + 1;
451
+ const run = alias(juniorAutomationRuns, "page_run");
452
+ const withRun = db.select({
453
+ activityAtMs: sql`${run.completedAtMs}`.mapWith(Number).as("activity_at_ms"),
454
+ id: collection.id,
455
+ kind: collection.kind
456
+ }).from(run).innerJoin(collection, eq(collection.lastRunId, run.id)).where(and(where, after ? and(lte(run.completedAtMs, after.activityAtMs), sql`(${run.completedAtMs}, ${collection.id}) < (${after.activityAtMs}, ${after.id})`) : void 0)).orderBy(desc(run.completedAtMs), desc(collection.id)).limit(limit);
457
+ const withoutRun = db.select({
458
+ activityAtMs: sql`${collection.createdAtMs}`.mapWith(Number).as("activity_at_ms"),
459
+ id: collection.id,
460
+ kind: collection.kind
461
+ }).from(collection).where(and(where, isNull(collection.lastRunId), after ? sql`(${collection.createdAtMs}, ${collection.id}) < (${after.activityAtMs}, ${after.id})` : void 0)).orderBy(desc(collection.createdAtMs), desc(collection.id)).limit(limit);
462
+ const rows = await unionAll(withRun, withoutRun).orderBy(desc(sql.identifier("activity_at_ms")), desc(sql.identifier("id"))).limit(limit);
463
+ const pageRows = rows.slice(0, pageSize);
464
+ const last = pageRows.at(-1);
465
+ return {
466
+ rows: pageRows,
467
+ ...rows.length > pageSize && last ? { next: {
468
+ activityAtMs: last.activityAtMs,
469
+ id: last.id
470
+ } } : void 0
471
+ };
472
+ }
473
+ /** Read an SQL page by offset and complete, access-scoped counts and filter options. */
430
474
  async function readAutomationCollection(viewer, input) {
475
+ const selection = await selectViewerAutomations(viewer, input);
476
+ const { collection, where } = selection;
477
+ const facets = await readAutomationFacets(selection);
478
+ const page = Math.min(input.page, Math.max(1, Math.ceil(facets.total / input.pageSize)));
479
+ const order = input.sort === "oldest" ? asc(collection.createdAtMs) : input.sort === "title" ? asc(sql`lower(coalesce(nullif(trim(${collection.title}), ''), ${collection.instruction}, ${collection.skill}))`) : input.sort === "activity" ? desc(collection.activityAtMs) : desc(collection.createdAtMs);
480
+ return {
481
+ rows: await getDb().select({
482
+ id: collection.id,
483
+ kind: collection.kind
484
+ }).from(collection).where(where).orderBy(order, desc(collection.id)).limit(input.pageSize).offset((page - 1) * input.pageSize),
485
+ page,
486
+ pageSize: input.pageSize,
487
+ ...facets
488
+ };
489
+ }
490
+ /**
491
+ * Read the match total, the scope counts, and the creator and Destination
492
+ * options. Separate statements run in parallel on their own connections,
493
+ * which measured faster than one grouped statement.
494
+ */
495
+ async function readAutomationFacets({ collection, where }) {
431
496
  const db = getDb();
432
- const collection = viewerAutomationCollection(viewer);
433
- const { attention, unavailable } = await attentionFilters(collection);
434
- const where = and(input.scope === "mine" ? eq(collection.owned, true) : input.scope === "public" ? eq(collection.isPublic, true) : input.scope === "attention" ? attention : void 0, input.type === "all" ? void 0 : eq(collection.kind, input.type), input.state === "all" ? void 0 : input.state === "unavailable" ? unavailable : eq(collection.state, input.state), input.creator ? eq(collection.creator, input.creator) : void 0, input.owner === "me" ? eq(collection.owned, true) : void 0, input.destination ? eq(collection.destination, input.destination) : void 0, input.skill ? eq(collection.skill, input.skill) : void 0, input.q ? sql`(strpos(lower(concat_ws(' ', ${collection.title}, ${collection.instruction}, ${collection.skill}, ${collection.resource})), ${input.q.toLowerCase()}) > 0 or strpos(${input.q.toLowerCase()}, lower(${collection.id})) > 0)` : void 0);
435
497
  const [totals, counts, creators, destinations] = await Promise.all([
436
498
  db.select({ total: count() }).from(collection).where(where),
437
499
  db.select({
@@ -449,17 +511,8 @@ async function readAutomationCollection(viewer, input) {
449
511
  label: sql`min(${collection.destinationLabel})`
450
512
  }).from(collection).groupBy(collection.destination).orderBy(sql`min(${collection.destinationLabel})`, collection.destination)
451
513
  ]);
452
- const total = totals[0].total;
453
- const page = Math.min(input.page, Math.max(1, Math.ceil(total / input.pageSize)));
454
- const order = input.sort === "oldest" ? asc(collection.createdAtMs) : input.sort === "title" ? asc(sql`lower(coalesce(nullif(trim(${collection.title}), ''), ${collection.instruction}, ${collection.skill}))`) : desc(collection.createdAtMs);
455
514
  return {
456
- rows: await db.select({
457
- id: collection.id,
458
- kind: collection.kind
459
- }).from(collection).where(where).orderBy(order, desc(collection.id)).limit(input.pageSize).offset((page - 1) * input.pageSize),
460
- total,
461
- page,
462
- pageSize: input.pageSize,
515
+ total: totals[0].total,
463
516
  counts: counts[0],
464
517
  creators,
465
518
  destinations
@@ -659,6 +712,91 @@ function requireAutomationTaskText(task, references) {
659
712
  });
660
713
  if (problem) throw new AutomationEditError(problem, `task.${label}`);
661
714
  }
715
+ // src/chat/automations/result.ts
716
+ /** Model-facing fields that every Automation result has. */
717
+ const automationResultFieldSchemas = {
718
+ destination: z.object({
719
+ id: z.string().min(1),
720
+ channel: z.string().min(1),
721
+ thread: z.string().min(1).nullable()
722
+ }).strict(),
723
+ credential_mode: z.enum(["system", "creator"]),
724
+ is_creator: z.boolean(),
725
+ outcomes: z.array(z.object({
726
+ action: z.literal("send_message"),
727
+ destination: z.object({
728
+ channel: z.string().min(1),
729
+ thread: z.string().min(1).nullable()
730
+ }).strict()
731
+ }).strict()).max(5),
732
+ created_by: z.object({
733
+ name: z.string().min(1).nullable(),
734
+ username: z.string().min(1).nullable()
735
+ }).strict()
736
+ };
737
+ /** Project the fields that every Automation has into its result shape. */
738
+ function automationResultFields(task, isCreator) {
739
+ return {
740
+ destination: {
741
+ id: destinationFilterValue(task.destination),
742
+ channel: task.destination.channelId,
743
+ thread: null
744
+ },
745
+ credential_mode: task.credentialMode,
746
+ is_creator: isCreator,
747
+ outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
748
+ action: outcome.action,
749
+ destination: {
750
+ channel: outcome.destination.channelId,
751
+ thread: outcome.destination.threadTs ?? null
752
+ }
753
+ })),
754
+ created_by: {
755
+ name: task.createdBy.fullName ?? null,
756
+ username: task.createdBy.userName ?? null
757
+ }
758
+ };
759
+ }
760
+ /**
761
+ * Return the status and warning that the card and the Slack details of an
762
+ * Automation show. The status is the saved status, except that an active
763
+ * Automation whose trigger cannot work shows as unavailable. Only a block or
764
+ * a trigger problem gives a warning, like Needs attention in `collection.ts`.
765
+ */
766
+ function automationCardStatus(automation) {
767
+ const problems = automation.triggerProblems ?? [];
768
+ const warning = [automation.status === "blocked" ? automation.statusReason ?? "This automation is blocked." : void 0, problems.length > 0 ? ["Trigger unavailable.", ...problems].join(" ") : void 0].filter(Boolean).join(" ");
769
+ return {
770
+ status: automation.status === "active" && problems.length > 0 ? "unavailable" : automation.status,
771
+ warning: warning || void 0
772
+ };
773
+ }
774
+ /** Save the card of an Automation that a tool changed, and return the tool result. */
775
+ async function saveAutomationCardResult(conversationId, automation, card) {
776
+ const description = automationTaskDescription(card.task);
777
+ const title = automation.title ?? fallbackShortTitle(description, card.fallbackTitle);
778
+ const { status, warning } = automationCardStatus({
779
+ status: automation.status,
780
+ statusReason: automation.status_reason,
781
+ triggerProblems: card.triggerProblems
782
+ });
783
+ const annotation = {
784
+ kind: "object",
785
+ objectType: "automation",
786
+ label: title,
787
+ key: automation.id,
788
+ title,
789
+ url: automation.dashboard_url,
790
+ description,
791
+ status,
792
+ trigger: card.trigger,
793
+ warning: warning ?? (status === "completed" ? "This automation has completed." : void 0)
794
+ };
795
+ return {
796
+ automation,
797
+ objectCards: await saveObjectAnnotations(conversationId, "junior", [annotation])
798
+ };
799
+ }
662
800
  // src/chat/event-automations/tool-support.ts
663
801
  /** Model-facing shape of one event automation. */
664
802
  const compactEventAutomationResultSchema = z.object({
@@ -684,24 +822,7 @@ const compactEventAutomationResultSchema = z.object({
684
822
  available: z.boolean(),
685
823
  problems: z.array(z.string().min(1)).min(1).optional()
686
824
  }).strict(),
687
- destination: z.object({
688
- id: z.string().min(1),
689
- channel: z.string().min(1),
690
- thread: z.string().min(1).nullable()
691
- }).strict(),
692
- credential_mode: z.enum(["system", "creator"]),
693
- is_creator: z.boolean(),
694
- outcomes: z.array(z.object({
695
- action: z.literal("send_message"),
696
- destination: z.object({
697
- channel: z.string().min(1),
698
- thread: z.string().min(1).nullable()
699
- }).strict()
700
- }).strict()).max(5),
701
- created_by: z.object({
702
- name: z.string().min(1).nullable(),
703
- username: z.string().min(1).nullable()
704
- }).strict()
825
+ ...automationResultFieldSchemas
705
826
  }).strict();
706
827
  /** Build the validated event trigger accepted by event-automation tools. */
707
828
  function registeredEventAutomationTriggerSchema(catalog) {
@@ -795,47 +916,18 @@ function compactEventAutomation(task, catalog, isCreator) {
795
916
  available: problems.length === 0,
796
917
  ...problems.length > 0 ? { problems } : void 0
797
918
  },
798
- destination: {
799
- id: destinationFilterValue(task.destination),
800
- channel: task.destination.channelId,
801
- thread: null
802
- },
803
- credential_mode: task.credentialMode,
804
- is_creator: isCreator,
805
- outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
806
- action: outcome.action,
807
- destination: {
808
- channel: outcome.destination.channelId,
809
- thread: outcome.destination.threadTs ?? null
810
- }
811
- })),
812
- created_by: {
813
- name: task.createdBy.fullName ?? null,
814
- username: task.createdBy.userName ?? null
815
- }
919
+ ...automationResultFields(task, isCreator)
816
920
  });
817
921
  }
818
922
  /** Return the standard successful event-automation tool result. */
819
923
  async function eventAutomationToolResult(conversationId, task, catalog, isCreator) {
820
- const automation = compactEventAutomation(task, catalog, isCreator);
821
924
  const description = describeEventAutomationTrigger(task.trigger, catalog);
822
- const taskDescription = automationTaskDescription(task.task);
823
- const title = automation.title ?? fallbackShortTitle(taskDescription, "Event automation");
824
- return {
825
- automation,
826
- objectCards: await saveObjectAnnotations(conversationId, "junior", [{
827
- kind: "object",
828
- objectType: "automation",
829
- label: title,
830
- key: task.id,
831
- title,
832
- url: automation.dashboard_url,
833
- description: taskDescription,
834
- status: description.problems.length === 0 ? "ready" : "unavailable",
835
- trigger: eventTriggerText(task.trigger.label, description),
836
- warning: description.problems.length > 0 ? ["Trigger unavailable.", ...description.problems].join(" ") : void 0
837
- }])
838
- };
925
+ return saveAutomationCardResult(conversationId, compactEventAutomation(task, catalog, isCreator), {
926
+ task: task.task,
927
+ fallbackTitle: "Event automation",
928
+ trigger: eventTriggerText(task.trigger.label, description),
929
+ triggerProblems: description.problems
930
+ });
839
931
  }
840
932
  // src/chat/event-automations/edit.ts
841
933
  function changesEventAutomationTrigger(current, next) {
@@ -961,19 +1053,23 @@ async function destinationDetails(destinations) {
961
1053
  }];
962
1054
  }));
963
1055
  }
964
- function executionSummaryFields(stats) {
1056
+ function rowStatsFields(stats) {
965
1057
  return {
966
1058
  lastRunStatus: stats?.lastRunStatus,
967
1059
  ...stats?.lastConversationId ? { lastConversationId: stats.lastConversationId } : void 0,
968
1060
  ...stats?.lastExecutedAtMs ? { lastRunAt: new Date(stats.lastExecutedAtMs).toISOString() } : void 0,
1061
+ recentRuns: stats?.recentRuns ?? []
1062
+ };
1063
+ }
1064
+ function totalFields(stats) {
1065
+ return {
969
1066
  costUsd: stats?.costUsd ?? emptyAutomationRunWindows(),
970
- recentRuns: stats?.recentRuns ?? [],
971
1067
  runs: stats?.runs ?? emptyAutomationRunWindows(),
972
1068
  totalCostUsd: stats?.totalCostUsd ?? 0,
973
1069
  totalRuns: stats?.totalRuns ?? 0
974
1070
  };
975
1071
  }
976
- function scheduledAutomationSummary(task, ownedByViewer, destination, stats, creator) {
1072
+ function scheduledAutomationListItem(task, ownedByViewer, destination, stats, creator) {
977
1073
  if (task.status === "deleted") throw new Error("Deleted scheduled automations cannot enter the Automations view");
978
1074
  const nextRunAtMs = task.status === "active" ? task.runNowAtMs ?? task.nextRunAtMs : void 0;
979
1075
  const description = displayText(automationTaskDescription(task.task), "Untitled scheduled automation");
@@ -991,7 +1087,7 @@ function scheduledAutomationSummary(task, ownedByViewer, destination, stats, cre
991
1087
  id: task.id,
992
1088
  task: task.task,
993
1089
  kind: "scheduled",
994
- ...executionSummaryFields(stats),
1090
+ ...rowStatsFields(stats),
995
1091
  ...nextRunAtMs !== void 0 ? { nextRunAt: new Date(nextRunAtMs).toISOString() } : void 0,
996
1092
  ownedByViewer,
997
1093
  schedule: displayText(task.schedule.description, "Schedule unavailable"),
@@ -1003,7 +1099,8 @@ function scheduledAutomationSummary(task, ownedByViewer, destination, stats, cre
1003
1099
  title: taskDisplayTitle(task.title, description, "Untitled scheduled automation")
1004
1100
  };
1005
1101
  }
1006
- function eventAutomationSummary(task, ownedByViewer, destination, stats, creator) {
1102
+ function eventAutomationListItem(task, ownedByViewer, destination, stats, creator) {
1103
+ if (task.status === "deleted") throw new Error("Deleted event automations cannot enter the Automations view");
1007
1104
  const description = automationTaskDescription(task.task);
1008
1105
  const catalog = getEventCatalog();
1009
1106
  return {
@@ -1020,18 +1117,27 @@ function eventAutomationSummary(task, ownedByViewer, destination, stats, creator
1020
1117
  id: task.id,
1021
1118
  task: task.task,
1022
1119
  kind: "event",
1023
- ...executionSummaryFields(stats),
1120
+ ...rowStatsFields(stats),
1024
1121
  ownedByViewer,
1025
1122
  resource: task.trigger.identifier ? `${task.trigger.label} · ${task.trigger.identifier}` : task.trigger.label,
1026
1123
  source: task.trigger.namespace,
1027
1124
  credentialMode: task.credentialMode,
1028
1125
  outcomes: effectiveTaskOutcomes(task.outcomes, task.destination),
1029
1126
  title: taskDisplayTitle(task.title, description, "Untitled event automation"),
1030
- status: task.status === "deleted" ? "active" : task.status,
1127
+ status: task.status,
1031
1128
  statusReason: task.statusReason,
1032
1129
  trigger: describeEventAutomationTrigger(task.trigger, catalog)
1033
1130
  };
1034
1131
  }
1132
+ /** Build one list row from loaded Destinations, creators, and run stats. */
1133
+ function automationListItem(candidate, destinations, creators, stats) {
1134
+ const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
1135
+ label: `Channel ${candidate.task.destination.channelId}`,
1136
+ visibility: "private"
1137
+ };
1138
+ const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
1139
+ return candidate.kind === "scheduled" ? scheduledAutomationListItem(candidate.task, candidate.ownedByViewer, destination, stats, creator) : eventAutomationListItem(candidate.task, candidate.ownedByViewer, destination, stats, creator);
1140
+ }
1035
1141
  function viewerTeamIds(viewer) {
1036
1142
  return [...new Set(viewer.identities.filter((identity) => identity.provider === "slack").map((identity) => identity.providerTenantId).filter((teamId) => Boolean(teamId)))];
1037
1143
  }
@@ -1082,13 +1188,11 @@ async function automationSummaryForCandidate(candidate) {
1082
1188
  creatorProfiles([candidate]),
1083
1189
  readAutomationExecutionSummaries([candidate.task.id])
1084
1190
  ]);
1085
- const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
1086
- label: `Channel ${candidate.task.destination.channelId}`,
1087
- visibility: "private"
1191
+ const summary = stats.get(candidate.task.id);
1192
+ return {
1193
+ ...automationListItem(candidate, destinations, creators, summary),
1194
+ ...totalFields(summary)
1088
1195
  };
1089
- const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
1090
- if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
1091
- return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
1092
1196
  }
1093
1197
  function emptyAutomationExecutionStatusDay(date) {
1094
1198
  return {
@@ -1135,27 +1239,42 @@ async function readTaskCandidates(viewer, ids) {
1135
1239
  return candidate ? [candidate] : [];
1136
1240
  });
1137
1241
  }
1138
- /** Read a page from the full accessible Automation collection. */
1139
- async function readViewerAutomations(user, input = automationListQuerySchema.parse({})) {
1140
- const { rows, ...page } = await readAutomationCollection(user, input);
1141
- const ids = rows.map((row) => row.id);
1142
- const selected = await readTaskCandidates(user, ids);
1143
- const [destinations, creators] = await Promise.all([destinationDetails(selected.map(({ task }) => task.destination)), creatorProfiles(selected)]);
1144
- const visible = selected.filter((candidate) => candidate.ownedByViewer || destinations.get(destinationKey(candidate.task.destination))?.visibility === "public");
1145
- const stats = await readAutomationExecutionSummaries(ids);
1242
+ async function readViewerAutomations(user, input = automationListQuerySchema.parse({}), after) {
1243
+ if (input.sort !== "activity") {
1244
+ const { rows, ...page } = await readAutomationCollection(user, input);
1245
+ return {
1246
+ automations: await readAutomationListItems(user, rows.map((row) => row.id)),
1247
+ ...page
1248
+ };
1249
+ }
1250
+ const selection = await selectViewerAutomations(user, input);
1251
+ const [facets, { automations, next }] = await Promise.all([after ? void 0 : readAutomationFacets(selection), readAutomationActivityPage(selection, input.pageSize, after).then(async ({ rows, next }) => ({
1252
+ automations: await readAutomationListItems(user, rows.map((row) => row.id)),
1253
+ next
1254
+ }))]);
1146
1255
  return {
1147
- automations: visible.map((candidate) => {
1148
- const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
1149
- label: `Channel ${candidate.task.destination.channelId}`,
1150
- visibility: "private"
1151
- };
1152
- const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
1153
- if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
1154
- return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
1155
- }),
1156
- ...page
1256
+ automations,
1257
+ page: 1,
1258
+ pageSize: input.pageSize,
1259
+ ...facets,
1260
+ ...next ? { next } : void 0
1157
1261
  };
1158
1262
  }
1263
+ /**
1264
+ * Build list items for collection rows, in their order. The run stats load
1265
+ * while the Destination and creator details do.
1266
+ */
1267
+ async function readAutomationListItems(user, ids) {
1268
+ const [{ selected, destinations, creators }, stats] = await Promise.all([readTaskCandidates(user, ids).then(async (selected) => {
1269
+ const [destinations, creators] = await Promise.all([destinationDetails(selected.map(({ task }) => task.destination)), creatorProfiles(selected)]);
1270
+ return {
1271
+ selected,
1272
+ destinations,
1273
+ creators
1274
+ };
1275
+ }), readAutomationRowStats(ids)]);
1276
+ return selected.filter((candidate) => candidate.ownedByViewer || destinations.get(destinationKey(candidate.task.destination))?.visibility === "public").map((candidate) => automationListItem(candidate, destinations, creators, stats.get(candidate.task.id)));
1277
+ }
1159
1278
  /** Load deleted scheduled automations the viewer still owns, newest first. */
1160
1279
  async function readDeletedOwnedScheduledAutomations(user) {
1161
1280
  const identityIds = user.identities.map((identity) => identity.id);
@@ -1234,10 +1353,8 @@ var ViewerTaskNotFoundError = class extends Error {
1234
1353
  };
1235
1354
  /** Read one viewer-visible task and its newest terminal executions. */
1236
1355
  async function readViewerAutomationExecutions(user, id) {
1237
- const candidate = await resolveViewerTaskCandidate(user, id);
1238
- if (!candidate) throw new ViewerTaskNotFoundError();
1239
- const [automation, executions, executionDays, executionHours] = await Promise.all([
1240
- automationSummaryForCandidate(candidate),
1356
+ if (!await resolveViewerTaskCandidate(user, id)) throw new ViewerTaskNotFoundError();
1357
+ const [executions, executionDays, executionHours] = await Promise.all([
1241
1358
  readAutomationExecutions({
1242
1359
  automationId: id,
1243
1360
  limit: 101
@@ -1250,7 +1367,6 @@ async function readViewerAutomationExecutions(user, id) {
1250
1367
  executionHours,
1251
1368
  executionSixHours: automationExecutionStatusSixHours(executionHours),
1252
1369
  executions: executions.slice(0, TASK_EXECUTION_LIST_LIMIT),
1253
- automation,
1254
1370
  truncated: executions.length > TASK_EXECUTION_LIST_LIMIT
1255
1371
  };
1256
1372
  }
@@ -1778,11 +1894,7 @@ const compactTaskResultSchema = z.object({
1778
1894
  timezone: z.string(),
1779
1895
  recurrence: z.unknown().nullable(),
1780
1896
  next_run_at: z.string().nullable(),
1781
- destination: z.object({
1782
- id: z.string().min(1),
1783
- channel: z.string().min(1),
1784
- thread: z.string().min(1).nullable()
1785
- }).strict(),
1897
+ ...automationResultFieldSchemas,
1786
1898
  conversation_access: z.object({
1787
1899
  audience: z.enum([
1788
1900
  "direct",
@@ -1791,19 +1903,6 @@ const compactTaskResultSchema = z.object({
1791
1903
  ]),
1792
1904
  visibility: z.enum(["private", "public"])
1793
1905
  }).strict(),
1794
- credential_mode: z.enum(["system", "creator"]),
1795
- is_creator: z.boolean(),
1796
- created_by: z.object({
1797
- name: z.string().min(1).nullable(),
1798
- username: z.string().min(1).nullable()
1799
- }).strict(),
1800
- outcomes: z.array(z.object({
1801
- action: z.literal("send_message"),
1802
- destination: z.object({
1803
- channel: z.string().min(1),
1804
- thread: z.string().min(1).nullable()
1805
- }).strict()
1806
- }).strict()).max(5),
1807
1906
  dashboard_url: z.string().url().nullable(),
1808
1907
  last_run_at: z.string().nullable(),
1809
1908
  run_now_at: z.string().nullable()
@@ -1850,25 +1949,8 @@ function compactTask(task, isCreator) {
1850
1949
  day_of_month: task.schedule.recurrence.dayOfMonth
1851
1950
  } : null,
1852
1951
  next_run_at: task.nextRunAtMs ? new Date(task.nextRunAtMs).toISOString() : null,
1853
- destination: {
1854
- id: destinationFilterValue(task.destination),
1855
- channel: task.destination.channelId,
1856
- thread: null
1857
- },
1952
+ ...automationResultFields(task, isCreator),
1858
1953
  conversation_access: task.conversationAccess,
1859
- credential_mode: task.credentialMode,
1860
- is_creator: isCreator,
1861
- created_by: {
1862
- name: task.createdBy.fullName ?? null,
1863
- username: task.createdBy.userName ?? null
1864
- },
1865
- outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
1866
- action: outcome.action,
1867
- destination: {
1868
- channel: outcome.destination.channelId,
1869
- thread: outcome.destination.threadTs ?? null
1870
- }
1871
- })),
1872
1954
  dashboard_url: getDashboardTaskLink(task.id) ?? null,
1873
1955
  last_run_at: task.lastRunAtMs ? new Date(task.lastRunAtMs).toISOString() : null,
1874
1956
  run_now_at: task.runNowAtMs ? new Date(task.runNowAtMs).toISOString() : null
@@ -1876,29 +1958,15 @@ function compactTask(task, isCreator) {
1876
1958
  }
1877
1959
  /** Build the result of a tool that changed one scheduled automation, with its card. */
1878
1960
  async function scheduleAutomationToolResult(conversationId, task, isCreator) {
1879
- const automation = compactTask(task, isCreator);
1880
- const description = automationTaskDescription(task.task);
1881
- const title = automation.title ?? fallbackShortTitle(description, "Scheduled automation");
1882
- const annotation = {
1883
- kind: "object",
1884
- objectType: "automation",
1885
- label: title,
1886
- key: task.id,
1887
- title,
1888
- url: automation.dashboard_url,
1889
- description,
1890
- status: automation.status,
1961
+ return saveAutomationCardResult(conversationId, compactTask(task, isCreator), {
1962
+ task: task.task,
1963
+ fallbackTitle: "Scheduled automation",
1891
1964
  trigger: task.schedule.kind === "one_off" && task.nextRunAtMs !== void 0 ? `${new Intl.DateTimeFormat("en-US", {
1892
1965
  dateStyle: "medium",
1893
1966
  timeStyle: "short",
1894
1967
  timeZone: task.schedule.timezone
1895
- }).format(task.nextRunAtMs)} · ${task.schedule.timezone}` : automation.schedule,
1896
- warning: automation.status === "blocked" ? automation.status_reason ?? "This automation is blocked." : automation.status === "completed" ? "This automation has completed." : void 0
1897
- };
1898
- return {
1899
- automation,
1900
- objectCards: await saveObjectAnnotations(conversationId, "junior", [annotation])
1901
- };
1968
+ }).format(task.nextRunAtMs)} · ${task.schedule.timezone}` : task.schedule.description
1969
+ });
1902
1970
  }
1903
1971
  // src/chat/tool-support/structured-result.ts
1904
1972
  const juniorToolContinuationSchema = z.object({
@@ -3503,7 +3571,7 @@ const CONVERSATIONS_TOOL_SOURCE = {
3503
3571
  description: "Search other conversations for past or current work, and read messages and events in retained conversations."
3504
3572
  };
3505
3573
  // src/chat/slack/tools/conversation-message-search.ts
3506
- const DEFAULT_LIMIT$4 = 20;
3574
+ const DEFAULT_LIMIT$3 = 20;
3507
3575
  const MAX_LIMIT$3 = 50;
3508
3576
  const conversationMessageSearchOutputSchema = juniorToolOutputSchema.extend({
3509
3577
  after: z.string().datetime().optional(),
@@ -3567,7 +3635,7 @@ const searchConversationMessagesToolDefinition = zodToolDefinition({
3567
3635
  before: z.string().datetime().nullable().describe("Include conversations active before this timestamp.").optional(),
3568
3636
  channel_id: slackChannelRefParam.nullable().optional(),
3569
3637
  query: z.string().trim().min(1).max(200).nullable().describe("Words or phrase to match in message text.").optional(),
3570
- limit: z.number().int().min(1).max(MAX_LIMIT$3).describe(`Maximum conversations. Default ${DEFAULT_LIMIT$4}; max ${MAX_LIMIT$3}.`).nullable().optional()
3638
+ limit: z.number().int().min(1).max(MAX_LIMIT$3).describe(`Maximum conversations. Default ${DEFAULT_LIMIT$3}; max ${MAX_LIMIT$3}.`).nullable().optional()
3571
3639
  }).strict(),
3572
3640
  outputSchema: conversationMessageSearchOutputSchema
3573
3641
  });
@@ -3586,7 +3654,7 @@ function createSlackConversationMessageSearchTool(teamId, currentConversationId)
3586
3654
  const matches = await getConversationMessageSearchStore().search({
3587
3655
  currentConversationId,
3588
3656
  filters,
3589
- limit: input.limit ?? DEFAULT_LIMIT$4
3657
+ limit: input.limit ?? DEFAULT_LIMIT$3
3590
3658
  });
3591
3659
  const matchesOutput = await Promise.all(matches.map(async (match) => {
3592
3660
  const reference = parseSlackThreadId(match.conversationId);
@@ -3981,7 +4049,7 @@ function createSlackListUpdateItemTool(state) {
3981
4049
  });
3982
4050
  }
3983
4051
  // src/chat/slack/tools/public-search.ts
3984
- const DEFAULT_LIMIT$3 = 10;
4052
+ const DEFAULT_LIMIT$2 = 10;
3985
4053
  const DEFAULT_CONTENT_TYPES = ["messages"];
3986
4054
  const CONTENT_TYPES = [
3987
4055
  "messages",
@@ -4251,7 +4319,7 @@ function createSlackPublicSearchTool(actionToken) {
4251
4319
  channel_types: ["public_channel"],
4252
4320
  content_types: normalizedContentTypes,
4253
4321
  include_bots: true,
4254
- limit: limit ?? DEFAULT_LIMIT$3,
4322
+ limit: limit ?? DEFAULT_LIMIT$2,
4255
4323
  ...normalizedAfter !== void 0 ? { after: normalizedAfter } : void 0,
4256
4324
  ...normalizedBefore !== void 0 ? { before: normalizedBefore } : void 0,
4257
4325
  ...cursor ? { cursor } : void 0,
@@ -5119,17 +5187,19 @@ async function getPausedTurnRequest(args) {
5119
5187
  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;
5120
5188
  let routing;
5121
5189
  try {
5122
- routing = await resolveTurnSessionRouting({
5190
+ routing = await resolveTurnResumeRouting({
5123
5191
  conversationId: args.conversationId,
5124
- conversationStore: args.conversationStore
5192
+ conversationStore: args.conversationStore,
5193
+ dispatchId: turn.dispatchId
5125
5194
  });
5126
5195
  } catch (error) {
5127
- await failTurnRecord({
5196
+ const failed = await failTurnRecord({
5128
5197
  conversationId: args.conversationId,
5129
5198
  expectedVersion: turn.version,
5130
5199
  turnId: args.turnId,
5131
5200
  errorMessage: error instanceof Error ? error.message : String(error)
5132
5201
  });
5202
+ if (failed) await recordFailedDispatchTurn(failed);
5133
5203
  return;
5134
5204
  }
5135
5205
  return {
@@ -5140,6 +5210,32 @@ async function getPausedTurnRequest(args) {
5140
5210
  traceContext: turn.traceContext
5141
5211
  };
5142
5212
  }
5213
+ /**
5214
+ * Record that a resume failed a dispatch turn for good. Without this outcome,
5215
+ * the dispatch runs the turn again, so a failed write is only logged.
5216
+ */
5217
+ async function recordFailedDispatchTurn(turn) {
5218
+ if (!turn.dispatchId) return;
5219
+ try {
5220
+ const dispatch = await getDispatchRecord(turn.dispatchId);
5221
+ await recordTurnSummary({
5222
+ conversationId: turn.conversationId,
5223
+ destination: dispatch?.destination,
5224
+ dispatchId: turn.dispatchId,
5225
+ dispatchOutcome: "failed",
5226
+ turnId: turn.turnId,
5227
+ sliceId: turn.sliceId,
5228
+ source: dispatch?.source,
5229
+ state: "failed",
5230
+ surface: turn.surface
5231
+ });
5232
+ } catch (error) {
5233
+ logException(error, "agent.continue.dispatch_failure_summary.failed", {
5234
+ "app.ai.conversation_id": turn.conversationId,
5235
+ "app.ai.session_id": turn.turnId
5236
+ });
5237
+ }
5238
+ }
5143
5239
  /** Wake the conversation worker for a paused turn. */
5144
5240
  async function wakePausedTurn(request, options = {}) {
5145
5241
  const nowMs = options.nowMs ?? Date.now();
@@ -7047,7 +7143,6 @@ function isChildAgentResult(status) {
7047
7143
  const childAgentKindSchema = z.enum(CHILD_AGENT_KINDS);
7048
7144
  /** Bound the agent invocations that one child agent listing reads. */
7049
7145
  const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
7050
- const CONVERSATION_LOOP_CHECK_CONCURRENCY = 8;
7051
7146
  /** Return whether a child's session stopped after its latest agent invocation. */
7052
7147
  function isChildAgentSessionStopped(latest, stoppedAtMs) {
7053
7148
  return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
@@ -7108,7 +7203,7 @@ async function listChildAgentsFromInvocations(parentConversationId) {
7108
7203
  const active = conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused");
7109
7204
  const activeIds = active.map((row) => row.conversationId);
7110
7205
  const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(activeIds), listActiveMailboxTurnSources(activeIds)]);
7111
- const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
7206
+ const limit = pLimit(8);
7112
7207
  const onConversationLoop = new Set((await Promise.all(active.map((row) => limit(async () => await runsOnConversationLoop(conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime(), workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []) ? row.conversationId : void 0)))).filter((id) => id !== void 0));
7113
7208
  const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
7114
7209
  ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
@@ -7151,7 +7246,7 @@ async function listChildAgentsWithoutAgentInvocations(parentConversationId) {
7151
7246
  }).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig), notExists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, juniorConversations.conversationId))))).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
7152
7247
  const ids = rows.map((row) => row.conversationId);
7153
7248
  const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
7154
- const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
7249
+ const limit = pLimit(8);
7155
7250
  return await Promise.all(rows.map(async (row) => {
7156
7251
  const kind = childAgentKindSchema.parse(row.kind);
7157
7252
  const stoppedAtMs = row.stoppedAt?.getTime();
@@ -7197,10 +7292,11 @@ async function listOpenLoopTurnIds(conversationId) {
7197
7292
  }
7198
7293
  async function listAnsweredLoopChildren(children, parentMessages) {
7199
7294
  if (children.length === 0 || parentMessages.length === 0) return [];
7200
- return (await Promise.all(children.map(async ({ childConversationId }) => {
7295
+ const limit = pLimit(8);
7296
+ return (await Promise.all(children.map(({ childConversationId }) => limit(async () => {
7201
7297
  const turnIds = await listOpenLoopTurnIds(childConversationId);
7202
7298
  return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
7203
- }))).filter((id) => id !== void 0);
7299
+ })))).filter((id) => id !== void 0);
7204
7300
  }
7205
7301
  /**
7206
7302
  * List the other child agents of one parent whose results have not reached
@@ -7279,10 +7375,11 @@ async function listAgentRelatives(input) {
7279
7375
  /** List the active watches that one Conversation owns, oldest first. */
7280
7376
  async function listOwnedWatches(conversationId) {
7281
7377
  const [own, childAgents] = await Promise.all([listWatches({ conversationId }), listDescendantAgents(conversationId)]);
7282
- const childWatches = await Promise.all(childAgents.map(async (childAgent) => (await listWatches({ conversationId: childAgent.conversationId })).map((watch) => ({
7378
+ const limit = pLimit(8);
7379
+ const childWatches = await Promise.all(childAgents.map((childAgent) => limit(async () => (await listWatches({ conversationId: childAgent.conversationId })).map((watch) => ({
7283
7380
  childAgent,
7284
7381
  watch
7285
- }))));
7382
+ })))));
7286
7383
  return [...own.map((watch) => ({ watch })), ...childWatches.flat()].sort((left, right) => left.watch.createdAtMs - right.watch.createdAtMs);
7287
7384
  }
7288
7385
  /**
@@ -7760,20 +7857,18 @@ async function verifyAttachmentUploads(args) {
7760
7857
  }
7761
7858
  /** Record checked uploads as attachments of their Conversation. */
7762
7859
  async function recordAttachmentUploads(args) {
7763
- for (const upload of args.uploads) {
7764
- if (upload.recorded) continue;
7765
- await recordUploadedAttachment({
7766
- attachment: {
7767
- ...upload.attachment,
7768
- conversationId: args.conversationId,
7769
- sha256: upload.sha256,
7770
- storageKey: upload.storageKey
7771
- },
7772
- db: args.db,
7773
- nowMs: args.nowMs ?? Date.now(),
7774
- storage: args.storage
7775
- });
7776
- }
7860
+ const limit = pLimit(8);
7861
+ await Promise.all(args.uploads.filter((upload) => !upload.recorded).map((upload) => limit(() => recordUploadedAttachment({
7862
+ attachment: {
7863
+ ...upload.attachment,
7864
+ conversationId: args.conversationId,
7865
+ sha256: upload.sha256,
7866
+ storageKey: upload.storageKey
7867
+ },
7868
+ db: args.db,
7869
+ nowMs: args.nowMs ?? Date.now(),
7870
+ storage: args.storage
7871
+ }))));
7777
7872
  return args.uploads.map((upload) => upload.attachment);
7778
7873
  }
7779
7874
  /**
@@ -8175,12 +8270,10 @@ async function sendReviewItemMessages(args) {
8175
8270
  conversationId,
8176
8271
  text
8177
8272
  })));
8178
- results.forEach((result, index) => {
8179
- if (result.status === "rejected") logWarn("review_item.message.failed", {
8180
- "app.review_item.id": args.item.id,
8181
- "app.review_item.change": args.change.kind,
8182
- "gen_ai.conversation.id": conversationIds[index]
8183
- });
8273
+ for (const [index, result] of results.entries()) if (result.status === "rejected") logWarn("review_item.message.failed", {
8274
+ "app.review_item.id": args.item.id,
8275
+ "app.review_item.change": args.change.kind,
8276
+ "gen_ai.conversation.id": conversationIds[index]
8184
8277
  });
8185
8278
  const failed = results.find((result) => result.status === "rejected");
8186
8279
  if (failed) throw failed.reason;
@@ -8221,7 +8314,7 @@ const REVIEW_DESK_TOOL_SOURCE = {
8221
8314
  id: "review-desk",
8222
8315
  description: "Update and search Review items: work on the review desk that needs a person."
8223
8316
  };
8224
- const DEFAULT_LIMIT$2 = 10;
8317
+ const DEFAULT_LIMIT$1 = 10;
8225
8318
  const MAX_LIMIT$2 = 25;
8226
8319
  const assigneesSchema = z.array(z.string().trim().min(1).max(320)).min(1).max(20).describe("Who can act on the item. Each entry is `everyone`, an email, or a mention such as `<@U123>`. Everyone means any person who can see the item.");
8227
8320
  const subjectSchema = z.object({
@@ -8535,7 +8628,7 @@ const searchReviewItemsToolDefinition = zodToolDefinition({
8535
8628
  assignee: z.string().trim().min(1).max(320).nullable().optional().describe("`everyone`, an email, or a mention such as `<@U123>`."),
8536
8629
  automation_id: z.string().trim().min(1).nullable().optional(),
8537
8630
  conversation_id: z.string().trim().min(1).nullable().optional(),
8538
- limit: z.number().int().min(1).max(MAX_LIMIT$2).nullable().optional().describe(`Default ${DEFAULT_LIMIT$2}; max ${MAX_LIMIT$2}.`)
8631
+ limit: z.number().int().min(1).max(MAX_LIMIT$2).nullable().optional().describe(`Default ${DEFAULT_LIMIT$1}; max ${MAX_LIMIT$2}.`)
8539
8632
  }).strict(),
8540
8633
  outputSchema: juniorToolOutputSchema
8541
8634
  });
@@ -8553,7 +8646,7 @@ function createSearchReviewItemsTool(context, services) {
8553
8646
  "dismissed"
8554
8647
  ] : [status];
8555
8648
  const items = await searchReviewItems(db, scope.reader, {
8556
- limit: input.limit ?? DEFAULT_LIMIT$2,
8649
+ limit: input.limit ?? DEFAULT_LIMIT$1,
8557
8650
  statuses,
8558
8651
  ...input.assignee ? { assignee: await resolveAssignee(db, input.assignee, scope.tenant, services.findMentionedUserId) } : void 0,
8559
8652
  ...input.automation_id ? { automationId: input.automation_id } : void 0,
@@ -9349,6 +9442,7 @@ const bashToolDefinition = zodToolDefinition({
9349
9442
  openWorldHint: false,
9350
9443
  readOnlyHint: false
9351
9444
  },
9445
+ approvalMode: "auto",
9352
9446
  description: "Run a bash command inside the isolated sandbox workspace. Use this for repository inspection/execution tasks that need shell access. Do not use for network-sensitive or destructive actions unless explicitly required.",
9353
9447
  inputSchema: z.object({
9354
9448
  command: z.string().min(1).describe("Bash command to run inside the sandbox."),
@@ -9428,7 +9522,7 @@ function createEditFileTool() {
9428
9522
  // src/chat/tool-support/result-cap.ts
9429
9523
  /** Default limit for the text that the model sees from one tool result. */
9430
9524
  const TOOL_RESULT_MAX_CHARS = 32e3;
9431
- const FULL_RESULT_DIR = "/tmp/jr";
9525
+ const FULL_RESULT_DIR = `${SANDBOX_SCRATCH_ROOT}/spills`;
9432
9526
  function fullResultPath(toolCallId) {
9433
9527
  const id = createHash("sha256").update(toolCallId).digest("hex").slice(0, 8);
9434
9528
  return `${FULL_RESULT_DIR}/${id}`;
@@ -9645,7 +9739,7 @@ function createWriteFileTool() {
9645
9739
  // src/chat/tools/search-conversations.ts
9646
9740
  const SUMMARY_MAX_LENGTH = 1e3;
9647
9741
  const CONVERSATION_IDS_MAX = 25;
9648
- const DEFAULT_LIMIT$1 = 10;
9742
+ const DEFAULT_LIMIT = 10;
9649
9743
  const MAX_LIMIT$1 = 25;
9650
9744
  /**
9651
9745
  * What the agent of the Conversation does now. The words match the
@@ -9715,7 +9809,7 @@ function searchConversationsInputSchema(channels) {
9715
9809
  ...channels ? { channel_id: channels.channelFilterSchema.nullable().optional().describe("Channel of the conversation.") } : void 0,
9716
9810
  roots_only: z.boolean().nullable().optional().describe("Return only root conversations. Set false to also find child agents (Threads and Tasks) by their own Brief, title, or linked resources. Default true."),
9717
9811
  include_archived: z.boolean().nullable().optional().describe("Include archived conversations, such as finished past work. Default false."),
9718
- limit: z.number().int().min(1).max(MAX_LIMIT$1).nullable().optional().describe(`Maximum results. Default ${DEFAULT_LIMIT$1}; max ${MAX_LIMIT$1}.`)
9812
+ limit: z.number().int().min(1).max(MAX_LIMIT$1).nullable().optional().describe(`Maximum results. Default ${DEFAULT_LIMIT}; max ${MAX_LIMIT$1}.`)
9719
9813
  }).strict();
9720
9814
  }
9721
9815
  /** Static definition of `searchConversations`, with the provider channel filter when there is one. */
@@ -9762,7 +9856,7 @@ function createSearchConversationsTool(context) {
9762
9856
  ...channelId ? { channelId } : void 0,
9763
9857
  ...conversationIds ? { conversationIds } : void 0,
9764
9858
  includeArchived: input.include_archived ?? false,
9765
- limit: input.limit ?? DEFAULT_LIMIT$1,
9859
+ limit: input.limit ?? DEFAULT_LIMIT,
9766
9860
  ...outcomeStatus ? { outcomeStatus } : void 0,
9767
9861
  ...query ? { query } : void 0,
9768
9862
  rootsOnly: input.roots_only ?? true
@@ -9772,11 +9866,209 @@ function createSearchConversationsTool(context) {
9772
9866
  }
9773
9867
  });
9774
9868
  }
9775
- // src/chat/tools/search-conversation-events.ts
9776
- const DEFAULT_LIMIT = 25;
9869
+ // src/chat/conversations/event-search.ts
9870
+ /**
9871
+ * Hybrid text search over the event history of one Conversation, across
9872
+ * every history version, so a query finds what compaction removed from the
9873
+ * model context.
9874
+ *
9875
+ * Two legs rank the searchable events. Keyword: BM25 over Postgres full-text
9876
+ * lexemes, which `event-lexemes.ts` stores after each Turn. An event with no
9877
+ * stored lexemes yet gets them computed for the query. Meaning: cosine
9878
+ * distance to the event embeddings that `event-embedding.ts` stores after
9879
+ * each Turn. Reciprocal rank fusion combines the two ranks, so neither leg
9880
+ * needs a score threshold.
9881
+ *
9882
+ * The agent's tool calls count half in the fusion, so what a tool returned
9883
+ * ranks above the call that repeats the query's words. The input of the
9884
+ * running Turn is not a result: it is in the model context already.
9885
+ *
9886
+ * The caller checks access to the Conversation first.
9887
+ *
9888
+ * Attributes on the `searchConversationEvents` `gen_ai.execute_tool` span:
9889
+ * - `app.event_search.keyword.candidate.count`: events with a query lexeme.
9890
+ * - `app.event_search.keyword.computed.count`: events whose lexemes were
9891
+ * computed for this query because none were stored yet.
9892
+ * - `app.event_search.keyword_ms`, `app.event_search.meaning_ms`: time of
9893
+ * each leg, which run at the same time.
9894
+ * - `app.event_search.meaning.candidate.count`: events with a vector.
9895
+ * - `app.event_search.meaning.top_distance`: cosine distance of the nearest
9896
+ * event, to tune a similarity floor.
9897
+ * - `app.event_search.result.count`: events returned.
9898
+ * Without an embedder, the meaning attributes are not set.
9899
+ * Policy: policies/observability.md.
9900
+ */
9901
+ const MAX_COMPUTED_EVENTS = 2e4;
9902
+ const CANDIDATES_PER_LEG = 100;
9903
+ const BM25_B = .75;
9904
+ const TOOL_CALL_WEIGHT = .5;
9905
+ /**
9906
+ * Rank keyword candidates with Okapi BM25. Document frequencies and the mean
9907
+ * length come from the candidates, which are every event that has a query
9908
+ * lexeme. Length is the count of distinct lexemes, the size that Postgres
9909
+ * stores for a tsvector.
9910
+ */
9911
+ function rankKeywordCandidates(candidates, searchedEvents) {
9912
+ if (candidates.length === 0) return [];
9913
+ const documentFrequency = /* @__PURE__ */ new Map();
9914
+ for (const candidate of candidates) for (const term of Object.keys(candidate.termFrequencies)) documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
9915
+ const total = Math.max(searchedEvents, candidates.length);
9916
+ const meanLength = candidates.reduce((sum, candidate) => sum + candidate.length, 0) / candidates.length;
9917
+ const score = (candidate) => Object.entries(candidate.termFrequencies).reduce((sum, [term, tf]) => {
9918
+ const idf = bm25InverseDocumentFrequency(total, documentFrequency.get(term) ?? 0);
9919
+ const frequency = bm25NormalizedFrequency(tf, candidate.length, meanLength, BM25_B);
9920
+ return sum + idf * bm25Saturation(frequency);
9921
+ }, 0);
9922
+ return candidates.map((candidate) => ({
9923
+ seq: candidate.seq,
9924
+ score: score(candidate)
9925
+ })).sort((left, right) => right.score - left.score || right.seq - left.seq).map(({ seq }) => seq);
9926
+ }
9927
+ /**
9928
+ * Fuse ranked event lists with reciprocal rank fusion. An event in both
9929
+ * lists ranks above an event in one. Events in `toolCalls` count
9930
+ * `TOOL_CALL_WEIGHT` as much. Ties go to the newer event.
9931
+ */
9932
+ function fuseEventRanks(lists, toolCalls = /* @__PURE__ */ new Set()) {
9933
+ const ranked = lists.flatMap((list) => {
9934
+ const entries = list.map((seq, index) => ({
9935
+ item: seq,
9936
+ rank: index + 1
9937
+ }));
9938
+ return [entries.filter((entry) => !toolCalls.has(entry.item)), entries.filter((entry) => toolCalls.has(entry.item))];
9939
+ });
9940
+ return fuseRankedLists(ranked, {
9941
+ key: (seq) => seq,
9942
+ tiebreak: (left, right) => right - left,
9943
+ weights: ranked.map((_, index) => index % 2 ? TOOL_CALL_WEIGHT : 1)
9944
+ });
9945
+ }
9946
+ async function searchBounds(db, search, types) {
9947
+ const events = juniorConversationEvents;
9948
+ return and(eq(events.conversationId, search.conversationId), inArray(events.type, [...types]), search.afterSeq === void 0 ? void 0 : gt(events.seq, search.afterSeq), search.beforeSeq === void 0 ? void 0 : lt(events.seq, search.beforeSeq), search.currentTurnId === void 0 ? void 0 : await notTurnInput(db, search.conversationId, search.currentTurnId));
9949
+ }
9950
+ async function notTurnInput(db, conversationId, turnId) {
9951
+ const events = juniorConversationEvents;
9952
+ const [started] = await db.select({
9953
+ seq: events.seq,
9954
+ inputMessageIds: sql`${events.payload}->'inputMessageIds'`
9955
+ }).from(events).where(and(eq(events.conversationId, conversationId), eq(events.type, "turn_started"), eq(sql`${events.payload}->>'turnId'`, turnId))).limit(1);
9956
+ if (!started) return void 0;
9957
+ return not(or(and(eq(events.type, "user_message"), gt(events.seq, started.seq)), and(inArray(events.type, ["message", "message_updated"]), inArray(sql`${events.payload}->>'messageId'`, started.inputMessageIds))));
9958
+ }
9959
+ async function toolCallSeqs(db, conversationId, seqs) {
9960
+ if (seqs.length === 0) return /* @__PURE__ */ new Set();
9961
+ const events = juniorConversationEvents;
9962
+ const rows = await db.select({ seq: events.seq }).from(events).where(and(eq(events.conversationId, conversationId), inArray(events.seq, [...seqs]), callsToolSql()));
9963
+ return new Set(rows.map((row) => row.seq));
9964
+ }
9965
+ async function keywordRanks(db, search, bounds) {
9966
+ const events = juniorConversationEvents;
9967
+ const stored = juniorConversationEventLexemes;
9968
+ const storedRow = and(eq(stored.conversationId, events.conversationId), eq(stored.seq, events.seq));
9969
+ const queryVector = lexemesSql(search.query);
9970
+ const tsquery = sql`regexp_replace(strip(${queryVector})::text, ''' ''', ''' | ''', 'g')::tsquery`;
9971
+ const storedDocuments = db.select({
9972
+ seq: events.seq,
9973
+ searchVector: sql`${stored.lexemes}`.as("search_vector")
9974
+ }).from(stored).innerJoin(events, storedRow).where(and(bounds, sql`${stored.lexemes} @@ ${tsquery}`)).as("stored_events");
9975
+ const unstored = await db.select({ seq: events.seq }).from(events).leftJoin(stored, storedRow).where(and(bounds, isNull(stored.seq))).orderBy(desc(events.seq)).limit(MAX_COMPUTED_EVENTS);
9976
+ const computedDocuments = db.select({
9977
+ seq: events.seq,
9978
+ searchVector: sql`${lexemesSql(searchedEventTextSql())}`.as("search_vector")
9979
+ }).from(events).where(and(eq(events.conversationId, search.conversationId), seqIn(unstored.map((row) => row.seq)))).limit(MAX_COMPUTED_EVENTS).as("computed_events");
9980
+ const [storedCandidates, computedCandidates, [searched]] = await Promise.all([
9981
+ keywordCandidates(db, storedDocuments, queryVector),
9982
+ unstored.length === 0 ? [] : keywordCandidates(db, computedDocuments, queryVector, tsquery),
9983
+ db.select({ total: count() }).from(events).where(bounds)
9984
+ ]);
9985
+ const candidates = [...storedCandidates, ...computedCandidates];
9986
+ return {
9987
+ candidates: candidates.length,
9988
+ computed: unstored.length,
9989
+ seqs: rankKeywordCandidates(candidates, searched?.total ?? 0).slice(0, CANDIDATES_PER_LEG)
9990
+ };
9991
+ }
9992
+ async function keywordCandidates(db, documents, queryVector, tsquery) {
9993
+ return (await db.select({
9994
+ seq: documents.seq,
9995
+ length: sql`length(${documents.searchVector})`,
9996
+ termFrequencies: sql`(
9997
+ SELECT coalesce(jsonb_object_agg(lexeme, coalesce(cardinality(positions), 1)), '{}'::jsonb)
9998
+ FROM unnest(ts_filter(setweight(${documents.searchVector}, 'A', tsvector_to_array(${queryVector})), '{a}'))
9999
+ )`
10000
+ }).from(documents).where(tsquery ? sql`${documents.searchVector} @@ ${tsquery}` : void 0)).map((row) => ({
10001
+ ...row,
10002
+ length: Number(row.length)
10003
+ }));
10004
+ }
10005
+ async function meaningRanks(db, search, bounds) {
10006
+ if (!search.embedder) return { seqs: [] };
10007
+ const query = await embedConversationQuery(search.embedder, search.query);
10008
+ const events = juniorConversationEvents;
10009
+ const embeddings = juniorConversationEventEmbeddings;
10010
+ const distance = guardedCosineDistance({
10011
+ column: embeddings.embedding,
10012
+ dimensions: embeddings.dimensions,
10013
+ query: query.vector,
10014
+ type: "halfvec"
10015
+ });
10016
+ const rows = await db.select({
10017
+ seq: embeddings.seq,
10018
+ distance
10019
+ }).from(embeddings).innerJoin(events, and(eq(events.conversationId, embeddings.conversationId), eq(events.seq, embeddings.seq))).where(and(bounds, eq(embeddings.provider, query.provider), eq(embeddings.model, query.model), eq(embeddings.dimensions, query.vector.length))).orderBy(distance).limit(CANDIDATES_PER_LEG);
10020
+ const top = rows[0];
10021
+ return {
10022
+ seqs: rows.map((row) => row.seq),
10023
+ ...top ? { topDistance: Number(top.distance) } : void 0
10024
+ };
10025
+ }
10026
+ /** Search the event text of one Conversation. Best match first. */
10027
+ async function searchConversationEventText(db, search) {
10028
+ const types = SEARCHABLE_EVENT_TYPES.filter((type) => !search.types || search.types.includes(type));
10029
+ if (types.length === 0) return [];
10030
+ const bounds = await searchBounds(db, search, types);
10031
+ const timed = async (work) => {
10032
+ const startedAt = Date.now();
10033
+ return {
10034
+ ...await work,
10035
+ ms: Date.now() - startedAt
10036
+ };
10037
+ };
10038
+ const [keyword, meaning] = await Promise.all([timed(keywordRanks(db, search, bounds)), timed(meaningRanks(db, search, bounds))]);
10039
+ const toolCalls = await toolCallSeqs(db, search.conversationId, [.../* @__PURE__ */ new Set([...keyword.seqs, ...meaning.seqs])]);
10040
+ const seqs = fuseEventRanks([keyword.seqs, meaning.seqs], toolCalls).slice(0, search.limit);
10041
+ setSpanAttributes({
10042
+ "app.event_search.keyword.candidate.count": keyword.candidates,
10043
+ "app.event_search.keyword.computed.count": keyword.computed,
10044
+ "app.event_search.keyword_ms": keyword.ms,
10045
+ "app.event_search.result.count": seqs.length,
10046
+ ...search.embedder ? {
10047
+ "app.event_search.meaning.candidate.count": meaning.seqs.length,
10048
+ "app.event_search.meaning.top_distance": meaning.topDistance,
10049
+ "app.event_search.meaning_ms": meaning.ms
10050
+ } : void 0
10051
+ });
10052
+ if (seqs.length === 0) return [];
10053
+ const events = juniorConversationEvents;
10054
+ const rows = await db.select({
10055
+ row: events,
10056
+ text: searchedEventTextSql()
10057
+ }).from(events).where(and(eq(events.conversationId, search.conversationId), inArray(events.seq, seqs)));
10058
+ const bySeq = new Map(rows.map((row) => [row.row.seq, row]));
10059
+ const terms = excerptTerms(search.query);
10060
+ return seqs.flatMap((seq) => {
10061
+ const match = bySeq.get(seq);
10062
+ return match ? [{
10063
+ event: eventFromRow(match.row),
10064
+ excerpt: eventExcerpt(match.text ?? "", terms)
10065
+ }] : [];
10066
+ });
10067
+ }
9777
10068
  const MAX_LIMIT = 100;
9778
10069
  const MAX_EVENT_DATA_BYTES = 4e3;
9779
10070
  const MAX_IDENTITY_CHARS = 256;
10071
+ const MAX_QUERY_CHARS = 200;
9780
10072
  const textEncoder = new TextEncoder();
9781
10073
  const knownEventTypeSchema = z.enum(KNOWN_CONVERSATION_EVENT_TYPES);
9782
10074
  const projectedEventSchema = z.object({
@@ -9784,16 +10076,17 @@ const projectedEventSchema = z.object({
9784
10076
  history_version: z.number().int().nonnegative().describe("Agent history generation after replacement."),
9785
10077
  created_at: z.iso.datetime().describe("When the event was recorded."),
9786
10078
  idempotency_key: z.string().min(1).optional().describe("Retry-stable event identity, when assigned."),
9787
- data: z.record(z.string(), z.unknown()).describe("Bounded event data. Read an omitted payload with readConversationEvent.")
10079
+ data: z.record(z.string(), z.unknown()).describe("Bounded event data. With a query, only its identity fields. Read an omitted payload with readConversationEvent."),
10080
+ excerpt: z.string().optional().describe("Event text around the best query match.")
9788
10081
  }).strict();
9789
10082
  const searchConversationEventsOutputSchema = juniorToolOutputSchema.extend({
9790
10083
  conversation_id: z.string().min(1),
9791
- events: z.array(projectedEventSchema),
9792
- has_older: z.boolean().describe("Whether matching older events exist."),
9793
- has_newer: z.boolean().describe("Whether matching newer events exist.")
10084
+ events: z.array(projectedEventSchema).describe("Best match first for a query, else in seq order."),
10085
+ has_older: z.boolean().optional().describe("Whether matching older events exist. Omitted for a query."),
10086
+ has_newer: z.boolean().optional().describe("Whether matching newer events exist. Omitted for a query.")
9794
10087
  });
9795
10088
  const searchConversationEventsToolDefinition = zodToolDefinition({
9796
- description: "Search the durable event log for one conversation, including messages, agent history, tool results, and compactions. Defaults to the current conversation. Outside the current conversation tree, only retained public conversations are accessible.",
10089
+ description: "Search the durable event log for one conversation, including messages, agent history, tool results, and compactions, across every history version. Finds events by words or meaning, or pages them in seq order. Defaults to the current conversation. Outside the current conversation tree, only retained public conversations are accessible.",
9797
10090
  exposure: "deferred",
9798
10091
  source: CONVERSATIONS_TOOL_SOURCE,
9799
10092
  annotations: {
@@ -9804,15 +10097,16 @@ const searchConversationEventsToolDefinition = zodToolDefinition({
9804
10097
  },
9805
10098
  inputSchema: z.object({
9806
10099
  conversation_id: z.string().trim().min(1).nullable().describe("Conversation ID to search. Omit or null for the current conversation.").optional(),
10100
+ query: z.string().trim().min(1).max(MAX_QUERY_CHARS).nullable().describe("Words or meaning to find in messages, agent history, and tool calls and results, such as a path, URL, id, or name. Any word may match. Omit or null to page in seq order.").optional(),
9807
10101
  after_seq: z.number().int().nonnegative().nullable().describe("Exclusive event sequence lower bound; returns ascending.").optional(),
9808
10102
  before_seq: z.number().int().nonnegative().nullable().describe("Exclusive event sequence upper bound.").optional(),
9809
- limit: z.number().int().min(1).max(MAX_LIMIT).nullable().describe(`Maximum events. Default ${DEFAULT_LIMIT}; max ${MAX_LIMIT}.`).optional(),
10103
+ limit: z.number().int().min(1).max(MAX_LIMIT).nullable().describe(`Maximum events. Default 25; max ${MAX_LIMIT}.`).optional(),
9810
10104
  types: z.array(knownEventTypeSchema).min(1).nullable().describe("Event types to include; omit for all types.").optional()
9811
10105
  }).strict(),
9812
10106
  outputSchema: searchConversationEventsOutputSchema
9813
10107
  });
9814
10108
  /** Create a deferred tool that searches one conversation's durable event log. */
9815
- function createSearchConversationEventsTool(context) {
10109
+ function createSearchConversationEventsTool(context, options = {}) {
9816
10110
  return zodTool({
9817
10111
  ...searchConversationEventsToolDefinition,
9818
10112
  execute: async (input) => {
@@ -9820,10 +10114,27 @@ function createSearchConversationEventsTool(context) {
9820
10114
  const conversationId = input.conversation_id?.trim() || currentConversationId;
9821
10115
  const afterSeq = input.after_seq ?? void 0;
9822
10116
  const beforeSeq = input.before_seq ?? void 0;
9823
- const limit = input.limit ?? DEFAULT_LIMIT;
10117
+ const limit = input.limit ?? 25;
9824
10118
  const types = input.types ?? void 0;
9825
10119
  if (afterSeq !== void 0 && beforeSeq !== void 0 && afterSeq >= beforeSeq) throw new ToolInputError("after_seq must be less than before_seq when both are provided");
9826
10120
  await assertCanReadConversationEvents(context, conversationId);
10121
+ const query = input.query ?? void 0;
10122
+ if (query) return {
10123
+ conversation_id: conversationId,
10124
+ events: (await searchConversationEventText(getDb(), {
10125
+ conversationId,
10126
+ limit,
10127
+ query,
10128
+ ...conversationId === currentConversationId && context.turnId ? { currentTurnId: context.turnId } : void 0,
10129
+ ...afterSeq === void 0 ? void 0 : { afterSeq },
10130
+ ...beforeSeq === void 0 ? void 0 : { beforeSeq },
10131
+ ...types === void 0 ? void 0 : { types },
10132
+ ...options.embedder ? { embedder: options.embedder } : void 0
10133
+ })).map((match) => ({
10134
+ ...projectEvent(match.event, { omitPayload: true }),
10135
+ excerpt: match.excerpt
10136
+ }))
10137
+ };
9827
10138
  const page = await getConversationEventStore().query(conversationId, {
9828
10139
  limit,
9829
10140
  ...afterSeq === void 0 ? void 0 : { afterSeq },
@@ -9832,15 +10143,15 @@ function createSearchConversationEventsTool(context) {
9832
10143
  });
9833
10144
  return {
9834
10145
  conversation_id: conversationId,
9835
- events: page.events.map(projectEvent),
10146
+ events: page.events.map((event) => projectEvent(event)),
9836
10147
  has_older: page.hasOlder,
9837
10148
  has_newer: page.hasNewer
9838
10149
  };
9839
10150
  }
9840
10151
  });
9841
10152
  }
9842
- function projectEvent(event) {
9843
- const data = boundEventData(stripReplacementHistory(event.data));
10153
+ function projectEvent(event, options = {}) {
10154
+ const data = boundEventData(stripReplacementHistory(event.data), options);
9844
10155
  return {
9845
10156
  seq: event.seq,
9846
10157
  history_version: event.historyVersion,
@@ -9849,9 +10160,9 @@ function projectEvent(event) {
9849
10160
  data
9850
10161
  };
9851
10162
  }
9852
- function boundEventData(data) {
10163
+ function boundEventData(data, options) {
9853
10164
  const payloadJsonBytes = jsonByteLength(data);
9854
- if (payloadJsonBytes <= MAX_EVENT_DATA_BYTES) return data;
10165
+ if (!options.omitPayload && payloadJsonBytes <= MAX_EVENT_DATA_BYTES) return data;
9855
10166
  return {
9856
10167
  ...eventIdentity(data),
9857
10168
  payload_omitted: true,
@@ -10867,13 +11178,13 @@ function createWebFetchTool(hooks, options = {}) {
10867
11178
  filename: filenameForUrl(safeUrl, contentType.split(";")[0] ?? "image/png"),
10868
11179
  mimeType: contentType.split(";")[0] ?? "application/octet-stream"
10869
11180
  }];
10870
- const artifactRefs = hooks.writeGeneratedArtifacts ? await hooks.writeGeneratedArtifacts(files) : [];
11181
+ const fileRefs = hooks.writeGeneratedFiles ? await hooks.writeGeneratedFiles(files) : [];
10871
11182
  return {
10872
11183
  url: safeUrl.toString(),
10873
11184
  media_type: contentType,
10874
11185
  bytes: bytes.byteLength,
10875
- images: artifactRefs,
10876
- delivery: artifactRefs.length > 0 ? options.canSendFilesToActiveConversation ? "Fetched images were written to sandbox paths. To share them, pass the returned image objects unchanged as sendFiles files." : "Fetched image was written to a sandbox path, but this runtime has no file-send tool for the active conversation." : "Fetched image bytes are available only in this tool result; this runtime has no file-send tool for the active conversation."
11186
+ images: fileRefs,
11187
+ delivery: fileRefs.length > 0 ? options.canSendFilesToActiveConversation ? "Fetched images were written to sandbox paths. To share them, pass the returned image objects unchanged as sendFiles files." : "Fetched image was written to a sandbox path, but this runtime has no file-send tool for the active conversation." : "Fetched image bytes are available only in this tool result; this runtime has no file-send tool for the active conversation."
10877
11188
  };
10878
11189
  }
10879
11190
  return await extractWebFetchResponse(safeUrl, response);
@@ -11638,12 +11949,18 @@ async function addStats(amounts, options = {}) {
11638
11949
  juniorStats.metric,
11639
11950
  juniorStats.name
11640
11951
  ],
11641
- set: { count: sql`${juniorStats.count} + excluded.count` }
11952
+ set: { count: sql`${juniorStats.count} + excluded.${sql.identifier(juniorStats.count.name)}` }
11642
11953
  });
11643
11954
  }
11644
11955
  /** Read daily counters inside an inclusive UTC date range. */
11645
11956
  async function readStats(start, end) {
11646
- return await getDb().select().from(juniorStats).where(and(gte(juniorStats.date, start), lte(juniorStats.date, end))).orderBy(asc(juniorStats.date), asc(juniorStats.namespace), asc(juniorStats.metric), asc(juniorStats.name));
11957
+ return await getDb().select({
11958
+ count: juniorStats.count,
11959
+ date: juniorStats.date,
11960
+ metric: juniorStats.metric,
11961
+ name: juniorStats.name,
11962
+ namespace: juniorStats.namespace
11963
+ }).from(juniorStats).where(and(gte(juniorStats.date, start), lte(juniorStats.date, end))).orderBy(asc(juniorStats.date), asc(juniorStats.namespace), asc(juniorStats.metric), asc(juniorStats.name));
11647
11964
  }
11648
11965
  /**
11649
11966
  * Return the first day with a counter in the namespace, if any. Days that
@@ -12285,11 +12602,12 @@ async function breakerOpen(state, modelId) {
12285
12602
  * models. Providers that no model uses are left out.
12286
12603
  */
12287
12604
  async function breakerStates(state, modelIds) {
12288
- const providers = new Set(modelIds.map(providerOf).filter((provider) => Object.hasOwn(CACHE_TTL_MS, provider)));
12289
- return Promise.all([...providers].map(async (provider) => ({
12605
+ const warmed = [...new Set(modelIds.map(providerOf).filter((provider) => Object.hasOwn(CACHE_TTL_MS, provider)))];
12606
+ const open = await getStateValues(state, warmed.map(breakerOpenKey));
12607
+ return warmed.map((provider, index) => ({
12290
12608
  provider,
12291
- open: await state.get(breakerOpenKey(provider)) === true
12292
- })));
12609
+ open: open[index] === true
12610
+ }));
12293
12611
  }
12294
12612
  /**
12295
12613
  * Close a provider's breaker so warming starts again, and forget its recent
@@ -12483,19 +12801,14 @@ async function definitionsChanged(state, definitions) {
12483
12801
  */
12484
12802
  /** `junior_stats` namespace of the cache warming counters. */
12485
12803
  const SAVINGS_NAMESPACE = "cache_warming";
12486
- /**
12487
- * Dollar counters store this many units per dollar. A day of one model then
12488
- * fits the integer counter up to about $200,000.
12489
- */
12490
- const UNITS_PER_USD = 1e4;
12491
12804
  const METRICS = {
12492
12805
  hits: "hits",
12493
12806
  idlePeriods: "idle_periods",
12494
- oracleSavings: "oracle_savings",
12495
- saved: "saved",
12807
+ oracleSavings: "oracle_savings_micro_usd",
12808
+ saved: "saved_micro_usd",
12496
12809
  unwarmedIdlePeriods: "unwarmed_idle_periods",
12497
- unwarmedOracleSavings: "unwarmed_oracle_savings",
12498
- warmupCost: "warmup_cost",
12810
+ unwarmedOracleSavings: "unwarmed_oracle_savings_micro_usd",
12811
+ warmupCost: "warmup_cost_micro_usd",
12499
12812
  historyDays: "history_days"
12500
12813
  };
12501
12814
  const TTL_START_DELAY_MS = 1e4;
@@ -12526,7 +12839,6 @@ function idlePeriodSavings(input) {
12526
12839
  savedUsd: hit ? writeSavedUsd : 0
12527
12840
  };
12528
12841
  }
12529
- const units = (usd) => Math.round(usd * UNITS_PER_USD);
12530
12842
  const savingsStats = (modelId, counts) => Object.entries(counts).map(([metric, count]) => ({
12531
12843
  namespace: SAVINGS_NAMESPACE,
12532
12844
  metric: METRICS[metric],
@@ -12534,12 +12846,12 @@ const savingsStats = (modelId, counts) => Object.entries(counts).map(([metric, c
12534
12846
  count
12535
12847
  }));
12536
12848
  function periodCounts(savings, warmed) {
12537
- const oracle = units(savings.oracleUsd);
12849
+ const oracle = usdToMicroUsd(savings.oracleUsd);
12538
12850
  return {
12539
12851
  idlePeriods: 1,
12540
12852
  hits: savings.hit ? 1 : 0,
12541
12853
  oracleSavings: oracle,
12542
- saved: units(savings.savedUsd),
12854
+ saved: usdToMicroUsd(savings.savedUsd),
12543
12855
  ...warmed === false ? {
12544
12856
  unwarmedIdlePeriods: 1,
12545
12857
  unwarmedOracleSavings: oracle
@@ -12566,7 +12878,7 @@ async function recordIdlePeriodSavings(modelId, savings, warmed) {
12566
12878
  }
12567
12879
  /** Add the cost of one warmup call. */
12568
12880
  async function recordWarmupCost(modelId, costUsd) {
12569
- await addSavingsStats(modelId, { warmupCost: units(costUsd) });
12881
+ await addSavingsStats(modelId, { warmupCost: usdToMicroUsd(costUsd) });
12570
12882
  }
12571
12883
  const utcDate = (ms) => new Date(ms).toISOString().slice(0, 10);
12572
12884
  /**
@@ -12617,11 +12929,11 @@ function savingsTotals(stats) {
12617
12929
  historyDays: sum(METRICS.historyDays),
12618
12930
  hits: sum(METRICS.hits),
12619
12931
  idlePeriods: sum(METRICS.idlePeriods),
12620
- oracleSavingsUsd: sum(METRICS.oracleSavings) / UNITS_PER_USD,
12621
- savedUsd: sum(METRICS.saved) / UNITS_PER_USD,
12932
+ oracleSavingsMicroUsd: sum(METRICS.oracleSavings),
12933
+ savedMicroUsd: sum(METRICS.saved),
12622
12934
  unwarmedIdlePeriods: sum(METRICS.unwarmedIdlePeriods),
12623
- unwarmedOracleSavingsUsd: sum(METRICS.unwarmedOracleSavings) / UNITS_PER_USD,
12624
- warmupCostUsd: sum(METRICS.warmupCost) / UNITS_PER_USD
12935
+ unwarmedOracleSavingsMicroUsd: sum(METRICS.unwarmedOracleSavings),
12936
+ warmupCostMicroUsd: sum(METRICS.warmupCost)
12625
12937
  };
12626
12938
  }
12627
12939
  // src/chat/cache-warming/snapshot.ts
@@ -12714,11 +13026,12 @@ async function loadSnapshot(state, conversationId, key) {
12714
13026
  const snapshot = await state.get(key);
12715
13027
  if (!snapshot) return "stopped";
12716
13028
  const context = JSON.parse((await zstdDecompress(Buffer.from(snapshot, "base64"))).toString("utf8"));
12717
- for (const part of context.messages.flatMap(imageParts)) {
12718
- if (!part.data.startsWith(IMAGE_REF_PREFIX)) continue;
12719
- const sha256 = part.data.slice(7);
12720
- const data = await state.get(imageKey(conversationId, sha256));
12721
- if (data === null) return "image_missing";
13029
+ const parts = context.messages.flatMap(imageParts).filter((part) => part.data.startsWith(IMAGE_REF_PREFIX));
13030
+ const limit = pLimit(8);
13031
+ const images = await Promise.all(parts.map((part) => limit(() => state.get(imageKey(conversationId, part.data.slice(7))))));
13032
+ for (const [index, part] of parts.entries()) {
13033
+ const data = images[index];
13034
+ if (data === null || data === void 0) return "image_missing";
12722
13035
  part.data = data;
12723
13036
  }
12724
13037
  return context;
@@ -13010,9 +13323,10 @@ async function listConversationWork(conversationIds) {
13010
13323
  const finishedAtById = /* @__PURE__ */ new Map();
13011
13324
  const unfinished = /* @__PURE__ */ new Set();
13012
13325
  let failed = false;
13013
- for (const plugin of getPlugins()) {
13326
+ const limit = pLimit(8);
13327
+ await Promise.all(getPlugins().map((plugin) => limit(async () => {
13014
13328
  const hook = plugin.hooks?.unfinishedWork;
13015
- if (!hook) continue;
13329
+ if (!hook) return;
13016
13330
  try {
13017
13331
  const result = await hook({
13018
13332
  conversationIds: queriedIds,
@@ -13046,7 +13360,7 @@ async function listConversationWork(conversationIds) {
13046
13360
  "exception.message": error instanceof Error ? error.message : String(error)
13047
13361
  });
13048
13362
  }
13049
- }
13363
+ })));
13050
13364
  return {
13051
13365
  assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
13052
13366
  failed,
@@ -13164,10 +13478,11 @@ async function scheduleWarmup(message, requestStartedAtMs, warm) {
13164
13478
  }
13165
13479
  async function recordGap(state, conversationId, generation, warm, gapMs) {
13166
13480
  if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
13167
- for (const segment of recordedSegments(warm)) await state.appendToList(segmentGapsKey(segment), gapMs, {
13481
+ const limit = pLimit(8);
13482
+ await Promise.all(recordedSegments(warm).map((segment) => limit(() => state.appendToList(segmentGapsKey(segment), gapMs, {
13168
13483
  maxLength: GLOBAL_GAPS_MAX,
13169
13484
  ttlMs: GLOBAL_GAPS_TTL_MS
13170
- });
13485
+ }))));
13171
13486
  await state.appendToList(conversationGapsKey(conversationId, decisionSegment(warm)), gapMs, {
13172
13487
  maxLength: CONVERSATION_GAPS_MAX,
13173
13488
  ttlMs: CONVERSATION_STATE_TTL_MS
@@ -13541,4 +13856,4 @@ async function runCacheWarmup(message) {
13541
13856
  }, startedAtMs, warm);
13542
13857
  }, attributes);
13543
13858
  }
13544
- export { createStopAgentTool as $, createSlackListGetItemsTool as $n, requireToolDestination as $r, readChildConversationSender as $t, createWebSearchTool as A, NO_REPLY_GAP_MS as Ai, wakeAuthorizedTurn as An, createDeleteAutomationTool as Ar, verifyAttachmentUploads as At, createSearchEventTypesTool as B, AgentRunError as Bn, automationTriggerSchema as Br, getActiveAgentInvocationForConversation as Bt, incrementStat as C, effectiveTaskOutcomes as Ci, findChildAgentConversationId as Cn, isMissingPathError as Cr, createConversationId as Ct, requireReadyWorkspaceSnapshot as D, IDLE_HORIZON_MS as Di, supersedeTurnForInput as Dn, createCanvas as Dr, AttachmentUploadError as Dt, processWorkspaceSnapshotJob as E, countOwnedAutomationsNeedingAttention as Ei, supersedeOpenMailboxTurns as En, createOperationKey as Er, resolveConversationDestination as Et, userLookupIdentityProviders as F, isAttemptInterrupt as Fn, automationIdForToolCall as Fr, listOwnedWatches as Ft, missingFileResult as G, jsonResponse as Gn, juniorToolOutputSchema as Gr, listAgentInvocationsForConversation as Gt, createSearchConversationsTool as H, createSetConversationSubscriptionTool as Hn, newAutomationTask as Hr, getChildAgentLabel as Ht, createUpdateUserCustomizationTool as I, selectAttemptMessages as In, automationSkillToolSchema as Ir, listChildAgents as It, capToolResult as J, renderAttachmentText as Jn, automationToolContext as Jr, markAgentInvocationParentMailboxAppended as Jt, sliceFileContent as K, throwApiError as Kn, makeStructuredToolOutput as Kr, listPendingAgentInvocationMailboxAppends as Kt, createSubmitFeedbackTool as L, createWebAuthorization as Ln, automationToolResult as Lr, listUnreportedSiblingAgents as Lt, createWatchTimerTool as M, getTurnAuthorization as Mn, parseToolInput as Mr, createReadConversationEventTool as Mt, createWatchEventsTool as N, canJoinTurn as Nn, zodTool as Nr, createRunOperatorSqlTool as Nt, prepareWorkspaceSnapshot as O, MINUTE_MS$1 as Oi, createPausedTurns as On, createSearchAutomationsTool as Or, collectAttachmentUploadGarbage as Ot, createUserLookupTool as P, canShareTurn as Pn, zodToolDefinition as Pr, createListWatchesTool as Pt, createUpdatePlanTool as Q, createSlackListUpdateItemTool as Qn, requireToolCreator as Qr, getChildAgentInputSender as Qt, createSystemTimeTool as R, deleteWebAuthorization as Rn, automationToolResultSchema as Rr, NON_TERMINAL_AGENT_INVOCATION_STATUSES as Rt, createWorkspaceTools as S, missingAutomationSkillReason as Si, AgentMessageTargetError as Sn, SLACK_TOOL_SOURCE as Sr, createAndEnqueueConversation as St, ensureWorkspaceSnapshotBuild as T, resolveTaskOutcomes as Ti, PARENT_AGENT_TARGET as Tn, resolveWorkspacePath as Tr, webActorFromUser as Tt, createWriteFileTool as U, setConversationSubscription as Un, triggerKind as Ur, getLatestAgentInvocationForConversation as Ut, createSearchConversationEventsTool as V, executeTurn as Vn, editedAutomationTask as Vr, getAgentInvocation as Vt, createReadFileTool as W, emptyResponse as Wn, injectContinuationToolName as Wr, isTerminalAgentInvocation as Wt, editFile as X, parseSlackMessageReference as Xn, requireToolAutomation as Xr, sendsResultToParent as Xt, createEditFileTool as Y, renderBlockText as Yn, automationToolsDisabledReason as Yr, reportReplacedWithoutOpenWork as Yt, createBashTool as Z, createSlackPublicSearchTool as Zn, requireToolCaller as Zr, childAgentInput as Zt, closeBreaker as _, requireEventAutomationTrigger as _i, recordSubagentEnded as _n, joinPublicChannel as _r, renderReviewItemMessage as _t, createCacheWarmingRecorder as a, readViewerAutomationEdit as ai, readParentMessage as an, parseSlackThreadId as ar, createNoReplyTool as at, coreToolSlots as b, requireAutomationSkill as bi, AgentDepthLimitError as bn, createSlackCanvasReadTool as br, appendAndEnqueueWebMessage as bt, isConversationWorkDone as c, readConversationSourceTask as ci, endActiveAgentInvocations as cn, createSlackChannelJoinTool as cr, readLastUserMessageAtByConversation as ct, addHistoryPeriod as d, readViewerAutomationSummary as di, resolveAgentInvocationId as dn, checkSlackChannelReadAccess as dr, markConversationRead as dt, activateViewerAutomationVersion as ei, routeChildInput as en, createSlackListCreateTool as er, createSpawnAgentTool as et, firstLiveSavingsDate as f, readViewerAutomationVersions as fi, dropOwnUnreadLoopReplies as fn, joinPublicChannelForRead as fr, reportConversationRead as ft, breakerStates as g, changedEventMatch as gi, completeCancelledConversationTurn as gn, isPublicSlackChannel as gr, deliverReviewItemChange as gt, savingsTotals as h, editEventAutomation as hi, cancelSignInWait as hn, isConversationMember as hr, createUpdateReviewItemTool as ht, GLOBAL_GAPS_TTL_MS as i, deleteViewerTask as ii, parentMessageText as in, createSlackChannelListMessagesTool as ir, createReplyTool as it, createWebFetchTool as j, gapSegment as ji, wakePausedTurn as jn, AUTOMATIONS_TOOL_SOURCE as jr, writeAttachmentUpload as jt, ingestEvent as k, MIN_WARMUP_PREFIX_TOKENS as ki, getPausedTurnRequest as kn, createRunAutomationNowTool as kr, createAttachmentUpload as kt, listConversationWork as l, readViewerAutomationExecutions as li, endAgentInvocationsOfStoppedWork as ln, resolveSlackChannelRef as lr, archiveConversation as lt, replaceHistorySavings as m, editScheduledAutomation as mi, stopChildAgentsOf as mn, getConversationInfo as mr, createSearchReviewItemsTool as mt, CONVERSATION_STATE_TTL_MS as n, changeAutomationLifecycle as ni, isParentMessageMeta as nn, createSlackConversationMessageSearchTool as nr, createReportProgressTool as nt, segmentGapsKey as o, updateViewerAutomation as oi, createAgentInvocationWorker as on, readSlackRawMessageContext as or, createMessageAgentTool as ot, idlePeriodSavings as p, readViewerAutomations as pi, stopChildAgentsBelow as pn, getChannelMessage as pr, createAddReviewItemTool as pt, TOOL_RESULT_MAX_CHARS as q, createSlackThreadReadTool as qn, getConversationAccess as qr, listPendingAgentInvocationResults as qt, GLOBAL_GAPS_MAX as r, changeViewerAutomationLifecycle as ri, logDroppedParentMessage as rn, createSlackConversationSearchChannelPort as rr, createReportBlockedTool as rt, warmup_exports as s, ViewerTaskNotFoundError as si, createAndEnqueueAgentInvocation as sn, resolveSlackChannelIdFromMessage as sr, createArchiveAgentTool as st, ANSWER_TOOL_ENDINGS as t, automationEditor as ti, childAgentTurnOptions as tn, createSlackListAddItemsTool as tr, createListAgentsTool as tt, SAVINGS_NAMESPACE as u, readViewerAutomationRuns as ui, enqueueAgentInvocation as un, slackChannelRefParam as ur, conversationReadPositionQuery as ut, connectedState as v, requireAutomationTaskText as vi, createAgentInvocationForMessage as vn, listThreadReplies as vr, reviewItemChangeRecord as vt, readStats as w, moveTaskOutcomes as wi, getAgentBinding as wn, positiveInteger$1 as wr, recordWebConversationActivity as wt, enabledMode as x, findAutomationSkill as xi, AgentMessagePausedError as xn, createSlackCanvasEditTool as xr, conversationTurnIdForMessage as xt, providerCacheTtlMs as y, AutomationEditError as yi, createAgentInvocationFromLatest as yn, createSlackCanvasWriteTool as yr, acceptsWebMessages as yt, createStopWatchingResourcesTool as z, getWebAuthorization as zn, automationTriggerChangesSchema as zr, TERMINAL_AGENT_INVOCATION_STATUSES as zt };
13859
+ export { createStopAgentTool as $, createSlackListUpdateItemTool as $n, requireToolCreator as $r, readChildConversationSender as $t, createWebSearchTool as A, MINUTE_MS$1 as Ai, recordFailedDispatchTurn as An, createRunAutomationNowTool as Ar, verifyAttachmentUploads as At, createSearchEventTypesTool as B, getWebAuthorization as Bn, automationTriggerChangesSchema as Br, getActiveAgentInvocationForConversation as Bt, incrementStat as C, findAutomationSkill as Ci, findChildAgentConversationId as Cn, SLACK_TOOL_SOURCE as Cr, createConversationId as Ct, requireReadyWorkspaceSnapshot as D, resolveTaskOutcomes as Di, supersedeTurnForInput as Dn, createOperationKey as Dr, AttachmentUploadError as Dt, processWorkspaceSnapshotJob as E, moveTaskOutcomes as Ei, supersedeOpenMailboxTurns as En, resolveWorkspacePath as Er, resolveConversationDestination as Et, userLookupIdentityProviders as F, canShareTurn as Fn, zodToolDefinition as Fr, listOwnedWatches as Ft, missingFileResult as G, emptyResponse as Gn, injectContinuationToolName as Gr, listAgentInvocationsForConversation as Gt, createSearchConversationsTool as H, executeTurn as Hn, editedAutomationTask as Hr, getChildAgentLabel as Ht, createUpdateUserCustomizationTool as I, isAttemptInterrupt as In, automationIdForToolCall as Ir, listChildAgents as It, capToolResult as J, createSlackThreadReadTool as Jn, getConversationAccess as Jr, markAgentInvocationParentMailboxAppended as Jt, sliceFileContent as K, jsonResponse as Kn, juniorToolOutputSchema as Kr, listPendingAgentInvocationMailboxAppends as Kt, createSubmitFeedbackTool as L, selectAttemptMessages as Ln, automationSkillToolSchema as Lr, listUnreportedSiblingAgents as Lt, createWatchTimerTool as M, NO_REPLY_GAP_MS as Mi, wakePausedTurn as Mn, AUTOMATIONS_TOOL_SOURCE as Mr, createReadConversationEventTool as Mt, createWatchEventsTool as N, gapSegment as Ni, getTurnAuthorization as Nn, parseToolInput as Nr, createRunOperatorSqlTool as Nt, prepareWorkspaceSnapshot as O, countOwnedAutomationsNeedingAttention as Oi, createPausedTurns as On, createCanvas as Or, collectAttachmentUploadGarbage as Ot, createUserLookupTool as P, canJoinTurn as Pn, zodTool as Pr, createListWatchesTool as Pt, createUpdatePlanTool as Q, createSlackPublicSearchTool as Qn, requireToolCaller as Qr, getChildAgentInputSender as Qt, createSystemTimeTool as R, createWebAuthorization as Rn, automationToolResult as Rr, NON_TERMINAL_AGENT_INVOCATION_STATUSES as Rt, createWorkspaceTools as S, requireAutomationSkill as Si, AgentMessageTargetError as Sn, createSlackCanvasEditTool as Sr, createAndEnqueueConversation as St, ensureWorkspaceSnapshotBuild as T, effectiveTaskOutcomes as Ti, PARENT_AGENT_TARGET as Tn, positiveInteger$1 as Tr, webActorFromUser as Tt, createWriteFileTool as U, createSetConversationSubscriptionTool as Un, newAutomationTask as Ur, getLatestAgentInvocationForConversation as Ut, createSearchConversationEventsTool as V, AgentRunError as Vn, automationTriggerSchema as Vr, getAgentInvocation as Vt, createReadFileTool as W, setConversationSubscription as Wn, triggerKind as Wr, isTerminalAgentInvocation as Wt, editFile as X, renderBlockText as Xn, automationToolsDisabledReason as Xr, sendsResultToParent as Xt, createEditFileTool as Y, renderAttachmentText as Yn, automationToolContext as Yr, reportReplacedWithoutOpenWork as Yt, createBashTool as Z, parseSlackMessageReference as Zn, requireToolAutomation as Zr, childAgentInput as Zt, closeBreaker as _, changedEventMatch as _i, recordSubagentEnded as _n, isPublicSlackChannel as _r, renderReviewItemMessage as _t, createCacheWarmingRecorder as a, deleteViewerTask as ai, readParentMessage as an, createSlackChannelListMessagesTool as ar, createNoReplyTool as at, coreToolSlots as b, requireAutomationTaskText as bi, AgentDepthLimitError as bn, createSlackCanvasWriteTool as br, appendAndEnqueueWebMessage as bt, isConversationWorkDone as c, ViewerTaskNotFoundError as ci, endActiveAgentInvocations as cn, resolveSlackChannelIdFromMessage as cr, readLastUserMessageAtByConversation as ct, addHistoryPeriod as d, readViewerAutomationRuns as di, resolveAgentInvocationId as dn, slackChannelRefParam as dr, markConversationRead as dt, requireToolDestination as ei, routeChildInput as en, createSlackListGetItemsTool as er, createSpawnAgentTool as et, firstLiveSavingsDate as f, readViewerAutomationSummary as fi, dropOwnUnreadLoopReplies as fn, checkSlackChannelReadAccess as fr, reportConversationRead as ft, breakerStates as g, editEventAutomation as gi, completeCancelledConversationTurn as gn, isConversationMember as gr, deliverReviewItemChange as gt, savingsTotals as h, editScheduledAutomation as hi, cancelSignInWait as hn, getConversationInfo as hr, createUpdateReviewItemTool as ht, GLOBAL_GAPS_TTL_MS as i, changeViewerAutomationLifecycle as ii, parentMessageText as in, createSlackConversationSearchChannelPort as ir, createReplyTool as it, createWebFetchTool as j, MIN_WARMUP_PREFIX_TOKENS as ji, wakeAuthorizedTurn as jn, createDeleteAutomationTool as jr, writeAttachmentUpload as jt, ingestEvent as k, IDLE_HORIZON_MS as ki, getPausedTurnRequest as kn, createSearchAutomationsTool as kr, createAttachmentUpload as kt, listConversationWork as l, readConversationSourceTask as li, endAgentInvocationsOfStoppedWork as ln, createSlackChannelJoinTool as lr, archiveConversation as lt, replaceHistorySavings as m, readViewerAutomations as mi, stopChildAgentsOf as mn, getChannelMessage as mr, createSearchReviewItemsTool as mt, CONVERSATION_STATE_TTL_MS as n, automationEditor as ni, isParentMessageMeta as nn, createSlackListAddItemsTool as nr, createReportProgressTool as nt, segmentGapsKey as o, readViewerAutomationEdit as oi, createAgentInvocationWorker as on, parseSlackThreadId as or, createMessageAgentTool as ot, idlePeriodSavings as p, readViewerAutomationVersions as pi, stopChildAgentsBelow as pn, joinPublicChannelForRead as pr, createAddReviewItemTool as pt, TOOL_RESULT_MAX_CHARS as q, throwApiError as qn, makeStructuredToolOutput as qr, listPendingAgentInvocationResults as qt, GLOBAL_GAPS_MAX as r, changeAutomationLifecycle as ri, logDroppedParentMessage as rn, createSlackConversationMessageSearchTool as rr, createReportBlockedTool as rt, warmup_exports as s, updateViewerAutomation as si, createAndEnqueueAgentInvocation as sn, readSlackRawMessageContext as sr, createArchiveAgentTool as st, ANSWER_TOOL_ENDINGS as t, activateViewerAutomationVersion as ti, childAgentTurnOptions as tn, createSlackListCreateTool as tr, createListAgentsTool as tt, SAVINGS_NAMESPACE as u, readViewerAutomationExecutions as ui, enqueueAgentInvocation as un, resolveSlackChannelRef as ur, conversationReadPositionQuery as ut, connectedState as v, requireEventAutomationTrigger as vi, createAgentInvocationForMessage as vn, joinPublicChannel as vr, reviewItemChangeRecord as vt, readStats as w, missingAutomationSkillReason as wi, getAgentBinding as wn, isMissingPathError as wr, recordWebConversationActivity as wt, enabledMode as x, AutomationEditError as xi, AgentMessagePausedError as xn, createSlackCanvasReadTool as xr, conversationTurnIdForMessage as xt, providerCacheTtlMs as y, automationCardStatus as yi, createAgentInvocationFromLatest as yn, listThreadReplies as yr, acceptsWebMessages as yt, createStopWatchingResourcesTool as z, deleteWebAuthorization as zn, automationToolResultSchema as zr, TERMINAL_AGENT_INVOCATION_STATUSES as zt };