@sentry/junior 0.284.0 → 0.286.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 (84) hide show
  1. package/dist/{adapter-CW5UW7vL.js → adapter-JQZaJ-B_.js} +37 -3
  2. package/dist/{admin-DUWN8zZX.js → admin-Dm2bimJ-.js} +1 -1
  3. package/dist/{agent-runner-Cqr21pOU.js → agent-runner-DGCwOEyL.js} +2180 -2735
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +8 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +166 -90
  8. package/dist/{app-CvGalMxi.d.ts → app-BKq0JzWx.d.ts} +2 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +225 -188
  11. package/dist/{assistant-reply-CFE-OZMS.js → assistant-reply-CAPafcUY.js} +1 -1
  12. package/dist/{automation-Zvx_I9Z5.js → automation-B-jJN_gM.js} +1 -1
  13. package/dist/{background-compaction-queue-CHFzrQbS.js → background-compaction-queue-Btu2oab_.js} +137 -3
  14. package/dist/{briefs-Cx7mkfSk.js → briefs-UMeYehUe.js} +5 -5
  15. package/dist/{catalog-runtime-dKOVbR7l.js → catalog-runtime-Bym8GVdh.js} +1 -1
  16. package/dist/cli/chat.js +19 -16
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/init.js +3 -0
  19. package/dist/cli/main.js +3 -3
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +5 -6
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +12 -17
  24. package/dist/{client-CMyH5rDz.js → client-B0aAs7wC.js} +2 -2
  25. package/dist/{config-Dt3CpG17.js → config-B9f9Lqo5.js} +1 -1
  26. package/dist/{connections-CCHPybZP.js → connections-CQ7p0aNJ.js} +16 -50
  27. package/dist/{conversation-DdT7SNar.js → conversation-BusI2uzj.js} +68 -7
  28. package/dist/{conversation-pending-messages-Dct5pheX.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
  29. package/dist/{conversation-privacy-BpHHhEVp.js → conversation-privacy-Cd_nZZBM.js} +1 -1
  30. package/dist/{credential-sync-BBPw8dam.js → credential-sync-DmiJi_At.js} +13 -13
  31. package/dist/{db-D7CCwAo8.d.ts → db-C5zi4ecs.d.ts} +18 -2
  32. package/dist/{executor-CyIwHz9r.js → executor-Dipi2Ixl.js} +19 -17
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{logging-Qo-7xGp1.js → logging-CMFhLLj4.js} +1 -1
  35. package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
  36. package/dist/{message-DFbtOWqv.js → message-D1xLljUF.js} +13 -23
  37. package/dist/nitro.d.ts +1 -1
  38. package/dist/nitro.js +2 -3
  39. package/dist/{oauth-callback-server-BB1gixWo.js → oauth-callback-server-DCAFIUQr.js} +2 -2
  40. package/dist/{projection-0UcUeuzn.js → projection-CoeMNxJ4.js} +545 -262
  41. package/dist/{prompt-CCtaGgbI.js → prompt-C9OQEfan.js} +8 -6
  42. package/dist/{registry-DOnPkI8g.js → registry-u-sFYtx_.js} +1 -1
  43. package/dist/{reporting-window-B-QP9zX1.js → reporting-window-B4TwyuJo.js} +14 -14
  44. package/dist/{resolve-Di3omymY.js → resolve-DYqgL3Eo.js} +3 -3
  45. package/dist/result-CescSwAw.js +299 -0
  46. package/dist/result-event-type-DD6BAgT7.js +11 -0
  47. package/dist/{runner-CnX_dTKw.js → runner-Cr67a8TB.js} +16 -12
  48. package/dist/{sandbox-egress-signals-CtxLJmmg.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
  49. package/dist/{schema-Bn3miEd_.js → schema-BUSi3sgv.js} +63 -5
  50. package/dist/{schema-B017enNE.d.ts → schema-Ih60j59-.d.ts} +194 -220
  51. package/dist/{service-account-KhZIqXRi.js → service-account-CGEqz9wG.js} +3 -3
  52. package/dist/{service-account-ewDAx4Mx.js → service-account-CsKxktLk.js} +3 -3
  53. package/dist/session-stop-CGz5DByb.js +2926 -0
  54. package/dist/{skills-CKyotM4g.js → skills-COCqf61f.js} +2 -2
  55. package/dist/{spawn-D5D2MQdz.js → spawn-C8F_iXWO.js} +13 -2
  56. package/dist/{stop-BSKRTaRS.js → stop-GyFZkHuQ.js} +7730 -7818
  57. package/dist/{store-ymkEUWe4.js → store-D0-8plWp.js} +30 -5
  58. package/dist/{turn-session-routing-D_GXfcAG.js → task-runner-xPuQmEot.js} +1440 -994
  59. package/dist/{store-G3S0kWSD.js → turn-failure-response-BOviBdT-.js} +404 -311
  60. package/dist/{validation-DJG_wrg2.js → validation-DZDKorGz.js} +1 -1
  61. package/dist/{version-i1An1eTS.js → version-BTIz7fGi.js} +1 -1
  62. package/dist/version.js +1 -1
  63. package/dist/{viewer-BlpnzZZa.js → viewer-CH-ASQzh.js} +208 -68
  64. package/dist/{work-BgCW3FDC.js → work-C75_IM5e.js} +311 -100
  65. package/dist/{worker-BJz1mwYt.js → worker-Dl47I729.js} +6 -6
  66. package/migrations/0083_conversation_kind.sql +11 -0
  67. package/migrations/0084_read_position_backfill.sql +25 -0
  68. package/migrations/0085_child_archived_at.sql +1 -0
  69. package/migrations/0086_shared_archive.sql +31 -0
  70. package/migrations/0087_child_location.sql +64 -0
  71. package/migrations/meta/0083_snapshot.json +4388 -0
  72. package/migrations/meta/0084_snapshot.json +4388 -0
  73. package/migrations/meta/0085_snapshot.json +4394 -0
  74. package/migrations/meta/0086_snapshot.json +4366 -0
  75. package/migrations/meta/0087_snapshot.json +4366 -0
  76. package/migrations/meta/_journal.json +35 -0
  77. package/package.json +5 -4
  78. package/dist/result-NvndYzCb.js +0 -483
  79. package/dist/session-stop-D_1SysjC.js +0 -1438
  80. package/dist/task-queue-BcOHzXxe.js +0 -139
  81. package/dist/task-runner-B65cDumh.js +0 -290
  82. package/dist/thread-state-D6rNGQu9.js +0 -173
  83. package/dist/turn-failure-response-BlO4nuDJ.js +0 -224
  84. package/dist/turn-lifecycle-BQ8ETk63.js +0 -58
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-dKOVbR7l.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Bym8GVdh.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.284.0";
2
+ var version = "0.286.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-i1An1eTS.js";
1
+ export { t as JUNIOR_VERSION } from "./version-BTIz7fGi.js";
@@ -1,9 +1,9 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-Dt3CpG17.js";
3
- import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-Qo-7xGp1.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";
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-CyIwHz9r.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";
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
7
  import { a as withLock } from "./locks-D-0h111u.js";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
@@ -46,14 +46,15 @@ async function resolveRootConversationId(executor, conversationId) {
46
46
  }
47
47
  /**
48
48
  * Upsert one linked user as a participant on a root conversation.
49
- * No-ops when the identity is missing, unlinked, or not a user.
49
+ * No-ops and returns false when the identity is missing, unlinked, or not a
50
+ * user.
50
51
  */
51
52
  async function recordConversationParticipant(executor, args) {
52
53
  const [identity] = await executor.db().select({
53
54
  kind: juniorIdentities.kind,
54
55
  userId: juniorIdentities.userId
55
56
  }).from(juniorIdentities).where(eq(juniorIdentities.id, args.actorIdentityId)).limit(1);
56
- if (!identity?.userId || identity.kind !== "user") return;
57
+ if (!identity?.userId || identity.kind !== "user") return false;
57
58
  const rootConversationId = await resolveRootConversationId(executor, args.conversationId);
58
59
  const at = new Date(args.atMs);
59
60
  await executor.db().insert(juniorConversationParticipants).values({
@@ -62,11 +63,9 @@ async function recordConversationParticipant(executor, args) {
62
63
  lastMessageAt: at
63
64
  }).onConflictDoUpdate({
64
65
  target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
65
- set: {
66
- lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`,
67
- ...args.restoreArchive ? { archivedAt: null } : void 0
68
- }
66
+ set: { lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)` }
69
67
  });
68
+ return true;
70
69
  }
71
70
  // src/chat/usage.ts
72
71
  const agentTurnUsageSchema = usageSchema;
@@ -737,6 +736,21 @@ function visibilityFromLocationRow(row) {
737
736
  if (!row) return;
738
737
  if (row.visibility === "public" || row.visibility === "private") return row.visibility;
739
738
  }
739
+ /**
740
+ * Give a root Conversation with no Location its first one, in the caller's
741
+ * SQL scope. The Location row becomes the Conversation Destination, so
742
+ * visibility then comes from that channel. Returns false when the
743
+ * Conversation already has a Location.
744
+ */
745
+ async function setFirstConversationLocation(executor, args) {
746
+ const location = locationSchema.parse(args.location);
747
+ return (await executor.db().update(juniorConversations).set({
748
+ location,
749
+ destinationId: location.id,
750
+ ...args.channelName ? { channelName: args.channelName } : void 0,
751
+ detailVersion: nextDetailVersion
752
+ }).where(and(eq(juniorConversations.conversationId, args.conversationId), isNull(juniorConversations.parentConversationId), isNull(juniorConversations.location))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
753
+ }
740
754
  /** Store a channel-level Location's first bound post as its thread. */
741
755
  async function startLocationThread(executor, binding) {
742
756
  const location = juniorConversations.location;
@@ -745,6 +759,50 @@ async function startLocationThread(executor, binding) {
745
759
  detailVersion: nextDetailVersion
746
760
  }).where(and(eq(juniorConversations.conversationId, binding.conversationId), sql`${location}->>'provider' = ${binding.provider}`, sql`${location}->>'teamId' = ${binding.providerTenantId}`, sql`${location}->>'channelId' = ${binding.providerDestinationId}`, isNull(sql`${location}->>'threadTs'`)));
747
761
  }
762
+ // src/chat/conversations/sql/conversation-row.ts
763
+ /**
764
+ * Establish the conversation metadata row on first contact for content writes
765
+ * (conversation events, visible transcript) that can land before activity has
766
+ * created the row, and whose tables FK to it.
767
+ *
768
+ * First contact creates the row; every later content write advances the
769
+ * activity clock so retention mirrors append-refresh semantics (each content
770
+ * append refreshes the retention window). Background observations may opt out
771
+ * and leave an existing row unchanged. The timestamp is content-intrinsic (the
772
+ * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
773
+ * imported historical write — which carries an old timestamp — can never
774
+ * regress `last_activity_at`.
775
+ */
776
+ async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
777
+ const at = new Date(atMs);
778
+ const insert = executor.db().insert(juniorConversations).values({
779
+ conversationId,
780
+ createdAt: at,
781
+ lastActivityAt: at,
782
+ updatedAt: at,
783
+ executionStatus: "idle",
784
+ kind: "root"
785
+ });
786
+ if (options.activity === "preserve") {
787
+ await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
788
+ return;
789
+ }
790
+ await insert.onConflictDoUpdate({
791
+ target: juniorConversations.conversationId,
792
+ set: {
793
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
794
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
795
+ transcriptPurgedAt: null,
796
+ detailVersion: nextDetailVersion
797
+ }
798
+ });
799
+ }
800
+ /** Decode a stored kind. A null kind comes from a writer of an older deploy. */
801
+ function conversationKindFromRow(row) {
802
+ const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
803
+ if (kind !== "root" && kind !== "thread" && kind !== "task") throw new Error("Conversation record kind is invalid");
804
+ return kind;
805
+ }
748
806
  // src/chat/conversations/sql/store.ts
749
807
  const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
750
808
  /** Serialize one conversation's durable mutations inside a SQL transaction. */
@@ -853,7 +911,9 @@ function conversationFromRow(readRow) {
853
911
  ...row.metricRunId ? { runId: row.metricRunId } : void 0,
854
912
  ...row.executionUsage ? { usage: row.executionUsage } : void 0
855
913
  },
914
+ kind: conversationKindFromRow(row),
856
915
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
916
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
857
917
  ...destination ? { destination } : void 0,
858
918
  ...location ? { location } : void 0,
859
919
  ...actor ? { actor } : void 0,
@@ -862,6 +922,7 @@ function conversationFromRow(readRow) {
862
922
  ...sessionSource ? { sessionSource } : void 0,
863
923
  ...row.title ? { title: row.title } : void 0,
864
924
  ...msFromDate(row.transcriptPurgedAt) !== void 0 ? { transcriptPurgedAtMs: msFromDate(row.transcriptPurgedAt) } : void 0,
925
+ ...msFromDate(row.stoppedAt) !== void 0 ? { stoppedAtMs: msFromDate(row.stoppedAt) } : void 0,
865
926
  ...visibility ? { visibility } : void 0
866
927
  };
867
928
  }
@@ -870,6 +931,7 @@ function emptyConversation(args) {
870
931
  schemaVersion: 1,
871
932
  conversationId: args.conversationId,
872
933
  createdAtMs: args.nowMs,
934
+ kind: "root",
873
935
  lastActivityAtMs: args.nowMs,
874
936
  updatedAtMs: args.nowMs,
875
937
  ...args.destination ? { destination: args.destination } : void 0,
@@ -903,18 +965,26 @@ var SqlStore = class {
903
965
  const existing = await this.get({ conversationId: args.childConversationId });
904
966
  if (existing) {
905
967
  if (existing.parentConversationId !== args.parentConversationId) throw new Error(`Conversation parent changed for ${args.childConversationId}`);
968
+ if (existing.kind !== args.kind) throw new Error(`Conversation kind changed for ${args.childConversationId}`);
906
969
  return;
907
970
  }
908
- if (!await this.get({ conversationId: args.parentConversationId })) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
971
+ const parentRow = await this.readConversationRow(args.parentConversationId);
972
+ if (!parentRow) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
973
+ const { location } = conversationFromRow(parentRow);
909
974
  const child = {
910
975
  ...emptyConversation({
911
976
  conversationId: args.childConversationId,
912
977
  nowMs,
913
978
  source: args.source
914
979
  }),
915
- parentConversationId: args.parentConversationId
980
+ kind: args.kind,
981
+ parentConversationId: args.parentConversationId,
982
+ ...location ? { location } : void 0
916
983
  };
917
- await this.upsertConversation({ conversation: child });
984
+ await this.upsertConversation({
985
+ conversation: child,
986
+ destinationId: parentRow.conversation.destinationId ?? void 0
987
+ });
918
988
  });
919
989
  });
