@sentry/junior 0.250.0 → 0.252.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 (61) hide show
  1. package/dist/{admin-DMKyXi83.js → admin-C_-XEdym.js} +1 -1
  2. package/dist/{agent-hooks-CtZuJPTU.js → agent-hooks-DcoKnnxn.js} +36 -13
  3. package/dist/{agent-runner-CNiTpIpb.js → agent-runner-B-7S_DCS.js} +357 -99
  4. package/dist/api/schema.d.ts +46 -32
  5. package/dist/api/schema.js +2 -2
  6. package/dist/api.js +50 -65
  7. package/dist/app.js +52 -81
  8. package/dist/{assistant-reply-K5r1pcgJ.js → assistant-reply-DbPLvsnL.js} +1 -1
  9. package/dist/{briefs-8xyS3oeV.js → briefs-D4SMqc-r.js} +4 -4
  10. package/dist/{catalog-runtime-BQ3g3OX_.js → catalog-runtime-BQQiwwA7.js} +1 -1
  11. package/dist/cli/chat.js +15 -15
  12. package/dist/cli/check.js +3 -3
  13. package/dist/cli/main.js +2 -2
  14. package/dist/cli/plugins.js +4 -4
  15. package/dist/cli/snapshot-create.js +3 -3
  16. package/dist/cli/upgrade.js +3 -3
  17. package/dist/{client-Q27hki0Y.js → client-ROZeVjq0.js} +2 -2
  18. package/dist/{config-Cb--Qs-g.js → config-DNNkxfGS.js} +2 -2
  19. package/dist/{connections-DZ70JeSN.js → connections-DJV6mLrH.js} +9 -9
  20. package/dist/{conversation-NutPJ8S8.js → conversation-T18Xlkx9.js} +9 -1
  21. package/dist/{conversation-privacy-BIDN1sW3.js → conversation-privacy-B19umzIL.js} +1 -1
  22. package/dist/{credential-sync-CyAN-Gos.js → credential-sync-CEd2F5PS.js} +14 -14
  23. package/dist/{executor-D8y7v95s.js → executor-_4bdoCxe.js} +59 -19
  24. package/dist/{images-BkGhqKIK.js → images-BAN7DHuO.js} +3 -3
  25. package/dist/instrumentation.js +2 -2
  26. package/dist/{job-queue-uGq6Grnt.js → job-queue-DSQx1qFY.js} +1 -1
  27. package/dist/{logging-C22RdmU8.js → logging-COUsTFIL.js} +1 -1
  28. package/dist/{message-D0RPetp-.js → message-CtDDEwwV.js} +3 -3
  29. package/dist/nitro.js +3 -3
  30. package/dist/{oauth-callback-server-DF_Odkvh.js → oauth-callback-server-CCiKrS0s.js} +2 -2
  31. package/dist/{pending-auth-Bg3A1-pE.js → pending-auth-DDx3EU4M.js} +2 -2
  32. package/dist/{profile-DK9umvav.js → profile-DP4LKL6V.js} +4 -4
  33. package/dist/{prompt-kYP1FAX_.js → prompt-C04mP1hu.js} +1 -1
  34. package/dist/{registry-BvsLuoLK.js → registry-CeEpPna6.js} +1 -1
  35. package/dist/{resolve-C9btOXju.js → resolve-B5ma3igH.js} +2 -2
  36. package/dist/{result-CcdQ2iau.js → result-Da0RVuWG.js} +7 -7
  37. package/dist/{runner-Bem4DUHN.js → runner-se1W_jGZ.js} +10 -10
  38. package/dist/{sandbox-egress-signals-Bl-4cF7E.js → sandbox-egress-signals-CS959-wm.js} +1 -1
  39. package/dist/{schema-DELmAdjR.js → schema-C9Vnyb_f.js} +1 -1
  40. package/dist/{session-stop-DteRDRCi.js → session-stop-DlRDisF5.js} +11 -11
  41. package/dist/{skills-CVwSL6Gc.js → skills-CSzgs0EC.js} +2 -2
  42. package/dist/{spawn-CA0YYtzr.js → spawn-DT9fMjtd.js} +2 -2
  43. package/dist/{store-Dw3eBN9S.js → store-Dx1U69mm.js} +6 -6
  44. package/dist/{task-queue-C7cyjcVj.js → task-queue-BX9YrIsw.js} +3 -3
  45. package/dist/{task-runner-BbSyWmOq.js → task-runner-CO55Olal.js} +46 -13
  46. package/dist/{tasks-B8nH3ND_.js → tasks-DwGlFX9i.js} +166 -212
  47. package/dist/{thread-state-BTOLzCM-.js → thread-state-Ces6tXmB.js} +6 -6
  48. package/dist/{turn-failure-response-BwNfO8Xt.js → turn-failure-response-B4VCvEQf.js} +8 -8
  49. package/dist/{turn-lifecycle-DSN0xGW7.js → turn-lifecycle-B1VV58Yo.js} +1 -1
  50. package/dist/{turn-session-routing-BRKYIn6n.js → turn-session-routing-Dw2Kamg9.js} +1 -1
  51. package/dist/{validation-CBkyzKCP.js → validation-yJF9LKOv.js} +1 -1
  52. package/dist/{version-CkwwLVLb.js → version-CZYqvIFh.js} +1 -1
  53. package/dist/version.js +1 -1
  54. package/dist/{viewer-DdzigZQh.js → viewer-D96vo_42.js} +3 -3
  55. package/dist/{web-input-BjdnnpuN.js → web-input-5mls-41-.js} +105 -104
  56. package/dist/{work-qQEjtmlv.js → work-D2M2-zCO.js} +9 -9
  57. package/dist/{worker-C-CSZMy_.js → worker-BwCpf8tB.js} +5 -5
  58. package/migrations/0055_automations.sql +125 -0
  59. package/migrations/meta/0055_snapshot.json +3948 -0
  60. package/migrations/meta/_journal.json +8 -1
  61. package/package.json +5 -5
@@ -1,13 +1,13 @@
1
- import { _ as getProviderErrorUserMessage, g as getProviderErrorAttributes, h as findProviderError, p as ProviderError } from "./client-Q27hki0Y.js";
2
- import { I as isRecord, t as buildTurnFailureResponse } from "./logging-C22RdmU8.js";
1
+ import { _ as getProviderErrorUserMessage, g as getProviderErrorAttributes, h as findProviderError, p as ProviderError } from "./client-ROZeVjq0.js";
2
+ import { I as isRecord, t as buildTurnFailureResponse } from "./logging-COUsTFIL.js";
3
3
  import { g as parseSlackMessageTs } from "./actor-BTtLaeWy.js";
4
- import { c as getConversationEventStore, d as getDb } from "./viewer-DdzigZQh.js";
5
- import { Gt as hydrateConversationMessages, an as markConversationMessage } from "./tasks-B8nH3ND_.js";
6
- import { Mt as listConversationAnnotations } from "./agent-hooks-CtZuJPTU.js";
7
- import { J as removedCardSchema, Y as resolveMessageCards, q as readMessageCardRefs } from "./conversation-NutPJ8S8.js";
8
- import { r as clearPendingAuth, u as buildDeterministicTurnId } from "./pending-auth-Bg3A1-pE.js";
4
+ import { c as getConversationEventStore, d as getDb } from "./viewer-D96vo_42.js";
5
+ import { Gt as hydrateConversationMessages, an as markConversationMessage } from "./tasks-DwGlFX9i.js";
6
+ import { Nt as listConversationAnnotations } from "./agent-hooks-DcoKnnxn.js";
7
+ import { J as removedCardSchema, Y as resolveMessageCards, q as readMessageCardRefs } from "./conversation-T18Xlkx9.js";
8
+ import { r as clearPendingAuth, u as buildDeterministicTurnId } from "./pending-auth-DDx3EU4M.js";
9
9
  import { d as markTurnCompleted, u as markTurnClosed } from "./oauth-authorization-BA4Dt6a7.js";
