@sentry/junior 0.301.0 → 0.302.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 (79) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-CY9RvsTX.js} +1380 -10601
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +91 -68
  8. package/dist/{app-HDZglaIu.d.ts → app-BpY3wtRP.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +66 -296
  11. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  12. package/dist/{briefs-x6Mzwxmg.js → briefs-B3NG-pid.js} +2 -2
  13. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-Dss0lSV6.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +4 -4
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-CmjhyqgB.js → config-CzeZiMKs.js} +2 -2
  22. package/dist/{connections-CfIRm0xv.js → connections-CDYhMfrs.js} +6 -6
  23. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-7Uf05ndC.js} +5 -6
  24. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-Clf_cv0n.js} +1 -0
  25. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-D9xnM5mK.js} +1 -1
  26. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-D7SEZgTG.js} +15 -16
  27. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DoD0gW-j.js} +13 -15
  28. package/dist/{db-Czra10QW.js → db-B-gtnNjr.js} +314 -5
  29. package/dist/{db-BdUHQhrC.d.ts → db-BdsCzytP.d.ts} +1 -1
  30. package/dist/{executor-D_023K0H.js → executor-DZg20EqU.js} +39 -4
  31. package/dist/install-t1KQyTUs.js +228 -0
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{state-CEbZuZD6.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  34. package/dist/{lineage-DmMIE0VL.js → lineage-C79GjoQr.js} +2 -2
  35. package/dist/{logging-DcjLDDqi.js → logging-C9oDAg4M.js} +7 -3
  36. package/dist/{message-C0JY9RJP.js → message-BLUCzJXN.js} +8 -8
  37. package/dist/{model-input-CBp-p24N.js → model-input-5jwNC45G.js} +3 -3
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +4 -3
  40. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-BBl66vCb.js} +2 -2
  41. package/dist/{projection-CQNDOi82.js → projection-CIBwgD3s.js} +282 -64
  42. package/dist/{prompt-DLUB5m72.js → prompt-CRQbzp5e.js} +14 -4
  43. package/dist/queue-DtCDaIct.js +115 -0
  44. package/dist/{registry-Dj377ADs.js → registry-DdFQHZ_d.js} +1 -1
  45. package/dist/{resolve-DJkh9Fky.js → resolve-CdW4BdrK.js} +4 -229
  46. package/dist/{result-C8iIpDl1.js → result-oOMv1t4O.js} +9 -9
  47. package/dist/{runner-DZqrOy8C.js → runner-DqitLtm-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  49. package/dist/{schema-CdZFn7Qd.d.ts → schema-BIFM-U1a.d.ts} +441 -30
  50. package/dist/{schema-DyHXiQKI.js → schema-DnVQepWP.js} +66 -29
  51. package/dist/{service-account-D6jGR4a1.js → service-account-B6mKAPVo.js} +3 -3
  52. package/dist/{service-account-suY004dx.js → service-account-CrZftRTb.js} +257 -6
  53. package/dist/{session-stop-BLmfFI3d.js → session-stop-DW63Z3kj.js} +543 -548
  54. package/dist/{skills-CmNG0dHb.js → skills-C16fz60Z.js} +2 -2
  55. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  56. package/dist/{spawn-CNjkpXpk.js → spawn-D_RnFYfy.js} +6 -6
  57. package/dist/{stop-Bjy2-K4H.js → stop-7p1i08CY.js} +724 -106
  58. package/dist/{store-DmV4CoNr.js → store-C28I0CVW.js} +5 -5
  59. package/dist/{task-queue-AhG1tSXR.js → task-queue-BVUJbQ28.js} +3 -3
  60. package/dist/{task-runner-BMxZI3o7.js → task-runner-CWi8j7Z6.js} +6 -8
  61. package/dist/{thread-context-CXLnbg7g.js → thread-context-D3-yYUd0.js} +7 -7
  62. package/dist/{store-Epv6t4vV.js → turn-session-routing-BFMS9ATF.js} +381 -10
  63. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-C3-O8Omt.js} +3 -3
  64. package/dist/{validation-DOz8X9BU.js → validation-BSFKUIb4.js} +1 -1
  65. package/dist/{version-CGMRmMPK.js → version-BHHXNi-0.js} +1 -1
  66. package/dist/version.js +1 -1
  67. package/dist/{viewer-H3EsMWtJ.js → viewer-B1SO21Qa.js} +3 -3
  68. package/dist/warmup-Bz9bzkzN.js +13927 -0
  69. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  70. package/dist/{worker-ClphajjD.js → worker-BspReIIK.js} +7 -7
  71. package/migrations/0108_conversation_embeddings.sql +13 -0
  72. package/migrations/meta/0108_snapshot.json +4688 -0
  73. package/migrations/meta/_journal.json +7 -0
  74. package/package.json +8 -6
  75. package/dist/adapter-CNjGEJO9.js +0 -303
  76. package/dist/reporting-window-DopzcOHh.js +0 -137
  77. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  78. package/dist/users-BxvYclQg.js +0 -424
  79. package/dist/warmup-CdU5hR49.js +0 -3715
