@sentry/junior 0.297.0 → 0.299.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 (94) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-DFnmLmfn.js → adapter-AgCNqqsG.js} +49 -133
  3. package/dist/{admin-tmGIw4KS.js → admin-1VwEXztm.js} +2 -2
  4. package/dist/{agent-runner-CneTquAE.js → agent-runner-Ciet8_nn.js} +1067 -1353
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +125 -43
  9. package/dist/{app-BJojZ7HL.d.ts → app--ky-Eu33.d.ts} +6 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +126 -299
  12. package/dist/{automation-BrP6ImrC.js → automation-M3RFJUBf.js} +1 -1
  13. package/dist/{background-compaction-queue-CwfJy3Cd.js → background-compaction-queue-CnimvRdk.js} +4 -4
  14. package/dist/{briefs-uFTuhMqA.js → briefs-CwzvgdCa.js} +4 -4
  15. package/dist/{catalog-runtime-0kuQqYL4.js → catalog-runtime-DaBaHY7u.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-Dj9M_nqB.js → config-CAXIpWQb.js} +80 -6
  24. package/dist/{connections-B96JUM5o.js → connections-Dy0hPdUq.js} +6 -6
  25. package/dist/continue-in-slack-DIOjFj76.js +176 -0
  26. package/dist/{conversation-CvcBU1z2.js → conversation-fCWD9Az3.js} +73 -13
  27. package/dist/{conversation-feed-BSMlGZnS.js → conversation-feed-BPK8vkkZ.js} +88 -3
  28. package/dist/{conversation-privacy-DI29jbZV.js → conversation-privacy-DUgtRkf8.js} +1 -1
  29. package/dist/{conversation-turn-CZWBr091.js → conversation-turn-DkJB6yMF.js} +85 -68
  30. package/dist/{credential-sync-Blhx4_xf.js → credential-sync-RX24Y8aY.js} +18 -18
  31. package/dist/{db-CrtyFRz7.d.ts → db-B07FtU9g.d.ts} +1 -1
  32. package/dist/{db-Br0tfAo7.js → db-COYOGzYS.js} +171 -12
  33. package/dist/{executor-BMPipFVA.js → executor-BWmAgSyi.js} +40 -11
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/lineage-D-5jm_oj.js +37 -0
  37. package/dist/{logging-CQjlDQYX.js → logging-DPLEa8Bn.js} +1 -1
  38. package/dist/media-BAHvgkok.js +85 -0
  39. package/dist/{message-BOZEIuxy.js → message-BIHR1yRk.js} +9 -10
  40. package/dist/model-input-BPZYH8Nd.js +82 -0
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +17 -9
  43. package/dist/{oauth-callback-server-V_DuMuNX.js → oauth-callback-server-R7qvSzFG.js} +2 -2
  44. package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
  45. package/dist/{projection-B08mfi0u.js → projection-DEdP1q6f.js} +261 -36
  46. package/dist/{prompt-BlutWLNt.js → prompt-4M98h_tC.js} +4 -4
  47. package/dist/{registry-BDWgCJDf.js → registry-BTKmKM-r.js} +3 -3
  48. package/dist/{resolve-2Z_o_SsI.js → resolve-B8hXNVZ3.js} +3 -3
  49. package/dist/{result-CAujiaci.js → result-g-XAaOj6.js} +158 -69
  50. package/dist/{runner-D2Chc02N.js → runner-BlPSA5A8.js} +9 -9
  51. package/dist/{sandbox-egress-signals-CFoJduFj.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
  52. package/dist/{schema-Bqa5NbcP.js → schema-BNnY_trV.js} +47 -7
  53. package/dist/{schema-Ce2XCS7O.d.ts → schema-DbuWR-DN.d.ts} +663 -346
  54. package/dist/{service-account-C9kRQEb_.js → service-account-9OLNQMyz.js} +4 -4
  55. package/dist/{service-account-CERfXEVU.js → service-account-BYGZ08DQ.js} +3 -3
  56. package/dist/session-stop-2XJrcNCy.js +3356 -0
  57. package/dist/{skills-B0m1nZ_j.js → skills-DpBQoeHV.js} +3 -3
  58. package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
  59. package/dist/spawn-09GssFod.js +73 -0
  60. package/dist/state-Cufq0_rH.js +132 -0
  61. package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
  62. package/dist/{stop-BCH9VNGf.js → stop-U7iUrR1g.js} +6011 -5773
  63. package/dist/{store-B59rOYbS.js → store-BHiaHCQu.js} +24 -4
  64. package/dist/{store-m5bmdmsP.js → store-CSgUTMdv.js} +10 -10
  65. package/dist/{task-queue-N0kuCknH.js → task-queue-bMNq0clp.js} +4 -4
  66. package/dist/{task-runner-COOwR8qm.js → task-runner-B__rxwxU.js} +10 -10
  67. package/dist/{thread-context-Cd44z_W5.js → thread-context-d0ceWbVT.js} +18 -18
  68. package/dist/{turn-session-routing-BlCtVFRN.js → turn-session-routing-BVZHBFCF.js} +5 -5
  69. package/dist/turn-user-message-BEw7acTP.js +355 -0
  70. package/dist/users-BK3dbxZL.js +424 -0
  71. package/dist/{validation-Ba2OcUse.js → validation-BDVJjO2E.js} +1 -1
  72. package/dist/{version-KNDzIAh6.js → version-DQgZoQ3D.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-BPpuN2f9.js → viewer-CAWfFo29.js} +25 -54
  75. package/dist/{warmup-Bskrwmk1.js → warmup-9ySPacF9.js} +1137 -143
  76. package/dist/{worker-B1skZlit.js → worker-D8jJO-WO.js} +8 -7
  77. package/migrations/0104_code_change_draft.sql +1 -0
  78. package/migrations/0105_attachment_uploads.sql +14 -0
  79. package/migrations/0106_conversation_agent_config.sql +1 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +4 -4
  85. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  86. package/dist/locks-D-0h111u.js +0 -48
  87. package/dist/notification-gusCgdQ6.js +0 -1284
  88. package/dist/prompt-input-Dxn8cDC0.js +0 -1424
  89. package/dist/session-stop-B-I1rAS1.js +0 -181
  90. package/dist/spawn-CwMjRRtn.js +0 -80
  91. package/dist/turn-cancel-DDu8TOwt.js +0 -201
  92. package/dist/turn-user-message-ygLG3ylQ.js +0 -641
  93. package/dist/turn-wake-DmQec4AG.js +0 -161
  94. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,6 +1,7 @@
1
- import { Bt as requestAnotherSlice$1, Ct as deadLetterAttempt$1, Dt as getConversationWorkState$1, Et as getConversation$1, Ht as startConversationWork$1, It as recordAttemptFailure$1, Lt as recordConversationRetry$1, Mt as listActiveConversationIds$1, Nt as markConversationWorkEnqueued$1, Rt as releaseConversationWork$1, Tt as dropPendingMessages$1, Ut as steerWebPendingMessages$1, Vt as requestConversationWork$1, Wt as stopConversationWork$1, _t as claimInboundMessage$1, bt as completeConversationStop$1, dt as ackMessages$1, ft as appendExclusiveInboundMessage, gt as checkInConversationWork$1, ht as cancelHumanFacingPendingMessages$1, kt as hasRunnableConversationWork, mt as beginConversationResume$1, pt as appendInboundMessage, vt as clearConsumedConversationWake$1, wt as drainConversationMailbox$1, xt as completeConversationWork$1, yt as clearExpiredConversationLease$1, zt as releaseInboundMessage } from "./projection-B08mfi0u.js";
2
- import { a as getConversationStore } from "./db-Br0tfAo7.js";
3
- import "./background-compaction-queue-CwfJy3Cd.js";
1
+ import { At as getConversationWorkStates$1, Bt as recordConversationRetry$1, Dt as dropPendingMessages$1, Et as drainConversationMailbox$1, Ft as listActiveConversationIds$1, Gt as startConversationWork$1, Ht as releaseInboundMessage, It as markConversationWorkEnqueued$1, Jt as takeDeferredConversationMove, Kt as steerWebPendingMessages$1, Mt as hasRunnableConversationWork, Ot as getConversation$1, St as completeConversationWork$1, Ut as requestAnotherSlice$1, Vt as releaseConversationWork$1, Wt as requestConversationWork$1, _t as checkInConversationWork$1, bt as clearExpiredConversationLease$1, ft as ackMessages$1, gt as cancelHumanFacingPendingMessages$1, ht as beginConversationResume$1, kt as getConversationWorkState$1, mt as appendInboundMessage, pt as appendExclusiveInboundMessage, qt as stopConversationWork$1, vt as claimInboundMessage$1, wt as deadLetterAttempt$1, xt as completeConversationStop$1, yt as clearConsumedConversationWake$1, zt as recordAttemptFailure$1 } from "./projection-DEdP1q6f.js";
2
+ import { p as logException } from "./logging-DPLEa8Bn.js";
3
+ import { a as getConversationStore } from "./db-COYOGzYS.js";
4
+ import "./background-compaction-queue-CnimvRdk.js";
4
5
  // src/chat/task-execution/store.ts
5
6
  function metadataStore(options) {
6
7
  return options.conversationStore ?? getConversationStore();
@@ -49,6 +50,10 @@ async function getConversation(args) {
49
50
  async function getConversationWorkState(args) {
50
51
  return await getConversationWorkState$1(args);
51
52
  }
53
+ /** Return the persisted work records of several Conversations in one read. */
54
+ async function getConversationWorkStates(conversationIds) {
55
+ return await getConversationWorkStates$1(conversationIds);
56
+ }
52
57
  /** Count one failed conversation execution and persist its terminal retry state. */
53
58
  async function recordConversationRetry(args) {
54
59
  const result = await recordConversationRetry$1(args);
@@ -288,8 +293,23 @@ async function releaseConversationWork(args) {
288
293
  async function completeConversationWork(args) {
289
294
  const result = await completeConversationWork$1(args);
290
295
  await recordExecutionMetadata(args);
296
+ if (result !== "lost_lease") await runDeferredMove(args);
291
297
  return result;
292
298
  }
299
+ /**
300
+ * Run the Slack "Continue here" click that waited for this Run to end. Its
301
+ * failure is logged here, so it never fails the Run that already finished.
302
+ */
303
+ async function runDeferredMove(args) {
304
+ const move = await takeDeferredConversationMove(args);
305
+ if (move === void 0) return;
306
+ try {
307
+ const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-BcDIWo67.js").then((n) => n.r);
308
+ await continueDeferredSlackClick(move, args.getSlackAdapter);
309
+ } catch (error) {
310
+ logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
311
+ }
312
+ }
293
313
  /** Record one failed delivery attempt and dead-letter messages at their limit. */
294
314
  async function recordAttemptFailure(args) {
295
315
  const result = await recordAttemptFailure$1(args);
@@ -312,4 +332,4 @@ async function clearExpiredConversationLease(args) {
312
332
  async function listActiveConversationIds(args = {}) {
313
333
  return await listActiveConversationIds$1(args);
314
334
  }
315
- export { requestConversationWork as C, stopConversationWork as E, requestAnotherSlice as S, steerWebPendingMessages as T, getConversationWorkState as _, cancelHumanFacingPendingMessages as a, recordConversationRetry as b, clearConsumedConversationWake as c, completeConversationWork as d, deadLetterAttempt as f, getConversation as g, ensureConversationWake as h, beginConversationResume as i, clearExpiredConversationLease as l, dropPendingMessages as m, appendAndEnqueueExclusiveInboundMessage as n, checkInConversationWork as o, drainConversationMailbox as p, appendAndEnqueueInboundMessage as r, claimInboundMessage as s, ackMessages as t, completeConversationStop as u, listActiveConversationIds as v, startConversationWork as w, releaseConversationWork as x, recordAttemptFailure as y };
335
+ export { requestAnotherSlice as C, stopConversationWork as D, steerWebPendingMessages as E, releaseConversationWork as S, startConversationWork as T, getConversationWorkState as _, cancelHumanFacingPendingMessages as a, recordAttemptFailure as b, clearConsumedConversationWake as c, completeConversationWork as d, deadLetterAttempt as f, getConversation as g, ensureConversationWake as h, beginConversationResume as i, clearExpiredConversationLease as l, dropPendingMessages as m, appendAndEnqueueExclusiveInboundMessage as n, checkInConversationWork as o, drainConversationMailbox as p, appendAndEnqueueInboundMessage as r, claimInboundMessage as s, ackMessages as t, completeConversationStop as u, getConversationWorkStates as v, requestConversationWork as w, recordConversationRetry as x, listActiveConversationIds as y };
@@ -1,14 +1,14 @@
1
- import { $i as escapeSlackMrkdwnText, Ci as getDashboardTaskLink, Ei as ToolInputError, ca as openSlackDirectMessage, da as postSlackMessage, ea as formatSlackLink, vi as JUNIOR_THREAD_STATE_TTL_MS, w as fallbackShortTitle } from "./projection-B08mfi0u.js";
2
- import { n as botConfig } from "./config-Dj9M_nqB.js";
3
- import { _ as runBestEffort, h as logWarn } from "./logging-CQjlDQYX.js";
4
- import { J as agentTurnTotalTokens, o as getDb, q as agentTurnCostUsd } from "./db-Br0tfAo7.js";
5
- import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-BMPipFVA.js";
6
- import { h as credentialSubjectSchema } from "./registry-BDWgCJDf.js";
7
- import { a as getStateAdapter } from "./state-DFnmLmfn.js";
8
- import { u as automationEventCatalog, v as registeredEventTriggerProblems } from "./turn-session-routing-BlCtVFRN.js";
9
- import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-BrP6ImrC.js";
10
- import { createHash } from "node:crypto";
1
+ import { Di as JUNIOR_THREAD_STATE_TTL_MS, Pi as getDashboardTaskLink, da as escapeSlackMrkdwnText, do as ToolInputError, fa as formatSlackLink, w as fallbackShortTitle, wa as postSlackMessage, xa as openSlackDirectMessage } from "./projection-DEdP1q6f.js";
2
+ import { n as botConfig } from "./config-CAXIpWQb.js";
3
+ import { _ as runBestEffort, h as logWarn } from "./logging-DPLEa8Bn.js";
4
+ import { X as agentTurnTotalTokens, Y as agentTurnCostUsd, o as getDb } from "./db-COYOGzYS.js";
5
+ import { d as juniorAutomationVersions, f as juniorAutomations, j as juniorConversations, u as juniorAutomationRuns } from "./executor-BWmAgSyi.js";
6
+ import { r as getStateAdapter } from "./adapter-AgCNqqsG.js";
7
+ import { h as credentialSubjectSchema } from "./registry-BTKmKM-r.js";
8
+ import { u as automationEventCatalog, v as registeredEventTriggerProblems } from "./turn-session-routing-BVZHBFCF.js";
9
+ import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-M3RFJUBf.js";
11
10
  import * as z from "zod";
11
+ import { createHash } from "node:crypto";
12
12
  import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
13
13
  import { destinationSchema, destinationVisibilitySchema, eventMatches, isSlackDestination, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
14
14
  // src/chat/automations/revision.ts
@@ -1,7 +1,7 @@
1
- import { h as logWarn } from "./logging-CQjlDQYX.js";
2
- import { C as queueCallback, S as verifyQueueMessage, T as getQueueProvider, b as QUEUE_SIGNATURE_MAX_AGE_MS, x as signQueueMessage } from "./background-compaction-queue-CwfJy3Cd.js";
3
- import { createHash } from "node:crypto";
1
+ import { h as logWarn } from "./logging-DPLEa8Bn.js";
2
+ import { C as queueCallback, S as verifyQueueMessage, T as getQueueProvider, b as QUEUE_SIGNATURE_MAX_AGE_MS, x as signQueueMessage } from "./background-compaction-queue-CnimvRdk.js";
4
3
  import * as z from "zod";
4
+ import { createHash } from "node:crypto";
5
5
  // src/chat/plugins/task-queue.ts
6
6
  /**
7
7
  * Delivery for plugin-registered tasks.
@@ -60,7 +60,7 @@ function pluginTaskCallback() {
60
60
  maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
61
61
  onRejected: logPluginTaskQueueMessageRejected,
62
62
  run: async (message) => {
63
- const { processPluginTask } = await import("./task-runner-COOwR8qm.js").then((n) => n.r);
63
+ const { processPluginTask } = await import("./task-runner-B__rxwxU.js").then((n) => n.r);
64
64
  await processPluginTask(message);
65
65
  },
66
66
  topic: PLUGIN_TASK_QUEUE_TOPIC,
@@ -1,14 +1,14 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { $a as createPluginModel, Co as createPluginConversationEvents, Di as createPluginState, Dn as normalizeToolNameFromResult, En as isToolResultMessage, Qa as createPluginEmbedder, Tn as isToolResultError, Zo as createPluginCache, ar as coreTaskRegistrations, do as createPluginModelCostRecorder, fo as createPluginLogger, gn as getPiMessageRole, kn as stripRuntimeTurnContext, nr as getPlugins, ot as getTurnRecord, v as hydrateConversationMessages, xn as instructionTextForProjection } from "./projection-B08mfi0u.js";
3
- import { E as withSpan } from "./logging-CQjlDQYX.js";
4
- import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
5
- import { a as getConversationStore, o as getDb } from "./db-Br0tfAo7.js";
6
- import { v as sameActorIdentity } from "./media-BepyEUNm.js";
7
- import { i as readActorIdentity } from "./viewer-BPpuN2f9.js";
8
- import { a as getStateAdapter } from "./state-DFnmLmfn.js";
9
- import { a as getPersistedThreadState, c as coerceThreadConversationState, t as resolveConversationRouting } from "./turn-session-routing-BlCtVFRN.js";
10
- import { c as getDispatchRecord } from "./store-m5bmdmsP.js";
11
- import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-N0kuCknH.js";
2
+ import { Dn as instructionTextForProjection, Do as createPluginModelCostRecorder, In as stripRuntimeTurnContext, Mn as isToolResultMessage, Oo as createPluginLogger, Pn as normalizeToolNameFromResult, Ri as createPluginState, Sn as getPiMessageRole, dr as getPlugins, ho as createPluginModel, jn as isToolResultError, mo as createPluginEmbedder, mr as coreTaskRegistrations, ps as createPluginCache, st as getTurnRecord, v as hydrateConversationMessages, zo as createPluginConversationEvents } from "./projection-DEdP1q6f.js";
3
+ import { E as withSpan } from "./logging-DPLEa8Bn.js";
4
+ import { v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
5
+ import { a as getConversationStore, o as getDb } from "./db-COYOGzYS.js";
6
+ import { m as sameActorIdentity } from "./history-IjdmO_r6.js";
7
+ import { r as getStateAdapter } from "./adapter-AgCNqqsG.js";
8
+ import { i as readActorIdentity } from "./viewer-CAWfFo29.js";
9
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, t as resolveConversationRouting } from "./turn-session-routing-BVZHBFCF.js";
10
+ import { c as getDispatchRecord } from "./store-CSgUTMdv.js";
11
+ import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-bMNq0clp.js";
12
12
  import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
13
13
  // src/chat/plugins/task-runner.ts
14
14
  /**
@@ -1,10 +1,11 @@
1
- import { E as buildConversationContext, Uo as listConversationAnnotations, X as clearPendingAuth, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-B08mfi0u.js";
2
- import { H as findProviderError, U as getProviderErrorAttributes, W as getProviderErrorUserMessage, z as ProviderError } from "./config-Dj9M_nqB.js";
3
- import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CQjlDQYX.js";
4
- import { o as getDb, r as getConversationEventStore } from "./db-Br0tfAo7.js";
5
- import { I as readMessageCardRefs, L as removedCardSchema, R as resolveMessageCards } from "./conversation-CvcBU1z2.js";
6
- import { dt as parseAgentReplyMessageId, ft as parseTurnReplyMessageId, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, rt as getAgentInvocationTurnId, ut as parseAgentInvocationResultMessageId, w as getAgentInvocation } from "./turn-user-message-ygLG3ylQ.js";
7
- import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-BlCtVFRN.js";
1
+ import { E as buildConversationContext, X as clearPendingAuth, as as listConversationAnnotations, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-DEdP1q6f.js";
2
+ import { H as findProviderError, U as getProviderErrorAttributes, W as getProviderErrorUserMessage, z as ProviderError } from "./config-CAXIpWQb.js";
3
+ import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-DPLEa8Bn.js";
4
+ import { o as getDb, r as getConversationEventStore } from "./db-COYOGzYS.js";
5
+ import { H as removedCardSchema, U as resolveMessageCards, V as readMessageCardRefs } from "./conversation-fCWD9Az3.js";
6
+ import { S as listChildMessages, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, x as isAgentInvocationResult } from "./turn-user-message-BEw7acTP.js";
7
+ import { _ as getConversationWorkState } from "./store-BHiaHCQu.js";
8
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-BVZHBFCF.js";
8
9
  // src/chat/conversations/pending-cards.ts
9
10
  /**
10
11
  * Add the cards that tool results selected since the last visible assistant
@@ -42,17 +43,16 @@ async function selectTurnCards(conversationId, selection, beforeSeq) {
42
43
  * Add the cards of child agents whose replies or results started this Turn.
43
44
  * A child cannot reply to people, so its parent's reply delivers its cards.
44
45
  */
45
- async function selectChildResultCards(inputMessageIds, selection) {
46
+ async function selectChildResultCards(conversationId, inputMessageIds, selection) {
47
+ if (inputMessageIds.length === 0) return;
46
48
  const events = getConversationEventStore();
47
- for (const messageId of [...inputMessageIds].reverse()) {
48
- const replyInvocationId = parseAgentReplyMessageId(messageId);
49
- const invocationId = replyInvocationId ?? parseAgentInvocationResultMessageId(messageId);
50
- const invocation = invocationId ? await getAgentInvocation(invocationId) : void 0;
51
- if (!invocation) continue;
52
- const turnId = parseTurnReplyMessageId(messageId) ?? getAgentInvocationTurnId(invocation.invocationId);
53
- const terminal = await events.loadByIdempotencyKey(invocation.childConversationId, `turn:${turnId}:terminal`);
54
- if (!terminal && !replyInvocationId) continue;
55
- await selectTurnCards(invocation.childConversationId, selection, terminal?.seq);
49
+ const execution = (await getConversationWorkState({ conversationId }))?.execution;
50
+ const messages = await listChildMessages(inputMessageIds, execution?.messageSenders ?? {});
51
+ for (const message of messages.reverse()) {
52
+ const { conversationId: childConversationId, turnId } = message.sender;
53
+ const terminal = await events.loadByIdempotencyKey(childConversationId, `turn:${turnId}:terminal`);
54
+ if (!terminal && isAgentInvocationResult(message)) continue;
55
+ await selectTurnCards(childConversationId, selection, terminal?.seq);
56
56
  }
57
57
  }
58
58
  /** Select undelivered cards and load their latest saved facts. */
@@ -61,7 +61,7 @@ async function loadPendingMessageCards(conversationId) {
61
61
  cards: /* @__PURE__ */ new Map(),
62
62
  deleted: /* @__PURE__ */ new Set()
63
63
  };
64
- await selectChildResultCards(await selectTurnCards(conversationId, selection), selection);
64
+ await selectChildResultCards(conversationId, await selectTurnCards(conversationId, selection), selection);
65
65
  if (selection.cards.size === 0) return [];
66
66
  return resolveMessageCards([...selection.cards.values()].reverse(), await listConversationAnnotations(getDb(), conversationId));
67
67
  }
@@ -1,7 +1,7 @@
1
- import { Ei as ToolInputError, Qo as createDurableLocationConfigurationService, b as persistConversationMessages, vi as JUNIOR_THREAD_STATE_TTL_MS } from "./projection-B08mfi0u.js";
2
- import { G as isRecord, K as toOptionalNumber, q as toOptionalString } from "./logging-CQjlDQYX.js";
3
- import { o as getDb } from "./db-Br0tfAo7.js";
4
- import { a as getStateAdapter } from "./state-DFnmLmfn.js";
1
+ import { Di as JUNIOR_THREAD_STATE_TTL_MS, b as persistConversationMessages, do as ToolInputError, ms as createDurableLocationConfigurationService } from "./projection-DEdP1q6f.js";
2
+ import { G as isRecord, K as toOptionalNumber, q as toOptionalString } from "./logging-DPLEa8Bn.js";
3
+ import { o as getDb } from "./db-COYOGzYS.js";
4
+ import { r as getStateAdapter } from "./adapter-AgCNqqsG.js";
5
5
  import * as z from "zod";
6
6
  import { agentEventMatchSchema, anyResourceMatchFields, describeEventTrigger, eventTriggerChoices, eventTriggerProblems, normalizeEventIdentifier, normalizeEventMatch } from "@sentry/junior-plugin-api";
7
7
  // src/chat/events/catalog.ts
@@ -338,7 +338,7 @@ function slackSourceForDestination(args) {
338
338
  * Reads parent Conversations when this Conversation has no Destination.
339
339
  */
340
340
  async function resolveConversationRouting(args) {
341
- const conversationStore = args.conversationStore ?? (await import("./db-Br0tfAo7.js").then((n) => n.n)).getConversationStore();
341
+ const conversationStore = args.conversationStore ?? (await import("./db-COYOGzYS.js").then((n) => n.n)).getConversationStore();
342
342
  const chain = await loadConversationChain(args.conversationId, conversationStore);
343
343
  let destination;
344
344
  let source;
@@ -0,0 +1,355 @@
1
+ import { Yt as readInboundMessageSender } from "./projection-DEdP1q6f.js";
2
+ import { v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
3
+ import { r as getConversationEventStore, s as getSqlExecutor } from "./db-COYOGzYS.js";
4
+ import { g as juniorAgentInvocations } from "./executor-BWmAgSyi.js";
5
+ import { createHash } from "node:crypto";
6
+ import { inArray } from "drizzle-orm";
7
+ // src/chat/state/turn-id.ts
8
+ /** Build a stable turn identifier from a message ID. */
9
+ function buildDeterministicTurnId(messageId) {
10
+ return `turn_${messageId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
11
+ }
12
+ /** Build the stable visible assistant-message identity for one logical turn. */
13
+ function buildDeterministicAssistantMessageId(turnId) {
14
+ return `${turnId}:assistant:1`;
15
+ }
16
+ // src/chat/agent-invocations/ids.ts
17
+ const CREATE_LOCK_PREFIX = "junior:agent_invocation:create";
18
+ /**
19
+ * Return the SQL lock that one parent Conversation takes to start, message,
20
+ * or stop its child agents.
21
+ */
22
+ function getChildAgentLockName(parentConversationId) {
23
+ return `${CREATE_LOCK_PREFIX}:${parentConversationId}`;
24
+ }
25
+ function stableId(prefix, ...parts) {
26
+ return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
27
+ }
28
+ /** Return the stable identity for one retry-safe delegated task. */
29
+ function getAgentInvocationId(parentConversationId, idempotencyKey) {
30
+ return stableId("agent-invocation", parentConversationId, idempotencyKey);
31
+ }
32
+ /** Return the stable child identity for one invocation without a named binding. */
33
+ function getUnnamedAgentConversationId(invocationId) {
34
+ return stableId("agent", invocationId);
35
+ }
36
+ /** Return the stable child identity for one named binding. */
37
+ function getNamedAgentConversationId(parentConversationId, name) {
38
+ return stableId("agent", parentConversationId, name);
39
+ }
40
+ /**
41
+ * Return the stable identity of the agent invocation that gives one child
42
+ * agent result to the child Conversation that started that child agent.
43
+ */
44
+ function getAgentInvocationIdForResult(resultInvocationId) {
45
+ return stableId("agent-invocation", "result", resultInvocationId);
46
+ }
47
+ /**
48
+ * Return the stable identity of the agent invocation that gives one message
49
+ * from a child agent to the child Conversation that started that child agent.
50
+ */
51
+ function getAgentInvocationIdForMessage(messageId) {
52
+ return stableId("agent-invocation", "message", messageId);
53
+ }
54
+ /**
55
+ * Return the stable identity of the agent invocation that gives one batch of
56
+ * watch events to a child Conversation. The first message of the batch names
57
+ * it.
58
+ */
59
+ function getAgentInvocationIdForEvents(messageId) {
60
+ return stableId("agent-invocation", "events", messageId);
61
+ }
62
+ /** Return the stable turn identity advanced by one agent invocation. */
63
+ function getAgentInvocationTurnId(invocationId) {
64
+ return `agent-invocation:${invocationId}`;
65
+ }
66
+ /** Return the stable mailbox identity for one agent invocation. */
67
+ function getAgentInvocationMessageId(invocationId) {
68
+ return `agent-invocation:${invocationId}:input`;
69
+ }
70
+ const REPLY_MESSAGE_PREFIX = "agent-reply:";
71
+ /**
72
+ * Return the parent mailbox identity of one child agent `reply` call.
73
+ * `senderId` is the Agent invocation that sent it, or the child Conversation
74
+ * when no Agent invocation names the child.
75
+ */
76
+ function getAgentReplyMessageId(senderId, toolCallId) {
77
+ return `${REPLY_MESSAGE_PREFIX}${senderId}:${toolCallId}`;
78
+ }
79
+ /**
80
+ * Return the key of the `reply` of one Turn on a child's Conversation loop.
81
+ * Readers take the sender from the message's sender fields, not this key.
82
+ */
83
+ function getTurnReplyKey(turnId, toolCallId) {
84
+ return `${turnId}:${toolCallId}`;
85
+ }
86
+ /** Return the stable parent mailbox identity for one terminal result. */
87
+ function getAgentInvocationResultMessageId(invocationId) {
88
+ return `agent-invocation:${invocationId}:result`;
89
+ }
90
+ // src/chat/agent-invocations/child-message.ts
91
+ /** Mailbox metadata that stores who sent one child reply or result. */
92
+ function childMessageSenderMetadata(sender) {
93
+ return { sender };
94
+ }
95
+ /** Read who sent one child reply or result in a parent's mailbox. */
96
+ async function readChildMessageSender(message) {
97
+ return readInboundMessageSender(message) ?? (await readLegacyChildMessageSenders([message.inboundMessageId])).get(message.inboundMessageId);
98
+ }
99
+ /**
100
+ * List the child replies and results among the ids that reached one
101
+ * mailbox, oldest first, with the sender fields that the mailbox keeps.
102
+ */
103
+ async function listChildMessages(inboundMessageIds, messageSenders) {
104
+ const legacy = await readLegacyChildMessageSenders(inboundMessageIds.filter((id) => !messageSenders[id]));
105
+ return inboundMessageIds.flatMap((inboundMessageId) => {
106
+ const sender = messageSenders[inboundMessageId] ?? legacy.get(inboundMessageId);
107
+ return sender ? [{
108
+ inboundMessageId,
109
+ sender
110
+ }] : [];
111
+ });
112
+ }
113
+ /**
114
+ * Return the Agent invocation whose own Turn sent the message. A Turn on the
115
+ * child's Conversation loop has none, even when the message names the
116
+ * child's newest Agent invocation.
117
+ *
118
+ * TODO(dcramer): Remove with Agent invocation rows (#3060 step 7).
119
+ */
120
+ function ownAgentInvocation(sender) {
121
+ const { agentInvocationId } = sender;
122
+ return agentInvocationId && sender.turnId === getAgentInvocationTurnId(agentInvocationId) ? agentInvocationId : void 0;
123
+ }
124
+ /** Return whether the message is the result of an Agent invocation. */
125
+ function isAgentInvocationResult(message) {
126
+ const agentInvocationId = ownAgentInvocation(message.sender);
127
+ return agentInvocationId !== void 0 && message.inboundMessageId === getAgentInvocationResultMessageId(agentInvocationId);
128
+ }
129
+ /**
130
+ * Return whether one Agent invocation sent a reply to its parent: a message
131
+ * names it as sender and is not its own result.
132
+ */
133
+ function hasAgentInvocationReply(messages, agentInvocationId) {
134
+ return messages.some((message) => message.sender.agentInvocationId === agentInvocationId && !isAgentInvocationResult(message));
135
+ }
136
+ const LEGACY_REPLY_ID = /^agent-reply:(agent(?:-invocation)?:[0-9a-f]{32}):(?:(turn_[A-Za-z0-9_-]+)(?::|$))?/;
137
+ const LEGACY_RESULT_ID = /^agent-invocation:(agent-invocation:[0-9a-f]{32}):result$/;
138
+ /**
139
+ * Read the sender of child messages that reached a mailbox before senders
140
+ * stored their fields, from their ids.
141
+ *
142
+ * TODO: remove one release after this ships. Step 7 of #3060 deletes it and
143
+ * makes the id a plain generated key.
144
+ */
145
+ async function readLegacyChildMessageSenders(inboundMessageIds) {
146
+ const senders = /* @__PURE__ */ new Map();
147
+ const byAgentInvocation = /* @__PURE__ */ new Map();
148
+ for (const id of inboundMessageIds) {
149
+ const result = LEGACY_RESULT_ID.exec(id);
150
+ const reply = result ? void 0 : LEGACY_REPLY_ID.exec(id);
151
+ const senderId = result?.[1] ?? reply?.[1];
152
+ if (!senderId) continue;
153
+ const turnId = reply?.[2];
154
+ if (senderId.startsWith("agent-invocation:")) byAgentInvocation.set(id, {
155
+ agentInvocationId: senderId,
156
+ turnId
157
+ });
158
+ else if (turnId) senders.set(id, {
159
+ conversationId: senderId,
160
+ turnId
161
+ });
162
+ }
163
+ if (byAgentInvocation.size === 0) return senders;
164
+ const rows = await getSqlExecutor().db().select({
165
+ childConversationId: juniorAgentInvocations.childConversationId,
166
+ invocationId: juniorAgentInvocations.invocationId
167
+ }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, [...new Set([...byAgentInvocation.values()].map((s) => s.agentInvocationId))]));
168
+ const childOf = new Map(rows.map((row) => [row.invocationId, row.childConversationId]));
169
+ for (const [id, { agentInvocationId, turnId }] of byAgentInvocation) {
170
+ const conversationId = childOf.get(agentInvocationId);
171
+ if (!conversationId) continue;
172
+ senders.set(id, {
173
+ agentInvocationId,
174
+ conversationId,
175
+ turnId: turnId ?? getAgentInvocationTurnId(agentInvocationId)
176
+ });
177
+ }
178
+ return senders;
179
+ }
180
+ // src/chat/conversations/turn-lifecycle.ts
181
+ /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
182
+ var ConversationTurnLifecycleService = class {
183
+ events;
184
+ constructor(events) {
185
+ this.events = events;
186
+ }
187
+ /** Record the turn start once after every input message is durable. */
188
+ async start(input) {
189
+ await this.events.append(input.conversationId, [{
190
+ idempotencyKey: `turn:${input.turnId}:started`,
191
+ createdAtMs: input.createdAtMs,
192
+ data: {
193
+ type: "turn_started",
194
+ turnId: input.turnId,
195
+ inputMessageIds: input.inputMessageIds,
196
+ surface: input.surface,
197
+ ...input.threadContextThroughSeq === void 0 ? void 0 : { threadContextThroughSeq: input.threadContextThroughSeq }
198
+ }
199
+ }]);
200
+ }
201
+ /** Return the input message ids that started a Turn, when it started. */
202
+ async loadInputMessageIds(conversationId, turnId) {
203
+ const event = await this.events.loadByIdempotencyKey(conversationId, `turn:${turnId}:started`);
204
+ return event?.data.type === "turn_started" ? event.data.inputMessageIds : void 0;
205
+ }
206
+ /** Record a completion that is not a failure once. */
207
+ async complete(input) {
208
+ await this.events.append(input.conversationId, [{
209
+ idempotencyKey: `turn:${input.turnId}:terminal`,
210
+ createdAtMs: input.createdAtMs,
211
+ data: {
212
+ type: "turn_completed",
213
+ turnId: input.turnId,
214
+ outcome: input.outcome
215
+ }
216
+ }]);
217
+ }
218
+ /** Record a classified failure once. Do not store raw error text. */
219
+ async fail(input) {
220
+ await this.events.append(input.conversationId, [{
221
+ idempotencyKey: `turn:${input.turnId}:terminal`,
222
+ createdAtMs: input.createdAtMs,
223
+ data: {
224
+ type: "turn_failed",
225
+ turnId: input.turnId,
226
+ failureCode: input.failureCode,
227
+ ...input.failureReason ? { failureReason: input.failureReason } : void 0,
228
+ ...input.eventId ? { eventId: input.eventId } : void 0
229
+ }
230
+ }]);
231
+ }
232
+ };
233
+ /** Return the Turn lifecycle that records Conversation events. */
234
+ function getTurnLifecycle() {
235
+ return new ConversationTurnLifecycleService(getConversationEventStore());
236
+ }
237
+ // src/chat/runtime/turn.ts
238
+ /** Classified Slack turn failure carrying the owning Sentry capture outward. */
239
+ var ConversationTurnBoundaryError = class extends Error {
240
+ eventId;
241
+ failureCode;
242
+ constructor(args) {
243
+ super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
244
+ this.name = "ConversationTurnBoundaryError";
245
+ this.eventId = args.eventId;
246
+ this.failureCode = args.failureCode;
247
+ }
248
+ };
249
+ /** Return a classified Slack boundary failure without erasing its cause. */
250
+ function getConversationTurnBoundaryError(error) {
251
+ return error instanceof ConversationTurnBoundaryError ? error : void 0;
252
+ }
253
+ /**
254
+ * Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
255
+ * and the Slack executor raises this at the worker boundary so the lease owner
256
+ * requeues the conversation.
257
+ */
258
+ var CooperativeTurnYieldError = class extends Error {
259
+ code = "cooperative_turn_yield";
260
+ constructor(message = "Agent turn yielded at a safe boundary") {
261
+ super(message);
262
+ this.name = "CooperativeTurnYieldError";
263
+ }
264
+ };
265
+ function isCooperativeTurnYieldError(error) {
266
+ return error instanceof CooperativeTurnYieldError;
267
+ }
268
+ /** Error indicating durable turn input could not be committed by the worker owner. */
269
+ var TurnInputCommitLostError = class extends Error {
270
+ code = "turn_input_commit_lost";
271
+ constructor(message = "Turn input commit lost its durable owner") {
272
+ super(message);
273
+ this.name = "TurnInputCommitLostError";
274
+ }
275
+ };
276
+ /** Return whether an error means the durable worker lost input ownership. */
277
+ function isTurnInputCommitLostError(error) {
278
+ return error instanceof TurnInputCommitLostError;
279
+ }
280
+ /** Error indicating durable turn input should stay pending for a later worker. */
281
+ var TurnInputDeferredError = class extends Error {
282
+ code = "turn_input_deferred";
283
+ constructor(message = "Turn input is deferred until the active resume ends") {
284
+ super(message);
285
+ this.name = "TurnInputDeferredError";
286
+ }
287
+ };
288
+ /** Return whether an error means the durable worker should redeliver input later. */
289
+ function isTurnInputDeferredError(error) {
290
+ return error instanceof TurnInputDeferredError;
291
+ }
292
+ /** Mark a turn as the active turn in conversation state. */
293
+ function startActiveTurn(args) {
294
+ args.conversation.processing.activeTurnId = args.nextTurnId;
295
+ }
296
+ function clearActiveTurn(conversation, sessionId) {
297
+ if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
298
+ }
299
+ /**
300
+ * Close the active turn without marking a Pi session reusable for future
301
+ * history. Use this for auth handoffs and recovery replies that end the live
302
+ * turn but do not produce a completed Pi session.
303
+ */
304
+ function markTurnClosed(args) {
305
+ clearActiveTurn(args.conversation, args.sessionId);
306
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
307
+ }
308
+ /**
309
+ * Mark a turn as completed after its assistant output has been handled.
310
+ */
311
+ function markTurnCompleted(args) {
312
+ clearActiveTurn(args.conversation, args.sessionId);
313
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
314
+ }
315
+ /**
316
+ * Mark a turn as failed when execution or final user-visible reply delivery
317
+ * cannot be completed. If `sessionId` is provided, `activeTurnId` is only
318
+ * cleared when it still matches the failing turn.
319
+ */
320
+ function markTurnFailed(args) {
321
+ clearActiveTurn(args.conversation, args.sessionId);
322
+ args.conversation.processing.lastCompletedAtMs = args.nowMs;
323
+ args.markConversationMessage(args.conversation, args.userMessageId, {
324
+ replied: false,
325
+ skippedReason: "reply failed"
326
+ });
327
+ }
328
+ // src/chat/runtime/turn-user-message.ts
329
+ /** Return the user message for a persisted turn/session, if one exists. */
330
+ function getTurnUserMessage(conversation, sessionId) {
331
+ for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
332
+ const message = conversation.messages[index];
333
+ if (message?.role !== "user") continue;
334
+ if (buildDeterministicTurnId(message.id) === sessionId) return message;
335
+ }
336
+ }
337
+ /** Return the persisted user-message id for a turn/session, if one exists. */
338
+ function getTurnUserMessageId(conversation, sessionId) {
339
+ return getTurnUserMessage(conversation, sessionId)?.id;
340
+ }
341
+ /** Return the Slack timestamp for the user message that a resumed turn acts on. */
342
+ function getTurnUserSlackMessageTs(message) {
343
+ return parseSlackMessageTs(message?.meta?.slackTs);
344
+ }
345
+ /** Rebuild attachment context for a resumed turn from the persisted user message. */
346
+ function getTurnUserReplyAttachmentContext(message) {
347
+ const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
348
+ const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
349
+ const imagesHydrated = message?.meta?.imagesHydrated === true;
350
+ return {
351
+ ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
352
+ ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
353
+ };
354
+ }
355
+ export { getAgentInvocationResultMessageId as A, ownAgentInvocation as C, getAgentInvocationIdForMessage as D, getAgentInvocationIdForEvents as E, getTurnReplyKey as F, getUnnamedAgentConversationId as I, buildDeterministicAssistantMessageId as L, getAgentReplyMessageId as M, getChildAgentLockName as N, getAgentInvocationIdForResult as O, getNamedAgentConversationId as P, buildDeterministicTurnId as R, listChildMessages as S, getAgentInvocationId as T, ConversationTurnLifecycleService as _, ConversationTurnBoundaryError as a, hasAgentInvocationReply as b, TurnInputDeferredError as c, isTurnInputCommitLostError as d, isTurnInputDeferredError as f, startActiveTurn as g, markTurnFailed as h, getTurnUserSlackMessageTs as i, getAgentInvocationTurnId as j, getAgentInvocationMessageId as k, getConversationTurnBoundaryError as l, markTurnCompleted as m, getTurnUserMessageId as n, CooperativeTurnYieldError as o, markTurnClosed as p, getTurnUserReplyAttachmentContext as r, TurnInputCommitLostError as s, getTurnUserMessage as t, isCooperativeTurnYieldError as u, getTurnLifecycle as v, readChildMessageSender as w, isAgentInvocationResult as x, childMessageSenderMetadata as y };