@sentry/junior 0.285.0 → 0.287.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-DN5AB4VU.js → adapter-CL-HUKgd.js} +1 -1
  2. package/dist/{admin-DOITMKnn.js → admin-C9urXVfi.js} +2 -1
  3. package/dist/{agent-runner-BsWhHe4N.js → agent-runner-Bfnw551N.js} +2174 -1323
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +73 -112
  8. package/dist/{app-DyMs9330.d.ts → app-DBY5TnfY.d.ts} +2 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +72 -42
  11. package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-u_PRYzuz.js} +1 -1
  12. package/dist/{automation-Mk8aaHzy.js → automation-DksGNDRO.js} +3 -6
  13. package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-CYI909P5.js} +137 -3
  14. package/dist/{briefs-Cl8-nK9B.js → briefs-DaXiMWzT.js} +6 -5
  15. package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-BCIuBe4d.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 +5 -6
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-DDbBucBw.js → config-CkHcUMN7.js} +580 -3
  24. package/dist/{connections-DA4LT9LL.js → connections-BnIj0wtx.js} +16 -50
  25. package/dist/{conversation-D8kVoCrP.js → conversation-E7ZPJx2H.js} +22 -6
  26. package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DVch6YQw.js} +2 -5
  27. package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-DF1hW0ja.js} +1 -1
  28. package/dist/{credential-sync-hcsYatw-.js → credential-sync-CzMar9hq.js} +13 -13
  29. package/dist/{viewer-1Ea81s0b.js → db-DJ11eZqq.js} +64 -367
  30. package/dist/{db-BhHZSuFw.d.ts → db-YDKKDxlh.d.ts} +4 -4
  31. package/dist/{executor-BLEMIgIZ.js → executor-BY9TB31g.js} +20 -19
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BfORLKoq.js → logging-BO5zU6Mt.js} +1 -1
  34. package/dist/{media-Bu9C6lz0.js → media-Cz1ZiV1U.js} +16 -4
  35. package/dist/{message-DqjuKzUx.js → message-CsUbuEc8.js} +10 -10
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -3
  38. package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-hiDKK0_n.js} +2 -2
  39. package/dist/{projection-DliWYrnT.js → projection-CL_YWeGf.js} +352 -356
  40. package/dist/{prompt-BvIUzY4y.js → prompt-BHOEQSmf.js} +182 -2
  41. package/dist/{registry-rC7MCxu8.js → registry-BriFLnaJ.js} +1 -1
  42. package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
  43. package/dist/{resolve-Biu8Qw3u.js → resolve-Bt6GgAiA.js} +3 -3
  44. package/dist/{result-DxJMCX47.js → result-Bo1TZu0Q.js} +8 -8
  45. package/dist/{runner-BQJSFLKg.js → runner-D3YeCQgt.js} +16 -12
  46. package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-CcnSPP4S.js} +1 -1
  47. package/dist/{schema-BasXTvi2.js → schema-BWE3RJEB.js} +19 -7
  48. package/dist/{schema-BUviRAs8.d.ts → schema-C6fsEwjo.d.ts} +90 -8
  49. package/dist/{service-account-BI5Wgx22.js → service-account-DiQQuuw7.js} +3 -3
  50. package/dist/{service-account-CAE-_1dR.js → service-account-r6fl0b-9.js} +3 -3
  51. package/dist/{session-stop-CA-jOJ84.js → session-stop-B2Nut40V.js} +27 -25
  52. package/dist/{skills-B22duVJU.js → skills-CD5aJdzg.js} +2 -2
  53. package/dist/spawn-CalgZQiu.js +79 -0
  54. package/dist/{stop-DioIcEAu.js → stop-kujZLbi0.js} +233 -1127
  55. package/dist/{store-Dn4W7qgH.js → store-DdIEUL1q.js} +3 -3
  56. package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-D_RDr2Hu.js} +1440 -993
  57. package/dist/{store-B26LV6UP.js → turn-failure-response-B5nV1Er-.js} +337 -6
  58. package/dist/{validation-TzhfQABF.js → validation-K4pqwoVZ.js} +1 -1
  59. package/dist/{version-DSk8CFvA.js → version-DBvhk1X9.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/viewer-DrMmFUul.js +337 -0
  62. package/dist/{work-ybG4_q5C.js → work-ljRoODGu.js} +110 -94
  63. package/dist/{worker-ccSyZRNz.js → worker-CYO1Q0Js.js} +5 -6
  64. package/migrations/0086_shared_archive.sql +31 -0
  65. package/migrations/0087_child_location.sql +64 -0
  66. package/migrations/0088_conversation_unsubscribe.sql +1 -0
  67. package/migrations/meta/0086_snapshot.json +4366 -0
  68. package/migrations/meta/0087_snapshot.json +4366 -0
  69. package/migrations/meta/0088_snapshot.json +4372 -0
  70. package/migrations/meta/_journal.json +21 -0
  71. package/package.json +5 -4
  72. package/dist/config-DqFnykQT.js +0 -579
  73. package/dist/spawn-BB2_4VYn.js +0 -31
  74. package/dist/task-queue-Bt0IoR2i.js +0 -139
  75. package/dist/task-runner-D8lddjzp.js +0 -290
  76. package/dist/thread-state-CrFk3K_7.js +0 -173
  77. package/dist/turn-failure-response-DaJ04qVj.js +0 -224
  78. package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
@@ -1,13 +1,12 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-DqFnykQT.js";
3
- import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-BfORLKoq.js";
2
+ import { i as getChatConfig } from "./config-CkHcUMN7.js";
3
+ import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-BO5zU6Mt.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 conversationReadColumns, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, S as juniorConversationMetrics, j as juniorConversations, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-BLEMIgIZ.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-Bu9C6lz0.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-BY9TB31g.js";
6
+ import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-Cz1ZiV1U.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({
@@ -65,7 +70,7 @@ async function recordConversationParticipant(executor, args) {
65
70
  target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
66
71
  set: {
67
72
  lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`,
68
- ...args.restoreArchive ? { archivedAt: null } : void 0
73
+ ...args.resubscribe ? { unsubscribedAt: null } : void 0
69
74
  }
70
75
  });
71
76
  return true;
@@ -916,7 +921,7 @@ function conversationFromRow(readRow) {
916
921
  },
917
922
  kind: conversationKindFromRow(row),
918
923
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
919
- ...row.childArchivedAt ? { childArchivedAtMs: row.childArchivedAt.getTime() } : void 0,
924
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
920
925
  ...destination ? { destination } : void 0,
921
926
  ...location ? { location } : void 0,
922
927
  ...actor ? { actor } : void 0,
@@ -971,7 +976,9 @@ var SqlStore = class {
971
976
  if (existing.kind !== args.kind) throw new Error(`Conversation kind changed for ${args.childConversationId}`);
972
977
  return;
973
978
  }
974
- if (!await this.get({ conversationId: args.parentConversationId })) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
979
+ const parentRow = await this.readConversationRow(args.parentConversationId);
980
+ if (!parentRow) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
981
+ const { location } = conversationFromRow(parentRow);
975
982
  const child = {
976
983
  ...emptyConversation({
977
984
  conversationId: args.childConversationId,
@@ -979,9 +986,13 @@ var SqlStore = class {
979
986
  source: args.source
980
987
  }),
981
988
  kind: args.kind,
982
- parentConversationId: args.parentConversationId
989
+ parentConversationId: args.parentConversationId,
990
+ ...location ? { location } : void 0
983
991
  };
984
- await this.upsertConversation({ conversation: child });
992
+ await this.upsertConversation({
993
+ conversation: child,
994
+ destinationId: parentRow.conversation.destinationId ?? void 0
995
+ });
985
996
  });
986
997
  });
987
998
  }
@@ -1082,7 +1093,7 @@ var SqlStore = class {
1082
1093
  }
1083
1094
  async listByActivity(args = {}) {
1084
1095
  const rows = await this.executor.db().select({
1085
- conversation: conversationReadColumns(),
1096
+ conversation: juniorConversations,
1086
1097
  destination: juniorDestinations,
1087
1098
  actorIdentity: juniorIdentities,
1088
1099
  actorUserDisplayName: juniorUsers.displayName
@@ -1120,7 +1131,7 @@ var SqlStore = class {
1120
1131
  }
1121
1132
  async readConversationRow(conversationId) {
1122
1133
  return (await this.executor.db().select({
1123
- conversation: conversationReadColumns(),
1134
+ conversation: juniorConversations,
1124
1135
  destination: juniorDestinations,
1125
1136
  actorIdentity: juniorIdentities,
1126
1137
  actorUserDisplayName: juniorUsers.displayName
@@ -1141,7 +1152,7 @@ var SqlStore = class {
1141
1152
  conversationId: conversation.conversationId,
1142
1153
  destination: conversation.destination,
1143
1154
  ...conversation.visibility ? { visibility: conversation.visibility } : void 0
1144
- }), conversation.updatedAtMs);
1155
+ }), conversation.updatedAtMs) ?? args.destinationId;
1145
1156
  const location = locationForWrite({
1146
1157
  destination: conversation.destination,
1147
1158
  destinationId,
@@ -1376,13 +1387,13 @@ function sanitizePostgresJson(value) {
1376
1387
  async function readConversationTrees(db, rootConversationIds) {
1377
1388
  if (rootConversationIds.length === 0) return /* @__PURE__ */ new Map();
1378
1389
  const rows = await db.select({
1379
- childArchivedAt: juniorConversations.childArchivedAt,
1390
+ archivedAt: juniorConversations.archivedAt,
1380
1391
  conversationId: juniorConversations.conversationId,
1381
1392
  kind: juniorConversations.kind,
1382
1393
  parentConversationId: juniorConversations.parentConversationId
1383
1394
  }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
1384
1395
  return new Map(rows.map((row) => [row.conversationId, {
1385
- childArchivedAt: row.childArchivedAt,
1396
+ archivedAt: row.archivedAt,
1386
1397
  conversationId: row.conversationId,
1387
1398
  kind: conversationKindFromRow(row),
1388
1399
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
@@ -1422,29 +1433,33 @@ function conversationDescendants(tree, conversationId) {
1422
1433
  }
1423
1434
  return descendants;
1424
1435
  }
1425
- /** Set or clear the shared archive of the given child Conversations. */
1426
- async function setChildArchivedAt(db, conversationIds, archivedAt) {
1436
+ /** Set or clear the shared archive of the given Conversations. */
1437
+ async function setArchivedAt(db, conversationIds, archivedAt) {
1427
1438
  if (conversationIds.length === 0) return;
1428
1439
  await db.update(juniorConversations).set({
1429
- childArchivedAt: archivedAt,
1440
+ archivedAt,
1430
1441
  detailVersion: nextDetailVersion
1431
1442
  }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
1432
1443
  }
1433
1444
  /**
1434
- * Restore one archived child and its archived ancestor children, so the child
1435
- * shows again. Its descendants keep their archive. A root has no child
1436
- * archive, so this changes nothing for a root.
1445
+ * Restore one archived Conversation and its archived ancestors, so it shows
1446
+ * again. Its descendants keep their archive.
1437
1447
  */
1438
- async function restoreArchivedChildPath(db, conversationId) {
1448
+ async function restoreArchivedPath(db, conversationId) {
1439
1449
  const [row] = await db.select({
1450
+ archivedAt: juniorConversations.archivedAt,
1440
1451
  parentConversationId: juniorConversations.parentConversationId,
1441
1452
  rootConversationId: juniorConversations.rootConversationId
1442
1453
  }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
1443
- if (!row?.parentConversationId || !row.rootConversationId) return;
1454
+ if (!row) return;
1455
+ if (!row.parentConversationId || !row.rootConversationId) {
1456
+ if (row.archivedAt) await setArchivedAt(db, [conversationId], null);
1457
+ return;
1458
+ }
1444
1459
  const tree = await readConversationTrees(db, [row.rootConversationId]);
1445
1460
  const node = tree.get(conversationId);
1446
1461
  if (!node) return;
1447
- await setChildArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.kind !== "root" && entry.childArchivedAt).map((entry) => entry.conversationId), null);
1462
+ await setArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.archivedAt).map((entry) => entry.conversationId), null);
1448
1463
  }
1449
1464
  // src/chat/conversations/sql/event-lock.ts
1450
1465
  /** Serialize event sequence allocation with other conversation writes. */
@@ -1463,6 +1478,16 @@ const HUMAN_INSTRUCTION_PLATFORMS = /* @__PURE__ */ new Set([
1463
1478
  "web"
1464
1479
  ]);
1465
1480
  /**
1481
+ * True when a Turn input message is addressed to Junior, which subscribes its
1482
+ * author again (contract: `api/conversations/subscription.ts`). A Slack
1483
+ * message in a subscribed thread that does not mention Junior is marked
1484
+ * `explicitMention: false`. Other Sources, such as the dashboard and Slack
1485
+ * mentions and DMs, always address Junior.
1486
+ */
1487
+ function eventAddressesJunior(data) {
1488
+ return data.type === "message" && data.meta?.explicitMention !== false;
1489
+ }
1490
+ /**
1466
1491
  * Whether one event should restore an archived conversation to the feed.
1467
1492
  *
1468
1493
  * Archive hides finished noise until a human comes back. Events,
@@ -1577,20 +1602,21 @@ var SqlConversationEventStore = class {
1577
1602
  */
1578
1603
  async recordTurnInputParticipants(conversationId, inputMessageIds) {
1579
1604
  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])));
1580
- let restoresChild = false;
1605
+ const rootArchived = await rootConversationIsArchived(this.executor, conversationId);
1606
+ let restores = false;
1581
1607
  for (const row of rows) {
1582
1608
  const { data } = eventFromRow(row);
1583
1609
  if (!row.actorIdentityId || data.type !== "message") continue;
1584
- const restoreArchive = eventUnarchivesConversation(data);
1610
+ const unarchives = eventUnarchivesConversation(data);
1585
1611
  const isPerson = await recordConversationParticipant(this.executor, {
1586
1612
  actorIdentityId: row.actorIdentityId,
1587
1613
  conversationId,
1588
1614
  atMs: row.createdAt.getTime(),
1589
- restoreArchive
1615
+ resubscribe: eventAddressesJunior(data) || rootArchived && unarchives
1590
1616
  });
1591
- restoresChild ||= isPerson && restoreArchive;
1617
+ restores ||= isPerson && unarchives;
1592
1618
  }
1593
- if (restoresChild) await restoreArchivedChildPath(this.executor.db(), conversationId);
1619
+ if (restores) await restoreArchivedPath(this.executor.db(), conversationId);
1594
1620
  }
1595
1621
  async replaceHistory(conversationId, replacement, options = {}) {
1596
1622
  const parsed = historyReplacementSchema.parse(replacement);
@@ -1638,17 +1664,18 @@ var SqlConversationEventStore = class {
1638
1664
  }
1639
1665
  async loadMessageHistory(conversationId) {
1640
1666
  const [compactionRow] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "messages_summarized"))).orderBy(desc(juniorConversationEvents.seq)).limit(1);
1641
- const compaction = compactionRow ? messagesSummarizedEventFromRow(compactionRow) : void 0;
1642
- const historyFromSeq = compaction?.data.historyFromSeq ?? 0;
1667
+ const historyFromSeq = compactionRow ? messagesSummarizedEventFromRow(compactionRow).data.historyFromSeq : 0;
1643
1668
  return {
1644
1669
  events: (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.type, messageHistoryEventTypes), gte(juniorConversationEvents.seq, historyFromSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow),
1645
- compaction,
1646
1670
  historyFromSeq
1647
1671
  };
1648
1672
  }
1649
1673
  async loadHistory(conversationId) {
1650
1674
  return (await this.executor.db().select().from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId)).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1651
1675
  }
1676
+ async loadEventsOfType(conversationId, type) {
1677
+ return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1678
+ }
1652
1679
  async query(conversationId, query) {
1653
1680
  if (query.limit < 1) throw new Error("Conversation event query limit must be at least 1");
1654
1681
  if (query.afterSeq !== void 0 && query.beforeSeq !== void 0 && query.afterSeq >= query.beforeSeq) return {
@@ -1773,8 +1800,6 @@ var SqlConversationMessageSearchStore = class {
1773
1800
  isNull(juniorConversations.parentConversationId),
1774
1801
  isNull(juniorConversations.transcriptPurgedAt),
1775
1802
  ne(juniorConversations.conversationId, args.currentConversationId),
1776
- eq(juniorDestinations.provider, args.scope.provider),
1777
- eq(juniorDestinations.providerTenantId, args.scope.providerTenantId),
1778
1803
  eq(juniorDestinations.visibility, "public"),
1779
1804
  eq(juniorConversationEvents.type, "message"),
1780
1805
  sql`${role} in ('user', 'assistant')`
@@ -1878,332 +1903,4 @@ async function closeDb() {
1878
1903
  current = void 0;
1879
1904
  await previous?.db.close();
1880
1905
  }
1881
- // src/chat/state/cache.ts
1882
- const MAX_CACHE_KEY_LENGTH = 512;
1883
- const LOAD_WAIT_MS = 1e4;
1884
- /**
1885
- * Create a cache in the state adapter under `junior:cache:{namespace}:`.
1886
- * Entries are wrapped, so `null` and `false` values are cache hits.
1887
- */
1888
- function createCache(state, namespace) {
1889
- return { async getOrLoad(key, load, options) {
1890
- if (!key.trim()) throw new Error("Cache key is required");
1891
- if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
1892
- const cacheKey = `junior:cache:${namespace}:${key}`;
1893
- const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
1894
- await state.connect();
1895
- const hit = await cached();
1896
- if (hit) return hit.value;
1897
- const attempt = await withLock(state, `${cacheKey}:load`, async () => {
1898
- const loadedMeanwhile = await cached();
1899
- if (loadedMeanwhile) return loadedMeanwhile.value;
1900
- const entry = await load();
1901
- if (entry.ttlMs !== void 0) {
1902
- if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
1903
- await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
1904
- }
1905
- return entry.value;
1906
- }, {
1907
- keepAlive: true,
1908
- waitMs: LOAD_WAIT_MS
1909
- });
1910
- if (attempt.acquired) return attempt.value;
1911
- return (await load()).value;
1912
- } };
1913
- }
1914
- // src/chat/identities/avatar.ts
1915
- /**
1916
- * Profile photos of people, saved on their native Slack and Google
1917
- * identities. Junior serves each photo from its own API, so browsers never
1918
- * load a photo from Slack or Google.
1919
- */
1920
- const AVATAR_HOSTS = {
1921
- slack: ["avatars.slack-edge.com"],
1922
- [GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
1923
- };
1924
- const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
1925
- const AVATAR_CACHE_TTL_MS = 864e5;
1926
- const AVATAR_FAILURE_TTL_MS = 3e5;
1927
- const AVATAR_FETCH_TIMEOUT_MS = 5e3;
1928
- const MAX_AVATAR_BYTES = 1048576;
1929
- const AVATAR_EDGE_PX = 96;
1930
- const MAX_AVATAR_REDIRECTS = 3;
1931
- /**
1932
- * Return the URL when it is HTTPS on a photo host of the provider or a
1933
- * subdomain. Junior fetches only these URLs.
1934
- */
1935
- function parseAvatarUrl(value, provider) {
1936
- const hosts = AVATAR_HOSTS[provider];
1937
- if (!hosts || !value || !URL.canParse(value)) return void 0;
1938
- const url = new URL(value);
1939
- if (url.protocol !== "https:" || url.username || url.password) return;
1940
- const host = url.hostname.toLowerCase();
1941
- return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
1942
- }
1943
- function avatarUrlHash(url) {
1944
- return createHash("sha256").update(url).digest("hex");
1945
- }
1946
- function avatarVersion(url) {
1947
- return avatarUrlHash(url).slice(0, 16);
1948
- }
1949
- function avatarPath(identityId, avatarUrl) {
1950
- return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
1951
- }
1952
- /**
1953
- * Read the photo path of each user: the Slack photo, then the Google photo.
1954
- * Users without a photo are not in the map.
1955
- */
1956
- async function readUserAvatarUrls(db, userIds) {
1957
- if (userIds.length === 0) return /* @__PURE__ */ new Map();
1958
- const rows = await db.select({
1959
- avatarUrl: juniorIdentities.avatarUrl,
1960
- identityId: juniorIdentities.id,
1961
- provider: juniorIdentities.provider,
1962
- updatedAt: juniorIdentities.updatedAt,
1963
- userId: juniorIdentities.userId
1964
- }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), eq(juniorIdentities.kind, "user"), inArray(juniorIdentities.provider, AVATAR_PROVIDERS), isNotNull(juniorIdentities.avatarUrl)));
1965
- const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
1966
- rows.sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
1967
- const avatars = /* @__PURE__ */ new Map();
1968
- for (const row of rows) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
1969
- return avatars;
1970
- }
1971
- /**
1972
- * Return the photo path for one Identity row. A linked Identity uses the
1973
- * photo of its user. An Identity without a user uses its own photo.
1974
- */
1975
- function identityAvatarUrl(row, userAvatarUrls) {
1976
- if (row.userId) return userAvatarUrls.get(row.userId);
1977
- return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
1978
- }
1979
- async function readBoundedBody(response, maxBytes) {
1980
- if (!response.body) return /* @__PURE__ */ new Uint8Array();
1981
- const reader = response.body.getReader();
1982
- const chunks = [];
1983
- let total = 0;
1984
- while (true) {
1985
- const { done, value } = await reader.read();
1986
- if (done) return Buffer.concat(chunks);
1987
- total += value.byteLength;
1988
- if (total > maxBytes) {
1989
- await reader.cancel();
1990
- return;
1991
- }
1992
- chunks.push(value);
1993
- }
1994
- }
1995
- function avatarFetchFailed(host, attributes) {
1996
- logWarn("avatar.fetch.failed", {
1997
- "server.address": host,
1998
- ...attributes
1999
- });
2000
- return null;
2001
- }
2002
- async function fetchAvatarResponse(url, provider, signal) {
2003
- let current = url;
2004
- for (let redirects = 0;; redirects += 1) {
2005
- const response = await fetch(current, {
2006
- redirect: "manual",
2007
- signal
2008
- });
2009
- const location = response.headers.get("location");
2010
- if (response.status < 300 || response.status >= 400 || !location) return response;
2011
- await response.body?.cancel();
2012
- const next = URL.canParse(location, current) ? parseAvatarUrl(new URL(location, current).href, provider) : void 0;
2013
- if (!next) return "redirect_off_host";
2014
- if (redirects >= MAX_AVATAR_REDIRECTS) return "too_many_redirects";
2015
- current = next;
2016
- }
2017
- }
2018
- async function fetchAvatarImage(url, provider) {
2019
- const host = new URL(url).hostname;
2020
- let data;
2021
- try {
2022
- const response = await fetchAvatarResponse(url, provider, AbortSignal.timeout(AVATAR_FETCH_TIMEOUT_MS));
2023
- if (typeof response === "string") return avatarFetchFailed(host, { "app.reason": response });
2024
- if (!response.ok) {
2025
- await response.body?.cancel();
2026
- return avatarFetchFailed(host, { "http.response.status_code": response.status });
2027
- }
2028
- data = await readBoundedBody(response, MAX_AVATAR_BYTES);
2029
- } catch (error) {
2030
- return avatarFetchFailed(host, { "exception.message": error instanceof Error ? error.message : String(error) });
2031
- }
2032
- if (!data) return avatarFetchFailed(host, { "app.reason": "too_large" });
2033
- const contentType = detectImageMediaType(data);
2034
- if (!contentType) return avatarFetchFailed(host, { "app.reason": "not_an_image" });
2035
- try {
2036
- return {
2037
- contentType: "image/webp",
2038
- data: await shrinkAvatar(data)
2039
- };
2040
- } catch (error) {
2041
- logWarn("avatar.resize.failed", {
2042
- "server.address": host,
2043
- "exception.message": error instanceof Error ? error.message : String(error)
2044
- });
2045
- return {
2046
- contentType,
2047
- data: Buffer.from(data).toString("base64")
2048
- };
2049
- }
2050
- }
2051
- async function shrinkAvatar(data) {
2052
- const { default: sharp } = await import("sharp");
2053
- return (await sharp(data).rotate().resize({
2054
- width: AVATAR_EDGE_PX,
2055
- height: AVATAR_EDGE_PX,
2056
- withoutEnlargement: true
2057
- }).webp({ quality: 80 }).toBuffer()).toString("base64");
2058
- }
2059
- /**
2060
- * Read the saved photo of one Identity and its version. Junior fetches it
2061
- * from the provider once, resizes it, and keeps it in the state cache for a
2062
- * day. Return undefined when the Identity has no photo or the provider does
2063
- * not return one.
2064
- */
2065
- async function readAvatarImage(db, state, identityId) {
2066
- const [row] = await db.select({
2067
- avatarUrl: juniorIdentities.avatarUrl,
2068
- provider: juniorIdentities.provider
2069
- }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
2070
- const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
2071
- if (!row?.avatarUrl || !url) return void 0;
2072
- const key = `avatar:${AVATAR_EDGE_PX}:${avatarUrlHash(url)}`;
2073
- const image = await createCache(state, "core").getOrLoad(key, async () => {
2074
- const loaded = await fetchAvatarImage(url, row.provider);
2075
- return {
2076
- value: loaded,
2077
- ttlMs: loaded ? AVATAR_CACHE_TTL_MS : AVATAR_FAILURE_TTL_MS
2078
- };
2079
- });
2080
- return image ? {
2081
- image,
2082
- version: avatarVersion(row.avatarUrl)
2083
- } : void 0;
2084
- }
2085
- // src/chat/plugins/viewer.ts
2086
- function identityFromRow(row) {
2087
- return identitySchema.parse({
2088
- id: row.id,
2089
- provider: row.provider,
2090
- providerSubjectId: row.providerSubjectId,
2091
- ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
2092
- ...row.displayName ? { displayName: row.displayName } : void 0,
2093
- ...row.handle ? { handle: row.handle } : void 0
2094
- });
2095
- }
2096
- async function readUserById(db, userRow) {
2097
- 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)));
2098
- }
2099
- function userFromRows(userRow, identityRows) {
2100
- return userSchema.parse({
2101
- email: userRow.primaryEmail,
2102
- id: userRow.id,
2103
- identities: identityRows.map(identityFromRow),
2104
- ...userRow.displayName ? { displayName: userRow.displayName } : void 0,
2105
- ...userRow.isAdmin ? { isAdmin: true } : void 0
2106
- });
2107
- }
2108
- async function readUserByNormalizedEmail(db, normalizedEmail) {
2109
- const rows = await db.select({
2110
- user: juniorUsers,
2111
- identity: juniorIdentities
2112
- }).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));
2113
- const userRow = rows[0]?.user;
2114
- if (!userRow) return void 0;
2115
- return userFromRows(userRow, rows.flatMap((row) => row.identity ? [row.identity] : []));
2116
- }
2117
- /** Resolve or create the canonical user for one verified viewer email. */
2118
- async function resolveViewerUserFromSql(db, email) {
2119
- const normalizedEmail = normalizeIdentityEmail(email);
2120
- if (!normalizedEmail) return void 0;
2121
- const existing = await readUserByNormalizedEmail(db, normalizedEmail);
2122
- if (existing) return existing;
2123
- const now = /* @__PURE__ */ new Date();
2124
- const userRow = (await db.insert(juniorUsers).values({
2125
- id: randomUUID(),
2126
- primaryEmail: email.trim(),
2127
- primaryEmailNormalized: normalizedEmail,
2128
- displayName: null,
2129
- createdAt: now,
2130
- updatedAt: now
2131
- }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
2132
- return userRow ? await readUserById(db, userRow) : void 0;
2133
- }
2134
- /** Resolve or create the canonical user for one authenticated viewer. */
2135
- async function resolveViewerUser(email) {
2136
- return await resolveViewerUserFromSql(getDb(), email);
2137
- }
2138
- /** Read one existing canonical user by verified email without creating a row. */
2139
- async function findUserByEmailFromSql(db, email) {
2140
- const normalizedEmail = normalizeIdentityEmail(email);
2141
- if (!normalizedEmail) return void 0;
2142
- return await readUserByNormalizedEmail(db, normalizedEmail);
2143
- }
2144
- /** Read one existing canonical user by verified email without creating a row. */
2145
- async function findUserByEmail(email) {
2146
- return await findUserByEmailFromSql(getDb(), email);
2147
- }
2148
- /** Update one canonical user's display name in SQL. */
2149
- async function updateViewerDisplayNameFromSql(db, userId, displayName) {
2150
- const userRow = (await db.update(juniorUsers).set({
2151
- displayName,
2152
- updatedAt: /* @__PURE__ */ new Date()
2153
- }).where(eq(juniorUsers.id, userId)).returning())[0];
2154
- return userRow ? await readUserById(db, userRow) : void 0;
2155
- }
2156
- /** Read the photo path of one canonical user: Slack, then Google. */
2157
- async function readViewerAvatarUrl(userId) {
2158
- return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
2159
- }
2160
- /** Update one canonical user's display name. */
2161
- async function updateViewerDisplayName(userId, displayName) {
2162
- return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
2163
- }
2164
- /**
2165
- * Grant or revoke the Junior-wide admin role for one email.
2166
- *
2167
- * Granting creates the canonical user when needed, so an operator can grant
2168
- * admin before that person first signs in. Revoking never creates a user.
2169
- */
2170
- async function setUserAdminFromSql(db, email, isAdmin) {
2171
- const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
2172
- if (!user) return void 0;
2173
- const userRow = (await db.update(juniorUsers).set({
2174
- isAdmin,
2175
- updatedAt: /* @__PURE__ */ new Date()
2176
- }).where(eq(juniorUsers.id, user.id)).returning())[0];
2177
- return userRow ? await readUserById(db, userRow) : void 0;
2178
- }
2179
- /** List every Junior admin by primary email. */
2180
- async function listAdminUsersFromSql(db) {
2181
- const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
2182
- return await Promise.all(rows.map((row) => readUserById(db, row)));
2183
- }
2184
- /** Resolve the stored identity and linked user for one runtime actor. */
2185
- async function readActorIdentityFromSql(db, actor) {
2186
- const identityId = await findActorIdentityId(db, actor);
2187
- return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
2188
- }
2189
- /** Resolve the stored identity and linked user for one runtime actor. */
2190
- async function readActorIdentity(actor) {
2191
- return await readActorIdentityFromSql(getDb(), actor);
2192
- }
2193
- /** Read one stored identity and its linked user by identity id. */
2194
- async function readIdentityByIdFromSql(db, identityId) {
2195
- const row = (await db.select({
2196
- identity: juniorIdentities,
2197
- user: juniorUsers
2198
- }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
2199
- if (!row) return void 0;
2200
- return {
2201
- identity: identityFromRow(row.identity),
2202
- ...row.user ? { user: await readUserById(db, row.user) } : void 0
2203
- };
2204
- }
2205
- /** Read one stored identity and its linked user by identity id. */
2206
- async function readIdentityById(identityId) {
2207
- return await readIdentityByIdFromSql(getDb(), identityId);
2208
- }
2209
- export { parseSessionSource as $, conversationAncestors as A, startLocationThread as B, getSqlExecutor as C, createSqlConversationEventStore as D, treeHasAnnotationKey as E, createSqlStore as F, deleteProviderIdentityForSlackUser as G, SYSTEM_IDENTITY_ID as H, withConversationMutationLock as I, readUserTimezone as J, deleteProviderIdentityForUser as K, conversationKindFromRow as L, readConversationTrees as M, setChildArchivedAt as N, eventFromRow as O, loadConversationSlackTenantIds as P, bindProviderConversation as Q, locationFromRow as R, getDb as S, hasAnnotationKey as T, resolveActorIdentityId as U, visibilityFromLocationRow as V, saveActorAvatar as W, saveUserTimezone as X, recordGoogleSignIn as Y, upsertLinkedIdentity as Z, closeDb as _, readActorIdentityFromSql as a, agentTurnTotalTokens as at, getConversationMessageSearchStore as b, readViewerAvatarUrl as c, resolveRootConversationId as ct, updateViewerDisplayName as d, requireSlackDestination as dt, conversationDetailTouch as et, identityAvatarUrl as f, sameDestination as ft, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, agentTurnCostUsd as it, conversationDescendants as j, withConversationEventLock as k, resolveViewerUser as l, createSlackDestination as lt, readAvatarImage as m, findUserByEmailFromSql as n, touchConversationDetail as nt, readIdentityById as o, agentTurnUsageSchema as ot, parseAvatarUrl as p, findUserByVerifiedEmails as q, listAdminUsersFromSql as r, addAgentTurnUsage as rt, readIdentityByIdFromSql as s, hasAgentTurnUsage as st, findUserByEmail as t, nextDetailVersion as tt, setUserAdminFromSql as u, parseDestination as ut, db_exports as v, conversationIdsWithAnnotation as w, getConversationStore as x, getConversationEventStore as y, setFirstConversationLocation as z };
1906
+ export { deleteProviderIdentityForUser as A, touchConversationDetail as B, setFirstConversationLocation as C, resolveActorIdentityId as D, findActorIdentityId as E, upsertLinkedIdentity as F, hasAgentTurnUsage as G, agentTurnCostUsd as H, bindProviderConversation as I, parseDestination as J, resolveRootConversationId as K, parseSessionSource as L, readUserTimezone as M, recordGoogleSignIn as N, saveActorAvatar as O, saveUserTimezone as P, conversationDetailTouch as R, locationFromRow as S, SYSTEM_IDENTITY_ID as T, agentTurnTotalTokens as U, addAgentTurnUsage as V, agentTurnUsageSchema as W, sameDestination as X, requireSlackDestination as Y, 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, createSlackDestination 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, nextDetailVersion as z };
@@ -1,4 +1,4 @@
1
- import "./schema-BUviRAs8.js";
1
+ import "./schema-C6fsEwjo.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -99,10 +99,10 @@ interface Conversation {
99
99
  /** Immutable parent Conversation. */
100
100
  parentConversationId?: string;
101
101
  /**
102
- * When a child Conversation was archived for everyone. Only child archive
103
- * and a person's message write it; `upsertConversation` does not.
102
+ * When the Conversation was archived for everyone. Only archive, auto-archive,
103
+ * pin, and a person's message write it; `upsertConversation` does not.
104
104
  */
105
- childArchivedAtMs?: number;
105
+ archivedAtMs?: number;
106
106
  /** Optional provider coordinates associated with this Conversation. */
107
107
  location?: Location;
108
108
  actor?: StoredSlackActor;