@sentry/junior 0.246.0 → 0.247.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 (68) hide show
  1. package/dist/{admin-Bh-MYw-j.js → admin-BGwaqDMs.js} +1 -1
  2. package/dist/{agent-hooks-DpklSWZg.js → agent-hooks-C72ByH0C.js} +11 -11
  3. package/dist/{agent-invocations-BO6ddZax.js → agent-invocations-D_YoNnAn.js} +8 -2
  4. package/dist/{agent-runner-DSKpHjHW.js → agent-runner-DsAFAKKs.js} +451 -2412
  5. package/dist/api/schema.js +2 -2
  6. package/dist/api.js +24 -21
  7. package/dist/{app-BYB7szGb.d.ts → app-4t4mPTdS.d.ts} +8 -1
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +30 -27
  10. package/dist/assistant-reply-ChOzcTBS.js +45 -0
  11. package/dist/{briefs-cZ5vWqP_.js → briefs-Dc7qZrhc.js} +4 -4
  12. package/dist/{catalog-runtime-CTaQXYqS.js → catalog-runtime-DS1k7fUG.js} +1 -1
  13. package/dist/cli/chat.js +22 -16
  14. package/dist/cli/check.js +3 -3
  15. package/dist/cli/main.js +2 -2
  16. package/dist/cli/plugins.js +4 -4
  17. package/dist/cli/snapshot-create.js +3 -3
  18. package/dist/cli/upgrade.js +3 -3
  19. package/dist/{client--xtsAxKP.js → client-BVnfNd3D.js} +2 -2
  20. package/dist/{config-BK53Ip5C.js → config-CgWvImQL.js} +2 -2
  21. package/dist/{conversation-CvBG57Io.js → conversation-CYsbVFLx.js} +71 -1
  22. package/dist/{conversation-privacy-BDBFw6Ws.js → conversation-privacy-D3TdVM9H.js} +1 -1
  23. package/dist/{credential-sync-BiuhC9Ds.js → credential-sync-DLw3jkv-.js} +14 -14
  24. package/dist/{executor-bmmuRY-w.js → executor-DQazjeGA.js} +3 -3
  25. package/dist/{images-DZliDtSH.js → images-C3e5E-p_.js} +4 -21
  26. package/dist/instrumentation.js +2 -2
  27. package/dist/{job-queue-Cz3M7gg4.js → job-queue-BEUqRhjC.js} +1 -1
  28. package/dist/{logging-DVtMYOdD.js → logging-CZEc8_v4.js} +1 -1
  29. package/dist/message-BIJa7lKh.js +59 -0
  30. package/dist/nitro.d.ts +1 -1
  31. package/dist/nitro.js +3 -3
  32. package/dist/{oauth-authorization-By_MVRDC.js → oauth-authorization-BA4Dt6a7.js} +1 -45
  33. package/dist/{oauth-callback-server-BrUo6w1e.js → oauth-callback-server-R9OSdLP1.js} +2 -2
  34. package/dist/{pending-auth-BuQLZ6dK.js → pending-auth-Oo5AQhaf.js} +2 -2
  35. package/dist/{profile-BevMNSlr.js → profile-aVLDAirh.js} +4 -4
  36. package/dist/{prompt-C9Q9cjD3.js → prompt-ZG1UCxjF.js} +1 -1
  37. package/dist/{registry-C2rSEio1.js → registry-CtaDOOM5.js} +1 -1
  38. package/dist/{resolve-qPhrznTf.js → resolve-Bdw4hu7s.js} +2 -2
  39. package/dist/result-DNgmkASh.js +463 -0
  40. package/dist/{runner-CNh5eMWx.js → runner-BUSScEu5.js} +11 -10
  41. package/dist/{sandbox-egress-signals-BnDEKu8d.js → sandbox-egress-signals-E9r8bf9G.js} +1 -1
  42. package/dist/{schema-BWMRg8JS.js → schema-tyd6hALh.js} +2 -2
  43. package/dist/session-stop-CAhBfBUT.js +782 -0
  44. package/dist/{skills-C6zJbudq.js → skills-DQy-mmBC.js} +2 -2
  45. package/dist/{spawn-C3efZSx3.js → spawn-DQ_MVWZ6.js} +3 -2
  46. package/dist/store-DjLA8GKs.js +1417 -0
  47. package/dist/{task-queue-BX4vG6uA.js → task-queue-BT2h_t8I.js} +3 -3
  48. package/dist/{task-runner-T51kll0U.js → task-runner-CiPepjIB.js} +11 -11
  49. package/dist/{tasks-B9OIjl2K.js → tasks-DMmRrIVl.js} +9 -9
  50. package/dist/{thread-state-AGZtVyXp.js → thread-state-ehZYGpX9.js} +7 -7
  51. package/dist/{turn-failure-response-DJ8KU2bo.js → turn-failure-response-D7J10z7l.js} +9 -9
  52. package/dist/{turn-lifecycle-DZJkJ95q.js → turn-lifecycle-Buswqs90.js} +1 -1
  53. package/dist/{turn-session-routing-mRqLbMZW.js → turn-session-routing-Bw-yiSb4.js} +1 -1
  54. package/dist/{validation-Dg0Ihxzo.js → validation-DTguegIe.js} +1 -1
  55. package/dist/{version-Deub4try.js → version-BrZSE5du.js} +1 -1
  56. package/dist/version.js +1 -1
  57. package/dist/{viewer-D5hbx6TE.js → viewer-BlAozHer.js} +4 -4
  58. package/dist/{web-authorization-DCxixz5S.js → web-authorization-DwyTlkAg.js} +6 -6
  59. package/dist/{web-input-0sorYVLh.js → web-input-DSYxI7Wi.js} +43 -208
  60. package/dist/{work-rm2X7jj4.js → work-CRBXkJoU.js} +89 -13
  61. package/dist/{worker-bnGsAOP3.js → worker-BVJKM9Ja.js} +7 -7
  62. package/migrations/0053_conversation_stopped_at.sql +1 -0
  63. package/migrations/0054_flowery_rage.sql +1 -0
  64. package/migrations/meta/0053_snapshot.json +3771 -0
  65. package/migrations/meta/0054_snapshot.json +3777 -0
  66. package/migrations/meta/_journal.json +14 -0
  67. package/package.json +6 -5
  68. package/dist/message-BSN-Ma5f.js +0 -317
