@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,13 +1,12 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-B9f9Lqo5.js";
3
- import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-CMFhLLj4.js";
2
+ import { i as getChatConfig } from "./config-CLJcyYEF.js";
3
+ import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-DbD-dErY.js";
4
4
  import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-6jsm_v96.js";
5
- import { A as juniorConversations, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-Dipi2Ixl.js";
6
- import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, r as detectImageMediaType, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-B-BpXo41.js";
7
- import { a as withLock } from "./locks-D-0h111u.js";
8
- import { createHash, randomUUID } from "node:crypto";
9
- import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
10
- import { destinationSchema, identitySchema, locationSchema, sourceSchema, userSchema } from "@sentry/junior-plugin-api";
5
+ import { A as juniorConversations, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-m0kIN71Q.js";
6
+ import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-IjdmO_r6.js";
7
+ import { randomUUID } from "node:crypto";
8
+ import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
9
+ import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
11
10
  import { alias } from "drizzle-orm/pg-core";
12
11
  // src/chat/destination.ts
13
12
  /** Build Junior's canonical destination from Slack workspace and channel ids. */
@@ -44,10 +43,16 @@ async function resolveRootConversationId(executor, conversationId) {
44
43
  const [row] = await executor.db().select({ rootConversationId: juniorConversations.rootConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
45
44
  return row?.rootConversationId ?? conversationId;
46
45
  }
46
+ /** True when the root of this conversation is archived. */
47
+ async function rootConversationIsArchived(executor, conversationId) {
48
+ const rootConversationId = await resolveRootConversationId(executor, conversationId);
49
+ const [row] = await executor.db().select({ archivedAt: juniorConversations.archivedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, rootConversationId)).limit(1);
50
+ return Boolean(row?.archivedAt);
51
+ }
47
52
  /**
48
53
  * Upsert one linked user as a participant on a root conversation.
49
54
  * No-ops and returns false when the identity is missing, unlinked, or not a
50
- * user.
55
+ * user. `resubscribe` ends an unsubscribe: the user addressed Junior again.
51
56
  */
52
57
  async function recordConversationParticipant(executor, args) {
53
58
  const [identity] = await executor.db().select({
@@ -63,7 +68,10 @@ async function recordConversationParticipant(executor, args) {
63
68
  lastMessageAt: at
64
69
  }).onConflictDoUpdate({
65
70
  target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
66
- set: { lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)` }
71
+ set: {
72
+ lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`,
73
+ ...args.resubscribe ? { unsubscribedAt: null } : void 0
74
+ }
67
75
  });
68
76
  return true;
69
77
  }
@@ -345,12 +353,19 @@ function parseSessionSource(value) {
345
353
  async function getConversationIdByProviderConversation(executor, args) {
346
354
  return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
347
355
  }
348
- /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
349
- async function bindProviderConversation(executor, args) {
350
- if (((await executor.db().insert(juniorConversationBindings).values({
356
+ /**
357
+ * Bind provider coordinates to a durable conversation unless another
358
+ * conversation has them. Return whether they belong to this conversation.
359
+ */
360
+ async function claimProviderConversation(executor, args) {
361
+ return ((await executor.db().insert(juniorConversationBindings).values({
351
362
  ...args,
352
363
  createdAt: /* @__PURE__ */ new Date()
353
- }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args)) !== args.conversationId) throw new Error("Provider conversation is already bound to another conversation");
364
+ }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args)) === args.conversationId;
365
+ }
366
+ /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
367
+ async function bindProviderConversation(executor, args) {
368
+ if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
354
369
  }
355
370
  // src/chat/identities/sql.ts
356
371
  function dateFromMs$1(ms) {
@@ -864,9 +879,6 @@ function executionStatusFromValue(value) {
864
879
  if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
865
880
  throw new Error("Conversation record execution status is invalid");
866
881
  }
867
- function executionStatusToSql(status) {
868
- return status === "paused" ? "awaiting_resume" : status;
869
- }
870
882
  function destinationFromRow(destination) {
871
883
  return parseDestination(destination?.provider === "slack" ? {
872
884
  platform: "slack",
@@ -979,7 +991,8 @@ var SqlStore = class {
979
991
  }),
980
992
  kind: args.kind,
981
993
  parentConversationId: args.parentConversationId,
982
- ...location ? { location } : void 0
994
+ ...location ? { location } : void 0,
995
+ ...args.title ? { title: args.title } : void 0
983
996
  };
984
997
  await this.upsertConversation({
985
998
  conversation: child,
@@ -1175,7 +1188,7 @@ var SqlStore = class {
1175
1188
  lastActivityAt: dateFromMs(conversation.lastActivityAtMs),
1176
1189
  updatedAt: dateFromMs(conversation.updatedAtMs),
1177
1190
  executionUpdatedAt: conversation.execution.updatedAtMs === void 0 ? null : dateFromMs(conversation.execution.updatedAtMs),
1178
- executionStatus: executionStatusToSql(conversation.execution.status),
1191
+ executionStatus: conversation.execution.status,
1179
1192
  runId: conversation.execution.runId ?? null,
1180
1193
  lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
1181
1194
  lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs),
@@ -1470,6 +1483,16 @@ const HUMAN_INSTRUCTION_PLATFORMS = /* @__PURE__ */ new Set([
1470
1483
  "web"
1471
1484
  ]);
1472
1485
  /**
1486
+ * True when a Turn input message is addressed to Junior, which subscribes its
1487
+ * author again (contract: `api/conversations/subscription.ts`). A Slack
1488
+ * message in a subscribed thread that does not mention Junior is marked
1489
+ * `explicitMention: false`. Other Sources, such as the dashboard and Slack
1490
+ * mentions and DMs, always address Junior.
1491
+ */
1492
+ function eventAddressesJunior(data) {
1493
+ return data.type === "message" && data.meta?.explicitMention !== false;
1494
+ }
1495
+ /**
1473
1496
  * Whether one event should restore an archived conversation to the feed.
1474
1497
  *
1475
1498
  * Archive hides finished noise until a human comes back. Events,
@@ -1584,16 +1607,19 @@ var SqlConversationEventStore = class {
1584
1607
  */
1585
1608
  async recordTurnInputParticipants(conversationId, inputMessageIds) {
1586
1609
  const rows = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), inArray(sql`${juniorConversationEvents.payload}->>'messageId'`, [...inputMessageIds])));
1610
+ const rootArchived = await rootConversationIsArchived(this.executor, conversationId);
1587
1611
  let restores = false;
1588
1612
  for (const row of rows) {
1589
1613
  const { data } = eventFromRow(row);
1590
1614
  if (!row.actorIdentityId || data.type !== "message") continue;
1615
+ const unarchives = eventUnarchivesConversation(data);
1591
1616
  const isPerson = await recordConversationParticipant(this.executor, {
1592
1617
  actorIdentityId: row.actorIdentityId,
1593
1618
  conversationId,
1594
- atMs: row.createdAt.getTime()
1619
+ atMs: row.createdAt.getTime(),
1620
+ resubscribe: eventAddressesJunior(data) || rootArchived && unarchives
1595
1621
  });
1596
- restores ||= isPerson && eventUnarchivesConversation(data);
1622
+ restores ||= isPerson && unarchives;
1597
1623
  }
1598
1624
  if (restores) await restoreArchivedPath(this.executor.db(), conversationId);
1599
1625
  }
@@ -1620,18 +1646,23 @@ var SqlConversationEventStore = class {
1620
1646
  return (await this.readCursor(conversationId)).maxHistoryVersion ?? 0;
1621
1647
  }
1622
1648
  async loadCurrentHistory(conversationId) {
1623
- const cursor = await this.readCursor(conversationId);
1624
- if (cursor.maxHistoryVersion === null) return [];
1625
- return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, cursor.maxHistoryVersion))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1649
+ const db = this.executor.db();
1650
+ const currentHistoryVersion = db.select({ historyVersion: sql`max(${juniorConversationEvents.historyVersion})` }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
1651
+ return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersion))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1626
1652
  }
1627
1653
  async loadByIdempotencyKey(conversationId, idempotencyKey) {
1628
1654
  const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.idempotencyKey, idempotencyKey))).limit(1);
1629
1655
  return row ? eventFromRow(row) : void 0;
1630
1656
  }
1657
+ async loadEventsAfter(conversationId, afterSeq) {
1658
+ return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), gt(juniorConversationEvents.seq, afterSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1659
+ }
1631
1660
  async loadHistoryContaining(conversationId, seq, throughSeq) {
1632
- const [boundary] = await this.executor.db().select({ historyVersion: juniorConversationEvents.historyVersion }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, seq))).limit(1);
1633
- if (!boundary) return void 0;
1634
- return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, boundary.historyVersion), throughSeq === void 0 ? void 0 : lte(juniorConversationEvents.seq, throughSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1661
+ const db = this.executor.db();
1662
+ const boundaryHistoryVersion = db.select({ historyVersion: juniorConversationEvents.historyVersion }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, seq)));
1663
+ const rows = await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, boundaryHistoryVersion), throughSeq === void 0 ? void 0 : lte(juniorConversationEvents.seq, Math.max(seq, throughSeq)))).orderBy(asc(juniorConversationEvents.seq));
1664
+ if (rows.length === 0) return void 0;
1665
+ return rows.filter((row) => throughSeq === void 0 || row.seq <= throughSeq).map(eventFromRow);
1635
1666
  }