@@ -1,7 +1,7 @@
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-CQNDOi82.js";
2
- import { p as logException } from "./logging-DcjLDDqi.js";
3
- import { a as getConversationStore } from "./db-Czra10QW.js";
4
- import "./background-compaction-queue-CNrZ3QcU.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-CIBwgD3s.js";
2
+ import { p as logException } from "./logging-C9oDAg4M.js";
3
+ import { a as getConversationStore } from "./db-B-gtnNjr.js";
4
+ import "./background-compaction-queue-CXFq1_Cz.js";
5
5
  // src/chat/task-execution/store.ts
6
6
  function metadataStore(options) {
7
7
  return options.conversationStore ?? getConversationStore();
@@ -304,7 +304,7 @@ async function runDeferredMove(args) {
304
304
  const move = await takeDeferredConversationMove(args);
305
305
  if (move === void 0) return;
306
306
  try {
307
- const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-Bty-DlHe.js").then((n) => n.r);
307
+ const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-BHhefEb7.js").then((n) => n.r);
308
308
  await continueDeferredSlackClick(move, args.getSlackAdapter);
309
309
  } catch (error) {
310
310
  logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
@@ -1,5 +1,5 @@
1
- import { h as logWarn } from "./logging-DcjLDDqi.js";
2
- import { C as verifyQueueMessage, E as getQueueProvider, S as signQueueMessage, w as queueCallback, x as QUEUE_SIGNATURE_MAX_AGE_MS } from "./background-compaction-queue-CNrZ3QcU.js";
1
+ import { h as logWarn } from "./logging-C9oDAg4M.js";
2
+ import { a as queueCallback, d as verifyQueueMessage, f as getQueueProvider, l as QUEUE_SIGNATURE_MAX_AGE_MS, u as signQueueMessage } from "./background-compaction-queue-CXFq1_Cz.js";
3
3
  import * as z from "zod";
4
4
  import { createHash } from "node:crypto";
5
5
  // src/chat/plugins/task-queue.ts
@@ -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-BMxZI3o7.js").then((n) => n.r);
63
+ const { processPluginTask } = await import("./task-runner-CWi8j7Z6.js").then((n) => n.r);
64
64
  await processPluginTask(message);
65
65
  },
66
66
  topic: PLUGIN_TASK_QUEUE_TOPIC,
@@ -1,14 +1,12 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Bi as createPluginState, Dn as instructionTextForProjection, In as stripRuntimeTurnContext, Mn as isToolResultMessage, Oo as createPluginConversationEvents, Pn as normalizeToolNameFromResult, Sn as getPiMessageRole, _o as createPluginLogger, fr as getPlugins, go as createPluginModelCostRecorder, hr as coreTaskRegistrations, io as createPluginModel, jn as isToolResultError, ro as createPluginEmbedder, st as getTurnRecord, v as hydrateConversationMessages, ys as createPluginCache } from "./projection-CQNDOi82.js";
3
- import { E as withSpan } from "./logging-DcjLDDqi.js";
2
+ import { Bi as createPluginState, Dn as instructionTextForProjection, In as stripRuntimeTurnContext, Mn as isToolResultMessage, Oo as createPluginConversationEvents, Pn as normalizeToolNameFromResult, Sn as getPiMessageRole, _o as createPluginLogger, go as createPluginModelCostRecorder, io as createPluginModel, jn as isToolResultError, mr as coreTaskRegistrations, ro as createPluginEmbedder, st as getTurnRecord, ur as getPlugins, v as hydrateConversationMessages, xs as createPluginCache } from "./projection-CIBwgD3s.js";
3
+ import { E as withSpan } from "./logging-C9oDAg4M.js";
4
4
  import { v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
5
- import { a as getConversationStore, o as getDb } from "./db-Czra10QW.js";
5
+ import { J as getStateAdapter, a as getConversationStore, o as getDb } from "./db-B-gtnNjr.js";
6
6
  import { m as sameActorIdentity } from "./history-IjdmO_r6.js";
7
- import { r as getStateAdapter } from "./adapter-CNjGEJO9.js";
8
- import { i as readActorIdentity } from "./viewer-H3EsMWtJ.js";
9
- import { a as getPersistedThreadState, c as coerceThreadConversationState, t as resolveConversationRouting } from "./turn-session-routing-BD3-jJl7.js";
10
- import { c as getDispatchRecord } from "./store-Epv6t4vV.js";
11
- import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-AhG1tSXR.js";
7
+ import { i as readActorIdentity } from "./viewer-B1SO21Qa.js";
8
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, g as getDispatchRecord, t as resolveConversationRouting } from "./turn-session-routing-BFMS9ATF.js";
9
+ import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-BVUJbQ28.js";
12
10
  import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
13
11
  // src/chat/plugins/task-runner.ts
14
12
  /**
@@ -1,11 +1,11 @@
1
- import { E as buildConversationContext, X as clearPendingAuth, ds as listConversationAnnotations, j as markConversationMessage, v as hydrateConversationMessages } from "./projection-CQNDOi82.js";
2
- import { B as ProviderError, G as getProviderErrorUserMessage, U as findProviderError, W as getProviderErrorAttributes } from "./config-CmjhyqgB.js";
3
- import { G as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-DcjLDDqi.js";
4
- import { o as getDb, r as getConversationEventStore } from "./db-Czra10QW.js";
1
+ import { E as buildConversationContext, X as clearPendingAuth, j as markConversationMessage, ps as listConversationAnnotations, v as hydrateConversationMessages } from "./projection-CIBwgD3s.js";
2
+ import { B as ProviderError, G as getProviderErrorUserMessage, U as findProviderError, W as getProviderErrorAttributes } from "./config-CzeZiMKs.js";
3
+ import { K as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-C9oDAg4M.js";
4
+ import { o as getDb, r as getConversationEventStore } from "./db-B-gtnNjr.js";
5
5
  import { H as readMessageCardRefs, U as removedCardSchema, W as resolveMessageCards } from "./conversation-BNXfq6Lb.js";
6
- import { S as listChildMessages, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, x as isAgentInvocationResult } from "./turn-user-message-DsUZi9gn.js";
7
- import { _ as getConversationWorkState } from "./store-DmV4CoNr.js";
8
- import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-BD3-jJl7.js";
6
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-BFMS9ATF.js";
7
+ import { S as listChildMessages, m as markTurnCompleted, n as getTurnUserMessageId, p as markTurnClosed, x as isAgentInvocationResult } from "./turn-user-message-C3-O8Omt.js";
8
+ import { _ as getConversationWorkState } from "./store-C28I0CVW.js";
9
9
  // src/chat/conversations/pending-cards.ts
10
10
  /**
11
11
  * Add the cards that tool results selected since the last visible assistant
@@ -1,16 +1,147 @@
1
- import { Da as postSlackMessage, Fi as getDashboardTaskLink, Oi as JUNIOR_THREAD_STATE_TTL_MS, eo as ToolInputError, ma as formatSlackLink, pa as escapeSlackMrkdwnText, w as fallbackShortTitle, wa as openSlackDirectMessage } from "./projection-CQNDOi82.js";
2
- import { n as botConfig } from "./config-CmjhyqgB.js";
3
- import { _ as runBestEffort, h as logWarn } from "./logging-DcjLDDqi.js";
4
- import { X as agentTurnTotalTokens, Y as agentTurnCostUsd, o as getDb } from "./db-Czra10QW.js";
5
- import { d as juniorAutomationVersions, f as juniorAutomations, j as juniorConversations, u as juniorAutomationRuns } from "./executor-D_023K0H.js";
6
- import { r as getStateAdapter } from "./adapter-CNjGEJO9.js";
7
- import { h as credentialSubjectSchema } from "./registry-Dj377ADs.js";
8
- import { u as automationEventCatalog, v as registeredEventTriggerProblems } from "./turn-session-routing-BD3-jJl7.js";
1
+ import { Da as postSlackMessage, Fi as getDashboardTaskLink, Oi as JUNIOR_THREAD_STATE_TTL_MS, Ss as createDurableLocationConfigurationService, b as persistConversationMessages, eo as ToolInputError, ma as formatSlackLink, pa as escapeSlackMrkdwnText, w as fallbackShortTitle, wa as openSlackDirectMessage } from "./projection-CIBwgD3s.js";
2
+ import { n as botConfig } from "./config-CzeZiMKs.js";
3
+ import { J as toOptionalString, K as isRecord, _ as runBestEffort, h as logWarn, q as toOptionalNumber } from "./logging-C9oDAg4M.js";
4
+ import { J as getStateAdapter, at as agentTurnCostUsd, o as getDb, ot as agentTurnTotalTokens } from "./db-B-gtnNjr.js";
5
+ import { M as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-DZg20EqU.js";
6
+ import { h as credentialSubjectSchema } from "./registry-DdFQHZ_d.js";
9
7
  import { B as automationTaskColumns, H as automationTaskSchema, M as scheduledAutomationSchema, S as automationVersionSchema, V as automationTaskDescription, k as eventAutomationSchema, z as automationSkillNameSchema } from "./automation-Cva5ZOwW.js";
10
8
  import * as z from "zod";
11
9
  import { createHash } from "node:crypto";
12
10
  import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
13
- import { destinationSchema, destinationVisibilitySchema, eventMatches, isSlackDestination, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
11
+ import { agentEventMatchSchema, anyResourceMatchFields, describeEventTrigger, destinationSchema, destinationVisibilitySchema, eventMatches, eventTriggerChoices, eventTriggerProblems, isSlackDestination, normalizeEventIdentifier, normalizeEventMatch, replyAttributionSchema, sourceSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
12
+ // src/chat/events/catalog.ts
13
+ /** A source with nothing enabled, for a namespace that the catalog lacks. */
14
+ const NO_SOURCE = {
15
+ resourceTypes: [],
16
+ events: {},
17
+ anyResourceFields: {}
18
+ };
19
+ /**
20
+ * Build one catalog entry. It merges the filters of every resource type here,
21
+ * once, so trigger checks for each event copy and each row do not merge them
22
+ * again.
23
+ */
24
+ function eventCatalogEntry(registration) {
25
+ return {
26
+ ...registration,
27
+ anyResourceFields: anyResourceMatchFields(registration.resourceTypes)
28
+ };
29
+ }
30
+ /** Core-owned event namespace. Not a plugin publisher. */
31
+ const CORE_EVENT_NAMESPACE = "junior";
32
+ /** True when the catalog has any enabled registration. */
33
+ function hasEventCatalogEntries(catalog) {
34
+ return Object.keys(catalog).length > 0;
35
+ }
36
+ /**
37
+ * Catalog entries that durable event automations may select.
38
+ *
39
+ * Resource types with `automation: false` stay out of create/update schemas
40
+ * and trigger availability. A namespace with no such resource type left is
41
+ * removed.
42
+ */
43
+ function automationEventCatalog(catalog) {
44
+ return Object.fromEntries(Object.entries(catalog).flatMap(([namespace, registration]) => {
45
+ const resourceTypes = registration.resourceTypes.filter((resourceType) => registration.limits?.[resourceType.type]?.automation !== false);
46
+ if (resourceTypes.length === 0) return [];
47
+ if (resourceTypes.length === registration.resourceTypes.length) return [[namespace, registration]];
48
+ const supported = new Set(resourceTypes.flatMap((resourceType) => resourceType.supportedEvents));
49
+ return [[namespace, eventCatalogEntry({
50
+ ...registration,
51
+ resourceTypes,
52
+ events: Object.fromEntries(Object.entries(registration.events).filter(([eventType]) => supported.has(eventType)))
53
+ })]];
54
+ }));
55
+ }
56
+ /** Return why watchEvents cannot watch one resource type, if it cannot. */
57
+ function eventWatchUnavailable(catalog, namespace, resourceType) {
58
+ const limits = catalog[namespace]?.limits?.[resourceType];
59
+ return limits?.watch === false ? limits.watchUnavailableMessage : void 0;
60
+ }
61
+ function enumSchema(values, unavailableMessage) {
62
+ if (values.length === 0) return z.string().refine(() => false, unavailableMessage);
63
+ return z.enum(values);
64
+ }
65
+ /** Build the model-facing namespace enum from enabled event plugins. */
66
+ function eventNamespaceSchema(catalog) {
67
+ return enumSchema(Object.keys(catalog).sort(), "No event namespaces are enabled.");
68
+ }
69
+ /** Build the model-facing event enum from enabled plugin registrations. */
70
+ function registeredEventTypeSchema(catalog) {
71
+ return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.flatMap((resourceType) => resourceType.supportedEvents)))].sort(), "No event types are enabled.");
72
+ }
73
+ /** Build the model-facing resource type enum from enabled plugin registrations. */
74
+ function registeredResourceTypeSchema(catalog) {
75
+ return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.map((resourceType) => resourceType.type)))].sort(), "No resource types are enabled.");
76
+ }
77
+ /**
78
+ * Return app guidance for one event of a namespace. The source declares it
79
+ * once for the event, so every resource type and a trigger with no resource
80
+ * type get the same guidance.
81
+ */
82
+ function eventGuidance(catalog, namespace, eventType) {
83
+ return catalog[namespace]?.events[eventType]?.guidance;
84
+ }
85
+ /** Build the match object the tools accept for one resource type. */
86
+ function registeredEventMatchSchema() {
87
+ return agentEventMatchSchema.optional().describe("Optional filters: exact values for the resource type match_fields, with snake_case keys. A single value must equal the event data. A list means the event value may be any one entry. For a field with list: true, the event value is a list, and it matches when it includes the value or any entry. A field with events is set only on those events, so every selected event must be in that list. Omit a key to ignore it. Unmatched events are dropped with no agent turn.");
88
+ }
89
+ /**
90
+ * List why a selection cannot work with the enabled plugins. Use it for new
91
+ * selections and for saved triggers, which can go stale after a plugin renames
92
+ * or removes a resource type, event, or filter.
93
+ */
94
+ function registeredEventTriggerProblems(catalog, selection, options) {
95
+ return eventTriggerProblems(catalog[selection.namespace] ?? NO_SOURCE, selection, options);
96
+ }
97
+ /**
98
+ * Describe a selection with the enabled plugins, for the dashboard and Slack.
99
+ * Its problems are the same as `registeredEventTriggerProblems`.
100
+ */
101
+ function describeRegisteredEventTrigger(catalog, selection) {
102
+ return describeEventTrigger(catalog[selection.namespace] ?? NO_SOURCE, selection);
103
+ }
104
+ function uniqueMatchValues(match) {
105
+ if (!match || Object.keys(match).length === 0) return void 0;
106
+ return Object.fromEntries(Object.entries(match).map(([key, value]) => [key, Array.isArray(value) ? [...new Set(value)] : value]));
107
+ }
108
+ /**
109
+ * Reject an event automation trigger or a Watch that cannot work, with every
110
+ * problem in one message for the agent. Return its match as it is saved:
111
+ * each text value in the case that its plugin declares, with no repeated
112
+ * list values. The dashboard clears `inputKeys` so messages name the filters
113
+ * as its plugin declares them.
114
+ */
115
+ function requireValidEventTrigger(catalog, selection, target, options = { inputKeys: true }) {
116
+ const fields = eventTriggerChoices(catalog[selection.namespace] ?? NO_SOURCE, selection)?.fields ?? {};
117
+ const normalized = {
118
+ ...selection,
119
+ match: normalizeEventMatch(fields, selection.match)
120
+ };
121
+ const problems = registeredEventTriggerProblems(catalog, normalized, options);
122
+ if (problems.length > 0) {
123
+ const source = catalog[selection.namespace]?.displayName ?? selection.namespace;
124
+ const resource = selection.resourceType ? `${source} ${selection.resourceType.replaceAll("_", " ")}` : source;
125
+ throw new ToolInputError([target === "watch" ? `This ${resource} watch cannot be created.` : `This ${resource} trigger cannot be saved.`, ...problems.map((problem) => problem.message)].join(" "));
126
+ }
127
+ return uniqueMatchValues(normalized.match);
128
+ }
129
+ /**
130
+ * Normalize one selector with the convention declared by its plugin.
131
+ *
132
+ * Reject a selector that does not fit its resource type. Resource types can
133
+ * share event types, so only the identifier shows which one a selector names.
134
+ */
135
+ function requireEventIdentifier(catalog, input) {
136
+ const registration = catalog[input.namespace];
137
+ const identifier = normalizeEventIdentifier(registration, input.identifier);
138
+ const resourceTypes = registration?.resourceTypes ?? [];
139
+ const fits = (resourceType) => resourceType.identifier !== void 0 && new RegExp(resourceType.identifier.pattern).test(identifier);
140
+ const resourceType = resourceTypes.find((candidate) => candidate.type === input.resourceType);
141
+ if (!resourceType?.identifier || fits(resourceType)) return identifier;
142
+ const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
143
+ throw new ToolInputError([`Identifier "${identifier}" does not fit resource_type "${input.resourceType}" in namespace "${input.namespace}". Expected format: "${resourceType.identifier.format}".`, ...fitting.length > 0 ? [`If the identifier is correct, use one of these resource_type values: ${fitting.map((type) => `"${type}"`).join(", ")}.`] : []].join(" "));
144
+ }
14
145
  // src/chat/automations/revision.ts