10
- import { o as persistThreadStateById, r as getPersistedThreadState, s as coerceThreadConversationState } from "./thread-state-BTOLzCM-.js";
10
+ import { o as persistThreadStateById, r as getPersistedThreadState, s as coerceThreadConversationState } from "./thread-state-Ces6tXmB.js";
11
11
  //#region src/chat/conversations/pending-cards.ts
12
12
  /** Select undelivered cards and load their latest saved facts. */
13
13
  async function loadPendingMessageCards(conversationId) {
@@ -1,4 +1,4 @@
1
- import { c as getConversationEventStore } from "./viewer-DdzigZQh.js";
1
+ import { c as getConversationEventStore } from "./viewer-D96vo_42.js";
2
2
  //#region src/chat/conversations/turn-lifecycle.ts
3
3
  /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
4
4
  var ConversationTurnLifecycleService = class {
@@ -34,7 +34,7 @@ function slackSourceForDestination(args) {
34
34
  * Reads parent Conversations when this Conversation has no Destination.
35
35
  */
36
36
  async function resolveConversationRouting(args) {
37
- const conversationStore = args.conversationStore ?? (await import("./viewer-DdzigZQh.js").then((n) => n.s)).getConversationStore();
37
+ const conversationStore = args.conversationStore ?? (await import("./viewer-D96vo_42.js").then((n) => n.s)).getConversationStore();
38
38
  const chain = await loadConversationChain(args.conversationId, conversationStore);
39
39
  let destination;
40
40
  let source;
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BQ3g3OX_.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BQQiwwA7.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  //#region src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.250.0";
2
+ var version = "0.252.0";
3
3
  //#endregion
4
4
  //#region src/version.ts
5
5
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as JUNIOR_VERSION } from "./version-CkwwLVLb.js";
1
+ import { t as JUNIOR_VERSION } from "./version-CZYqvIFh.js";
2
2
  export { JUNIOR_VERSION };
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { F as normalizeIdentityEmail } from "./logging-C22RdmU8.js";
3
- import { i as getChatConfig } from "./config-Cb--Qs-g.js";
2
+ import { F as normalizeIdentityEmail } from "./logging-COUsTFIL.js";
3
+ import { i as getChatConfig } from "./config-DNNkxfGS.js";
4
4
  import { d as parseSlackTeamId, o as parseActorUserId, u as parseSlackChannelReferenceId } from "./actor-BTtLaeWy.js";
5
5
  import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-D_YoNnAn.js";
6
- import { _ as juniorConversationEvents, f as juniorConversationParticipants, g as juniorConversationMetrics, h as CONVERSATION_METRICS, p as juniorConversationBindings, t as createJuniorSqlExecutor, y as juniorConversationAnnotations } from "./executor-D8y7v95s.js";
6
+ import { d as juniorConversationParticipants, f as juniorConversationBindings, g as juniorConversationEvents, h as juniorConversationMetrics, m as CONVERSATION_METRICS, t as createJuniorSqlExecutor, v as juniorConversationAnnotations } from "./executor-_4bdoCxe.js";
7
7
  import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-9pO1Zd4Y.js";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
@@ -1,44 +1,43 @@
1
- import { A as resolveSlackChannelIdFromMessage, B as effectiveTaskOutcomes, C as renderBlockText, D as storeAttachment, Ft as createUserTokenStore, It as buildSteeringPiMessage, Lt as withoutSavedSteeringMessages, M as getConversationInfo, N as listThreadReplies, O as parseSlackThreadId, Rt as RetryableDeliveryError, S as renderAttachmentText, Ut as shouldEmitDevAgentTrace, Vt as AuthorizationFlowDisabledError, a as buildAuthPauseResponse, h as latestProgressStatus, j as resolveSlackChannelIdFromThreadId, k as readSlackRawMessageContext, m as PluginCredentialFailureError, n as executeAgentRun, r as createContextCompactor, t as createAgentRunner, z as eventAutomationTriggerAvailable } from "./agent-runner-CNiTpIpb.js";
2
- import { f as escapeXml, i as completeText, r as completeObject, v as isProviderRetryError } from "./client-Q27hki0Y.js";
3
- import { C as withLogContext, I as isRecord, L as toOptionalNumber, R as toOptionalString, _ as setSentryUser, b as setTags, d as logException, f as logInfo, n as createChatSdkLogger, o as getActiveTraceId, p as logWarn, t as buildTurnFailureResponse, u as logError, v as setSpanAttributes, w as withSpan } from "./logging-C22RdmU8.js";
4
- import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-Cb--Qs-g.js";
1
+ import { A as resolveSlackChannelIdFromMessage, B as effectiveTaskOutcomes, Bt as RetryableDeliveryError, C as renderBlockText, D as storeAttachment, Gt as shouldEmitDevAgentTrace, Lt as createUserTokenStore, M as getConversationInfo, N as listThreadReplies, O as parseSlackThreadId, Rt as buildSteeringPiMessage, S as renderAttachmentText, Ut as AuthorizationFlowDisabledError, a as buildAuthPauseResponse, h as latestProgressStatus, j as resolveSlackChannelIdFromThreadId, k as readSlackRawMessageContext, m as PluginCredentialFailureError, n as executeAgentRun, r as createContextCompactor, t as createAgentRunner, z as eventAutomationTriggerAvailable, zt as withoutSavedSteeringMessages } from "./agent-runner-B-7S_DCS.js";
2
+ import { f as escapeXml, i as completeText, r as completeObject, v as isProviderRetryError } from "./client-ROZeVjq0.js";
3
+ import { C as withLogContext, I as isRecord, L as toOptionalNumber, R as toOptionalString, _ as setSentryUser, b as setTags, d as logException, f as logInfo, n as createChatSdkLogger, o as getActiveTraceId, p as logWarn, t as buildTurnFailureResponse, u as logError, v as setSpanAttributes, w as withSpan } from "./logging-COUsTFIL.js";
4
+ import { c as getSlackClientSecret, i as getChatConfig, l as getSlackSigningSecret, n as botConfig, o as getSlackBotToken, s as getSlackClientId, v as normalizeSlackEmojiName } from "./config-DNNkxfGS.js";
5
5
  import { o as modelIdForProfile, r as defaultModelId } from "./model-profile-BwU8mqwD.js";
6
6
  import { a as isUserActor, g as parseSlackMessageTs, i as isActorUserId, l as parseSlackChannelId, n as createSlackActor, o as parseActorUserId, r as createSlackResumeActor, t as createActor } from "./actor-BTtLaeWy.js";
7
- import { M as createSlackDestination, P as requireSlackDestination, c as getConversationEventStore, d as getDb, f as getSqlExecutor, u as getConversationStore } from "./viewer-DdzigZQh.js";
7
+ import { M as createSlackDestination, P as requireSlackDestination, c as getConversationEventStore, d as getDb, f as getSqlExecutor, u as getConversationStore } from "./viewer-D96vo_42.js";
8
8
  import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers } from "./agent-invocations-D_YoNnAn.js";
9
- import { c as juniorAutomationExecutions, o as juniorSchedulerTasks, u as juniorEventAutomations } from "./executor-D8y7v95s.js";
9
+ import { c as juniorAutomationExecutions, s as juniorAutomations } from "./executor-_4bdoCxe.js";
10
10
  import { p as instructionProvenanceFor } from "./history-9pO1Zd4Y.js";
11
- import { d as credentialContextForActor } from "./registry-BvsLuoLK.js";
12
- import { $ as listTurnSummaries, $t as appendThreadContextMessages, At as loadProjection, D as sameDefinitionValue, Et as commitMessages, Gt as hydrateConversationMessages, H as removeReactionFromMessage, I as truncateStatusText, J as saveTurnCheckpoint, Jt as persistConversationMessageSummaries, Kt as persistConversationMessages, L as addReactionToMessage, Lt as recordAuthorizationCompleted, M as formatSlackLink, N as normalizeSlackReplyMarkdown, Ot as loadConversationProjection, P as normalizeSlackStatusText, Q as getTurnRecord, St as trimTrailingAssistantMessages, T as listAutomationVersions, Tt as commitAcceptedReply, V as postSlackMessage, Vt as recordSubscribedReplyRoute, X as completeTurnRecord, Y as abandonTurnRecord, Yt as resolveConversationTitle, Z as failTurnRecord, Zt as fallbackShortTitle, _ as listDeletedEventAutomationsCreatedBy, a as readScheduledAutomation, an as markConversationMessage, cn as turnHasReply, en as buildConversationContext, et as recordTurnSummary, g as getEventAutomation, i as parseScheduledAutomationRow, in as isHumanConversationMessage, j as escapeSlackMrkdwnText, l as withScheduledAutomationLock, ln as upsertConversationMessage, m as eventAutomationBelongsToUser, nn as estimateConversationContextTokens, on as normalizeConversationText, ot as buildTurnErrorResponse, p as deleteEventAutomation, q as loadTurnCheckpoint, rn as getConversationMessageSlackTs, s as saveScheduledAutomationInLock, sn as recordDeliveredAssistantMessage, tn as createConversationMemoryService, tt as persistWithRetry, w as automationDefinition, y as parseEventAutomationRow } from "./tasks-B8nH3ND_.js";
13
- import { Bt as getHeaderString, Dt as readAttachmentVisionSummary, Gt as runWithSlackInstallationToken, It as lookupSlackUser, Lt as SlackActionError, Ot as recordSlackAttachment, Rt as downloadPrivateSlackFile, Tt as getSlackFileId, Ut as isDmChannel, V as cancelSubscriptions, Vt as getSlackClient, Wt as normalizeSlackConversationId, at as getDashboardObjectIconLink, it as getDashboardConversationLink, nt as verifyTimerWatchCredentialSubject, o as getPluginSlackConversationLink, rt as JUNIOR_THREAD_STATE_TTL_MS, wt as buildSentryConversationUrl } from "./agent-hooks-CtZuJPTU.js";
14
- import { F as readMessageAttachments, R as isVisionImageMediaType } from "./conversation-NutPJ8S8.js";
15
- import { E as acquireActiveLock, O as withLock, T as MUTATION_LOCK_TTL_MS, w as getStateAdapter } from "./profile-DK9umvav.js";
16
- import { a as wasPendingAuthStopped, c as getThreadStopDecision, l as buildDeterministicAssistantMessageId, o as decideSubscribedThreadReply, r as clearPendingAuth, s as getSubscribedReplyPreflightDecision, u as buildDeterministicTurnId } from "./pending-auth-Bg3A1-pE.js";
11
+ import { d as credentialContextForActor } from "./registry-CeEpPna6.js";
12
+ import { $ as listTurnSummaries, $t as appendThreadContextMessages, At as loadProjection, D as sameDefinitionValue, Et as commitMessages, Gt as hydrateConversationMessages, H as removeReactionFromMessage, I as truncateStatusText, J as saveTurnCheckpoint, Jt as persistConversationMessageSummaries, Kt as persistConversationMessages, L as addReactionToMessage, Lt as recordAuthorizationCompleted, M as formatSlackLink, N as normalizeSlackReplyMarkdown, Ot as loadConversationProjection, P as normalizeSlackStatusText, Q as getTurnRecord, St as trimTrailingAssistantMessages, T as listAutomationVersions, Tt as commitAcceptedReply, V as postSlackMessage, Vt as recordSubscribedReplyRoute, X as completeTurnRecord, Y as abandonTurnRecord, Yt as resolveConversationTitle, Z as failTurnRecord, Zt as fallbackShortTitle, _ as listDeletedEventAutomationsCreatedBy, a as readScheduledAutomation, an as markConversationMessage, cn as turnHasReply, en as buildConversationContext, et as recordTurnSummary, g as getEventAutomation, i as parseScheduledAutomationRow, in as isHumanConversationMessage, j as escapeSlackMrkdwnText, l as withScheduledAutomationLock, ln as upsertConversationMessage, m as eventAutomationBelongsToUser, nn as estimateConversationContextTokens, on as normalizeConversationText, ot as buildTurnErrorResponse, p as deleteEventAutomation, q as loadTurnCheckpoint, rn as getConversationMessageSlackTs, s as saveScheduledAutomationInLock, sn as recordDeliveredAssistantMessage, tn as createConversationMemoryService, tt as persistWithRetry, w as automationDefinition, y as parseEventAutomationRow } from "./tasks-DwGlFX9i.js";
13
+ import { Et as getSlackFileId, Gt as normalizeSlackConversationId, Ht as getSlackClient, Kt as runWithSlackInstallationToken, Lt as lookupSlackUser, Ot as readAttachmentVisionSummary, Rt as SlackActionError, Tt as buildSentryConversationUrl, V as cancelSubscriptions, Vt as getHeaderString, Wt as isDmChannel, at as getDashboardConversationLink, it as JUNIOR_THREAD_STATE_TTL_MS, kt as recordSlackAttachment, o as getPluginSlackConversationLink, ot as getDashboardObjectIconLink, rt as verifyTimerWatchCredentialSubject, zt as downloadPrivateSlackFile } from "./agent-hooks-DcoKnnxn.js";
14
+ import { F as readMessageAttachments, R as isVisionImageMediaType } from "./conversation-T18Xlkx9.js";
15
+ import { E as acquireActiveLock, O as withLock, T as MUTATION_LOCK_TTL_MS, w as getStateAdapter } from "./profile-DP4LKL6V.js";
16
+ import { a as wasPendingAuthStopped, c as getThreadStopDecision, l as buildDeterministicAssistantMessageId, o as decideSubscribedThreadReply, r as clearPendingAuth, s as getSubscribedReplyPreflightDecision, u as buildDeterministicTurnId } from "./pending-auth-DDx3EU4M.js";
17
17
  import { a as TurnInputDeferredError, c as isTurnInputCommitLostError, d as markTurnCompleted, f as markTurnFailed, i as TurnInputCommitLostError, l as isTurnInputDeferredError, n as ConversationTurnBoundaryError, o as getConversationTurnBoundaryError, p as startActiveTurn, r as CooperativeTurnYieldError, s as isCooperativeTurnYieldError, u as markTurnClosed } from "./oauth-authorization-BA4Dt6a7.js";
18
- import { n as getAssistantReplyText } from "./assistant-reply-K5r1pcgJ.js";
19
- import { A as recordFinishedTurnForAutomatedLimit, F as finishedRunReply, P as deliversFinalText, R as runDispatchOutcome, c as timerWatchCredentialSubject, i as skipInputBeforeConversationStop, k as maybePostAutomatedTurnLimitNotice, l as getEventCatalog, s as isEventMailboxMetadata, v as automationEventCatalog } from "./session-stop-DteRDRCi.js";
20
- import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-kYP1FAX_.js";
21
- import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline } from "./job-queue-uGq6Grnt.js";
22
- import { E as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-Dw3eBN9S.js";
18
+ import { n as getAssistantReplyText } from "./assistant-reply-DbPLvsnL.js";
19
+ import { A as recordFinishedTurnForAutomatedLimit, F as finishedRunReply, P as deliversFinalText, R as runDispatchOutcome, c as timerWatchCredentialSubject, i as skipInputBeforeConversationStop, k as maybePostAutomatedTurnLimitNotice, l as getEventCatalog, s as isEventMailboxMetadata, v as automationEventCatalog } from "./session-stop-DlRDisF5.js";
20
+ import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-C04mP1hu.js";
21
+ import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline } from "./job-queue-DSQx1qFY.js";
22
+ import { E as stopConversationWork, g as getConversationWorkState, h as getConversation, m as ensureConversationWake, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage, w as requestConversationWork } from "./store-Dx1U69mm.js";
23
23
  import { l as automationListQuerySchema } from "./automation-gznOMaQ2.js";
24
24
  import { r as isExperimentalFeatureEnabled } from "./experimental-Qn9rKLgx.js";
25
25
  import { c as sumUtcHoursIntoSixHours, m as healthReportSchema, t as webMessageId } from "./web-message-id-xPI_EFSC.js";
26
- import { C as readAutomationExecutionHours, D as readAutomationExecutions, E as readAutomationExecutionSummaries, O as readAutomationRuns, S as readAutomationExecutionDays, T as readAutomationExecutionStatusHours, _ as markDispatchFailed, a as confirmDispatchMailboxAppend, b as emptyAutomationRunWindows, c as getDispatchInputMessageId, f as isTerminalDispatchStatus, g as markDispatchCompleted, h as markDispatchBlocked, i as claimDispatchMailboxAppend, l as getDispatchRecord, m as markDispatchAwaitingResume, n as scheduleSessionCompletedPluginTasks, s as getDispatchConversationId, t as processPluginTask, u as getDispatchTurnId, v as markDispatchRunning, w as readAutomationExecutionStatusDays, x as readAutomationExecutionByConversationId } from "./task-runner-BbSyWmOq.js";
27
- import { a as withAgentInvocationResultActors, c as resolveMailboxTurnWork, f as joinMailboxText, i as startAgentInvocationsForChildInput, l as sourceFromTurnInput, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as enqueueAgentInvocationResult, u as turnInputFactsFromConversationMessage } from "./result-CcdQ2iau.js";
28
- import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-DSN0xGW7.js";
29
- import { i as resolveAgentInvocationId, o as AgentRunError, s as executeTurn, t as createAgentInvocationWorker } from "./work-qQEjtmlv.js";
30
- import { a as persistThreadState, c as configValueSchema, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as persistThreadStateById, r as getPersistedThreadState, s as coerceThreadConversationState, t as getLocationConfigurationService } from "./thread-state-BTOLzCM-.js";
31
- import { c as deleteWebAuthorization, d as getPausedTurnRequest, m as getTurnAuthorization, p as wakePausedTurn, s as createWebAuthorization, u as createPausedTurns } from "./connections-DZ70JeSN.js";
32
- import { n as resolveTurnSessionRouting } from "./turn-session-routing-BRKYIn6n.js";
33
- import { t as bindMessageAgent } from "./message-D0RPetp-.js";
34
- import { t as bindSpawnAgent } from "./spawn-CA0YYtzr.js";
35
- import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, d as loadPendingMessageCards, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as getInterruptionMarker } from "./turn-failure-response-BwNfO8Xt.js";
36
- import { r as storeInputImages } from "./images-BkGhqKIK.js";
26
+ import { C as readAutomationExecutionDays, D as readAutomationExecutionSummaries, E as readAutomationExecutionStatusHours, O as readAutomationExecutions, S as readAutomationExecutionByConversationId, T as readAutomationExecutionStatusDays, _ as markDispatchCompleted, a as confirmDispatchMailboxAppend, c as getDispatchIdForConversation, d as getDispatchTurnId, g as markDispatchBlocked, h as markDispatchAwaitingResume, i as claimDispatchMailboxAppend, k as readAutomationRuns, l as getDispatchInputMessageId, n as scheduleSessionCompletedPluginTasks, p as isTerminalDispatchStatus, s as getDispatchConversationId, t as processPluginTask, u as getDispatchRecord, v as markDispatchFailed, w as readAutomationExecutionHours, x as emptyAutomationRunWindows, y as markDispatchRunning } from "./task-runner-CO55Olal.js";
27
+ import { a as withAgentInvocationResultActors, c as resolveMailboxTurnWork, f as joinMailboxText, i as startAgentInvocationsForChildInput, l as sourceFromTurnInput, o as getAuthPausedConversationTurnId, s as getEventBatchDelayMs, t as enqueueAgentInvocationResult, u as turnInputFactsFromConversationMessage } from "./result-Da0RVuWG.js";
28
+ import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-B1VV58Yo.js";
29
+ import { i as resolveAgentInvocationId, o as AgentRunError, s as executeTurn, t as createAgentInvocationWorker } from "./work-D2M2-zCO.js";
30
+ import { a as persistThreadState, c as configValueSchema, i as persistThreadRuntimeState, n as getPersistedSandboxState, o as persistThreadStateById, r as getPersistedThreadState, s as coerceThreadConversationState, t as getLocationConfigurationService } from "./thread-state-Ces6tXmB.js";
31
+ import { c as deleteWebAuthorization, d as getPausedTurnRequest, m as getTurnAuthorization, p as wakePausedTurn, s as createWebAuthorization, u as createPausedTurns } from "./connections-DJV6mLrH.js";
32
+ import { n as resolveTurnSessionRouting } from "./turn-session-routing-Dw2Kamg9.js";
33
+ import { t as bindMessageAgent } from "./message-CtDDEwwV.js";
34
+ import { t as bindSpawnAgent } from "./spawn-DT9fMjtd.js";
35
+ import { a as persistAuthPauseTurnState, c as getTurnUserSlackMessageTs, d as loadPendingMessageCards, i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, n as getAgentTurnDiagnosticsAttributes, o as getTurnUserMessage, r as requireTurnFailureEventId, s as getTurnUserReplyAttachmentContext, t as finalizeFailedTurnReplyWithEvent, u as getInterruptionMarker } from "./turn-failure-response-B4VCvEQf.js";
36
+ import { r as storeInputImages } from "./images-BAN7DHuO.js";
37
37
  import { z } from "zod";