1636
1667
  async loadLatestStructuredEvent(conversationId, namespace, name) {
1637
1668
  const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${namespace}`, sql`${juniorConversationEvents.payload}->>'name' = ${name}`)).orderBy(desc(juniorConversationEvents.seq)).limit(1);
@@ -1652,6 +1683,9 @@ var SqlConversationEventStore = class {
1652
1683
  async loadHistory(conversationId) {
1653
1684
  return (await this.executor.db().select().from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId)).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1654
1685
  }
1686
+ async loadEventsOfType(conversationId, type) {
1687
+ return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1688
+ }
1655
1689
  async query(conversationId, query) {
1656
1690
  if (query.limit < 1) throw new Error("Conversation event query limit must be at least 1");
1657
1691
  if (query.afterSeq !== void 0 && query.beforeSeq !== void 0 && query.afterSeq >= query.beforeSeq) return {
@@ -1776,8 +1810,6 @@ var SqlConversationMessageSearchStore = class {
1776
1810
  isNull(juniorConversations.parentConversationId),
1777
1811
  isNull(juniorConversations.transcriptPurgedAt),
1778
1812
  ne(juniorConversations.conversationId, args.currentConversationId),
1779
- eq(juniorDestinations.provider, args.scope.provider),
1780
- eq(juniorDestinations.providerTenantId, args.scope.providerTenantId),
1781
1813
  eq(juniorDestinations.visibility, "public"),
1782
1814
  eq(juniorConversationEvents.type, "message"),
1783
1815
  sql`${role} in ('user', 'assistant')`
@@ -1881,332 +1913,4 @@ async function closeDb() {
1881
1913
  current = void 0;
1882
1914
  await previous?.db.close();
1883
1915
  }
1884
- // src/chat/state/cache.ts
1885
- const MAX_CACHE_KEY_LENGTH = 512;
1886
- const LOAD_WAIT_MS = 1e4;
1887
- /**
1888
- * Create a cache in the state adapter under `junior:cache:{namespace}:`.
1889
- * Entries are wrapped, so `null` and `false` values are cache hits.
1890
- */
1891
- function createCache(state, namespace) {
1892
- return { async getOrLoad(key, load, options) {
1893
- if (!key.trim()) throw new Error("Cache key is required");
1894
- if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
1895
- const cacheKey = `junior:cache:${namespace}:${key}`;
1896
- const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
1897
- await state.connect();
1898
- const hit = await cached();
1899
- if (hit) return hit.value;
1900
- const attempt = await withLock(state, `${cacheKey}:load`, async () => {
1901
- const loadedMeanwhile = await cached();
1902
- if (loadedMeanwhile) return loadedMeanwhile.value;
1903
- const entry = await load();
1904
- if (entry.ttlMs !== void 0) {
1905
- if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
1906
- await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
1907
- }
1908
- return entry.value;
1909
- }, {
1910
- keepAlive: true,
1911
- waitMs: LOAD_WAIT_MS
1912
- });
1913
- if (attempt.acquired) return attempt.value;
1914
- return (await load()).value;
1915
- } };
1916
- }
1917
- // src/chat/identities/avatar.ts
1918
- /**
1919
- * Profile photos of people, saved on their native Slack and Google
1920
- * identities. Junior serves each photo from its own API, so browsers never
1921
- * load a photo from Slack or Google.
1922
- */
1923
- const AVATAR_HOSTS = {
1924
- slack: ["avatars.slack-edge.com"],
1925
- [GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
1926
- };
1927
- const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
1928
- const AVATAR_CACHE_TTL_MS = 864e5;
1929
- const AVATAR_FAILURE_TTL_MS = 3e5;
1930
- const AVATAR_FETCH_TIMEOUT_MS = 5e3;
1931
- const MAX_AVATAR_BYTES = 1048576;
1932
- const AVATAR_EDGE_PX = 96;
1933
- const MAX_AVATAR_REDIRECTS = 3;
1934
- /**
1935
- * Return the URL when it is HTTPS on a photo host of the provider or a
1936
- * subdomain. Junior fetches only these URLs.
1937
- */
1938
- function parseAvatarUrl(value, provider) {
1939
- const hosts = AVATAR_HOSTS[provider];
1940
- if (!hosts || !value || !URL.canParse(value)) return void 0;
1941
- const url = new URL(value);
1942
- if (url.protocol !== "https:" || url.username || url.password) return;
1943
- const host = url.hostname.toLowerCase();
1944
- return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
1945
- }
1946
- function avatarUrlHash(url) {
1947
- return createHash("sha256").update(url).digest("hex");
1948
- }
1949
- function avatarVersion(url) {
1950
- return avatarUrlHash(url).slice(0, 16);
1951
- }
1952
- function avatarPath(identityId, avatarUrl) {
1953
- return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
1954
- }
1955
- /**
1956
- * Read the photo path of each user: the Slack photo, then the Google photo.
1957
- * Users without a photo are not in the map.
1958
- */
1959
- async function readUserAvatarUrls(db, userIds) {
1960
- if (userIds.length === 0) return /* @__PURE__ */ new Map();
1961
- const rows = await db.select({
1962
- avatarUrl: juniorIdentities.avatarUrl,
1963
- identityId: juniorIdentities.id,
1964
- provider: juniorIdentities.provider,
1965
- updatedAt: juniorIdentities.updatedAt,
1966
- userId: juniorIdentities.userId
1967
- }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), eq(juniorIdentities.kind, "user"), inArray(juniorIdentities.provider, AVATAR_PROVIDERS), isNotNull(juniorIdentities.avatarUrl)));
1968
- const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
1969
- rows.sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
1970
- const avatars = /* @__PURE__ */ new Map();
1971
- for (const row of rows) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
1972
- return avatars;
1973
- }
1974
- /**
1975
- * Return the photo path for one Identity row. A linked Identity uses the
1976
- * photo of its user. An Identity without a user uses its own photo.
1977
- */
1978
- function identityAvatarUrl(row, userAvatarUrls) {
1979
- if (row.userId) return userAvatarUrls.get(row.userId);
1980
- return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
1981
- }
1982
- async function readBoundedBody(response, maxBytes) {
1983
- if (!response.body) return /* @__PURE__ */ new Uint8Array();
1984
- const reader = response.body.getReader();
1985
- const chunks = [];
1986
- let total = 0;
1987
- while (true) {
1988
- const { done, value } = await reader.read();
1989
- if (done) return Buffer.concat(chunks);
1990
- total += value.byteLength;
1991
- if (total > maxBytes) {
1992
- await reader.cancel();
1993
- return;
1994
- }
1995
- chunks.push(value);
1996
- }
1997
- }
1998
- function avatarFetchFailed(host, attributes) {
1999
- logWarn("avatar.fetch.failed", {
2000
- "server.address": host,
2001
- ...attributes
2002
- });
2003
- return null;
2004
- }
2005
- async function fetchAvatarResponse(url, provider, signal) {
2006
- let current = url;
2007
- for (let redirects = 0;; redirects += 1) {
2008
- const response = await fetch(current, {
2009
- redirect: "manual",
2010
- signal
2011
- });
2012
- const location = response.headers.get("location");
2013
- if (response.status < 300 || response.status >= 400 || !location) return response;
2014
- await response.body?.cancel();
2015
- const next = URL.canParse(location, current) ? parseAvatarUrl(new URL(location, current).href, provider) : void 0;
2016
- if (!next) return "redirect_off_host";
2017
- if (redirects >= MAX_AVATAR_REDIRECTS) return "too_many_redirects";
2018
- current = next;
2019
- }
2020
- }
2021
- async function fetchAvatarImage(url, provider) {
2022
- const host = new URL(url).hostname;
2023
- let data;
2024
- try {
2025
- const response = await fetchAvatarResponse(url, provider, AbortSignal.timeout(AVATAR_FETCH_TIMEOUT_MS));
2026
- if (typeof response === "string") return avatarFetchFailed(host, { "app.reason": response });
2027
- if (!response.ok) {
2028
- await response.body?.cancel();
2029
- return avatarFetchFailed(host, { "http.response.status_code": response.status });
2030
- }
2031
- data = await readBoundedBody(response, MAX_AVATAR_BYTES);
2032
- } catch (error) {
2033
- return avatarFetchFailed(host, { "exception.message": error instanceof Error ? error.message : String(error) });
2034
- }
2035
- if (!data) return avatarFetchFailed(host, { "app.reason": "too_large" });
2036
- const contentType = detectImageMediaType(data);
2037
- if (!contentType) return avatarFetchFailed(host, { "app.reason": "not_an_image" });
2038
- try {
2039
- return {
2040
- contentType: "image/webp",
2041
- data: await shrinkAvatar(data)
2042
- };
2043
- } catch (error) {
2044
- logWarn("avatar.resize.failed", {
2045
- "server.address": host,
2046
- "exception.message": error instanceof Error ? error.message : String(error)
2047
- });
2048
- return {
2049
- contentType,
2050
- data: Buffer.from(data).toString("base64")
2051
- };
2052
- }
2053
- }
2054
- async function shrinkAvatar(data) {
2055
- const { default: sharp } = await import("sharp");
2056
- return (await sharp(data).rotate().resize({
2057
- width: AVATAR_EDGE_PX,
2058
- height: AVATAR_EDGE_PX,
2059
- withoutEnlargement: true
2060
- }).webp({ quality: 80 }).toBuffer()).toString("base64");
2061
- }
2062
- /**
2063
- * Read the saved photo of one Identity and its version. Junior fetches it
2064
- * from the provider once, resizes it, and keeps it in the state cache for a
2065
- * day. Return undefined when the Identity has no photo or the provider does
2066
- * not return one.
2067
- */
2068
- async function readAvatarImage(db, state, identityId) {
2069
- const [row] = await db.select({
2070
- avatarUrl: juniorIdentities.avatarUrl,
2071
- provider: juniorIdentities.provider
2072
- }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
2073
- const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
2074
- if (!row?.avatarUrl || !url) return void 0;
2075
- const key = `avatar:${AVATAR_EDGE_PX}:${avatarUrlHash(url)}`;
2076
- const image = await createCache(state, "core").getOrLoad(key, async () => {
2077
- const loaded = await fetchAvatarImage(url, row.provider);
2078
- return {
2079
- value: loaded,
2080
- ttlMs: loaded ? AVATAR_CACHE_TTL_MS : AVATAR_FAILURE_TTL_MS
2081
- };
2082
- });
2083
- return image ? {
2084
- image,
2085
- version: avatarVersion(row.avatarUrl)
2086
- } : void 0;
2087
- }
2088
- // src/chat/plugins/viewer.ts
2089
- function identityFromRow(row) {
2090
- return identitySchema.parse({
2091
- id: row.id,
2092
- provider: row.provider,
2093
- providerSubjectId: row.providerSubjectId,
2094
- ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
2095
- ...row.displayName ? { displayName: row.displayName } : void 0,
2096
- ...row.handle ? { handle: row.handle } : void 0
2097
- });
2098
- }
2099
- async function readUserById(db, userRow) {
2100
- 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)));
2101
- }
2102
- function userFromRows(userRow, identityRows) {
2103
- return userSchema.parse({
2104
- email: userRow.primaryEmail,
2105
- id: userRow.id,
2106
- identities: identityRows.map(identityFromRow),
2107
- ...userRow.displayName ? { displayName: userRow.displayName } : void 0,
2108
- ...userRow.isAdmin ? { isAdmin: true } : void 0
2109
- });
2110
- }
2111
- async function readUserByNormalizedEmail(db, normalizedEmail) {
2112
- const rows = await db.select({
2113
- user: juniorUsers,
2114
- identity: juniorIdentities
2115
- }).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));
2116
- const userRow = rows[0]?.user;
2117
- if (!userRow) return void 0;
2118
- return userFromRows(userRow, rows.flatMap((row) => row.identity ? [row.identity] : []));
2119
- }
2120
- /** Resolve or create the canonical user for one verified viewer email. */
2121
- async function resolveViewerUserFromSql(db, email) {
2122
- const normalizedEmail = normalizeIdentityEmail(email);
2123
- if (!normalizedEmail) return void 0;
2124
- const existing = await readUserByNormalizedEmail(db, normalizedEmail);
2125
- if (existing) return existing;
2126
- const now = /* @__PURE__ */ new Date();
2127
- const userRow = (await db.insert(juniorUsers).values({
2128
- id: randomUUID(),
2129
- primaryEmail: email.trim(),
2130
- primaryEmailNormalized: normalizedEmail,
2131
- displayName: null,
2132
- createdAt: now,
2133
- updatedAt: now
2134
- }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
2135
- return userRow ? await readUserById(db, userRow) : void 0;
2136
- }
2137
- /** Resolve or create the canonical user for one authenticated viewer. */
2138
- async function resolveViewerUser(email) {
2139
- return await resolveViewerUserFromSql(getDb(), email);
2140
- }
2141
- /** Read one existing canonical user by verified email without creating a row. */
2142
- async function findUserByEmailFromSql(db, email) {
2143
- const normalizedEmail = normalizeIdentityEmail(email);
2144
- if (!normalizedEmail) return void 0;
2145
- return await readUserByNormalizedEmail(db, normalizedEmail);
2146
- }
2147
- /** Read one existing canonical user by verified email without creating a row. */
2148
- async function findUserByEmail(email) {
2149
- return await findUserByEmailFromSql(getDb(), email);
2150
- }
2151
- /** Update one canonical user's display name in SQL. */
2152
- async function updateViewerDisplayNameFromSql(db, userId, displayName) {
2153
- const userRow = (await db.update(juniorUsers).set({
2154
- displayName,
2155
- updatedAt: /* @__PURE__ */ new Date()
2156
- }).where(eq(juniorUsers.id, userId)).returning())[0];
2157
- return userRow ? await readUserById(db, userRow) : void 0;
2158
- }
2159
- /** Read the photo path of one canonical user: Slack, then Google. */
2160
- async function readViewerAvatarUrl(userId) {
2161
- return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
2162
- }
2163
- /** Update one canonical user's display name. */
2164
- async function updateViewerDisplayName(userId, displayName) {
2165
- return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
2166
- }
2167
- /**
2168
- * Grant or revoke the Junior-wide admin role for one email.
2169
- *
2170
- * Granting creates the canonical user when needed, so an operator can grant
2171
- * admin before that person first signs in. Revoking never creates a user.
2172
- */
2173
- async function setUserAdminFromSql(db, email, isAdmin) {
2174
- const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
2175
- if (!user) return void 0;
2176
- const userRow = (await db.update(juniorUsers).set({
2177
- isAdmin,
2178
- updatedAt: /* @__PURE__ */ new Date()
2179
- }).where(eq(juniorUsers.id, user.id)).returning())[0];
2180
- return userRow ? await readUserById(db, userRow) : void 0;
2181
- }
2182
- /** List every Junior admin by primary email. */
2183
- async function listAdminUsersFromSql(db) {
2184
- const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
2185
- return await Promise.all(rows.map((row) => readUserById(db, row)));
2186
- }
2187
- /** Resolve the stored identity and linked user for one runtime actor. */
2188
- async function readActorIdentityFromSql(db, actor) {
2189
- const identityId = await findActorIdentityId(db, actor);
2190
- return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
2191
- }
2192
- /** Resolve the stored identity and linked user for one runtime actor. */
2193
- async function readActorIdentity(actor) {
2194
- return await readActorIdentityFromSql(getDb(), actor);
2195
- }
2196
- /** Read one stored identity and its linked user by identity id. */
2197
- async function readIdentityByIdFromSql(db, identityId) {
2198
- const row = (await db.select({
2199
- identity: juniorIdentities,
2200
- user: juniorUsers
2201
- }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
2202
- if (!row) return void 0;
2203
- return {
2204
- identity: identityFromRow(row.identity),
2205
- ...row.user ? { user: await readUserById(db, row.user) } : void 0
2206
- };
2207
- }
2208
- /** Read one stored identity and its linked user by identity id. */
2209
- async function readIdentityById(identityId) {
2210
- return await readIdentityByIdFromSql(getDb(), identityId);
2211
- }
2212
- export { conversationDetailTouch as $, conversationAncestors as A, startLocationThread as B, getSqlExecutor as C, createSqlConversationEventStore as D, treeHasAnnotationKey as E, createSqlStore as F, deleteProviderIdentityForUser as G, resolveActorIdentityId as H, withConversationMutationLock as I, recordGoogleSignIn as J, findUserByVerifiedEmails as K, conversationKindFromRow as L, readConversationTrees as M, setArchivedAt as N, eventFromRow as O, loadConversationSlackTenantIds as P, parseSessionSource as Q, locationFromRow as R, getDb as S, hasAnnotationKey as T, saveActorAvatar as U, SYSTEM_IDENTITY_ID as V, deleteProviderIdentityForSlackUser as W, upsertLinkedIdentity as X, saveUserTimezone as Y, bindProviderConversation as Z, closeDb as _, readActorIdentityFromSql as a, agentTurnUsageSchema as at, getConversationMessageSearchStore as b, readViewerAvatarUrl as c, createSlackDestination as ct, updateViewerDisplayName as d, sameDestination as dt, nextDetailVersion as et, identityAvatarUrl as f, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, agentTurnTotalTokens as it, conversationDescendants as j, withConversationEventLock as k, resolveViewerUser as l, parseDestination as lt, readAvatarImage as m, findUserByEmailFromSql as n, addAgentTurnUsage as nt, readIdentityById as o, hasAgentTurnUsage as ot, parseAvatarUrl as p, readUserTimezone as q, listAdminUsersFromSql as r, agentTurnCostUsd as rt, readIdentityByIdFromSql as s, resolveRootConversationId as st, findUserByEmail as t, touchConversationDetail as tt, setUserAdminFromSql as u, requireSlackDestination as ut, db_exports as v, conversationIdsWithAnnotation as w, getConversationStore as x, getConversationEventStore as y, setFirstConversationLocation as z };
1916
+ export { deleteProviderIdentityForUser as A, conversationDetailTouch as B, setFirstConversationLocation as C, resolveActorIdentityId as D, findActorIdentityId as E, upsertLinkedIdentity as F, agentTurnTotalTokens as G, touchConversationDetail as H, bindProviderConversation as I, resolveRootConversationId as J, agentTurnUsageSchema as K, claimProviderConversation as L, readUserTimezone as M, recordGoogleSignIn as N, saveActorAvatar as O, saveUserTimezone as P, sameDestination as Q, getConversationIdByProviderConversation as R, locationFromRow as S, SYSTEM_IDENTITY_ID as T, addAgentTurnUsage as U, nextDetailVersion as V, agentTurnCostUsd as W, parseDestination as X, createSlackDestination as Y, requireSlackDestination as Z, setArchivedAt as _, getConversationStore as a, withConversationMutationLock as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, findUserByVerifiedEmails as j, deleteProviderIdentityForSlackUser as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, getDb as o, withConversationEventLock as p, hasAgentTurnUsage as q, getConversationEventStore as r, getSqlExecutor as s, closeDb as t, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, startLocationThread as w, conversationKindFromRow as x, createSqlStore as y, parseSessionSource as z };
@@ -1,4 +1,4 @@
1
- import "./schema-Ih60j59-.js";
1
+ import "./schema-B_6aOcx5.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -129,13 +129,17 @@ interface Conversation {
129
129
  }
130
130
  /** Persist and read durable conversation metadata for reporting surfaces. */
131
131
  interface ConversationStore {
132
- /** Create one Conversation with an immutable parent and kind. */
132
+ /**
133
+ * Create one Conversation with an immutable parent and kind. `title` is
134
+ * saved only when the child is new.
135
+ */
133
136
  createChild(args: {
134
137
  childConversationId: string;
135
138
  kind: Exclude<ConversationKind, "root">;
136
139
  parentConversationId: string;
137
140
  nowMs?: number;
138
141
  source?: ConversationSource;
142
+ title?: string;
139
143
  }): Promise<void>;
140
144
  get(args: {
141
145
  conversationId: string;