15
146
  /** Storage revisions prevent stale edits from replacing newer values. */
16
147
  var AutomationConflictError = class extends ToolInputError {
@@ -1418,4 +1549,244 @@ async function getPluginDispatchProjection(args) {
1418
1549
  if (!record || record.plugin !== args.plugin) return;
1419
1550
  return toDispatchProjection(record);
1420
1551
  }
1421
- export { eventAutomationRunLimitReason as $, conversationRangeColumns as A, scheduledRunId as B, readAutomationExecutionStatusHours as C, readAutomationTitlesByConversationId as D, readAutomationRuns as E, listScheduledAutomationsForTeam as F, deleteEventAutomation as G, blockEventAutomation as H, parseScheduledAutomationRow as I, listDeletedEventAutomationsCreatedBy as J, findMatchingEventAutomations as K, readScheduledAutomation as L, blockScheduledAutomation as M, createScheduledAutomation as N, recordAutomationExecution as O, deleteScheduledAutomation as P, admitEventAutomationRun as Q, saveScheduledAutomation as R, readAutomationExecutionStatusDays as S, readAutomationExecutions as T, collectEventAutomationMatchKeys as U, withScheduledAutomationLock as V, createEventAutomation as W, saveEventAutomation as X, parseEventAutomationRow as Y, setEventAutomationStatus as Z, markDispatchRunning as _, getDispatchConversationId as a, AutomationConflictError as at, existingConversationId as b, getDispatchRecord as c, isTerminalDispatchStatus as d, automationDefinition as et, listPendingDispatchMailboxAppends as f, markDispatchFailed as g, markDispatchCompleted as h, createOrGetDispatch as i, sameDefinitionValue as it, conversationUsageCostExpr as j, conversationAggregateColumns as k, getDispatchTurnId as l, markDispatchBlocked as m, claimDispatchMailboxAppend as n, listAutomationVersions as nt, getDispatchIdForConversation as o, automationRevision as ot, markDispatchAwaitingResume as p, getEventAutomation as q, confirmDispatchMailboxAppend as r, readAutomationVersion as rt, getDispatchInputMessageId as s, requireAutomationRevision as st, buildDispatchId as t, automationVersionOf as tt, getPluginDispatchProjection as u, notifyAutomationBlocked as v, readAutomationExecutionSummaries as w, readAutomationExecutionByConversationId as x, emptyAutomationRunWindows as y, saveScheduledAutomationInLock as z };
1552
+ // src/chat/state/conversation.ts
1553
+ function defaultConversationState() {
1554
+ return {
1555
+ schemaVersion: 1,
1556
+ messages: [],
1557
+ processing: {},
1558
+ vision: { byFileId: {} }
1559
+ };
1560
+ }
1561
+ function coercePendingAuthState(value) {
1562
+ if (!isRecord(value)) return;
1563
+ const kind = value.kind;
1564
+ const provider = toOptionalString(value.provider);
1565
+ const actorId = toOptionalString(value.actorId);
1566
+ const authSessionId = toOptionalString(value.authSessionId);
1567
+ const scope = toOptionalString(value.scope);
1568
+ const sessionId = toOptionalString(value.sessionId);
1569
+ const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
1570
+ if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
1571
+ const base = {
1572
+ provider,
1573
+ actorId,
1574
+ ...scope ? { scope } : void 0,
1575
+ sessionId,
1576
+ linkSentAtMs
1577
+ };
1578
+ return kind === "mcp" ? {
1579
+ ...base,
1580
+ authSessionId,
1581
+ kind
1582
+ } : {
1583
+ ...base,
1584
+ kind
1585
+ };
1586
+ }
1587
+ /** Safely coerce an unknown persisted value into a ThreadConversationState. */
1588
+ function coerceThreadConversationState(value) {
1589
+ if (!isRecord(value)) return defaultConversationState();
1590
+ const root = value;
1591
+ const rawConversation = isRecord(root.conversation) ? root.conversation : {};
1592
+ const messages = [];
1593
+ const rawProcessing = isRecord(rawConversation.processing) ? rawConversation.processing : {};
1594
+ const processing = {
1595
+ activeTurnId: toOptionalString(rawProcessing.activeTurnId),
1596
+ lastCompletedAtMs: toOptionalNumber(rawProcessing.lastCompletedAtMs),
1597
+ pendingAuth: coercePendingAuthState(rawProcessing.pendingAuth)
1598
+ };
1599
+ const rawVision = isRecord(rawConversation.vision) ? rawConversation.vision : {};
1600
+ const rawVisionByFileId = isRecord(rawVision.byFileId) ? rawVision.byFileId : {};
1601
+ const byFileId = {};
1602
+ for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
1603
+ if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
1604
+ if (!isRecord(value)) continue;
1605
+ const summary = toOptionalString(value.summary);
1606
+ const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
1607
+ if (!summary || !analyzedAtMs) continue;
1608
+ byFileId[fileId] = {
1609
+ summary,
1610
+ analyzedAtMs
1611
+ };
1612
+ }
1613
+ return {
1614
+ schemaVersion: 1,
1615
+ messages,
1616
+ processing,
1617
+ vision: {
1618
+ backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
1619
+ byFileId
1620
+ }
1621
+ };
1622
+ }
1623
+ /**
1624
+ * Wrap active conversation control into the thread scratch envelope.
1625
+ *
1626
+ * Visible history lives in SQL. Image summaries use a separate disposable
1627
+ * cache, so thread scratch does not retain them.
1628
+ */
1629
+ function buildConversationStatePatch(conversation) {
1630
+ return { conversation: {
1631
+ schemaVersion: 1,
1632
+ processing: { ...conversation.processing }
1633
+ } };
1634
+ }
1635
+ // src/chat/runtime/thread-state.ts
1636
+ function threadStateKey(threadId) {
1637
+ return `thread-state:${threadId}`;
1638
+ }
1639
+ function channelStateKey(channelId) {
1640
+ return `channel-state:${channelId}`;
1641
+ }
1642
+ function buildThreadStatePayload(patch) {
1643
+ const payload = {};
1644
+ if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
1645
+ if (patch.sandboxRef !== void 0) {
1646
+ payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
1647
+ payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
1648
+ payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
1649
+ }
1650
+ return payload;
1651
+ }
1652
+ /**
1653
+ * Merge a payload into thread scratch with Junior's TTL.
1654
+ *
1655
+ * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
1656
+ * shorter retention policy for the same scratch keys.
1657
+ */
1658
+ async function mergePersistedState(key, payload) {
1659
+ if (Object.keys(payload).length === 0) return;
1660
+ const stateAdapter = getStateAdapter();
1661
+ await stateAdapter.connect();
1662
+ const existing = await stateAdapter.get(key) ?? {};
1663
+ await stateAdapter.set(key, {
1664
+ ...existing,
1665
+ ...payload
1666
+ }, JUNIOR_THREAD_STATE_TTL_MS);
1667
+ }
1668
+ /** Extract persisted sandbox metadata from thread state payload. */
1669
+ function getPersistedSandboxState(state) {
1670
+ const id = toOptionalString(state.app_sandbox_id);
1671
+ if (!id) return;
1672
+ const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
1673
+ const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
1674
+ return {
1675
+ id,
1676
+ ...profileHash ? { profileHash } : void 0,
1677
+ ...workspaceId ? { workspaceId } : void 0
1678
+ };
1679
+ }
1680
+ /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
1681
+ async function persistThreadRuntimeState(conversationId, patch) {
1682
+ await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
1683
+ }
1684
+ /** Load the persisted state payload for a thread without requiring a Chat singleton. */
1685
+ async function getPersistedThreadState(threadId) {
1686
+ const stateAdapter = getStateAdapter();
1687
+ await stateAdapter.connect();
1688
+ return await stateAdapter.get(threadStateKey(threadId)) ?? {};
1689
+ }
1690
+ /** Persist a thread-state patch by thread id without constructing a Chat thread. */
1691
+ async function persistThreadStateById(threadId, patch) {
1692
+ if (patch.conversation) await persistConversationMessages({
1693
+ conversation: patch.conversation,
1694
+ conversationId: threadId
1695
+ });
1696
+ await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
1697
+ }
1698
+ /** Load legacy Redis-backed channel state during the SQL cutover. */
1699
+ async function getLegacyChannelState(channelId) {
1700
+ const stateAdapter = getStateAdapter();
1701
+ await stateAdapter.connect();
1702
+ return await stateAdapter.get(channelStateKey(channelId)) ?? {};
1703
+ }
1704
+ /**
1705
+ * Resolve durable location configuration.
1706
+ *
1707
+ * Slack still reads the old channel-id Redis bag once during cutover.
1708
+ */
1709
+ function getLocationConfigurationService(destination) {
1710
+ if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
1711
+ return createDurableLocationConfigurationService({
1712
+ destination,
1713
+ db: getDb(),
1714
+ loadLegacy: async () => await getLegacyChannelState(destination.channelId)
1715
+ });
1716
+ }
1717
+ // src/chat/services/turn-session-routing.ts
1718
+ async function loadConversationChain(conversationId, conversationStore) {
1719
+ const chain = [];
1720
+ const seen = /* @__PURE__ */ new Set();
1721
+ let cursor = conversationId;
1722
+ while (cursor && !seen.has(cursor)) {
1723
+ seen.add(cursor);
1724
+ const conversation = await conversationStore.get({ conversationId: cursor });
1725
+ if (!conversation) break;
1726
+ chain.push(conversation);
1727
+ cursor = conversation.parentConversationId;
1728
+ }
1729
+ return chain;
1730
+ }
1731
+ /**
1732
+ * Normalize a stored Slack session source against the conversation destination.
1733
+ *
1734
+ * Does not create channel or thread values from the conversation id.
1735
+ */
1736
+ function slackSourceForDestination(args) {
1737
+ if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
1738
+ const threadTs = args.source.threadTs?.trim();
1739
+ return {
1740
+ kind: "slack",
1741
+ visibility: args.source.visibility ?? "public",
1742
+ teamId: args.source.teamId?.trim() || args.destination.teamId,
1743
+ channelId: args.source.channelId,
1744
+ ...threadTs ? { threadTs } : void 0
1745
+ };
1746
+ }
1747
+ /**
1748
+ * Resolve the Conversation Location, Destination, and session Source.
1749
+ *
1750
+ * Reads parent Conversations when this Conversation has no Destination.
1751
+ */
1752
+ async function resolveConversationRouting(args) {
1753
+ const conversationStore = args.conversationStore ?? (await import("./db-B-gtnNjr.js").then((n) => n.n)).getConversationStore();
1754
+ const chain = await loadConversationChain(args.conversationId, conversationStore);
1755
+ let destination;
1756
+ let source;
1757
+ let location;
1758
+ for (const conversation of chain) {
1759
+ destination ??= conversation.destination;
1760
+ source ??= conversation.sessionSource;
1761
+ location ??= conversation.location;
1762
+ if (destination && source) break;
1763
+ }
1764
+ if (!destination) return;
1765
+ if (destination.platform === "slack") {
1766
+ const slackSource = slackSourceForDestination({
1767
+ destination,
1768
+ source
1769
+ });
1770
+ return {
1771
+ destination,
1772
+ ...location ? { location } : void 0,
1773
+ ...slackSource ? { source: slackSource } : void 0
1774
+ };
1775
+ }
1776
+ return {
1777
+ destination,
1778
+ ...location ? { location } : void 0,
1779
+ ...source ? { source } : void 0
1780
+ };
1781
+ }
1782
+ /** Require the Conversation Destination and Source from SQL. */
1783
+ async function resolveTurnSessionRouting(args) {
1784
+ const routing = await resolveConversationRouting(args);
1785
+ if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
1786
+ return {
1787
+ destination: routing.destination,
1788
+ ...routing.location ? { location: routing.location } : void 0,
1789
+ source: routing.source
1790
+ };
1791
+ }
1792
+ export { deleteEventAutomation as $, readAutomationExecutionStatusDays as A, blockScheduledAutomation as B, markDispatchCompleted as C, hasEventCatalogEntries as Ct, emptyAutomationRunWindows as D, registeredResourceTypeSchema as Dt, notifyAutomationBlocked as E, registeredEventTypeSchema as Et, readAutomationTitlesByConversationId as F, readScheduledAutomation as G, deleteScheduledAutomation as H, recordAutomationExecution as I, scheduledRunId as J, saveScheduledAutomation as K, conversationAggregateColumns as L, readAutomationExecutionSummaries as M, readAutomationExecutions as N, existingConversationId as O, requireEventIdentifier as Ot, readAutomationRuns as P, createEventAutomation as Q, conversationRangeColumns as R, markDispatchBlocked as S, eventWatchUnavailable as St, markDispatchRunning as T, registeredEventTriggerProblems as Tt, listScheduledAutomationsForTeam as U, createScheduledAutomation as V, parseScheduledAutomationRow as W, blockEventAutomation as X, withScheduledAutomationLock as Y, collectEventAutomationMatchKeys as Z, getDispatchTurnId as _, automationEventCatalog as _t, getPersistedThreadState as a, setEventAutomationStatus as at, listPendingDispatchMailboxAppends as b, eventGuidance as bt, coerceThreadConversationState as c, automationDefinition as ct, confirmDispatchMailboxAppend as d, readAutomationVersion as dt, findMatchingEventAutomations as et, createOrGetDispatch as f, sameDefinitionValue as ft, getDispatchRecord as g, CORE_EVENT_NAMESPACE as gt, getDispatchInputMessageId as h, requireAutomationRevision as ht, getPersistedSandboxState as i, saveEventAutomation as it, readAutomationExecutionStatusHours as j, readAutomationExecutionByConversationId as k, requireValidEventTrigger as kt, buildDispatchId as l, automationVersionOf as lt, getDispatchIdForConversation as m, automationRevision as mt, resolveTurnSessionRouting as n, listDeletedEventAutomationsCreatedBy as nt, persistThreadRuntimeState as o, admitEventAutomationRun as ot, getDispatchConversationId as p, AutomationConflictError as pt, saveScheduledAutomationInLock as q, getLocationConfigurationService as r, parseEventAutomationRow as rt, persistThreadStateById as s, eventAutomationRunLimitReason as st, resolveConversationRouting as t, getEventAutomation as tt, claimDispatchMailboxAppend as u, listAutomationVersions as ut, getPluginDispatchProjection as v, describeRegisteredEventTrigger as vt, markDispatchFailed as w, registeredEventMatchSchema as wt, markDispatchAwaitingResume as x, eventNamespaceSchema as xt, isTerminalDispatchStatus as y, eventCatalogEntry as yt, conversationUsageCostExpr as z };
@@ -1,7 +1,7 @@
1
- import { Yt as readInboundMessageSender } from "./projection-CQNDOi82.js";
1
+ import { Yt as readInboundMessageSender } from "./projection-CIBwgD3s.js";
2
2
  import { v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
3
- import { r as getConversationEventStore, s as getSqlExecutor } from "./db-Czra10QW.js";
4
- import { g as juniorAgentInvocations } from "./executor-D_023K0H.js";
3
+ import { r as getConversationEventStore, s as getSqlExecutor } from "./db-B-gtnNjr.js";
4
+ import { g as juniorAgentInvocations } from "./executor-DZg20EqU.js";
5
5
  import { createHash } from "node:crypto";
6
6
  import { inArray } from "drizzle-orm";
7
7
  // src/chat/state/turn-id.ts
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BEY6EGRi.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  // src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.301.0";
2
+ var version = "0.302.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-CGMRmMPK.js";
1
+ export { t as JUNIOR_VERSION } from "./version-BHHXNi-0.js";
@@ -1,6 +1,6 @@
1
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail } from "./logging-DcjLDDqi.js";
2
- import { H as clearCachedUser, M as findActorIdentityId, U as readCachedUserByEmail, o as getDb } from "./db-Czra10QW.js";
3
- import { M as juniorIdentities, N as juniorUsers } from "./executor-D_023K0H.js";
1
+ import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER } from "./logging-C9oDAg4M.js";
2
+ import { N as findActorIdentityId, U as clearCachedUser, W as readCachedUserByEmail, o as getDb } from "./db-B-gtnNjr.js";
3
+ import { N as juniorIdentities, P as juniorUsers } from "./executor-DZg20EqU.js";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
6
6
  import { identitySchema, userSchema } from "@sentry/junior-plugin-api";