920
990
  }
@@ -983,6 +1053,7 @@ var SqlStore = class {
983
1053
  schemaVersion: 1,
984
1054
  conversationId: args.conversationId,
985
1055
  createdAtMs: args.createdAtMs,
1056
+ kind: existing?.kind ?? "root",
986
1057
  lastActivityAtMs: args.lastActivityAtMs,
987
1058
  updatedAtMs: args.updatedAtMs,
988
1059
  ...existing?.parentConversationId ? { parentConversationId: existing.parentConversationId } : void 0,
@@ -1014,7 +1085,7 @@ var SqlStore = class {
1014
1085
  }
1015
1086
  async listByActivity(args = {}) {
1016
1087
  const rows = await this.executor.db().select({
1017
- conversation: conversationReadColumns(),
1088
+ conversation: juniorConversations,
1018
1089
  destination: juniorDestinations,
1019
1090
  actorIdentity: juniorIdentities,
1020
1091
  actorUserDisplayName: juniorUsers.displayName
@@ -1052,7 +1123,7 @@ var SqlStore = class {
1052
1123
  }
1053
1124
  async readConversationRow(conversationId) {
1054
1125
  return (await this.executor.db().select({
1055
- conversation: conversationReadColumns(),
1126
+ conversation: juniorConversations,
1056
1127
  destination: juniorDestinations,
1057
1128
  actorIdentity: juniorIdentities,
1058
1129
  actorUserDisplayName: juniorUsers.displayName
@@ -1061,6 +1132,7 @@ var SqlStore = class {
1061
1132
  /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
1062
1133
  async upsertConversation(args) {
1063
1134
  const { conversation } = args;
1135
+ if (conversation.kind === "root" !== !conversation.parentConversationId) throw new Error(`Conversation ${conversation.conversationId} kind does not match its parent`);
1064
1136
  if (!conversation.parentConversationId && !conversation.destination) {
1065
1137
  if (!await this.get({ conversationId: conversation.conversationId })) throw new Error(`Conversation ${conversation.conversationId} requires a destination at create`);
1066
1138
  }
@@ -1072,7 +1144,7 @@ var SqlStore = class {
1072
1144
  conversationId: conversation.conversationId,
1073
1145
  destination: conversation.destination,
1074
1146
  ...conversation.visibility ? { visibility: conversation.visibility } : void 0
1075
- }), conversation.updatedAtMs);
1147
+ }), conversation.updatedAtMs) ?? args.destinationId;
1076
1148
  const location = locationForWrite({
1077
1149
  destination: conversation.destination,
1078
1150
  destinationId,
@@ -1108,6 +1180,7 @@ var SqlStore = class {
1108
1180
  lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
1109
1181
  lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs),
1110
1182
  parentConversationId: conversation.parentConversationId ?? null,
1183
+ kind: conversation.kind,
1111
1184
  rootConversationId
1112
1185
  }).onConflictDoUpdate({
1113
1186
  target: juniorConversations.conversationId,
@@ -1130,6 +1203,7 @@ var SqlStore = class {
1130
1203
  lastCheckpointAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_checkpoint_at, ${juniorConversations.lastCheckpointAt}) else ${juniorConversations.lastCheckpointAt} end`,
1131
1204
  lastEnqueuedAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_enqueued_at, ${juniorConversations.lastEnqueuedAt}) else ${juniorConversations.lastEnqueuedAt} end`,
1132
1205
  rootConversationId: sql`coalesce(${juniorConversations.rootConversationId}, excluded.root_conversation_id)`,
1206
+ kind: sql`coalesce(${juniorConversations.kind}, excluded.kind)`,
1133
1207
  detailVersion: nextDetailVersion
1134
1208
  }
1135
1209
  }).returning({
@@ -1138,6 +1212,7 @@ var SqlStore = class {
1138
1212
  rootConversationId: juniorConversations.rootConversationId
1139
1213
  }))[0];
1140
1214
  if (!row?.rootConversationId) throw new Error("Conversation parent is missing its persisted root");
1215
+ if (row.parentConversationId !== (conversation.parentConversationId ?? null)) throw new Error(`Conversation parent changed for ${conversation.conversationId}`);
1141
1216
  if (row.actorIdentityId && row.parentConversationId === null) await recordConversationParticipant(this.executor, {
1142
1217
  actorIdentityId: row.actorIdentityId,
1143
1218
  conversationId: conversation.conversationId,
@@ -1179,43 +1254,6 @@ var SqlStore = class {
1179
1254
  function createSqlStore(executor) {
1180
1255
  return new SqlStore(executor);
1181
1256
  }
1182
- // src/chat/conversations/sql/conversation-row.ts
1183
- /**
1184
- * Establish the conversation metadata row on first contact for content writes
1185
- * (conversation events, visible transcript) that can land before activity has
1186
- * created the row, and whose tables FK to it.
1187
- *
1188
- * First contact creates the row; every later content write advances the
1189
- * activity clock so retention mirrors append-refresh semantics (each content
1190
- * append refreshes the retention window). Background observations may opt out
1191
- * and leave an existing row unchanged. The timestamp is content-intrinsic (the
1192
- * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
1193
- * imported historical write — which carries an old timestamp — can never
1194
- * regress `last_activity_at`.
1195
- */
1196
- async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
1197
- const at = new Date(atMs);
1198
- const insert = executor.db().insert(juniorConversations).values({
1199
- conversationId,
1200
- createdAt: at,
1201
- lastActivityAt: at,
1202
- updatedAt: at,
1203
- executionStatus: "idle"
1204
- });
1205
- if (options.activity === "preserve") {
1206
- await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
1207
- return;
1208
- }
1209
- await insert.onConflictDoUpdate({
1210
- target: juniorConversations.conversationId,
1211
- set: {
1212
- lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
1213
- updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
1214
- transcriptPurgedAt: null,
1215
- detailVersion: nextDetailVersion
1216
- }
1217
- });
1218
- }
1219
1257
  // src/chat/conversations/sql/event-actor.ts
1220
1258
  function isRecord(value) {
1221
1259
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -1333,6 +1371,88 @@ function sanitizePostgresJson(value) {
1333
1371
  if (prototype !== Object.prototype && prototype !== null) return value;
1334
1372
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
1335
1373
  }
1374
+ // src/chat/conversations/sql/conversation-tree.ts
1375
+ /**
1376
+ * Read every Conversation in the trees of the given roots. Every descendant
1377
+ * shares `root_conversation_id`, so one indexed read covers any depth.
1378
+ */
1379
+ async function readConversationTrees(db, rootConversationIds) {
1380
+ if (rootConversationIds.length === 0) return /* @__PURE__ */ new Map();
1381
+ const rows = await db.select({
1382
+ archivedAt: juniorConversations.archivedAt,
1383
+ conversationId: juniorConversations.conversationId,
1384
+ kind: juniorConversations.kind,
1385
+ parentConversationId: juniorConversations.parentConversationId
1386
+ }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
1387
+ return new Map(rows.map((row) => [row.conversationId, {
1388
+ archivedAt: row.archivedAt,
1389
+ conversationId: row.conversationId,
1390
+ kind: conversationKindFromRow(row),
1391
+ ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
1392
+ }]));
1393
+ }
1394
+ /** List the ancestors of one Conversation, nearest first, root last. */
1395
+ function conversationAncestors(tree, conversationId) {
1396
+ const ancestors = [];
1397
+ const seen = /* @__PURE__ */ new Set([conversationId]);
1398
+ let parentId = tree.get(conversationId)?.parentConversationId;
1399
+ while (parentId && !seen.has(parentId)) {
1400
+ const parent = tree.get(parentId);
1401
+ if (!parent) break;
1402
+ ancestors.push(parent);
1403
+ seen.add(parentId);
1404
+ parentId = parent.parentConversationId;
1405
+ }
1406
+ return ancestors;
1407
+ }
1408
+ /** List every descendant of one Conversation, at any depth. */
1409
+ function conversationDescendants(tree, conversationId) {
1410
+ const childrenByParent = /* @__PURE__ */ new Map();
1411
+ for (const node of tree.values()) {
1412
+ if (!node.parentConversationId) continue;
1413
+ const siblings = childrenByParent.get(node.parentConversationId) ?? [];
1414
+ siblings.push(node);
1415
+ childrenByParent.set(node.parentConversationId, siblings);
1416
+ }
1417
+ const descendants = [];
1418
+ const seen = /* @__PURE__ */ new Set([conversationId]);
1419
+ const pending = [conversationId];
1420
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) for (const child of childrenByParent.get(id) ?? []) {
1421
+ if (seen.has(child.conversationId)) continue;
1422
+ seen.add(child.conversationId);
1423
+ descendants.push(child);
1424
+ pending.push(child.conversationId);
1425
+ }
1426
+ return descendants;
1427
+ }
1428
+ /** Set or clear the shared archive of the given Conversations. */
1429
+ async function setArchivedAt(db, conversationIds, archivedAt) {
1430
+ if (conversationIds.length === 0) return;
1431
+ await db.update(juniorConversations).set({
1432
+ archivedAt,
1433
+ detailVersion: nextDetailVersion
1434
+ }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
1435
+ }
1436
+ /**
1437
+ * Restore one archived Conversation and its archived ancestors, so it shows
1438
+ * again. Its descendants keep their archive.
1439
+ */
1440
+ async function restoreArchivedPath(db, conversationId) {
1441
+ const [row] = await db.select({
1442
+ archivedAt: juniorConversations.archivedAt,
1443
+ parentConversationId: juniorConversations.parentConversationId,
1444
+ rootConversationId: juniorConversations.rootConversationId
1445
+ }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
1446
+ if (!row) return;
1447
+ if (!row.parentConversationId || !row.rootConversationId) {
1448
+ if (row.archivedAt) await setArchivedAt(db, [conversationId], null);
1449
+ return;
1450
+ }
1451
+ const tree = await readConversationTrees(db, [row.rootConversationId]);
1452
+ const node = tree.get(conversationId);
1453
+ if (!node) return;
1454
+ await setArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.archivedAt).map((entry) => entry.conversationId), null);
1455
+ }
1336
1456
  // src/chat/conversations/sql/event-lock.ts
1337
1457
  /** Serialize event sequence allocation with other conversation writes. */
1338
1458
  async function withConversationEventLock(executor, conversationId, callback) {
@@ -1464,16 +1584,18 @@ var SqlConversationEventStore = class {
1464
1584
  */
1465
1585
  async recordTurnInputParticipants(conversationId, inputMessageIds) {
1466
1586
  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])));
1587
+ let restores = false;
1467
1588
  for (const row of rows) {
1468
1589
  const { data } = eventFromRow(row);
1469
1590
  if (!row.actorIdentityId || data.type !== "message") continue;
1470
- await recordConversationParticipant(this.executor, {
1591
+ const isPerson = await recordConversationParticipant(this.executor, {
1471
1592
  actorIdentityId: row.actorIdentityId,
1472
1593
  conversationId,
1473
- atMs: row.createdAt.getTime(),
1474
- restoreArchive: eventUnarchivesConversation(data)
1594
+ atMs: row.createdAt.getTime()
1475
1595
  });
1596
+ restores ||= isPerson && eventUnarchivesConversation(data);
1476
1597
  }
1598
+ if (restores) await restoreArchivedPath(this.executor.db(), conversationId);
1477
1599
  }
1478
1600
  async replaceHistory(conversationId, replacement, options = {}) {
1479
1601
  const parsed = historyReplacementSchema.parse(replacement);
@@ -1521,11 +1643,9 @@ var SqlConversationEventStore = class {
1521
1643
  }
1522
1644
  async loadMessageHistory(conversationId) {
1523
1645
  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);
1524
- const compaction = compactionRow ? messagesSummarizedEventFromRow(compactionRow) : void 0;
1525
- const historyFromSeq = compaction?.data.historyFromSeq ?? 0;
1646
+ const historyFromSeq = compactionRow ? messagesSummarizedEventFromRow(compactionRow).data.historyFromSeq : 0;
1526
1647
  return {
1527
1648
  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),
1528
- compaction,
1529
1649
  historyFromSeq
1530
1650
  };
1531
1651
  }
@@ -1809,6 +1929,7 @@ const AVATAR_CACHE_TTL_MS = 864e5;
1809
1929
  const AVATAR_FAILURE_TTL_MS = 3e5;
1810
1930
  const AVATAR_FETCH_TIMEOUT_MS = 5e3;
1811
1931
  const MAX_AVATAR_BYTES = 1048576;
1932
+ const AVATAR_EDGE_PX = 96;
1812
1933
  const MAX_AVATAR_REDIRECTS = 3;
1813
1934
  /**
1814
1935
  * Return the URL when it is HTTPS on a photo host of the provider or a
@@ -1914,16 +2035,35 @@ async function fetchAvatarImage(url, provider) {
1914
2035
  if (!data) return avatarFetchFailed(host, { "app.reason": "too_large" });
1915
2036
  const contentType = detectImageMediaType(data);
1916
2037
  if (!contentType) return avatarFetchFailed(host, { "app.reason": "not_an_image" });
1917
- return {
1918
- contentType,
1919
- data: Buffer.from(data).toString("base64")
1920
- };
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");
1921
2061
  }
1922
2062
  /**
1923
2063
  * Read the saved photo of one Identity and its version. Junior fetches it
1924
- * from the provider once and keeps it in the state cache for a day. Return
1925
- * undefined when the Identity has no photo or the provider does not return
1926
- * one.
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.
1927
2067
  */
1928
2068
  async function readAvatarImage(db, state, identityId) {
1929
2069
  const [row] = await db.select({
@@ -1932,7 +2072,7 @@ async function readAvatarImage(db, state, identityId) {
1932
2072
  }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
1933
2073
  const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
1934
2074
  if (!row?.avatarUrl || !url) return void 0;
1935
- const key = `avatar:${avatarUrlHash(url)}`;
2075
+ const key = `avatar:${AVATAR_EDGE_PX}:${avatarUrlHash(url)}`;
1936
2076
  const image = await createCache(state, "core").getOrLoad(key, async () => {
1937
2077
  const loaded = await fetchAvatarImage(url, row.provider);
1938
2078
  return {
@@ -2069,4 +2209,4 @@ async function readIdentityByIdFromSql(db, identityId) {
2069
2209
  async function readIdentityById(identityId) {
2070
2210
  return await readIdentityByIdFromSql(getDb(), identityId);
2071
2211
  }
2072
- export { agentTurnUsageSchema as $, loadConversationSlackTenantIds as A, findUserByVerifiedEmails as B, getSqlExecutor as C, createSqlConversationEventStore as D, treeHasAnnotationKey as E, SYSTEM_IDENTITY_ID as F, bindProviderConversation as G, recordGoogleSignIn as H, resolveActorIdentityId as I, nextDetailVersion as J, parseSessionSource as K, saveActorAvatar as L, withConversationMutationLock as M, locationFromRow as N, eventFromRow as O, startLocationThread as P, agentTurnTotalTokens as Q, deleteProviderIdentityForSlackUser as R, getDb as S, hasAnnotationKey as T, saveUserTimezone as U, readUserTimezone as V, upsertLinkedIdentity as W, addAgentTurnUsage as X, touchConversationDetail as Y, agentTurnCostUsd as Z, closeDb as _, readActorIdentityFromSql as a, sameDestination as at, getConversationMessageSearchStore as b, readViewerAvatarUrl as c, updateViewerDisplayName as d, hasAgentTurnUsage as et, identityAvatarUrl as f, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, requireSlackDestination as it, createSqlStore as j, withConversationEventLock as k, resolveViewerUser as l, readAvatarImage as m, findUserByEmailFromSql as n, createSlackDestination as nt, readIdentityById as o, parseAvatarUrl as p, conversationDetailTouch as q, listAdminUsersFromSql as r, parseDestination as rt, readIdentityByIdFromSql as s, findUserByEmail as t, resolveRootConversationId as tt, setUserAdminFromSql as u, db_exports as v, conversationIdsWithAnnotation as w, getConversationStore as x, getConversationEventStore as y, deleteProviderIdentityForUser as z };
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 };