38
38
  import { createHash } from "node:crypto";
39
39
  import { and, asc, count, desc, eq, exists, inArray, ne, or, sql } from "drizzle-orm";
40
40
  import { createSlackSource, createWebSource, localDestinationSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
41
- import { unionAll } from "drizzle-orm/pg-core";
42
41
  import { del, get, put } from "@vercel/blob";
43
42
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
44
43
  import { SlackFormatConverter, createSlackAdapter } from "@chat-adapter/slack";
@@ -2741,65 +2740,37 @@ function viewerAutomationCollection(user) {
2741
2740
  const db = getDb();
2742
2741
  const identities = user.identities.filter((identity) => identity.provider === "slack");
2743
2742
  const teamIds = identities.flatMap((identity) => identity.providerTenantId ? [identity.providerTenantId] : []);
2744
- const scheduled = juniorSchedulerTasks;
2745
- const event = juniorEventAutomations;
2743
+ const automation = juniorAutomations;
2746
2744
  const destination = juniorDestinations;
2747
- const scheduledOwned = inArray(scheduled.creatorIdentityId, user.identities.map((identity) => identity.id));
2748
- const eventOwned = or(...identities.map((identity) => and(eq(event.teamId, identity.providerTenantId ?? ""), sql`${event.task}->'createdBy'->>'slackUserId' = ${identity.providerSubjectId}`))) ?? sql`false`;
2745
+ const isScheduled = eq(automation.kind, "scheduled");
2746
+ const owned = or(and(isScheduled, inArray(automation.creatorIdentityId, user.identities.map((identity) => identity.id))), ...identities.map((identity) => and(eq(automation.kind, "event"), eq(automation.teamId, identity.providerTenantId ?? ""), eq(automation.creatorSlackUserId, identity.providerSubjectId)))) ?? sql`false`;
2749
2747
  const publicDestination = sql`coalesce(${destination.visibility} = 'public', false)`;
2750
- const scheduledPublic = and(inArray(scheduled.teamId, teamIds), publicDestination, ne(scheduled.status, "completed"));
2751
- const eventPublic = and(inArray(event.teamId, teamIds), publicDestination);
2752
- function fields(record, teamId) {
2753
- return {
2754
- creator: sql`${teamId} || ':' || (${record}->'createdBy'->>'slackUserId')`.as("creator"),
2755
- creatorLabel: sql`coalesce(nullif(trim(${record}->'createdBy'->>'fullName'), ''), nullif(trim(${record}->'createdBy'->>'userName'), ''), ${record}->'createdBy'->>'slackUserId')`.as("creator_label"),
2756
- destination: sql`${teamId} || ':' || (${record}->'destination'->>'channelId')`.as("destination"),
2757
- destinationLabel: sql`coalesce(nullif(${destination.displayName}, ''), ${record}->'destination'->>'channelId')`.as("destination_label"),
2758
- isPublic: publicDestination.as("is_public"),
2759
- instruction: sql`${record}->'task'->>'text'`.as("instruction")
2760
- };
2761
- }
2762
- function destinationJoin(record, teamId) {
2763
- return and(eq(destination.provider, "slack"), sql`${destination.providerTenantId} = ${teamId}`, sql`${destination.providerDestinationId} = ${record}->'destination'->>'channelId'`);
2764
- }
2765
- const available = or(...Object.entries(automationEventCatalog(getEventCatalog())).map(([namespace, registration]) => {
2748
+ const publicToViewer = and(inArray(automation.teamId, teamIds), publicDestination, ne(automation.status, "completed"));
2749
+ const available = or(isScheduled, ...Object.entries(automationEventCatalog(getEventCatalog())).map(([namespace, registration]) => {
2766
2750
  const events = registration.resourceTypes.flatMap((resource) => resource.supportedEvents);
2767
- return and(eq(event.namespace, namespace), sql`${event.task}->'trigger'->'events' <@ ${JSON.stringify(events)}::jsonb`);
2751
+ return and(eq(automation.namespace, namespace), sql`${automation.record}->'trigger'->'events' <@ ${JSON.stringify(events)}::jsonb`);
2768
2752
  })) ?? sql`false`;
2769
2753
  const executions = juniorAutomationExecutions;
2770
- function lastRunNeedsAttention(kind, id) {
2771
- return sql`coalesce((select ${executions.status} in ('failed', 'blocked') from ${executions}
2772
- where ${executions.kind} = ${kind} and ${executions.namespace} = 'junior' and ${executions.automationId} = ${id}
2754
+ const lastRunNeedsAttention = sql`coalesce((select ${executions.status} in ('failed', 'blocked') from ${executions}
2755
+ where ${executions.kind} = ${automation.kind} and ${executions.namespace} = 'junior' and ${executions.automationId} = ${automation.id}
2773
2756
  order by ${executions.executedAtMs} desc, ${executions.executionId} desc limit 1), false)`;
2774
- }
2775
- return unionAll(db.select({
2776
- kind: sql`'scheduled'`.as("kind"),
2777
- id: scheduled.id,
2778
- title: sql`${scheduled.title}`.as("title"),
2779
- createdAtMs: scheduled.createdAtMs,
2780
- state: sql`${scheduled.status}`.as("state"),
2781
- unavailable: sql`false`.as("unavailable"),
2782
- attention: sql`${scheduled.status} not in ('paused', 'completed') and (${scheduled.status} = 'blocked' or ${lastRunNeedsAttention("scheduled", scheduled.id)})`.as("attention"),
2783
- owned: sql`${scheduledOwned}`.as("owned"),
2784
- resource: sql`''`.as("resource"),
2785
- ...fields(scheduled.record, scheduled.teamId)
2786
- }).from(scheduled).leftJoin(destination, destinationJoin(scheduled.record, scheduled.teamId)).where(and(inArray(scheduled.status, [
2787
- "active",
2788
- "blocked",
2789
- "paused",
2790
- "completed"
2791
- ]), or(scheduledOwned, scheduledPublic))), db.select({
2792
- kind: sql`'event'`.as("kind"),
2793
- id: event.id,
2794
- title: sql`${event.title}`.as("title"),
2795
- createdAtMs: event.createdAtMs,
2796
- state: sql`${event.status}`.as("state"),
2757
+ return db.select({
2758
+ kind: automation.kind,
2759
+ id: automation.id,
2760
+ title: automation.title,
2761
+ createdAtMs: automation.createdAtMs,
2762
+ state: sql`${automation.status}`.as("state"),
2797
2763
  unavailable: sql`not (${available})`.as("unavailable"),
2798
- attention: sql`${event.status} <> 'paused' and (${event.status} = 'blocked' or not (${available}) or ${lastRunNeedsAttention("event", event.id)})`.as("attention"),
2799
- owned: sql`${eventOwned}`.as("owned"),
2800
- resource: sql`concat_ws(' ', ${event.identifier}, ${event.task}->'trigger'->>'label', ${event.namespace})`.as("resource"),
2801
- ...fields(event.task, event.teamId)
2802
- }).from(event).leftJoin(destination, destinationJoin(event.task, event.teamId)).where(and(ne(event.status, "deleted"), or(eventOwned, eventPublic)))).as("accessible_automations");
2764
+ attention: sql`${automation.status} not in ('paused', 'completed') and (${automation.status} = 'blocked' or not (${available}) or ${lastRunNeedsAttention})`.as("attention"),
2765
+ owned: sql`${owned}`.as("owned"),
2766
+ resource: sql`case when ${isScheduled} then '' else concat_ws(' ', ${automation.identifier}, ${automation.record}->'trigger'->>'label', ${automation.namespace}) end`.as("resource"),
2767
+ creator: sql`${automation.teamId} || ':' || ${automation.creatorSlackUserId}`.as("creator"),
2768
+ creatorLabel: sql`coalesce(nullif(trim(${automation.record}->'createdBy'->>'fullName'), ''), nullif(trim(${automation.record}->'createdBy'->>'userName'), ''), ${automation.creatorSlackUserId})`.as("creator_label"),
2769
+ destination: sql`${automation.teamId} || ':' || ${automation.channelId}`.as("destination"),
2770
+ destinationLabel: sql`coalesce(nullif(${destination.displayName}, ''), ${automation.channelId})`.as("destination_label"),
2771
+ isPublic: publicDestination.as("is_public"),
2772
+ instruction: automation.instruction
2773
+ }).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, publicToViewer))).as("accessible_automations");
2803
2774
  }
2804
2775
  /** Read an SQL page and complete, access-scoped counts and filter options. */
2805
2776
  async function readAutomationCollection(user, input) {
@@ -3085,27 +3056,28 @@ async function readViewerAutomations(user, input = automationListQuerySchema.par
3085
3056
  const { rows, ...page } = await readAutomationCollection(user, input);
3086
3057
  const db = getDb();
3087
3058
  const ids = rows.map((row) => row.id);
3088
- const [scheduled, events] = ids.length ? await Promise.all([db.select().from(juniorSchedulerTasks).where(inArray(juniorSchedulerTasks.id, ids)), db.select().from(juniorEventAutomations).where(inArray(juniorEventAutomations.id, ids))]) : [[], []];
3059
+ const stored = ids.length ? await db.select().from(juniorAutomations).where(inArray(juniorAutomations.id, ids)) : [];
3089
3060
  const identityIds = new Set(user.identities.map((identity) => identity.id));
3090
3061
  const candidates = /* @__PURE__ */ new Map();
3091
- for (const row of scheduled) {
3092
- const task = parseScheduledAutomationRow(row);
3093
- if (task && task.status !== "deleted") candidates.set(`scheduled:${task.id}`, {
3094
- kind: "scheduled",
3095
- task,
3096
- ownedByViewer: identityIds.has(task.creatorIdentityId)
3097
- });
3098
- }
3099
- for (const row of events) {
3062
+ for (const row of stored) {
3063
+ if (row.kind === "scheduled") {
3064
+ const task = parseScheduledAutomationRow(row);
3065
+ if (task && task.status !== "deleted") candidates.set(task.id, {
3066
+ kind: "scheduled",
3067
+ task,
3068
+ ownedByViewer: identityIds.has(task.creatorIdentityId)
3069
+ });
3070
+ continue;
3071
+ }
3100
3072
  const task = parseEventAutomationRow(row);
3101
- if (task.status !== "deleted") candidates.set(`event:${task.id}`, {
3073
+ if (task.status !== "deleted") candidates.set(task.id, {
3102
3074
  kind: "event",
3103
3075
  task,
3104
3076
  ownedByViewer: eventAutomationBelongsToUser(task, user)
3105
3077
  });
3106
3078
  }
3107
3079
  const selected = rows.flatMap((row) => {
3108
- const candidate = candidates.get(`${row.kind}:${row.id}`);
3080
+ const candidate = candidates.get(row.id);
3109
3081
  return candidate ? [candidate] : [];
3110
3082
  });
3111
3083
  const [destinations, creators] = await Promise.all([destinationDetails(selected.map(({ task }) => task.destination)), creatorProfiles(selected)]);
@@ -3139,12 +3111,7 @@ async function readViewerAutomations(user, input = automationListQuerySchema.par
3139
3111
  async function readDeletedOwnedScheduledAutomations(user) {
3140
3112
  const identityIds = user.identities.map((identity) => identity.id);
3141
3113
  if (identityIds.length === 0) return [];
3142
- return (await getDb().select({
3143
- creatorIdentityId: juniorSchedulerTasks.creatorIdentityId,
3144
- id: juniorSchedulerTasks.id,
3145
- record: juniorSchedulerTasks.record,
3146
- title: juniorSchedulerTasks.title
3147
- }).from(juniorSchedulerTasks).where(and(eq(juniorSchedulerTasks.status, "deleted"), inArray(juniorSchedulerTasks.creatorIdentityId, identityIds))).orderBy(desc(juniorSchedulerTasks.createdAtMs), desc(juniorSchedulerTasks.id)).limit(TASK_EXECUTION_LIST_LIMIT)).map(parseScheduledAutomationRow).filter((task) => task?.status === "deleted");
3114
+ return (await getDb().select().from(juniorAutomations).where(and(eq(juniorAutomations.kind, "scheduled"), eq(juniorAutomations.status, "deleted"), inArray(juniorAutomations.creatorIdentityId, identityIds))).orderBy(desc(juniorAutomations.createdAtMs), desc(juniorAutomations.id)).limit(TASK_EXECUTION_LIST_LIMIT)).map(parseScheduledAutomationRow).filter((task) => task?.status === "deleted");
3148
3115
  }
3149
3116
  /** Load deleted event automations the viewer still owns, newest first. */
3150
3117
  async function readDeletedOwnedEventAutomations(user) {
@@ -3249,7 +3216,7 @@ async function readViewerAutomationExecutions(user, kind, id) {
3249
3216
  async function readViewerAutomationVersions(user, kind, id) {
3250
3217
  const candidate = await resolveViewerTaskCandidate(user, kind, id);
3251
3218
  if (!candidate) throw new ViewerTaskNotFoundError();
3252
- const versions = await listAutomationVersions(getDb(), kind, id, 101);
3219
+ const versions = await listAutomationVersions(getDb(), id, 101);
3253
3220
  const current = automationDefinition(candidate.task);
3254
3221
  const listed = versions.slice(0, AUTOMATION_VERSION_LIST_LIMIT);
3255
3222
  return {
@@ -3258,28 +3225,62 @@ async function readViewerAutomationVersions(user, kind, id) {
3258
3225
  truncated: versions.length > AUTOMATION_VERSION_LIST_LIMIT
3259
3226
  };
3260
3227
  }
3228
+ /** Name the event in a trigger, such as "opened" for `pull_request.opened`. */
3229
+ function eventActionLabel(eventName) {
3230
+ const [, ...action] = eventName.split(".");
3231
+ return (action.length > 0 ? action : [eventName]).join(" ").replaceAll("_", " ");
3232
+ }
3233
+ /**
3234
+ * Read whose access one run used from its dispatch record. Return nothing when
3235
+ * the record is gone, because the Automation's current setting can differ.
3236
+ */
3237
+ async function readRunCredential(dispatchId, creator) {
3238
+ if (!dispatchId) return {};
3239
+ const dispatch = await getDispatchRecord(dispatchId);
3240
+ if (!dispatch) return {};
3241
+ const subject = dispatch.credentialSubject;
3242
+ if (!subject) return { credentialMode: "system" };
3243
+ return {
3244
+ credentialMode: "creator",
3245
+ credentialUser: subject.userId === creator.slackUserId ? creatorLabel(creator) : subject.userId
3246
+ };
3247
+ }
3261
3248
  /** Resolve the source task for one conversation when a terminal execution links it. */
3262
3249
  async function readConversationSourceTask(args) {
3263
3250
  const execution = await readAutomationExecutionByConversationId({ conversationId: args.conversationId });
3264
3251
  if (!execution) return void 0;
3265
- if (!args.viewer) return { kind: execution.kind };
3252
+ const dispatchId = getDispatchIdForConversation(args.conversationId);
3253
+ const base = {
3254
+ kind: execution.kind,
3255
+ ...dispatchId ? { triggerMessageId: getDispatchInputMessageId(dispatchId) } : void 0
3256
+ };
3257
+ if (!args.viewer) return base;
3266
3258
  const candidate = await resolveViewerTaskCandidate(args.viewer, execution.kind, execution.automationId);
3267
- if (!candidate) return { kind: execution.kind };
3259
+ if (!candidate) return base;
3260
+ const credential = await readRunCredential(dispatchId, candidate.task.createdBy);
3268
3261
  if (candidate.kind === "scheduled") {
3269
3262
  const instruction = displayText(candidate.task.task.text, "Untitled scheduled automation");
3263
+ const schedule = candidate.task.schedule.description.trim();
3270
3264
  return {
3265
+ ...base,
3266
+ ...credential,
3271
3267
  id: candidate.task.id,
3272
3268
  kind: "scheduled",
3273
3269
  label: instruction,
3274
- title: taskDisplayTitle(candidate.task.title, instruction, "Untitled scheduled automation")
3270
+ title: taskDisplayTitle(candidate.task.title, instruction, "Untitled scheduled automation"),
3271
+ ...schedule ? { triggerLabel: schedule } : void 0
3275
3272
  };
3276
3273
  }
3277
3274
  const instruction = displayText(candidate.task.task.text, "Untitled event automation");
3275
+ const { events, label } = candidate.task.trigger;
3278
3276
  return {
3277
+ ...base,
3278
+ ...credential,
3279
3279
  id: candidate.task.id,
3280
3280
  kind: "event",
3281
3281
  label: instruction,
3282
- title: taskDisplayTitle(candidate.task.title, instruction, "Untitled event automation")
3282
+ title: taskDisplayTitle(candidate.task.title, instruction, "Untitled event automation"),
3283
+ triggerLabel: events.length === 1 ? `${label} ${eventActionLabel(events[0])}` : label
3283
3284
  };
3284
3285
  }
3285
3286
  /** Delete one viewer-owned scheduled or event automation. */
@@ -1,15 +1,15 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { $ as getAgentInvocation, G as recordSubagentStarted, H as stopChildAgentsOf, Ht as readBlockedReport, It as buildSteeringPiMessage, J as createAgentInvocation, Lt as withoutSavedSteeringMessages, Q as getActiveAgentInvocationForConversation, Vt as AuthorizationFlowDisabledError, W as recordSubagentEnded, at as getAgentInvocationTurnId, ct as isTerminalAgentInvocation, dt as markAgentInvocationMailboxAppended, gt as reportReplacedAgentInvocation, ht as markAgentInvocationSteered, m as PluginCredentialFailureError, mt as markAgentInvocationRunning, pt as markAgentInvocationPaused, q as completeAgentInvocation, rt as getAgentInvocationMessageId, st as getLatestAgentInvocationForConversation } from "./agent-runner-CNiTpIpb.js";
3
- import { n as botConfig } from "./config-Cb--Qs-g.js";
4
- import { c as getConversationEventStore, u as getConversationStore } from "./viewer-DdzigZQh.js";
2
+ import { $ as getAgentInvocation, G as recordSubagentStarted, H as stopChildAgentsOf, J as createAgentInvocation, Q as getActiveAgentInvocationForConversation, Rt as buildSteeringPiMessage, Ut as AuthorizationFlowDisabledError, W as recordSubagentEnded, Wt as readBlockedReport, at as getAgentInvocationTurnId, ct as isTerminalAgentInvocation, dt as markAgentInvocationMailboxAppended, gt as reportReplacedAgentInvocation, ht as markAgentInvocationSteered, m as PluginCredentialFailureError, mt as markAgentInvocationRunning, pt as markAgentInvocationPaused, q as completeAgentInvocation, rt as getAgentInvocationMessageId, st as getLatestAgentInvocationForConversation, zt as withoutSavedSteeringMessages } from "./agent-runner-B-7S_DCS.js";
3
+ import { n as botConfig } from "./config-DNNkxfGS.js";
4
+ import { c as getConversationEventStore, u as getConversationStore } from "./viewer-D96vo_42.js";
5
5
  import { m as sameActorIdentity, u as agentInstructionProvenance } from "./history-9pO1Zd4Y.js";
6
- import { J as saveTurnCheckpoint, Nt as openConversationProjection, Q as getTurnRecord, Y as abandonTurnRecord, Z as failTurnRecord, ct as isTurnExecutionLimitExceededError, dt as getTerminalAssistantMessages } from "./tasks-B8nH3ND_.js";
6
+ import { J as saveTurnCheckpoint, Nt as openConversationProjection, Q as getTurnRecord, Y as abandonTurnRecord, Z as failTurnRecord, ct as isTurnExecutionLimitExceededError, dt as getTerminalAssistantMessages } from "./tasks-DwGlFX9i.js";
7
7
  import { c as isTurnInputCommitLostError, i as TurnInputCommitLostError, o as getConversationTurnBoundaryError } from "./oauth-authorization-BA4Dt6a7.js";
8
- import { n as getAssistantReplyText } from "./assistant-reply-K5r1pcgJ.js";
9
- import { A as recordFinishedTurnForAutomatedLimit, j as resetAutomatedTurnLimit, k as maybePostAutomatedTurnLimitNotice } from "./session-stop-DteRDRCi.js";
10
- import { r as appendAndEnqueueInboundMessage } from "./store-Dw3eBN9S.js";
11
- import { t as ConversationTurnLifecycleService } from "./turn-lifecycle-DSN0xGW7.js";
12
- import { n as getPersistedSandboxState, o as persistThreadStateById, r as getPersistedThreadState } from "./thread-state-BTOLzCM-.js";
8
+ import { n as getAssistantReplyText } from "./assistant-reply-DbPLvsnL.js";
9
+ import { A as recordFinishedTurnForAutomatedLimit, j as resetAutomatedTurnLimit, k as maybePostAutomatedTurnLimitNotice } from "./session-stop-DlRDisF5.js";
10
+ import { r as appendAndEnqueueInboundMessage } from "./store-Dx1U69mm.js";
11
+ import { t as ConversationTurnLifecycleService } from "./turn-lifecycle-B1VV58Yo.js";
12
+ import { n as getPersistedSandboxState, o as persistThreadStateById, r as getPersistedThreadState } from "./thread-state-Ces6tXmB.js";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import { z } from "zod";
15
15
  //#region src/chat/runtime/turn-execution.ts
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { v as isProviderRetryError } from "./client-Q27hki0Y.js";
3
- import { C as withLogContext, d as logException, f as logInfo, p as logWarn } from "./logging-C22RdmU8.js";
4
- import { i as getChatConfig } from "./config-Cb--Qs-g.js";
5
- import { f as getTurnRequestDeadline, m as ConversationQueueMessageRejectedError } from "./job-queue-uGq6Grnt.js";
6
- import { C as requestAnotherSlice, M as isInvalidConversationRecordError, T as startConversationWork, b as recordConversationRetry, d as countPendingConversationMessages, f as deadLetterAttempt, g as getConversationWorkState, i as beginConversationResume, j as isFinalAttempt, k as hasConversationStop, l as completeConversationStop, m as ensureConversationWake, o as checkInConversationWork, p as drainConversationMailbox, s as clearConsumedConversationWake, t as ackMessages, u as completeConversationWork, x as releaseConversationWork, y as recordAttemptFailure } from "./store-Dw3eBN9S.js";
2
+ import { v as isProviderRetryError } from "./client-ROZeVjq0.js";
3
+ import { C as withLogContext, d as logException, f as logInfo, p as logWarn } from "./logging-COUsTFIL.js";
4
+ import { i as getChatConfig } from "./config-DNNkxfGS.js";
5
+ import { f as getTurnRequestDeadline, m as ConversationQueueMessageRejectedError } from "./job-queue-DSQx1qFY.js";
6
+ import { C as requestAnotherSlice, M as isInvalidConversationRecordError, T as startConversationWork, b as recordConversationRetry, d as countPendingConversationMessages, f as deadLetterAttempt, g as getConversationWorkState, i as beginConversationResume, j as isFinalAttempt, k as hasConversationStop, l as completeConversationStop, m as ensureConversationWake, o as checkInConversationWork, p as drainConversationMailbox, s as clearConsumedConversationWake, t as ackMessages, u as completeConversationWork, x as releaseConversationWork, y as recordAttemptFailure } from "./store-Dx1U69mm.js";
7
7
  //#region src/chat/task-execution/worker.ts
8
8
  var worker_exports = /* @__PURE__ */ __exportAll({
9
9
  CONVERSATION_WORK_DEFER_DELAY_MS: () => CONVERSATION_WORK_DEFER_DELAY_MS,
@@ -0,0 +1,125 @@
1
+ CREATE TABLE "junior_automations" (
2
+ "id" text PRIMARY KEY NOT NULL,
3
+ "kind" text NOT NULL,
4
+ "team_id" text NOT NULL,
5
+ "channel_id" text NOT NULL,
6
+ "creator_slack_user_id" text NOT NULL,
7
+ "creator_identity_id" text,
8
+ "status" text NOT NULL,
9
+ "status_reason" text,
10
+ "title" text,
11
+ "instruction" text NOT NULL,
12
+ "created_at_ms" bigint NOT NULL,
13
+ "next_run_at_ms" bigint,
14
+ "run_now_at_ms" bigint,
15
+ "namespace" text,
16
+ "identifier" text,
17
+ "record" jsonb NOT NULL,
18
+ CONSTRAINT "junior_automations_kind_check" CHECK ("junior_automations"."kind" in ('scheduled', 'event')),
19
+ CONSTRAINT "junior_automations_status_check" CHECK ("junior_automations"."status" in ('active', 'blocked', 'paused', 'completed', 'deleted')),
20
+ CONSTRAINT "junior_automations_record_check" CHECK (jsonb_typeof("junior_automations"."record") = 'object'),
21
+ CONSTRAINT "junior_automations_trigger_check" CHECK (("junior_automations"."kind" = 'scheduled' and "junior_automations"."namespace" is null and "junior_automations"."identifier" is null) or ("junior_automations"."kind" = 'event' and "junior_automations"."namespace" is not null and "junior_automations"."identifier" is not null and "junior_automations"."next_run_at_ms" is null and "junior_automations"."run_now_at_ms" is null and "junior_automations"."status" <> 'completed'))
22
+ );
23
+ --> statement-breakpoint
24
+ -- Stop before the copy if a Scheduled automation and an event automation
25
+ -- have the same id.
26
+ DO $$
27
+ BEGIN
28
+ IF EXISTS (
29
+ SELECT 1
30
+ FROM "junior_scheduler_tasks" AS "scheduled"
31
+ JOIN "junior_event_tasks" AS "event" ON "event"."id" = "scheduled"."id"
32
+ ) THEN
33
+ RAISE EXCEPTION 'junior_scheduler_tasks and junior_event_tasks share an Automation id';
34
+ END IF;
35
+ END
36
+ $$;
37
+ --> statement-breakpoint
38
+ -- Copy both old tables. Old workers still use them during the deploy, so they
39
+ -- stay. The copy keeps what the old readers read:
40
+ -- - A Scheduled automation takes its status and status reason from its JSON.
41
+ -- - A title and a creator identity come from the column, or else from the
42
+ -- legacy JSON key.
43
+ -- - A status that the new check does not allow becomes "deleted".
44
+ -- JSON keys that now have a column are removed from the record.
45
+ INSERT INTO "junior_automations" (
46
+ "id", "kind", "team_id", "channel_id", "creator_slack_user_id",
47
+ "creator_identity_id", "status", "status_reason", "title", "instruction",
48
+ "created_at_ms", "next_run_at_ms", "run_now_at_ms", "namespace",
49
+ "identifier", "record"
50
+ )
51
+ SELECT
52
+ "id",
53
+ "kind",
54
+ "team_id",
55
+ coalesce("record"->'destination'->>'channelId', ''),
56
+ coalesce("record"->'createdBy'->>'slackUserId', ''),
57
+ "creator_identity_id",
58
+ CASE
59
+ WHEN "status" IN ('active', 'blocked', 'paused', 'completed', 'deleted') THEN "status"
60
+ ELSE 'deleted'
61
+ END,
62
+ "status_reason",
63
+ nullif(btrim(coalesce("title", "record"->>'title')), ''),
64
+ coalesce("record"->'task'->>'text', ''),
65
+ "created_at_ms",
66
+ "next_run_at_ms",
67
+ "run_now_at_ms",
68
+ "namespace",
69
+ "identifier",
70
+ "record" - ARRAY['createdAtMs', 'creatorIdentityId', 'id', 'nextRunAtMs', 'runNowAtMs', 'status', 'statusReason', 'title', 'version']
71
+ FROM (
72
+ SELECT
73
+ 'scheduled' AS "kind",
74
+ "id",
75
+ "team_id",
76
+ coalesce("creator_identity_id", "record"->>'creatorIdentityId') AS "creator_identity_id",
77
+ "record"->>'status' AS "status",
78
+ "record"->>'statusReason' AS "status_reason",
79
+ "title",
80
+ "created_at_ms",
81
+ "next_run_at_ms",
82
+ "run_now_at_ms",
83
+ NULL AS "namespace",
84
+ NULL AS "identifier",
85
+ "record"
86
+ FROM "junior_scheduler_tasks"
87
+ UNION ALL
88
+ SELECT
89
+ 'event',
90
+ "id",
91
+ "team_id",
92
+ NULL,
93
+ "status",
94
+ "status_reason",
95
+ "title",
96
+ "created_at_ms",
97
+ NULL,
98
+ NULL,
99
+ "namespace",
100
+ "identifier",
101
+ "task_json"
102
+ FROM "junior_event_tasks"
103
+ ) AS "source";
104
+ --> statement-breakpoint
105
+ CREATE INDEX "junior_automations_team_idx" ON "junior_automations" USING btree ("team_id","created_at_ms","id") WHERE "junior_automations"."status" <> 'deleted';
106
+ --> statement-breakpoint
107
+ CREATE INDEX "junior_automations_creator_idx" ON "junior_automations" USING btree ("team_id","creator_slack_user_id","created_at_ms","id");
108
+ --> statement-breakpoint
109
+ CREATE INDEX "junior_automations_creator_identity_idx" ON "junior_automations" USING btree ("creator_identity_id","created_at_ms","id") WHERE "junior_automations"."creator_identity_id" IS NOT NULL;
110
+ --> statement-breakpoint
111
+ CREATE INDEX "junior_automations_run_now_due_idx" ON "junior_automations" USING btree ("run_now_at_ms","created_at_ms","id") WHERE "junior_automations"."status" = 'active' AND "junior_automations"."run_now_at_ms" IS NOT NULL;
112
+ --> statement-breakpoint
113
+ CREATE INDEX "junior_automations_next_run_due_idx" ON "junior_automations" USING btree ("next_run_at_ms","created_at_ms","id") WHERE "junior_automations"."status" = 'active' AND "junior_automations"."next_run_at_ms" IS NOT NULL;
114
+ --> statement-breakpoint
115
+ CREATE INDEX "junior_automations_match_idx" ON "junior_automations" USING btree ("namespace","identifier","created_at_ms","id") WHERE "junior_automations"."status" <> 'deleted';
116
+ --> statement-breakpoint
117
+ -- Versions now key on the Automation id. Old workers still write kind during
118
+ -- the deploy, so kind stays as a nullable column until PR 3 of #2176.
119
+ ALTER TABLE "junior_automation_versions" DROP CONSTRAINT "junior_automation_versions_pk";
120
+ --> statement-breakpoint
121
+ ALTER TABLE "junior_automation_versions" ADD CONSTRAINT "junior_automation_versions_pk" PRIMARY KEY("automation_id","version");
122
+ --> statement-breakpoint
123
+ ALTER TABLE "junior_automation_versions" ALTER COLUMN "kind" DROP NOT NULL;
124
+ --> statement-breakpoint
125
+ ALTER TABLE "junior_automation_versions" ADD CONSTRAINT "junior_automation_versions_automation_id_fk" FOREIGN KEY ("automation_id") REFERENCES "public"."junior_automations"("id") ON DELETE cascade ON UPDATE no action;