@@ -1,5 +1,5 @@
1
- import { p as logWarn } from "./logging-DVtMYOdD.js";
2
- import { c as QUEUE_SIGNATURE_MAX_AGE_MS, d as createVercelQueueClient, l as signQueueMessage, p as runWithTurnRequestDeadline, u as verifyQueueMessage } from "./job-queue-Cz3M7gg4.js";
1
+ import { p as logWarn } from "./logging-CZEc8_v4.js";
2
+ import { c as QUEUE_SIGNATURE_MAX_AGE_MS, d as createVercelQueueClient, l as signQueueMessage, p as runWithTurnRequestDeadline, u as verifyQueueMessage } from "./job-queue-BEUqRhjC.js";
3
3
  import { z } from "zod";
4
4
  import { createHash } from "node:crypto";
5
5
  import { handleCallback, registerDevConsumer } from "@vercel/queue";
@@ -115,7 +115,7 @@ function pluginTaskCallback() {
115
115
  maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
116
116
  onRejected: logPluginTaskQueueMessageRejected,
117
117
  run: async (message) => {
118
- const { processPluginTask } = await import("./task-runner-T51kll0U.js").then((n) => n.r);
118
+ const { processPluginTask } = await import("./task-runner-CiPepjIB.js").then((n) => n.r);
119
119
  await processPluginTask(message);
120
120
  },
121
121
  topic: PLUGIN_TASK_QUEUE_TOPIC,
@@ -1,17 +1,17 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { h as runBestEffort, p as logWarn } from "./logging-DVtMYOdD.js";
2
+ import { h as runBestEffort, p as logWarn } from "./logging-CZEc8_v4.js";
3
3
  import { g as parseSlackMessageTs } from "./actor-BTtLaeWy.js";
4
- import { C as agentTurnTotalTokens, S as agentTurnCostUsd, d as getDb, r as readActorIdentity, u as getConversationStore } from "./viewer-D5hbx6TE.js";
5
- import { s as juniorConversations } from "./agent-invocations-BO6ddZax.js";
6
- import { c as juniorAutomationExecutions } from "./executor-bmmuRY-w.js";
4
+ import { C as agentTurnTotalTokens, S as agentTurnCostUsd, d as getDb, r as readActorIdentity, u as getConversationStore } from "./viewer-BlAozHer.js";
5
+ import { s as juniorConversations } from "./agent-invocations-D_YoNnAn.js";
6
+ import { c as juniorAutomationExecutions } from "./executor-DQazjeGA.js";
7
7
  import { p as sameActorIdentity } from "./history-Nte1oVed.js";
8
- import { p as credentialSubjectSchema } from "./registry-C2rSEio1.js";
9
- import { Ht as hydrateConversationMessages, Jt as fallbackShortTitle, M as formatSlackLink, Q as getTurnRecord, V as postSlackMessage, a as readScheduledAutomation, dt as instructionTextForProjection, g as getEventAutomation, gt as normalizeToolNameFromResult, ht as isToolResultMessage, j as escapeSlackMrkdwnText, mt as isToolResultError, st as getPiMessageRole, u as blockEventAutomation, vt as stripRuntimeTurnContext, z as openSlackDirectMessage } from "./tasks-B9OIjl2K.js";
10
- import { ct as createPluginModel, it as getDashboardTaskLink, lt as createPluginLogger, ot as createPluginState, p as coreTaskRegistrations, st as createPluginEmbedder, tt as JUNIOR_THREAD_STATE_TTL_MS, u as getPlugins, yt as createPluginConversationEvents } from "./agent-hooks-DpklSWZg.js";
11
- import { w as getStateAdapter } from "./profile-BevMNSlr.js";
12
- import { r as getPersistedThreadState, s as coerceThreadConversationState } from "./thread-state-AGZtVyXp.js";
13
- import { t as resolveConversationRouting } from "./turn-session-routing-mRqLbMZW.js";
14
- import { i as pluginTaskParamsSchema, o as sendVercelPluginTask, r as pluginTaskId } from "./task-queue-BX4vG6uA.js";
8
+ import { p as credentialSubjectSchema } from "./registry-CtaDOOM5.js";
9
+ import { Ht as hydrateConversationMessages, Jt as fallbackShortTitle, M as formatSlackLink, Q as getTurnRecord, V as postSlackMessage, a as readScheduledAutomation, dt as instructionTextForProjection, g as getEventAutomation, gt as normalizeToolNameFromResult, ht as isToolResultMessage, j as escapeSlackMrkdwnText, mt as isToolResultError, st as getPiMessageRole, u as blockEventAutomation, vt as stripRuntimeTurnContext, z as openSlackDirectMessage } from "./tasks-DMmRrIVl.js";
10
+ import { ct as createPluginModel, it as getDashboardTaskLink, lt as createPluginLogger, ot as createPluginState, p as coreTaskRegistrations, st as createPluginEmbedder, tt as JUNIOR_THREAD_STATE_TTL_MS, u as getPlugins, yt as createPluginConversationEvents } from "./agent-hooks-C72ByH0C.js";
11
+ import { w as getStateAdapter } from "./profile-aVLDAirh.js";
12
+ import { r as getPersistedThreadState, s as coerceThreadConversationState } from "./thread-state-ehZYGpX9.js";
13
+ import { t as resolveConversationRouting } from "./turn-session-routing-Bw-yiSb4.js";
14
+ import { i as pluginTaskParamsSchema, o as sendVercelPluginTask, r as pluginTaskId } from "./task-queue-BT2h_t8I.js";
15
15
  import { z } from "zod";
16
16
  import { createHash } from "node:crypto";
17
17
  import { and, asc, count, desc, eq, gte, inArray, lte, max, or, sql } from "drizzle-orm";
@@ -1,15 +1,15 @@
1
- import { d as unwrapCurrentInstruction, f as escapeXml, i as completeText, o as resolveGatewayModel } from "./client--xtsAxKP.js";
2
- import { d as logException, o as getActiveTraceId, p as logWarn, s as getLogContextAttributes, t as buildTurnFailureResponse, v as setSpanAttributes } from "./logging-DVtMYOdD.js";
1
+ import { d as unwrapCurrentInstruction, f as escapeXml, i as completeText, o as resolveGatewayModel } from "./client-BVnfNd3D.js";
2
+ import { d as logException, o as getActiveTraceId, p as logWarn, s as getLogContextAttributes, t as buildTurnFailureResponse, v as setSpanAttributes } from "./logging-CZEc8_v4.js";
3
3
  import { n as captureMessage } from "./sentry-CgWZM_kV.js";
4
- import { n as botConfig, v as normalizeSlackEmojiName } from "./config-BK53Ip5C.js";
4
+ import { n as botConfig, v as normalizeSlackEmojiName } from "./config-CgWvImQL.js";
5
5
  import { c as toStoredSlackActor, f as parseSlackUserId, g as parseSlackMessageTs } from "./actor-BTtLaeWy.js";
6
- import { c as getConversationEventStore, f as getSqlExecutor, m as withConversationEventLock, p as createSqlConversationEventStore, u as getConversationStore, v as startLocationThread, x as addAgentTurnUsage, y as bindProviderConversation } from "./viewer-D5hbx6TE.js";
7
- import { a as juniorSchedulerRuns, o as juniorSchedulerTasks, s as juniorAutomationVersions, u as juniorEventAutomations } from "./executor-bmmuRY-w.js";
6
+ import { c as getConversationEventStore, f as getSqlExecutor, m as withConversationEventLock, p as createSqlConversationEventStore, u as getConversationStore, v as startLocationThread, x as addAgentTurnUsage, y as bindProviderConversation } from "./viewer-BlAozHer.js";
7
+ import { a as juniorSchedulerRuns, o as juniorSchedulerTasks, s as juniorAutomationVersions, u as juniorEventAutomations } from "./executor-DQazjeGA.js";
8
8
  import { d as instructionActors, f as instructionProvenanceFor, n as agentHistoryItemSchema, u as contextProvenance } from "./history-Nte1oVed.js";
9
- import { p as credentialSubjectSchema } from "./registry-C2rSEio1.js";
10
- import { Ft as SlackActionError, Ht as normalizeSlackConversationId, Jt as agentsInstructionsUpdatedEvent, Wt as withSlackRetries, Xt as authenticationUnlinkedEvent, Yt as authenticationLinkedEvent, n as applyPluginFormatMarkdown, qt as JUNIOR_NATIVE_EVENT_NAMESPACE, zt as getSlackClient } from "./agent-hooks-DpklSWZg.js";
11
- import { U as messageCardRef } from "./conversation-CvBG57Io.js";
12
- import { D as fenceLock, O as withLock, T as MUTATION_LOCK_TTL_MS, k as sleep, w as getStateAdapter } from "./profile-BevMNSlr.js";
9
+ import { p as credentialSubjectSchema } from "./registry-CtaDOOM5.js";
10
+ import { Ft as SlackActionError, Ht as normalizeSlackConversationId, Jt as agentsInstructionsUpdatedEvent, Wt as withSlackRetries, Xt as authenticationUnlinkedEvent, Yt as authenticationLinkedEvent, n as applyPluginFormatMarkdown, qt as JUNIOR_NATIVE_EVENT_NAMESPACE, zt as getSlackClient } from "./agent-hooks-C72ByH0C.js";
11
+ import { W as messageCardRef } from "./conversation-CYsbVFLx.js";
12
+ import { D as fenceLock, O as withLock, T as MUTATION_LOCK_TTL_MS, k as sleep, w as getStateAdapter } from "./profile-aVLDAirh.js";
13
13
  import { A as eventAutomationSchema, D as scheduledRunSchema, E as scheduledAutomationSchema, S as automationVersionSchema } from "./automation-gznOMaQ2.js";
14
14
  import { isDeepStrictEqual } from "node:util";
15
15
  import { z } from "zod";
@@ -1,10 +1,10 @@
1
- import { I as isRecord, L as toOptionalNumber, R as toOptionalString } from "./logging-DVtMYOdD.js";
2
- import { d as getDb } from "./viewer-D5hbx6TE.js";
3
- import { d as juniorDestinations } from "./agent-invocations-BO6ddZax.js";
4
- import { d as juniorLocationConfigurations } from "./executor-bmmuRY-w.js";
5
- import { Ut as persistConversationMessages } from "./tasks-B9OIjl2K.js";
6
- import { tt as JUNIOR_THREAD_STATE_TTL_MS } from "./agent-hooks-DpklSWZg.js";
7
- import { w as getStateAdapter } from "./profile-BevMNSlr.js";
1
+ import { I as isRecord, L as toOptionalNumber, R as toOptionalString } from "./logging-CZEc8_v4.js";
2
+ import { d as getDb } from "./viewer-BlAozHer.js";
3
+ import { d as juniorDestinations } from "./agent-invocations-D_YoNnAn.js";
4
+ import { d as juniorLocationConfigurations } from "./executor-DQazjeGA.js";
5
+ import { Ut as persistConversationMessages } from "./tasks-DMmRrIVl.js";
6
+ import { tt as JUNIOR_THREAD_STATE_TTL_MS } from "./agent-hooks-C72ByH0C.js";
7
+ import { w as getStateAdapter } from "./profile-aVLDAirh.js";
8
8
  import { z } from "zod";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { and, eq, sql } from "drizzle-orm";
@@ -1,13 +1,13 @@
1
- import { _ as getProviderErrorUserMessage, g as getProviderErrorAttributes, h as findProviderError, p as ProviderError } from "./client--xtsAxKP.js";
2
- import { I as isRecord, t as buildTurnFailureResponse } from "./logging-DVtMYOdD.js";
1
+ import { _ as getProviderErrorUserMessage, g as getProviderErrorAttributes, h as findProviderError, p as ProviderError } from "./client-BVnfNd3D.js";
2
+ import { I as isRecord, t as buildTurnFailureResponse } from "./logging-CZEc8_v4.js";
3
3
  import { g as parseSlackMessageTs } from "./actor-BTtLaeWy.js";
4
- import { c as getConversationEventStore, d as getDb } from "./viewer-D5hbx6TE.js";
5
- import { Ht as hydrateConversationMessages, nn as markConversationMessage } from "./tasks-B9OIjl2K.js";
6
- import { At as listConversationAnnotations } from "./agent-hooks-DpklSWZg.js";
7
- import { G as readMessageCardRefs, K as removedCardSchema, q as resolveMessageCards } from "./conversation-CvBG57Io.js";
8
- import { r as clearPendingAuth, u as buildDeterministicTurnId } from "./pending-auth-BuQLZ6dK.js";
9
- import { g as markTurnCompleted, h as markTurnClosed } from "./oauth-authorization-By_MVRDC.js";
10
- import { o as persistThreadStateById, r as getPersistedThreadState, s as coerceThreadConversationState } from "./thread-state-AGZtVyXp.js";
4
+ import { c as getConversationEventStore, d as getDb } from "./viewer-BlAozHer.js";
5
+ import { Ht as hydrateConversationMessages, nn as markConversationMessage } from "./tasks-DMmRrIVl.js";
6
+ import { At as listConversationAnnotations } from "./agent-hooks-C72ByH0C.js";
7
+ import { J as resolveMessageCards, K as readMessageCardRefs, q as removedCardSchema } from "./conversation-CYsbVFLx.js";
8
+ import { r as clearPendingAuth, u as buildDeterministicTurnId } from "./pending-auth-Oo5AQhaf.js";
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-ehZYGpX9.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-D5hbx6TE.js";
1
+ import { c as getConversationEventStore } from "./viewer-BlAozHer.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-D5hbx6TE.js").then((n) => n.s)).getConversationStore();
37
+ const conversationStore = args.conversationStore ?? (await import("./viewer-BlAozHer.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-CTaQXYqS.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DS1k7fUG.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.246.0";
2
+ var version = "0.247.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-Deub4try.js";
1
+ import { t as JUNIOR_VERSION } from "./version-BrZSE5du.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-DVtMYOdD.js";
3
- import { i as getChatConfig } from "./config-BK53Ip5C.js";
2
+ import { F as normalizeIdentityEmail } from "./logging-CZEc8_v4.js";
3
+ import { i as getChatConfig } from "./config-CgWvImQL.js";
4
4
  import { d as parseSlackTeamId, o as parseActorUserId, u as parseSlackChannelReferenceId } from "./actor-BTtLaeWy.js";
5
- import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers, o as conversationReadColumns, s as juniorConversations } from "./agent-invocations-BO6ddZax.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-bmmuRY-w.js";
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-DQazjeGA.js";
7
7
  import { c as newConversationEventSchema, l as encodeHistoryPayload, m as usageSchema, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-Nte1oVed.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,9 +1,9 @@
1
- import { Vt as ensureConversationWake, Zt as requestConversationWork } from "./agent-runner-DSKpHjHW.js";
2
- import { c as getConversationEventStore } from "./viewer-D5hbx6TE.js";
3
- import { Q as getTurnRecord, Z as failTurnRecord, q as loadTurnCheckpoint } from "./tasks-B9OIjl2K.js";
4
- import { w as getStateAdapter } from "./profile-BevMNSlr.js";
5
- import { a as getVercelConversationWorkQueue } from "./job-queue-Cz3M7gg4.js";
6
- import { n as resolveTurnSessionRouting } from "./turn-session-routing-mRqLbMZW.js";
1
+ import { c as getConversationEventStore } from "./viewer-BlAozHer.js";
2
+ import { Q as getTurnRecord, Z as failTurnRecord, q as loadTurnCheckpoint } from "./tasks-DMmRrIVl.js";
3
+ import { w as getStateAdapter } from "./profile-aVLDAirh.js";
4
+ import { a as getVercelConversationWorkQueue } from "./job-queue-BEUqRhjC.js";
5
+ import { m as ensureConversationWake, w as requestConversationWork } from "./store-DjLA8GKs.js";
6
+ import { n as resolveTurnSessionRouting } from "./turn-session-routing-Bw-yiSb4.js";
7
7
  import { z } from "zod";
8
8
  import { randomUUID } from "node:crypto";
9
9
  //#region src/chat/task-execution/authorized-turn.ts
@@ -1,39 +1,43 @@
1
- import { $t as stopConversationWork, A as resolveSlackChannelIdFromMessage, An as finishedRunReply, At as appendAndEnqueueInboundMessage, B as effectiveTaskOutcomes, C as renderBlockText, Cn as buildSteeringPiMessage, D as storeAttachment, Dn as AuthorizationFlowDisabledError, Et as automationEventCatalog, Ht as getConversation, M as getConversationInfo, Mn as shouldEmitDevAgentTrace, N as listThreadReplies, O as parseSlackThreadId, S as renderAttachmentText, Sn as createUserTokenStore, St as getEventCatalog, Ut as getConversationWorkState, Vt as ensureConversationWake, Zt as requestConversationWork, a as buildAuthPauseResponse, bt as isEventMailboxMetadata, cn as recordFinishedTurnForAutomatedLimit, h as latestProgressStatus, j as resolveSlackChannelIdFromThreadId, jn as runDispatchOutcome, k as readSlackRawMessageContext, kn as deliversFinalText, kt as appendAndEnqueueExclusiveInboundMessage, m as PluginCredentialFailureError, n as executeAgentRun, r as createContextCompactor, sn as maybePostAutomatedTurnLimitNotice, t as createAgentRunner, wn as RetryableDeliveryError, xt as timerWatchCredentialSubject, yt as EVENT_WAIT_MS, z as eventAutomationTriggerAvailable } from "./agent-runner-DSKpHjHW.js";
2
- import { f as escapeXml, i as completeText, r as completeObject, v as isProviderRetryError } from "./client--xtsAxKP.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-DVtMYOdD.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-BK53Ip5C.js";
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-DsAFAKKs.js";
2
+ import { f as escapeXml, i as completeText, r as completeObject, v as isProviderRetryError } from "./client-BVnfNd3D.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-CZEc8_v4.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-CgWvImQL.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-D5hbx6TE.js";
8
- import { c as juniorIdentities, d as juniorDestinations, l as juniorUsers } from "./agent-invocations-BO6ddZax.js";
9
- import { c as juniorAutomationExecutions, o as juniorSchedulerTasks, u as juniorEventAutomations } from "./executor-bmmuRY-w.js";
7
+ import { M as createSlackDestination, P as requireSlackDestination, c as getConversationEventStore, d as getDb, f as getSqlExecutor, u as getConversationStore } from "./viewer-BlAozHer.js";
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-DQazjeGA.js";
10
10
  import { f as instructionProvenanceFor } from "./history-Nte1oVed.js";
11
- import { d as credentialContextForActor } from "./registry-C2rSEio1.js";
12
- import { $ as listTurnSummaries, $t as estimateConversationContextTokens, Ct as commitMessages, D as sameDefinitionValue, Dt as loadProjection, Gt as persistConversationMessageSummaries, H as removeReactionFromMessage, Ht as hydrateConversationMessages, I as truncateStatusText, J as saveTurnCheckpoint, Jt as fallbackShortTitle, Kt as resolveConversationTitle, L as addReactionToMessage, M as formatSlackLink, N as normalizeSlackReplyMarkdown, P as normalizeSlackStatusText, Pt as recordAuthorizationCompleted, Q as getTurnRecord, Qt as createConversationMemoryService, Rt as recordSubscribedReplyRoute, St as commitAcceptedReply, T as listAutomationVersions, Tt as loadConversationProjection, Ut as persistConversationMessages, V as postSlackMessage, X as completeTurnRecord, Xt as appendThreadContextMessages, Y as abandonTurnRecord, Z as failTurnRecord, Zt as buildConversationContext, _ as listDeletedEventAutomationsCreatedBy, a as readScheduledAutomation, an as turnHasReply, en as getConversationMessageSlackTs, et as recordTurnSummary, g as getEventAutomation, i as parseScheduledAutomationRow, in as recordDeliveredAssistantMessage, it as buildTurnErrorResponse, j as escapeSlackMrkdwnText, l as withScheduledAutomationLock, m as eventAutomationBelongsToUser, nn as markConversationMessage, on as upsertConversationMessage, p as deleteEventAutomation, q as loadTurnCheckpoint, rn as normalizeConversationText, s as saveScheduledAutomationInLock, tn as isHumanConversationMessage, tt as persistWithRetry, w as automationDefinition, y as parseEventAutomationRow, yt as trimTrailingAssistantMessages } from "./tasks-B9OIjl2K.js";
13
- import { Ct as getSlackFileId, Et as recordSlackAttachment, Ft as SlackActionError, Ht as normalizeSlackConversationId, It as downloadPrivateSlackFile, Pt as lookupSlackUser, Rt as getHeaderString, St as buildSentryConversationUrl, Tt as readAttachmentVisionSummary, Ut as runWithSlackInstallationToken, Vt as isDmChannel, et as verifyTimerWatchCredentialSubject, nt as getDashboardConversationLink, o as getPluginSlackConversationLink, rt as getDashboardObjectIconLink, tt as JUNIOR_THREAD_STATE_TTL_MS, z as cancelSubscriptions, zt as getSlackClient } from "./agent-hooks-DpklSWZg.js";
14
- import { I as isVisionImageMediaType, P as readMessageAttachments } from "./conversation-CvBG57Io.js";
15
- import { E as acquireActiveLock, O as withLock, T as MUTATION_LOCK_TTL_MS, w as getStateAdapter } from "./profile-BevMNSlr.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-BuQLZ6dK.js";
17
- import { _ as markTurnFailed, c as CooperativeTurnYieldError, d as getConversationTurnBoundaryError, f as isCooperativeTurnYieldError, g as markTurnCompleted, h as markTurnClosed, l as TurnInputCommitLostError, m as isTurnInputDeferredError, p as isTurnInputCommitLostError, r as getAssistantReplyText, s as ConversationTurnBoundaryError, u as TurnInputDeferredError, v as startActiveTurn } from "./oauth-authorization-By_MVRDC.js";
18
- import { a as EVENT_SYSTEM_ACTOR, i as EVENT_MESSAGE_AUTHOR, o as isEventConversationMessage } from "./prompt-C9Q9cjD3.js";
19
- import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline } from "./job-queue-Cz3M7gg4.js";
11
+ import { d as credentialContextForActor } from "./registry-CtaDOOM5.js";
12
+ import { $ as listTurnSummaries, $t as estimateConversationContextTokens, Ct as commitMessages, D as sameDefinitionValue, Dt as loadProjection, Gt as persistConversationMessageSummaries, H as removeReactionFromMessage, Ht as hydrateConversationMessages, I as truncateStatusText, J as saveTurnCheckpoint, Jt as fallbackShortTitle, Kt as resolveConversationTitle, L as addReactionToMessage, M as formatSlackLink, N as normalizeSlackReplyMarkdown, P as normalizeSlackStatusText, Pt as recordAuthorizationCompleted, Q as getTurnRecord, Qt as createConversationMemoryService, Rt as recordSubscribedReplyRoute, St as commitAcceptedReply, T as listAutomationVersions, Tt as loadConversationProjection, Ut as persistConversationMessages, V as postSlackMessage, X as completeTurnRecord, Xt as appendThreadContextMessages, Y as abandonTurnRecord, Z as failTurnRecord, Zt as buildConversationContext, _ as listDeletedEventAutomationsCreatedBy, a as readScheduledAutomation, an as turnHasReply, en as getConversationMessageSlackTs, et as recordTurnSummary, g as getEventAutomation, i as parseScheduledAutomationRow, in as recordDeliveredAssistantMessage, it as buildTurnErrorResponse, j as escapeSlackMrkdwnText, l as withScheduledAutomationLock, m as eventAutomationBelongsToUser, nn as markConversationMessage, on as upsertConversationMessage, p as deleteEventAutomation, q as loadTurnCheckpoint, rn as normalizeConversationText, s as saveScheduledAutomationInLock, tn as isHumanConversationMessage, tt as persistWithRetry, w as automationDefinition, y as parseEventAutomationRow, yt as trimTrailingAssistantMessages } from "./tasks-DMmRrIVl.js";
13
+ import { Ct as getSlackFileId, Et as recordSlackAttachment, Ft as SlackActionError, Ht as normalizeSlackConversationId, It as downloadPrivateSlackFile, Pt as lookupSlackUser, Rt as getHeaderString, St as buildSentryConversationUrl, Tt as readAttachmentVisionSummary, Ut as runWithSlackInstallationToken, Vt as isDmChannel, et as verifyTimerWatchCredentialSubject, nt as getDashboardConversationLink, o as getPluginSlackConversationLink, rt as getDashboardObjectIconLink, tt as JUNIOR_THREAD_STATE_TTL_MS, z as cancelSubscriptions, zt as getSlackClient } from "./agent-hooks-C72ByH0C.js";
14
+ import { L as isVisionImageMediaType, P as readMessageAttachments } from "./conversation-CYsbVFLx.js";
15
+ import { E as acquireActiveLock, O as withLock, T as MUTATION_LOCK_TTL_MS, w as getStateAdapter } from "./profile-aVLDAirh.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-Oo5AQhaf.js";
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-ChOzcTBS.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-CAhBfBUT.js";
20
+ import { a as EVENT_SYSTEM_ACTOR, o as isEventConversationMessage } from "./prompt-ZG1UCxjF.js";
21
+ import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline } from "./job-queue-BEUqRhjC.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-DjLA8GKs.js";
20
23
  import { l as automationListQuerySchema } from "./automation-gznOMaQ2.js";
