@sentry/junior 0.286.0 → 0.288.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 (78) hide show
  1. package/dist/{adapter-JQZaJ-B_.js → adapter-Cikcqdty.js} +1 -1
  2. package/dist/{admin-Dm2bimJ-.js → admin-BcSxHuTB.js} +2 -1
  3. package/dist/{agent-runner-DGCwOEyL.js → agent-runner-9MXyWUL8.js} +784 -368
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +9 -8
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +411 -65
  8. package/dist/{app-BKq0JzWx.d.ts → app-BUklJVBe.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +555 -71
  11. package/dist/{assistant-reply-CAPafcUY.js → assistant-reply-mj47jMRV.js} +1 -1
  12. package/dist/{automation-B-jJN_gM.js → automation-DDXwHQs5.js} +4 -7
  13. package/dist/{background-compaction-queue-Btu2oab_.js → background-compaction-queue-CjllSPir.js} +161 -90
  14. package/dist/{briefs-UMeYehUe.js → briefs-DW9iuolG.js} +7 -5
  15. package/dist/{catalog-runtime-Bym8GVdh.js → catalog-runtime-B3gfH58M.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/config-CLJcyYEF.js +1762 -0
  24. package/dist/{connections-CQ7p0aNJ.js → connections-BtdJftow.js} +9 -9
  25. package/dist/{conversation-BusI2uzj.js → conversation-DhoqHtQ7.js} +30 -6
  26. package/dist/{conversation-pending-messages-DwehU0Fd.js → conversation-pending-messages-DHV0S4uF.js} +2 -5
  27. package/dist/{conversation-privacy-Cd_nZZBM.js → conversation-privacy-BPirIVlX.js} +1 -1
  28. package/dist/core-model-BTt5E5b0.js +182 -0
  29. package/dist/{credential-sync-DmiJi_At.js → credential-sync-Co8Q2xRW.js} +28 -20
  30. package/dist/{viewer-CH-ASQzh.js → db-Co7DTYYh.js} +62 -358
  31. package/dist/{db-C5zi4ecs.d.ts → db-zIs8-Ba3.d.ts} +6 -2
  32. package/dist/{executor-Dipi2Ixl.js → executor-m0kIN71Q.js} +102 -14
  33. package/dist/{media-B-BpXo41.js → history-IjdmO_r6.js} +8 -88
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{logging-CMFhLLj4.js → logging-DbD-dErY.js} +3 -2
  36. package/dist/media-BAHvgkok.js +85 -0
  37. package/dist/{message-D1xLljUF.js → message-DKTdTYm-.js} +10 -10
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +19 -41
  40. package/dist/{oauth-callback-server-DCAFIUQr.js → oauth-callback-server-CpbepSbp.js} +2 -2
  41. package/dist/{projection-CoeMNxJ4.js → projection-BViECfYu.js} +361 -746
  42. package/dist/{prompt-C9OQEfan.js → prompt-KT6MaDHN.js} +1 -1
  43. package/dist/{registry-u-sFYtx_.js → registry-D-Acyjhh.js} +1 -1
  44. package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
  45. package/dist/{resolve-DYqgL3Eo.js → resolve-gkT2R66z.js} +3 -3
  46. package/dist/{result-CescSwAw.js → result-DHmCFEt8.js} +8 -8
  47. package/dist/{runner-Cr67a8TB.js → runner-DBKjGjH-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-DLOazy5W.js → sandbox-egress-signals-9n8hqx29.js} +1 -1
  49. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  50. package/dist/{schema-Ih60j59-.d.ts → schema-B_6aOcx5.d.ts} +159 -3
  51. package/dist/{schema-BUSi3sgv.js → schema-DxicIQbc.js} +79 -14
  52. package/dist/{service-account-CsKxktLk.js → service-account-Bi0HsY6w.js} +3 -3
  53. package/dist/{service-account-CGEqz9wG.js → service-account-CDlC9ssy.js} +3 -3
  54. package/dist/{session-stop-CGz5DByb.js → session-stop-BWOsuo8p.js} +62 -20
  55. package/dist/{skills-COCqf61f.js → skills-DO5K68Rq.js} +2 -2
  56. package/dist/spawn-BBqZDcPa.js +79 -0
  57. package/dist/{stop-GyFZkHuQ.js → stop-WC97cmHz.js} +832 -552
  58. package/dist/{store-D0-8plWp.js → store-ByR1Lr7e.js} +4 -16
  59. package/dist/{task-runner-xPuQmEot.js → task-runner-B-Ewf8TX.js} +30 -21
  60. package/dist/{turn-failure-response-BOviBdT-.js → turn-failure-response-CpdPoZSl.js} +25 -11
  61. package/dist/{validation-DZDKorGz.js → validation-B4sbIoES.js} +1 -1
  62. package/dist/{version-BTIz7fGi.js → version-D6lpuAgL.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/viewer-CeP27tC3.js +337 -0
  65. package/dist/warmup-P_GJCL1c.js +767 -0
  66. package/dist/{work-C75_IM5e.js → work-DI7x1Slm.js} +32 -20
  67. package/dist/{worker-Dl47I729.js → worker-CYPTOT4j.js} +6 -7
  68. package/migrations/0088_conversation_unsubscribe.sql +1 -0
  69. package/migrations/0089_conversation_paused_status.sql +3 -0
  70. package/migrations/0090_guardian_review_time_index.sql +20 -0
  71. package/migrations/meta/0088_snapshot.json +4372 -0
  72. package/migrations/meta/0089_snapshot.json +4372 -0
  73. package/migrations/meta/0090_snapshot.json +4388 -0
  74. package/migrations/meta/_journal.json +21 -0
  75. package/package.json +5 -4
  76. package/dist/client-B0aAs7wC.js +0 -793
  77. package/dist/config-B9f9Lqo5.js +0 -579
  78. package/dist/spawn-C8F_iXWO.js +0 -42
@@ -1,6 +1,6 @@
1
- import { Bt as stopConversationWork$1, Ct as getConversationWorkState$1, Ft as removeActiveConversation$1, It as requestAnotherSlice$1, Lt as requestConversationWork$1, Mt as recordConversationRetry$1, Nt as releaseConversationWork$1, Ot as listActiveConversationIds$1, Pt as releaseInboundMessage, Rt as startConversationWork$1, St as getConversation$1, _t as clearExpiredConversationLease$1, bt as deadLetterAttempt$1, dt as appendInboundMessage, ft as beginConversationResume$1, gt as clearConsumedConversationWake$1, ht as claimInboundMessage$1, jt as recordAttemptFailure$1, kt as markConversationWorkEnqueued$1, lt as ackMessages$1, mt as checkInConversationWork$1, pt as cancelHumanFacingPendingMessages$1, ut as appendExclusiveInboundMessage, vt as completeConversationStop$1, xt as drainConversationMailbox$1, yt as completeConversationWork$1, zt as steerWebPendingMessages$1 } from "./projection-CoeMNxJ4.js";
2
- import { x as getConversationStore } from "./viewer-CH-ASQzh.js";
3
- import "./background-compaction-queue-Btu2oab_.js";
1
+ import { Bt as requestAnotherSlice$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, St as completeConversationWork$1, Tt as drainConversationMailbox$1, Ut as steerWebPendingMessages$1, Vt as requestConversationWork$1, Wt as stopConversationWork$1, _t as checkInConversationWork$1, bt as clearExpiredConversationLease$1, ft as ackMessages$1, gt as cancelHumanFacingPendingMessages$1, ht as beginConversationResume$1, kt as hasRunnableConversationWork, mt as appendInboundMessage, pt as appendExclusiveInboundMessage, vt as claimInboundMessage$1, wt as deadLetterAttempt$1, xt as completeConversationStop$1, yt as clearConsumedConversationWake$1, zt as releaseInboundMessage } from "./projection-BViECfYu.js";
2
+ import { a as getConversationStore } from "./db-Co7DTYYh.js";
3
+ import "./background-compaction-queue-CjllSPir.js";
4
4
  // src/chat/task-execution/store.ts
5
5
  function metadataStore(options) {
6
6
  return options.conversationStore ?? getConversationStore();
@@ -55,14 +55,6 @@ async function recordConversationRetry(args) {
55
55
  await recordExecutionMetadata(args);
56
56
  return result;
57
57
  }
58
- /** Count mailbox messages that have not yet reached the conversation event log. */
59
- function countPendingConversationMessages(conversation) {
60
- return conversation.execution.pendingMessages.length;
61
- }
62
- /** Return whether a conversation has pending or resumable execution work. */
63
- function hasRunnableConversationWork(conversation) {
64
- return conversation.execution.status !== "idle" || countPendingConversationMessages(conversation) > 0;
65
- }
66
58
  /**
67
59
  * Ensure runnable conversation work has one accepted queue wake-up nudge.
68
60
  *
@@ -309,12 +301,8 @@ async function clearExpiredConversationLease(args) {
309
301
  await recordExecutionMetadata(args);
310
302
  return result;
311
303
  }
312
- /** Remove one conversation from the active index after it is missing or idle. */
313
- async function removeActiveConversation(args) {
314
- return await removeActiveConversation$1(args);
315
- }
316
304
  /** List active conversation ids by oldest execution update first. */
317
305
  async function listActiveConversationIds(args = {}) {
318
306
  return await listActiveConversationIds$1(args);
319
307
  }
320
- export { removeActiveConversation as C, steerWebPendingMessages as D, startConversationWork as E, stopConversationWork as O, releaseConversationWork as S, requestConversationWork as T, getConversationWorkState as _, cancelHumanFacingPendingMessages as a, recordAttemptFailure as b, clearConsumedConversationWake as c, completeConversationWork as d, countPendingConversationMessages as f, getConversation as g, ensureConversationWake as h, beginConversationResume as i, clearExpiredConversationLease as l, drainConversationMailbox as m, appendAndEnqueueExclusiveInboundMessage as n, checkInConversationWork as o, deadLetterAttempt as p, appendAndEnqueueInboundMessage as r, claimInboundMessage as s, ackMessages as t, completeConversationStop as u, hasRunnableConversationWork as v, requestAnotherSlice as w, recordConversationRetry as x, listActiveConversationIds as y };
308
+ export { startConversationWork as C, requestConversationWork as S, stopConversationWork as T, listActiveConversationIds as _, cancelHumanFacingPendingMessages as a, releaseConversationWork as b, clearConsumedConversationWake as c, completeConversationWork as d, deadLetterAttempt as f, getConversationWorkState as g, getConversation as h, beginConversationResume as i, clearExpiredConversationLease as l, ensureConversationWake as m, appendAndEnqueueExclusiveInboundMessage as n, checkInConversationWork as o, drainConversationMailbox as p, appendAndEnqueueInboundMessage as r, claimInboundMessage as s, ackMessages as t, completeConversationStop as u, recordAttemptFailure as v, steerWebPendingMessages as w, requestAnotherSlice as x, recordConversationRetry as y };
@@ -1,15 +1,16 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Bi as formatSlackLink, Ji as openSlackDirectMessage, La as createPluginEmbedder, Mo as createPluginCache, No as createDurableLocationConfigurationService, Qn as coreTaskRegistrations, Ra as createPluginModel, T as fallbackShortTitle, Xa as createPluginModelCostRecorder, Yn as getPlugins, Za as createPluginLogger, Zi as postSlackMessage, Zt as getPiMessageRole, ai as JUNIOR_THREAD_STATE_TTL_MS, b as persistConversationMessages, cn as normalizeToolNameFromResult, fi as ToolInputError, it as getTurnRecord, nn as instructionTextForProjection, on as isToolResultError, pi as createPluginState, sn as isToolResultMessage, so as createPluginConversationEvents, ui as getDashboardTaskLink, un as stripRuntimeTurnContext, v as hydrateConversationMessages, zi as escapeSlackMrkdwnText } from "./projection-CoeMNxJ4.js";
3
- import { n as botConfig } from "./config-B9f9Lqo5.js";
4
- import { E as withSpan, G as toOptionalNumber, K as toOptionalString, W as isRecord$1, _ as runBestEffort, h as logWarn } from "./logging-CMFhLLj4.js";
2
+ import { Bn as getPlugins, Ga as createPluginModelCostRecorder, Gi as postSlackMessage, Hi as openSlackDirectMessage, Ka as createPluginLogger, Ma as createPluginEmbedder, Na as createPluginModel, Ni as escapeSlackMrkdwnText, Oo as createPluginCache, Pi as formatSlackLink, Qr as JUNIOR_THREAD_STATE_TTL_MS, T as fallbackShortTitle, Un as coreTaskRegistrations, b as persistConversationMessages, dn as isToolResultMessage, fn as normalizeToolNameFromResult, ko as createDurableLocationConfigurationService, mn as stripRuntimeTurnContext, oi as ToolInputError, on as instructionTextForProjection, ri as getDashboardTaskLink, ro as createPluginConversationEvents, si as createPluginState, st as getTurnRecord, tn as getPiMessageRole, un as isToolResultError, v as hydrateConversationMessages } from "./projection-BViECfYu.js";
3
+ import { n as botConfig } from "./config-CLJcyYEF.js";
4
+ import { E as withSpan, J as toOptionalString, K as isRecord$1, _ as runBestEffort, h as logWarn, q as toOptionalNumber } from "./logging-DbD-dErY.js";
5
5
  import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
6
- import { S as getDb, i as readActorIdentity, it as agentTurnTotalTokens, rt as agentTurnCostUsd, x as getConversationStore } from "./viewer-CH-ASQzh.js";
7
- import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-Dipi2Ixl.js";
8
- import { v as sameActorIdentity } from "./media-B-BpXo41.js";
9
- import { h as credentialSubjectSchema } from "./registry-u-sFYtx_.js";
10
- import { r as getStateAdapter } from "./adapter-JQZaJ-B_.js";
11
- import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-Btu2oab_.js";
12
- import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-B-jJN_gM.js";
6
+ import { G as agentTurnTotalTokens, W as agentTurnCostUsd, a as getConversationStore, o as getDb } from "./db-Co7DTYYh.js";
7
+ import { A as juniorConversations, d as juniorAutomationVersions, f as juniorAutomations, u as juniorAutomationRuns } from "./executor-m0kIN71Q.js";
8
+ import { m as sameActorIdentity } from "./history-IjdmO_r6.js";
9
+ import { h as credentialSubjectSchema } from "./registry-D-Acyjhh.js";
10
+ import { i as readActorIdentity } from "./viewer-CeP27tC3.js";
11
+ import { r as getStateAdapter } from "./adapter-Cikcqdty.js";
12
+ import { c as pluginTaskParamsSchema, d as sendVercelPluginTask, s as pluginTaskId } from "./background-compaction-queue-CjllSPir.js";
13
+ import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-DDXwHQs5.js";
13
14
  import { createHash } from "node:crypto";
14
15
  import * as z from "zod";
15
16
  import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
@@ -348,7 +349,7 @@ function slackSourceForDestination(args) {
348
349
  * Reads parent Conversations when this Conversation has no Destination.
349
350
  */
350
351
  async function resolveConversationRouting(args) {
351
- const conversationStore = args.conversationStore ?? (await import("./viewer-CH-ASQzh.js").then((n) => n.v)).getConversationStore();
352
+ const conversationStore = args.conversationStore ?? (await import("./db-Co7DTYYh.js").then((n) => n.n)).getConversationStore();
352
353
  const chain = await loadConversationChain(args.conversationId, conversationStore);
353
354
  let destination;
354
355
  let source;
@@ -1234,19 +1235,25 @@ async function collectEventAutomationMatchKeys(db, input) {
1234
1235
  return [...keys].sort();
1235
1236
  }
1236
1237
  /**
1237
- * Find every live task matching one normalized event: tasks for its exact
1238
- * identifier, and tasks with no identifier whose filters match. The gate
1239
- * skips a row whose trigger and identifier column disagree, and a row with
1240
- * no identifier whose trigger the enabled `catalog` rejects.
1238
+ * Find every live task matching each normalized event, with one read for all
1239
+ * of them: tasks for its exact identifier, and tasks with no identifier whose
1240
+ * filters match. Returns one list per event, in order. The events must share
1241
+ * one namespace. The gate skips a row whose trigger and identifier column
1242
+ * disagree, and a row with no identifier whose trigger the enabled `catalog`
1243
+ * rejects.
1241
1244
  */
1242
- async function findMatchingEventAutomations(db, event, teamId, catalog) {
1243
- return (await readGatedEventAutomations(db, {
1245
+ async function findMatchingEventAutomations(db, events, teamId, catalog) {
1246
+ const namespace = events[0]?.namespace;
1247
+ if (namespace === void 0) return [];
1248
+ if (events.some((event) => event.namespace !== namespace)) throw new Error("Events to match must share one namespace.");
1249
+ const tasks = await readGatedEventAutomations(db, {
1244
1250
  catalog,
1245
- eventTypes: [event.eventType],
1246
- identifiers: [event.identifier],
1247
- namespace: event.namespace,
1251
+ eventTypes: [...new Set(events.map((event) => event.eventType))],
1252
+ identifiers: [...new Set(events.map((event) => event.identifier))],
1253
+ namespace,
1248
1254
  teamId
1249
- })).filter((task) => task.trigger.events.includes(event.eventType) && eventMatches(task.trigger.match, event.data));
1255
+ });
1256
+ return events.map((event) => tasks.filter((task) => (task.trigger.identifier === void 0 || task.trigger.identifier === event.identifier) && task.trigger.events.includes(event.eventType) && eventMatches(task.trigger.match, event.data)));
1250
1257
  }
1251
1258
  /**
1252
1259
  * Change lifecycle under the same row lock as edits, without changing
@@ -1499,6 +1506,7 @@ const dispatchRecordSchema = z.object({
1499
1506
  source: sourceSchema,
1500
1507
  outcomes: z.array(taskOutcomeSchema).max(5).optional(),
1501
1508
  status: dispatchStatusSchema,
1509
+ title: z.string().min(1).optional(),
1502
1510
  updatedAtMs: z.number().finite()
1503
1511
  }).strict().superRefine((record, ctx) => {
1504
1512
  if (!isSlackDestination(record.destination)) {
@@ -1666,6 +1674,7 @@ async function createOrGetDispatch(args) {
1666
1674
  ...args.options.outcomes ? { outcomes: args.options.outcomes } : void 0,
1667
1675
  status: "pending",
1668
1676
  source: args.options.source,
1677
+ ...args.options.title?.trim() ? { title: args.options.title.trim() } : void 0,
1669
1678
  updatedAtMs: args.nowMs
1670
1679
  };
1671
1680
  await updatePendingDispatchMailboxAppendIndex(state, (ids) => ids.includes(id) ? ids : [...ids, id]);
@@ -1,18 +1,26 @@
1
- import { D as buildConversationContext, Eo as listConversationAnnotations, M as markConversationMessage, Sn as buildDeterministicTurnId, q as clearPendingAuth, v as hydrateConversationMessages } from "./projection-CoeMNxJ4.js";
2
- import { b as getProviderErrorUserMessage, g as ProviderError, v as findProviderError, y as getProviderErrorAttributes } from "./client-B0aAs7wC.js";
3
- import { g as TURN_REASONING_LEVELS } from "./config-B9f9Lqo5.js";
4
- import { W as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CMFhLLj4.js";
1
+ import { D as buildConversationContext, M as markConversationMessage, So as listConversationAnnotations, Z as clearPendingAuth, v as hydrateConversationMessages } from "./projection-BViECfYu.js";
2
+ import { B as ProviderError, H as findProviderError, U as getProviderErrorAttributes, W as getProviderErrorUserMessage, g as TURN_REASONING_LEVELS } from "./config-CLJcyYEF.js";
3
+ import { K as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-DbD-dErY.js";
5
4
  import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
6
- import { C as getSqlExecutor, S as getDb, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
7
- import { g as juniorAgentInvocations } from "./executor-Dipi2Ixl.js";
8
- import { p as credentialContextSchema } from "./registry-u-sFYtx_.js";
9
- import { F as removedCardSchema, I as resolveMessageCards, P as readMessageCardRefs } from "./conversation-BusI2uzj.js";
10
- import { S as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, x as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B4TwyuJo.js";
11
- import { _t as getPersistedThreadState, bt as coerceThreadConversationState, yt as persistThreadStateById } from "./task-runner-xPuQmEot.js";
5
+ import { o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-Co7DTYYh.js";
6
+ import { g as juniorAgentInvocations } from "./executor-m0kIN71Q.js";
7
+ import { p as credentialContextSchema } from "./registry-D-Acyjhh.js";
8
+ import { B as resolveMessageCards, R as readMessageCardRefs, z as removedCardSchema } from "./conversation-DhoqHtQ7.js";
9
+ import { C as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, S as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B3Ze-Qnt.js";
10
+ import { _t as getPersistedThreadState, bt as coerceThreadConversationState, yt as persistThreadStateById } from "./task-runner-B-Ewf8TX.js";
12
11
  import { createHash } from "node:crypto";
13
12
  import * as z from "zod";
14
13
  import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
15
14
  import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
15
+ // src/chat/state/turn-id.ts
16
+ /** Build a stable turn identifier from a message ID. */
17
+ function buildDeterministicTurnId(messageId) {
18
+ return `turn_${messageId.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
19
+ }
20
+ /** Build the stable visible assistant-message identity for one logical turn. */
21
+ function buildDeterministicAssistantMessageId(turnId) {
22
+ return `${turnId}:assistant:1`;
23
+ }
16
24
  // src/chat/runtime/turn.ts
17
25
  /** Classified Slack turn failure carrying the owning Sentry capture outward. */
18
26
  var ConversationTurnBoundaryError = class extends Error {
@@ -227,6 +235,11 @@ function agentTypeInstructions(type) {
227
235
  // src/chat/agent-invocations/types.ts
228
236
  const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
229
237
  const agentNameSchema = exactStringSchema.max(64);
238
+ /**
239
+ * Kind of a new child Conversation. A Thread is a child that people can
240
+ * message; a Task is one that only its parent messages.
241
+ */
242
+ const CHILD_AGENT_KINDS = ["thread", "task"];
230
243
  /** `messageAgent` target for the parent of a child agent. */
231
244
  const PARENT_AGENT_TARGET = "parent";
232
245
  const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
@@ -284,6 +297,7 @@ const createAgentInvocationSchema = z.object({
284
297
  destination: destinationSchema,
285
298
  idempotencyKey: exactStringSchema,
286
299
  input: exactStringSchema,
300
+ kind: z.enum(CHILD_AGENT_KINDS).default("task"),
287
301
  parentConversationId: exactStringSchema,
288
302
  parentToolCallId: exactStringSchema.optional(),
289
303
  agentType: agentTypeSchema.optional(),
@@ -799,4 +813,4 @@ function finalizeFailedTurnReplyWithEvent(args) {
799
813
  }
800
814
  };
801
815
  }
802
- export { parseAgentInvocationResultMessageId as $, markAgentInvocationPaused as A, agentTypeInstructions as B, isTerminalAgentInvocation as C, listPendingAgentInvocationResults as D, listPendingAgentInvocationMailboxAppends as E, PARENT_AGENT_TARGET as F, getAgentInvocationIdForMessage as G, formatAgentTypes as H, agentBindingSchema as I, getAgentInvocationResultMessageId as J, getAgentInvocationIdForResult as K, agentNameSchema as L, markAgentInvocationSteered as M, reportReplacedAgentInvocation as N, markAgentInvocationMailboxAppended as O, CHILD_AGENT_RESULTS as P, getUnnamedAgentConversationId as Q, createAgentInvocationSchema as R, invocationFromRow as S, listOpenAgentInvocations as T, getAgentInvocationId as U, agentTypeStartsWithParentHistory as V, getAgentInvocationIdForEvents as W, getChildAgentLockName as X, getAgentInvocationTurnId as Y, getNamedAgentConversationId as Z, completeAgentInvocation as _, persistAuthPauseTurnState as a, isCooperativeTurnYieldError as at, getChildAgentLabel as b, getTurnUserSlackMessageTs as c, markTurnClosed as ct, loadThreadContextTrimFloor as d, startActiveTurn as dt, ConversationTurnBoundaryError as et, ConversationTurnLifecycleService as f, NON_TERMINAL_AGENT_INVOCATION_STATUSES as g, ACTIVE_AGENT_INVOCATION_STATUSES as h, completeAuthPauseTurn as i, getConversationTurnBoundaryError as it, markAgentInvocationRunning as j, markAgentInvocationParentMailboxAppended as k, buildDeliveredTurnStatePatch as l, markTurnCompleted as lt, loadPendingMessageCards as m, getAgentTurnDiagnosticsAttributes as n, TurnInputCommitLostError as nt, getTurnUserMessage as o, isTurnInputCommitLostError as ot, getTurnLifecycle as p, getAgentInvocationMessageId as q, requireTurnFailureEventId as r, TurnInputDeferredError as rt, getTurnUserReplyAttachmentContext as s, isTurnInputDeferredError as st, finalizeFailedTurnReplyWithEvent as t, CooperativeTurnYieldError as tt, buildTurnThreadContext as u, markTurnFailed as ut, getActiveAgentInvocationForConversation as v, listAgentInvocationsForConversation as w, getLatestAgentInvocationForConversation as x, getAgentInvocation as y, AGENT_TYPES as z };
816
+ export { getUnnamedAgentConversationId as $, markAgentInvocationPaused as A, AGENT_TYPES as B, isTerminalAgentInvocation as C, listPendingAgentInvocationResults as D, listPendingAgentInvocationMailboxAppends as E, CHILD_AGENT_RESULTS as F, getAgentInvocationIdForEvents as G, agentTypeStartsWithParentHistory as H, PARENT_AGENT_TARGET as I, getAgentInvocationMessageId as J, getAgentInvocationIdForMessage as K, agentBindingSchema as L, markAgentInvocationSteered as M, reportReplacedAgentInvocation as N, markAgentInvocationMailboxAppended as O, CHILD_AGENT_KINDS as P, getNamedAgentConversationId as Q, agentNameSchema as R, invocationFromRow as S, listOpenAgentInvocations as T, formatAgentTypes as U, agentTypeInstructions as V, getAgentInvocationId as W, getAgentInvocationTurnId as X, getAgentInvocationResultMessageId as Y, getChildAgentLockName as Z, completeAgentInvocation as _, persistAuthPauseTurnState as a, getConversationTurnBoundaryError as at, getChildAgentLabel as b, getTurnUserSlackMessageTs as c, isTurnInputDeferredError as ct, loadThreadContextTrimFloor as d, markTurnFailed as dt, parseAgentInvocationResultMessageId as et, ConversationTurnLifecycleService as f, startActiveTurn as ft, NON_TERMINAL_AGENT_INVOCATION_STATUSES as g, ACTIVE_AGENT_INVOCATION_STATUSES as h, completeAuthPauseTurn as i, TurnInputDeferredError as it, markAgentInvocationRunning as j, markAgentInvocationParentMailboxAppended as k, buildDeliveredTurnStatePatch as l, markTurnClosed as lt, loadPendingMessageCards as m, buildDeterministicTurnId as mt, getAgentTurnDiagnosticsAttributes as n, CooperativeTurnYieldError as nt, getTurnUserMessage as o, isCooperativeTurnYieldError as ot, getTurnLifecycle as p, buildDeterministicAssistantMessageId as pt, getAgentInvocationIdForResult as q, requireTurnFailureEventId as r, TurnInputCommitLostError as rt, getTurnUserReplyAttachmentContext as s, isTurnInputCommitLostError as st, finalizeFailedTurnReplyWithEvent as t, ConversationTurnBoundaryError as tt, buildTurnThreadContext as u, markTurnCompleted as ut, getActiveAgentInvocationForConversation as v, listAgentInvocationsForConversation as w, getLatestAgentInvocationForConversation as x, getAgentInvocation as y, createAgentInvocationSchema as z };
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Bym8GVdh.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B3gfH58M.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.286.0";
2
+ var version = "0.288.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-BTIz7fGi.js";
1
+ export { t as JUNIOR_VERSION } from "./version-D6lpuAgL.js";
@@ -0,0 +1,337 @@
1
+ import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-DbD-dErY.js";
2
+ import { E as findActorIdentityId, o as getDb } from "./db-Co7DTYYh.js";
3
+ import { M as juniorUsers, j as juniorIdentities } from "./executor-m0kIN71Q.js";
4
+ import { a as withLock } from "./locks-D-0h111u.js";
5
+ import { r as detectImageMediaType } from "./media-BAHvgkok.js";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
8
+ import { identitySchema, userSchema } from "@sentry/junior-plugin-api";
9
+ // src/chat/state/cache.ts
10
+ const MAX_CACHE_KEY_LENGTH = 512;
11
+ const LOAD_WAIT_MS = 1e4;
12
+ /**
13
+ * Create a cache in the state adapter under `junior:cache:{namespace}:`.
14
+ * Entries are wrapped, so `null` and `false` values are cache hits.
15
+ */
16
+ function createCache(state, namespace) {
17
+ return { async getOrLoad(key, load, options) {
18
+ if (!key.trim()) throw new Error("Cache key is required");
19
+ if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
20
+ const cacheKey = `junior:cache:${namespace}:${key}`;
21
+ const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
22
+ await state.connect();
23
+ const hit = await cached();
24
+ if (hit) return hit.value;
25
+ const attempt = await withLock(state, `${cacheKey}:load`, async () => {
26
+ const loadedMeanwhile = await cached();
27
+ if (loadedMeanwhile) return loadedMeanwhile.value;
28
+ const entry = await load();
29
+ if (entry.ttlMs !== void 0) {
30
+ if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
31
+ await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
32
+ }
33
+ return entry.value;
34
+ }, {
35
+ keepAlive: true,
36
+ waitMs: LOAD_WAIT_MS
37
+ });
38
+ if (attempt.acquired) return attempt.value;
39
+ return (await load()).value;
40
+ } };
41
+ }
42
+ // src/chat/identities/avatar.ts
43
+ /**
44
+ * Profile photos of people, saved on their native Slack and Google
45
+ * identities. Junior serves each photo from its own API, so browsers never
46
+ * load a photo from Slack or Google.
47
+ */
48
+ const AVATAR_HOSTS = {
49
+ slack: ["avatars.slack-edge.com"],
50
+ [GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
51
+ };
52
+ const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
53
+ const AVATAR_CACHE_TTL_MS = 864e5;
54
+ const AVATAR_FAILURE_TTL_MS = 3e5;
55
+ const AVATAR_FETCH_TIMEOUT_MS = 5e3;
56
+ const MAX_AVATAR_BYTES = 1048576;
57
+ const AVATAR_EDGE_PX = 96;
58
+ const MAX_AVATAR_REDIRECTS = 3;
59
+ /**
60
+ * Return the URL when it is HTTPS on a photo host of the provider or a
61
+ * subdomain. Junior fetches only these URLs.
62
+ */
63
+ function parseAvatarUrl(value, provider) {
64
+ const hosts = AVATAR_HOSTS[provider];
65
+ if (!hosts || !value || !URL.canParse(value)) return void 0;
66
+ const url = new URL(value);
67
+ if (url.protocol !== "https:" || url.username || url.password) return;
68
+ const host = url.hostname.toLowerCase();
69
+ return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
70
+ }
71
+ function avatarUrlHash(url) {
72
+ return createHash("sha256").update(url).digest("hex");
73
+ }
74
+ function avatarVersion(url) {
75
+ return avatarUrlHash(url).slice(0, 16);
76
+ }
77
+ function avatarPath(identityId, avatarUrl) {
78
+ return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
79
+ }
80
+ /**
81
+ * Read the photo path of each user: the Slack photo, then the Google photo.
82
+ * Users without a photo are not in the map.
83
+ */
84
+ async function readUserAvatarUrls(db, userIds) {
85
+ if (userIds.length === 0) return /* @__PURE__ */ new Map();
86
+ const rows = await db.select({
87
+ avatarUrl: juniorIdentities.avatarUrl,
88
+ identityId: juniorIdentities.id,
89
+ provider: juniorIdentities.provider,
90
+ updatedAt: juniorIdentities.updatedAt,
91
+ userId: juniorIdentities.userId
92
+ }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), eq(juniorIdentities.kind, "user"), inArray(juniorIdentities.provider, AVATAR_PROVIDERS), isNotNull(juniorIdentities.avatarUrl)));
93
+ const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
94
+ rows.sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
95
+ const avatars = /* @__PURE__ */ new Map();
96
+ for (const row of rows) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
97
+ return avatars;
98
+ }
99
+ /**
100
+ * Return the photo path for one Identity row. A linked Identity uses the
101
+ * photo of its user. An Identity without a user uses its own photo.
102
+ */
103
+ function identityAvatarUrl(row, userAvatarUrls) {
104
+ if (row.userId) return userAvatarUrls.get(row.userId);
105
+ return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
106
+ }
107
+ async function readBoundedBody(response, maxBytes) {
108
+ if (!response.body) return /* @__PURE__ */ new Uint8Array();
109
+ const reader = response.body.getReader();
110
+ const chunks = [];
111
+ let total = 0;
112
+ while (true) {
113
+ const { done, value } = await reader.read();
114
+ if (done) return Buffer.concat(chunks);
115
+ total += value.byteLength;
116
+ if (total > maxBytes) {
117
+ await reader.cancel();
118
+ return;
119
+ }
120
+ chunks.push(value);
121
+ }
122
+ }
123
+ function avatarFetchFailed(host, attributes) {
124
+ logWarn("avatar.fetch.failed", {
125
+ "server.address": host,
126
+ ...attributes
127
+ });
128
+ return null;
129
+ }
130
+ async function fetchAvatarResponse(url, provider, signal) {
131
+ let current = url;
132
+ for (let redirects = 0;; redirects += 1) {
133
+ const response = await fetch(current, {
134
+ redirect: "manual",
135
+ signal
136
+ });
137
+ const location = response.headers.get("location");
138
+ if (response.status < 300 || response.status >= 400 || !location) return response;
139
+ await response.body?.cancel();
140
+ const next = URL.canParse(location, current) ? parseAvatarUrl(new URL(location, current).href, provider) : void 0;
141
+ if (!next) return "redirect_off_host";
142
+ if (redirects >= MAX_AVATAR_REDIRECTS) return "too_many_redirects";
143
+ current = next;
144
+ }
145
+ }
146
+ async function fetchAvatarImage(url, provider) {
147
+ const host = new URL(url).hostname;
148
+ let data;
149
+ try {
150
+ const response = await fetchAvatarResponse(url, provider, AbortSignal.timeout(AVATAR_FETCH_TIMEOUT_MS));
151
+ if (typeof response === "string") return avatarFetchFailed(host, { "app.reason": response });
152
+ if (!response.ok) {
153
+ await response.body?.cancel();
154
+ return avatarFetchFailed(host, { "http.response.status_code": response.status });
155
+ }
156
+ data = await readBoundedBody(response, MAX_AVATAR_BYTES);
157
+ } catch (error) {
158
+ return avatarFetchFailed(host, { "exception.message": error instanceof Error ? error.message : String(error) });
159
+ }
160
+ if (!data) return avatarFetchFailed(host, { "app.reason": "too_large" });
161
+ const contentType = detectImageMediaType(data);
162
+ if (!contentType) return avatarFetchFailed(host, { "app.reason": "not_an_image" });
163
+ try {
164
+ return {
165
+ contentType: "image/webp",
166
+ data: await shrinkAvatar(data)
167
+ };
168
+ } catch (error) {
169
+ logWarn("avatar.resize.failed", {
170
+ "server.address": host,
171
+ "exception.message": error instanceof Error ? error.message : String(error)
172
+ });
173
+ return {
174
+ contentType,
175
+ data: Buffer.from(data).toString("base64")
176
+ };
177
+ }
178
+ }
179
+ async function shrinkAvatar(data) {
180
+ const { default: sharp } = await import("sharp");
181
+ return (await sharp(data).rotate().resize({
182
+ width: AVATAR_EDGE_PX,
183
+ height: AVATAR_EDGE_PX,
184
+ withoutEnlargement: true
185
+ }).webp({ quality: 80 }).toBuffer()).toString("base64");
186
+ }
187
+ /**
188
+ * Read the saved photo of one Identity and its version. Junior fetches it
189
+ * from the provider once, resizes it, and keeps it in the state cache for a
190
+ * day. Return undefined when the Identity has no photo or the provider does
191
+ * not return one.
192
+ */
193
+ async function readAvatarImage(db, state, identityId) {
194
+ const [row] = await db.select({
195
+ avatarUrl: juniorIdentities.avatarUrl,
196
+ provider: juniorIdentities.provider
197
+ }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
198
+ const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
199
+ if (!row?.avatarUrl || !url) return void 0;
200
+ const key = `avatar:${AVATAR_EDGE_PX}:${avatarUrlHash(url)}`;
201
+ const image = await createCache(state, "core").getOrLoad(key, async () => {
202
+ const loaded = await fetchAvatarImage(url, row.provider);
203
+ return {
204
+ value: loaded,
205
+ ttlMs: loaded ? AVATAR_CACHE_TTL_MS : AVATAR_FAILURE_TTL_MS
206
+ };
207
+ });
208
+ return image ? {
209
+ image,
210
+ version: avatarVersion(row.avatarUrl)
211
+ } : void 0;
212
+ }
213
+ // src/chat/plugins/viewer.ts
214
+ function identityFromRow(row) {
215
+ return identitySchema.parse({
216
+ id: row.id,
217
+ provider: row.provider,
218
+ providerSubjectId: row.providerSubjectId,
219
+ ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
220
+ ...row.displayName ? { displayName: row.displayName } : void 0,
221
+ ...row.handle ? { handle: row.handle } : void 0
222
+ });
223
+ }
224
+ async function readUserById(db, userRow) {
225
+ return userFromRows(userRow, await db.select().from(juniorIdentities).where(and(eq(juniorIdentities.userId, userRow.id), eq(juniorIdentities.kind, "user"))).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId)));
226
+ }
227
+ function userFromRows(userRow, identityRows) {
228
+ return userSchema.parse({
229
+ email: userRow.primaryEmail,
230
+ id: userRow.id,
231
+ identities: identityRows.map(identityFromRow),
232
+ ...userRow.displayName ? { displayName: userRow.displayName } : void 0,
233
+ ...userRow.isAdmin ? { isAdmin: true } : void 0
234
+ });
235
+ }
236
+ async function readUserByNormalizedEmail(db, normalizedEmail) {
237
+ const rows = await db.select({
238
+ user: juniorUsers,
239
+ identity: juniorIdentities
240
+ }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
241
+ const userRow = rows[0]?.user;
242
+ if (!userRow) return void 0;
243
+ return userFromRows(userRow, rows.flatMap((row) => row.identity ? [row.identity] : []));
244
+ }
245
+ /** Resolve or create the canonical user for one verified viewer email. */
246
+ async function resolveViewerUserFromSql(db, email) {
247
+ const normalizedEmail = normalizeIdentityEmail(email);
248
+ if (!normalizedEmail) return void 0;
249
+ const existing = await readUserByNormalizedEmail(db, normalizedEmail);
250
+ if (existing) return existing;
251
+ const now = /* @__PURE__ */ new Date();
252
+ const userRow = (await db.insert(juniorUsers).values({
253
+ id: randomUUID(),
254
+ primaryEmail: email.trim(),
255
+ primaryEmailNormalized: normalizedEmail,
256
+ displayName: null,
257
+ createdAt: now,
258
+ updatedAt: now
259
+ }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
260
+ return userRow ? await readUserById(db, userRow) : void 0;
261
+ }
262
+ /** Resolve or create the canonical user for one authenticated viewer. */
263
+ async function resolveViewerUser(email) {
264
+ return await resolveViewerUserFromSql(getDb(), email);
265
+ }
266
+ /** Read one existing canonical user by verified email without creating a row. */
267
+ async function findUserByEmailFromSql(db, email) {
268
+ const normalizedEmail = normalizeIdentityEmail(email);
269
+ if (!normalizedEmail) return void 0;
270
+ return await readUserByNormalizedEmail(db, normalizedEmail);
271
+ }
272
+ /** Read one existing canonical user by verified email without creating a row. */
273
+ async function findUserByEmail(email) {
274
+ return await findUserByEmailFromSql(getDb(), email);
275
+ }
276
+ /** Update one canonical user's display name in SQL. */
277
+ async function updateViewerDisplayNameFromSql(db, userId, displayName) {
278
+ const userRow = (await db.update(juniorUsers).set({
279
+ displayName,
280
+ updatedAt: /* @__PURE__ */ new Date()
281
+ }).where(eq(juniorUsers.id, userId)).returning())[0];
282
+ return userRow ? await readUserById(db, userRow) : void 0;
283
+ }
284
+ /** Read the photo path of one canonical user: Slack, then Google. */
285
+ async function readViewerAvatarUrl(userId) {
286
+ return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
287
+ }
288
+ /** Update one canonical user's display name. */
289
+ async function updateViewerDisplayName(userId, displayName) {
290
+ return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
291
+ }
292
+ /**
293
+ * Grant or revoke the Junior-wide admin role for one email.
294
+ *
295
+ * Granting creates the canonical user when needed, so an operator can grant
296
+ * admin before that person first signs in. Revoking never creates a user.
297
+ */
298
+ async function setUserAdminFromSql(db, email, isAdmin) {
299
+ const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
300
+ if (!user) return void 0;
301
+ const userRow = (await db.update(juniorUsers).set({
302
+ isAdmin,
303
+ updatedAt: /* @__PURE__ */ new Date()
304
+ }).where(eq(juniorUsers.id, user.id)).returning())[0];
305
+ return userRow ? await readUserById(db, userRow) : void 0;
306
+ }
307
+ /** List every Junior admin by primary email. */
308
+ async function listAdminUsersFromSql(db) {
309
+ const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
310
+ return await Promise.all(rows.map((row) => readUserById(db, row)));
311
+ }
312
+ /** Resolve the stored identity and linked user for one runtime actor. */
313
+ async function readActorIdentityFromSql(db, actor) {
314
+ const identityId = await findActorIdentityId(db, actor);
315
+ return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
316
+ }
317
+ /** Resolve the stored identity and linked user for one runtime actor. */
318
+ async function readActorIdentity(actor) {
319
+ return await readActorIdentityFromSql(getDb(), actor);
320
+ }
321
+ /** Read one stored identity and its linked user by identity id. */
322
+ async function readIdentityByIdFromSql(db, identityId) {
323
+ const row = (await db.select({
324
+ identity: juniorIdentities,
325
+ user: juniorUsers
326
+ }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
327
+ if (!row) return void 0;
328
+ return {
329
+ identity: identityFromRow(row.identity),
330
+ ...row.user ? { user: await readUserById(db, row.user) } : void 0
331
+ };
332
+ }
333
+ /** Read one stored identity and its linked user by identity id. */
334
+ async function readIdentityById(identityId) {
335
+ return await readIdentityByIdFromSql(getDb(), identityId);
336
+ }
337
+ export { readActorIdentityFromSql as a, readViewerAvatarUrl as c, updateViewerDisplayName as d, identityAvatarUrl as f, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, resolveViewerUser as l, readAvatarImage as m, findUserByEmailFromSql as n, readIdentityById as o, parseAvatarUrl as p, listAdminUsersFromSql as r, readIdentityByIdFromSql as s, findUserByEmail as t, setUserAdminFromSql as u };