21
24
  import { r as isExperimentalFeatureEnabled } from "./experimental-Qn9rKLgx.js";
22
25
  import { c as sumUtcHoursIntoSixHours, m as healthReportSchema, t as webMessageId } from "./web-message-id-xPI_EFSC.js";
23
- 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-T51kll0U.js";
24
- import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-DZJkJ95q.js";
25
- import { i as resolveAgentInvocationId, o as AgentRunError, s as executeTurn, t as createAgentInvocationWorker } from "./work-rm2X7jj4.js";
26
- 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-AGZtVyXp.js";
27
- import { a as withAgentInvocationResultActors, i as startAgentInvocationsForChildResults, r as enqueueAgentInvocationResult, t as bindMessageAgent } from "./message-BSN-Ma5f.js";
28
- import { a as getPausedTurnRequest, c as getTurnAuthorization, i as createPausedTurns, n as deleteWebAuthorization, s as wakePausedTurn, t as createWebAuthorization } from "./web-authorization-DCxixz5S.js";
29
- import { n as resolveTurnSessionRouting } from "./turn-session-routing-mRqLbMZW.js";
30
- import { t as bindSpawnAgent } from "./spawn-C3efZSx3.js";
31
- 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-DJ8KU2bo.js";
32
- import { r as storeInputImages } from "./images-DZliDtSH.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-CiPepjIB.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-DNgmkASh.js";
28
+ import { n as getTurnLifecycle, t as ConversationTurnLifecycleService } from "./turn-lifecycle-Buswqs90.js";
29
+ import { i as resolveAgentInvocationId, o as AgentRunError, s as executeTurn, t as createAgentInvocationWorker } from "./work-CRBXkJoU.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-ehZYGpX9.js";
31
+ import { a as getPausedTurnRequest, c as getTurnAuthorization, i as createPausedTurns, n as deleteWebAuthorization, s as wakePausedTurn, t as createWebAuthorization } from "./web-authorization-DwyTlkAg.js";
32
+ import { n as resolveTurnSessionRouting } from "./turn-session-routing-Bw-yiSb4.js";
33
+ import { t as bindMessageAgent } from "./message-BIJa7lKh.js";
34
+ import { t as bindSpawnAgent } from "./spawn-DQ_MVWZ6.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-D7J10z7l.js";
36
+ import { r as storeInputImages } from "./images-C3e5E-p_.js";
33
37
  import { z } from "zod";
34
38
  import { createHash } from "node:crypto";
35
39
  import { and, asc, count, desc, eq, exists, inArray, ne, or, sql } from "drizzle-orm";
36
- import { createEventSource, createLocalSource, createSlackSource, createWebSource, localDestinationSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
40
+ import { createSlackSource, createWebSource, localDestinationSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
37
41
  import { unionAll } from "drizzle-orm/pg-core";
38
42
  import { del, get, put } from "@vercel/blob";
39
43
  import { Message, ThreadImpl, stringifyMarkdown } from "chat";
@@ -1569,144 +1573,6 @@ function createSlackTurnRuntime(deps) {
1569
1573
  };
1570
1574
  }
1571
1575
  //#endregion
1572
- //#region src/chat/conversations/web-mailbox.ts
1573
- /** Parse web mailbox metadata written before Source and Actor were complete. */
1574
- const legacyWebMailboxMetadataSchema = z.object({
1575
- authorEmail: z.string().email(),
1576
- authorFullName: z.string().min(1).optional(),
1577
- authorUserId: z.string().min(1),
1578
- authorUserName: z.string().min(1).optional(),
1579
- kind: z.literal("api_turn"),
1580
- messageId: z.string().min(1)
1581
- }).strict();
1582
- //#endregion
1583
- //#region src/chat/task-execution/mailbox-turn.ts
1584
- /**
1585
- * Restore Turn input facts, with saved Message fallback for legacy cursors.
1586
- *
1587
- * TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
1588
- * after no deployed Turn cursor can omit either field.
1589
- */
1590
- function turnInputFactsFromConversationMessage(message, args) {
1591
- if (isEventConversationMessage(message)) return {
1592
- actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
1593
- author: message.author ?? EVENT_MESSAGE_AUTHOR,
1594
- source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
1595
- };
1596
- const actor = args.savedActor ?? createActor(message.author, {
1597
- platform: "web",
1598
- userId: message.author?.userId
1599
- });
1600
- if (actor?.platform !== "web") return;
1601
- return {
1602
- actor,
1603
- author: message.author ?? { userId: actor.userId },
1604
- source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
1605
- };
1606
- }
1607
- /** Normalize the selected mailbox Source with current Conversation visibility. */
1608
- function sourceFromTurnInput(args) {
1609
- if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
1610
- return args.source;
1611
- }
1612
- function hasEventActor(actors) {
1613
- return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
1614
- }
1615
- /** Return the active web Turn for one Conversation, if it has one. */
1616
- async function getActiveConversationTurnId(conversationId) {
1617
- const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
1618
- if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
1619
- const turnId = active[0]?.turnId;
1620
- if (!turnId) return void 0;
1621
- const record = await getTurnRecord(conversationId, turnId);
1622
- return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
1623
- }
1624
- /** Return the active web or event mailbox Turn. */
1625
- async function getActiveMailboxTurnId(conversationId) {
1626
- const summaries = await listTurnSummaries(conversationId);
1627
- const active = (await Promise.all(summaries.filter((summary) => !summary.dispatchId && (summary.state === "paused" || summary.state === "running")).map((summary) => getTurnRecord(conversationId, summary.turnId)))).filter((record) => record && !record.dispatchId && (record.source?.kind === "web" || record.source?.kind === "event" || !record.source && (record.surface === "api" || hasEventActor(record.actors))) && (record.state === "paused" || record.state === "running"));
1628
- if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
1629
- return active[0]?.turnId;
1630
- }
1631
- /** Return the idle auth-paused web Turn for one Conversation. */
1632
- async function getAuthPausedConversationTurnId(conversationId) {
1633
- const turnId = await getActiveConversationTurnId(conversationId);
1634
- if (!turnId) return void 0;
1635
- const record = await getTurnRecord(conversationId, turnId);
1636
- return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
1637
- }
1638
- function parseWebMessages(messages) {
1639
- if (messages.length === 0) return [];
1640
- const parsed = messages.map((message) => ({
1641
- message,
1642
- metadata: legacyWebMailboxMetadataSchema.safeParse(message.input.metadata)
1643
- }));
1644
- if (parsed.every((entry) => !entry.metadata.success)) return [];
1645
- if (parsed.some((entry) => !entry.metadata.success)) throw new Error("A Turn cannot combine different kinds of input");
1646
- return parsed.map((entry) => {
1647
- if (!entry.metadata.success) throw new Error("User message has invalid metadata");
1648
- const metadata = entry.metadata.data;
1649
- const actor = {
1650
- platform: "web",
1651
- userId: metadata.authorUserId,
1652
- email: metadata.authorEmail.trim().toLowerCase(),
1653
- ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
1654
- ...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
1655
- };
1656
- return {
1657
- actor,
1658
- author: {
1659
- email: actor.email,
1660
- ...actor.fullName ? { fullName: actor.fullName } : void 0,
1661
- userId: actor.userId,
1662
- ...actor.userName ? { userName: actor.userName } : void 0
1663
- },
1664
- message: entry.message,
1665
- source: createWebSource(entry.message.conversationId)
1666
- };
1667
- });
1668
- }
1669
- function parseEventMessages(messages) {
1670
- if (messages.length === 0) return [];
1671
- if (!messages.every((message) => message.source === "event" && isEventMailboxMetadata(message.input.metadata))) return [];
1672
- return messages.map((message) => {
1673
- if (!isEventMailboxMetadata(message.input.metadata)) throw new Error("Event has invalid metadata");
1674
- return {
1675
- actor: EVENT_SYSTEM_ACTOR,
1676
- author: EVENT_MESSAGE_AUTHOR,
1677
- message,
1678
- source: createEventSource({
1679
- eventKey: message.input.metadata.event.eventKey,
1680
- eventType: message.input.metadata.event.eventType,
1681
- identifier: message.input.metadata.event.identifier,
1682
- namespace: message.input.metadata.event.namespace
1683
- })
1684
- };
1685
- });
1686
- }
1687
- /**
1688
- * Select web or event work from new mailbox input or a saved Turn.
1689
- * Saved Actor data identifies a resumed event Turn.
1690
- */
1691
- async function resolveMailboxTurnWork(context) {
1692
- const batch = parseWebMessages(context.attempt.messages);
1693
- if (batch.length > 0) return {
1694
- kind: "mailbox",
1695
- batch
1696
- };
1697
- const resourceBatch = parseEventMessages(context.attempt.messages);
1698
- if (resourceBatch.length > 0) return {
1699
- kind: "mailbox",
1700
- batch: resourceBatch
1701
- };
1702
- if (context.attempt.messages.length > 0) return;
1703
- const turnId = await getActiveMailboxTurnId(context.conversationId);
1704
- return turnId ? {
1705
- kind: "resume",
1706
- turnId
1707
- } : void 0;
1708
- }
1709
- //#endregion
1710
1576
  //#region src/chat/conversations/stop.ts
1711
1577
  /** Stop the current Conversation Turn and wake an idle resume when needed. */
1712
1578
  async function stopConversationTurn(args) {
@@ -4257,17 +4123,6 @@ async function resolveDestinationVisibility(args) {
4257
4123
  }
4258
4124
  //#endregion
4259
4125
  //#region src/chat/providers/slack/input.ts
4260
- /**
4261
- * Return a stable key for one steering message. Resolved attachments may change
4262
- * when Junior retries a mailbox delivery, so only the message time and text
4263
- * form the key.
4264
- */
4265
- function steeringMessageKey(message) {
4266
- if (message.role !== "user") return;
4267
- const first = Array.isArray(message.content) ? message.content[0] : void 0;
4268
- const text = first && typeof first === "object" && "text" in first ? String(first.text ?? "") : "";
4269
- return `${message.timestamp}:${text}`;
4270
- }
4271
4126
  function renderRecentThreadMessageLines(conversationContext, messages) {
4272
4127
  const messagesForContext = messages.filter((queued) => {
4273
4128
  if (queued.explicitMention) return false;
@@ -4362,11 +4217,7 @@ async function saveSteeringMessages(args) {
4362
4217
  if (!lock) return false;
4363
4218
  try {
4364
4219
  const projection = await loadConversationProjection({ conversationId: args.conversationId });
4365
- const savedKeys = new Set(projection.messages.map(steeringMessageKey).filter((key) => key !== void 0));
4366
- const missing = args.messages.filter((entry) => {
4367
- const key = steeringMessageKey(entry.message);
4368
- return key === void 0 || !savedKeys.has(key);
4369
- });
4220
+ const missing = withoutSavedSteeringMessages(projection.messages, args.messages, (entry) => entry.message);
4370
4221
  if (missing.length === 0) return true;
4371
4222
  await commitMessages({
4372
4223
  conversationId: args.conversationId,
@@ -4901,11 +4752,7 @@ function createSlackTurn(deps) {
4901
4752
  throw new TurnInputDeferredError();
4902
4753
  }
4903
4754
  if (batchedSteeringMessages.length > 0) {
4904
- const presentKeys = new Set((piMessages ?? []).map(steeringMessageKey).filter((key) => key !== void 0));
4905
- const newSteeringMessages = batchedSteeringMessages.map((entry) => entry.message).filter((batchedMessage) => {
4906
- const key = steeringMessageKey(batchedMessage);
4907
- return key === void 0 || !presentKeys.has(key);
4908
- });
4755
+ const newSteeringMessages = withoutSavedSteeringMessages(piMessages ?? [], batchedSteeringMessages.map((entry) => entry.message), (message) => message);
4909
4756
  if (newSteeringMessages.length > 0) piMessages = [...piMessages ?? [], ...newSteeringMessages];
4910
4757
  }
4911
4758
  status.update();
@@ -6710,12 +6557,6 @@ async function commitAssistantMessage(args) {
6710
6557
  }
6711
6558
  }
6712
6559
  //#endregion
6713
- //#region src/chat/task-execution/mailbox-input.ts
6714
- /** Join non-empty mailbox Message text for one Turn. */
6715
- function joinMailboxText(messages) {
6716
- return messages.map((message) => message.input.text.trim()).filter(Boolean).join("\n\n");
6717
- }
6718
- //#endregion
6719
6560
  //#region src/chat/conversations/destination.ts
6720
6561
  function requireLocalDestination(conversationId) {
6721
6562
  const parsed = localDestinationSchema.safeParse({
@@ -6738,10 +6579,6 @@ function resolveConversationDestination(args) {
6738
6579
  //#endregion
6739
6580
  //#region src/chat/task-execution/conversation-turn.ts
6740
6581
  /** Run a mailbox Turn and store its assistant Messages. */
6741
- /** Extra debounce time added per additional event already batched. */
6742
- const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
6743
- /** Upper bound on the debounce window regardless of batch size. */
6744
- const EVENT_MAX_WAIT_MS = 6e4;
6745
6582
  function stableHex$1(...parts) {
6746
6583
  return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 24);
6747
6584
  }
@@ -6805,15 +6642,11 @@ async function completeCancelledConversationTurn(args) {
6805
6642
  function createConversationTurnWorker(agentRunner, deliverMessage) {
6806
6643
  return async (context, resolved) => {
6807
6644
  if (resolved.kind === "mailbox") {
6808
- const first = resolved.batch[0];
6809
- if (isEventMailboxMetadata(first.message.input.metadata)) {
6810
- const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (resolved.batch.length - 1));
6811
- const delayMs = first.message.receivedAtMs + waitMs - Date.now();
6812
- if (delayMs > 0) return {
6813
- status: "deferred",
6814
- delayMs
6815
- };
6816
- }
6645
+ const delayMs = getEventBatchDelayMs(resolved.batch.map((entry) => entry.message));
6646
+ if (delayMs > 0) return {
6647
+ status: "deferred",
6648
+ delayMs
6649
+ };
6817
6650
  }
6818
6651
  const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
6819
6652
  const isResume = resolved.kind === "resume";
@@ -7310,11 +7143,13 @@ function createConversationWork(options) {
7310
7143
  throw new Error(`Conversation ${context.conversationId} has a ${destination.platform} destination but no matching conversation worker`);
7311
7144
  };
7312
7145
  const run = async (context) => {
7313
- const childResults = await startAgentInvocationsForChildResults(context, {
7146
+ const skipped = await skipInputBeforeConversationStop(context);
7147
+ if (skipped) return skipped;
7148
+ const childInput = await startAgentInvocationsForChildInput(context, {
7314
7149
  queue: options.queue,
7315
7150
  state: options.state
7316
7151
  });
7317
- if (childResults) return childResults;
7152
+ if (childInput) return childInput;
7318
7153
  const mailboxTurn = await resolveMailboxTurnWork(context);
7319
7154
  if (mailboxTurn) return await conversationTurnWorker(context, await withAgentInvocationResultActors(mailboxTurn));
7320
7155
  const invocationId = await resolveAgentInvocationId(context);
@@ -7549,4 +7384,4 @@ async function appendAndEnqueueWebMessage(input, options) {
7549
7384
  };
7550
7385
  }
7551
7386
  //#endregion
7552
- export { withNormalizedThreadId as A, enqueueAgentDispatch as B, buildSlackInboundMessage as C, isSlackMessageStopped as D, verifySlackSignature as E, startProcessingReaction as F, readHealthReport as H, parseContent as I, renderSlackObjectCard as L, getAuthPausedConversationTurnId as M, legacyWebMailboxMetadataSchema as N, stopSlackThread as O, THREAD_OPTOUT_ACK as P, createVercelAttachmentStorage as R, recordSkippedConversationMessage as S, runWithSlackInstallation as T, GET as V, readViewerAutomationRuns as _, recordWebConversationActivity as a, readViewerAutomations as b, createProductionSlackWebhookServices as c, resolveSlackConversationContextFromThreadId as d, createSlackWebApiStatusSender as f, readViewerAutomationExecutions as g, readConversationSourceTask as h, createConversationId as i, stopConversationTurn as j, normalizeIncomingSlackThreadId as k, getProductionSlackAdapter as l, deleteViewerTask as m, conversationTurnIdForMessage as n, webActorFromEmail as o, ViewerTaskNotFoundError as p, createAndEnqueueConversation as r, createProductionConversationWorkOptions as s, appendAndEnqueueWebMessage as t, formatSlackConversationRedactedLabel as u, readViewerAutomationSummary as v, clearSlackPendingReactions as w, resolveViewerTaskCandidate as x, readViewerAutomationVersions as y, AGENT_DISPATCH_MAX_AGE_MS as z };
7387
+ export { withNormalizedThreadId as A, readHealthReport as B, buildSlackInboundMessage as C, isSlackMessageStopped as D, verifySlackSignature as E, renderSlackObjectCard as F, createVercelAttachmentStorage as I, AGENT_DISPATCH_MAX_AGE_MS as L, THREAD_OPTOUT_ACK as M, startProcessingReaction as N, stopSlackThread as O, parseContent as P, enqueueAgentDispatch as R, recordSkippedConversationMessage as S, runWithSlackInstallation as T, readViewerAutomationRuns as _, recordWebConversationActivity as a, readViewerAutomations as b, createProductionSlackWebhookServices as c, resolveSlackConversationContextFromThreadId as d, createSlackWebApiStatusSender as f, readViewerAutomationExecutions as g, readConversationSourceTask as h, createConversationId as i, stopConversationTurn as j, normalizeIncomingSlackThreadId as k, getProductionSlackAdapter as l, deleteViewerTask as m, conversationTurnIdForMessage as n, webActorFromEmail as o, ViewerTaskNotFoundError as p, createAndEnqueueConversation as r, createProductionConversationWorkOptions as s, appendAndEnqueueWebMessage as t, formatSlackConversationRedactedLabel as u, readViewerAutomationSummary as v, clearSlackPendingReactions as w, resolveViewerTaskCandidate as x, readViewerAutomationVersions as y, GET as z };