@sentry/junior 0.283.0 → 0.285.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 (83) hide show
  1. package/dist/{adapter-D8-lqOBF.js → adapter-DN5AB4VU.js} +37 -3
  2. package/dist/{admin-Dnw5SCXp.js → admin-DOITMKnn.js} +1 -1
  3. package/dist/{agent-runner-Bj7GhysW.js → agent-runner-BsWhHe4N.js} +583 -1655
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +8 -6
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +214 -43
  8. package/dist/{app-CMBP-N43.d.ts → app-DyMs9330.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +230 -187
  11. package/dist/{assistant-reply-CdYsLbXL.js → assistant-reply-9Jip5bsr.js} +1 -1
  12. package/dist/{automation-MLWOrghe.js → automation-Mk8aaHzy.js} +2 -2
  13. package/dist/{background-compaction-queue-Bbsqx8Vm.js → background-compaction-queue-DXkLsWoH.js} +2 -2
  14. package/dist/{briefs-C4qBY-jb.js → briefs-Cl8-nK9B.js} +5 -5
  15. package/dist/{catalog-runtime-B7NRB7eH.js → catalog-runtime-Bte6jRB2.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 +4 -4
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +25 -4
  24. package/dist/{client-a3Ib6wxr.js → client-DDbBucBw.js} +2 -2
  25. package/dist/{config-DFVlYCeY.js → config-DqFnykQT.js} +1 -1
  26. package/dist/{connections-BtnvpBEV.js → connections-DA4LT9LL.js} +10 -10
  27. package/dist/{conversation-DdT7SNar.js → conversation-D8kVoCrP.js} +58 -6
  28. package/dist/{conversation-pending-messages-Dct5pheX.js → conversation-pending-messages-BvROq1bq.js} +1 -1
  29. package/dist/{conversation-privacy-DLq-abjU.js → conversation-privacy-D0j_h70R.js} +1 -1
  30. package/dist/{credential-sync-B4XFVcjM.js → credential-sync-hcsYatw-.js} +13 -13
  31. package/dist/{db-A_WrTY-s.d.ts → db-BhHZSuFw.d.ts} +18 -2
  32. package/dist/{executor-HPgHGAWK.js → executor-BLEMIgIZ.js} +29 -4
  33. package/dist/instrumentation.js +37 -13
  34. package/dist/{logging-2BXvW7Mp.js → logging-BfORLKoq.js} +1 -1
  35. package/dist/{message-BG1v1lXX.js → message-DqjuKzUx.js} +13 -23
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +3 -3
  38. package/dist/{oauth-callback-server-CXNZJymo.js → oauth-callback-server-CFSRzu1n.js} +2 -2
  39. package/dist/{projection-BfKkpOGQ.js → projection-DliWYrnT.js} +575 -74
  40. package/dist/{prompt-CCtaGgbI.js → prompt-BvIUzY4y.js} +8 -6
  41. package/dist/push-endpoint-CO-nomUd.js +36 -0
  42. package/dist/{registry-CLooHPAz.js → registry-rC7MCxu8.js} +1 -1
  43. package/dist/{reporting-window-B-QP9zX1.js → reporting-window-B4TwyuJo.js} +14 -14
  44. package/dist/{resolve-D3MK9oRJ.js → resolve-Biu8Qw3u.js} +3 -3
  45. package/dist/result-DxJMCX47.js +299 -0
  46. package/dist/result-event-type-DD6BAgT7.js +11 -0
  47. package/dist/{runner-Ds31u3rB.js → runner-BQJSFLKg.js} +11 -11
  48. package/dist/{sandbox-egress-signals-CLd5RPUw.js → sandbox-egress-signals-6aMxJSDn.js} +1 -1
  49. package/dist/{cadence-R7Em4RjE.js → schedule-BTp__wrw.js} +81 -1
  50. package/dist/{schema-jW3ccLjp.d.ts → schema-BUviRAs8.d.ts} +196 -220
  51. package/dist/{schema-CHNP0GfH.js → schema-BasXTvi2.js} +94 -5
  52. package/dist/{service-account-D6AMahy7.js → service-account-BI5Wgx22.js} +3 -3
  53. package/dist/{service-account-CWpTsoIM.js → service-account-CAE-_1dR.js} +3 -3
  54. package/dist/session-stop-CA-jOJ84.js +2924 -0
  55. package/dist/{skills-DuOKByQH.js → skills-B22duVJU.js} +2 -2
  56. package/dist/{spawn-CNIQGgAS.js → spawn-BB2_4VYn.js} +2 -2
  57. package/dist/{stop-DX2oOIgl.js → stop-DioIcEAu.js} +4830 -4200
  58. package/dist/{store-61mD4ZSh.js → store-B26LV6UP.js} +78 -311
  59. package/dist/{store-DAJntSEv.js → store-Dn4W7qgH.js} +30 -5
  60. package/dist/{task-queue-BE70Pb9p.js → task-queue-Bt0IoR2i.js} +3 -3
  61. package/dist/{task-runner-CmmfddSZ.js → task-runner-D8lddjzp.js} +17 -8
  62. package/dist/{thread-state-0UfRMWYd.js → thread-state-CrFk3K_7.js} +4 -4
  63. package/dist/{turn-failure-response-DKdzxJHE.js → turn-failure-response-DaJ04qVj.js} +7 -7
  64. package/dist/{turn-lifecycle-24sBZ4Ip.js → turn-lifecycle-C2mXS7AZ.js} +1 -1
  65. package/dist/{turn-session-routing-CzCnNAUO.js → turn-session-routing-CGMKrYOj.js} +10 -10
  66. package/dist/{validation-Cs_knhR8.js → validation-TzhfQABF.js} +1 -1
  67. package/dist/{version-ZMC4cXWN.js → version-DSk8CFvA.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{viewer-CYB9T4rm.js → viewer-1Ea81s0b.js} +190 -53
  70. package/dist/{work-J1n6RQkY.js → work-ybG4_q5C.js} +238 -32
  71. package/dist/{worker-s1fCvj1z.js → worker-ccSyZRNz.js} +6 -6
  72. package/migrations/0082_push_notifications.sql +14 -0
  73. package/migrations/0083_conversation_kind.sql +11 -0
  74. package/migrations/0084_read_position_backfill.sql +25 -0
  75. package/migrations/0085_child_archived_at.sql +1 -0
  76. package/migrations/meta/0082_snapshot.json +4373 -0
  77. package/migrations/meta/0083_snapshot.json +4388 -0
  78. package/migrations/meta/0084_snapshot.json +4388 -0
  79. package/migrations/meta/0085_snapshot.json +4394 -0
  80. package/migrations/meta/_journal.json +28 -0
  81. package/package.json +7 -5
  82. package/dist/result-BPCjUefO.js +0 -483
  83. package/dist/session-stop-D8LGC3H6.js +0 -1438
@@ -1,11 +1,11 @@
1
- import { Ei as openSlackDirectMessage, Hr as getDashboardTaskLink, Rr as JUNIOR_THREAD_STATE_TTL_MS, Wr as ToolInputError, _i as escapeSlackMrkdwnText, ki as postSlackMessage, vi as formatSlackLink, w as fallbackShortTitle } from "./projection-BfKkpOGQ.js";
2
- import { n as botConfig } from "./config-DFVlYCeY.js";
3
- import { _ as runBestEffort, h as logWarn } from "./logging-2BXvW7Mp.js";
4
- import { Q as agentTurnTotalTokens, S as getDb, Z as agentTurnCostUsd } from "./viewer-CYB9T4rm.js";
5
- import { A as juniorConversations, d as juniorAutomations, l as juniorAutomationRuns, u as juniorAutomationVersions } from "./executor-HPgHGAWK.js";
6
- import { h as credentialSubjectSchema } from "./registry-CLooHPAz.js";
7
- import { r as getStateAdapter } from "./adapter-D8-lqOBF.js";
8
- import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-MLWOrghe.js";
1
+ import { Ki as openSlackDirectMessage, Li as escapeSlackMrkdwnText, Ri as formatSlackLink, T as fallbackShortTitle, Yi as postSlackMessage, ci as getDashboardTaskLink, ri as JUNIOR_THREAD_STATE_TTL_MS, ui as ToolInputError } from "./projection-DliWYrnT.js";
2
+ import { n as botConfig } from "./config-DqFnykQT.js";
3
+ import { _ as runBestEffort, h as logWarn } from "./logging-BfORLKoq.js";
4
+ import { S as getDb, at as agentTurnTotalTokens, it as agentTurnCostUsd } from "./viewer-1Ea81s0b.js";
5
+ import { d as juniorAutomationVersions, f as juniorAutomations, j as juniorConversations, u as juniorAutomationRuns } from "./executor-BLEMIgIZ.js";
6
+ import { h as credentialSubjectSchema } from "./registry-rC7MCxu8.js";
7
+ import { r as getStateAdapter } from "./adapter-DN5AB4VU.js";
8
+ import { O as eventAutomationSchema, S as automationVersionSchema, j as scheduledAutomationSchema } from "./automation-Mk8aaHzy.js";
9
9
  import { createHash } from "node:crypto";
10
10
  import * as z from "zod";
11
11
  import { and, asc, count, desc, eq, gte, inArray, isNotNull, isNull, lte, max, ne, or, sql } from "drizzle-orm";
@@ -815,7 +815,7 @@ function conversationAggregateColumns(sources) {
815
815
  costUsd: sql`SUM(${costValue(metrics)})::double precision`,
816
816
  durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
817
817
  failed: sql`${conversationCount} FILTER (
818
- WHERE ${roots.executionStatus} = 'failed'
818
+ WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
819
819
  )::integer`,
820
820
  inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
821
821
  tokens: sql`SUM(${tokenValue(metrics)})::double precision`
@@ -1583,7 +1583,7 @@ function slackSourceForDestination(args) {
1583
1583
  * Reads parent Conversations when this Conversation has no Destination.
1584
1584
  */
1585
1585
  async function resolveConversationRouting(args) {
1586
- const conversationStore = args.conversationStore ?? (await import("./viewer-CYB9T4rm.js").then((n) => n.v)).getConversationStore();
1586
+ const conversationStore = args.conversationStore ?? (await import("./viewer-1Ea81s0b.js").then((n) => n.v)).getConversationStore();
1587
1587
  const chain = await loadConversationChain(args.conversationId, conversationStore);
1588
1588
  let destination;
1589
1589
  let source;
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B7NRB7eH.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Bte6jRB2.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.283.0";
2
+ var version = "0.285.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-ZMC4cXWN.js";
1
+ export { t as JUNIOR_VERSION } from "./version-DSk8CFvA.js";
@@ -1,8 +1,8 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-DFVlYCeY.js";
3
- import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-2BXvW7Mp.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";
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, C as juniorConversationEvents, M as juniorUsers, N as juniorDestinations, T as juniorConversationAnnotations, _ as juniorConversationParticipants, b as CONVERSATION_METRICS, j as juniorIdentities, k as conversationReadColumns, t as createJuniorSqlExecutor, v as juniorConversationBindings, x as juniorConversationMetrics } from "./executor-HPgHGAWK.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
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
7
  import { a as withLock } from "./locks-D-0h111u.js";
8
8
  import { createHash, randomUUID } from "node:crypto";
@@ -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({
@@ -67,6 +68,7 @@ async function recordConversationParticipant(executor, args) {
67
68
  ...args.restoreArchive ? { archivedAt: null } : void 0
68
69
  }
69
70
  });
71
+ return true;
70
72
  }
71
73
  // src/chat/usage.ts
72
74
  const agentTurnUsageSchema = usageSchema;
@@ -737,6 +739,21 @@ function visibilityFromLocationRow(row) {
737
739
  if (!row) return;
738
740
  if (row.visibility === "public" || row.visibility === "private") return row.visibility;
739
741
  }
742
+ /**
743
+ * Give a root Conversation with no Location its first one, in the caller's
744
+ * SQL scope. The Location row becomes the Conversation Destination, so
745
+ * visibility then comes from that channel. Returns false when the
746
+ * Conversation already has a Location.
747
+ */
748
+ async function setFirstConversationLocation(executor, args) {
749
+ const location = locationSchema.parse(args.location);
750
+ return (await executor.db().update(juniorConversations).set({
751
+ location,
752
+ destinationId: location.id,
753
+ ...args.channelName ? { channelName: args.channelName } : void 0,
754
+ detailVersion: nextDetailVersion
755
+ }).where(and(eq(juniorConversations.conversationId, args.conversationId), isNull(juniorConversations.parentConversationId), isNull(juniorConversations.location))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
756
+ }
740
757
  /** Store a channel-level Location's first bound post as its thread. */
741
758
  async function startLocationThread(executor, binding) {
742
759
  const location = juniorConversations.location;
@@ -745,6 +762,50 @@ async function startLocationThread(executor, binding) {
745
762
  detailVersion: nextDetailVersion
746
763
  }).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
764
  }
765
+ // src/chat/conversations/sql/conversation-row.ts
766
+ /**
767
+ * Establish the conversation metadata row on first contact for content writes
768
+ * (conversation events, visible transcript) that can land before activity has
769
+ * created the row, and whose tables FK to it.
770
+ *
771
+ * First contact creates the row; every later content write advances the
772
+ * activity clock so retention mirrors append-refresh semantics (each content
773
+ * append refreshes the retention window). Background observations may opt out
774
+ * and leave an existing row unchanged. The timestamp is content-intrinsic (the
775
+ * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
776
+ * imported historical write — which carries an old timestamp — can never
777
+ * regress `last_activity_at`.
778
+ */
779
+ async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
780
+ const at = new Date(atMs);
781
+ const insert = executor.db().insert(juniorConversations).values({
782
+ conversationId,
783
+ createdAt: at,
784
+ lastActivityAt: at,
785
+ updatedAt: at,
786
+ executionStatus: "idle",
787
+ kind: "root"
788
+ });
789
+ if (options.activity === "preserve") {
790
+ await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
791
+ return;
792
+ }
793
+ await insert.onConflictDoUpdate({
794
+ target: juniorConversations.conversationId,
795
+ set: {
796
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
797
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
798
+ transcriptPurgedAt: null,
799
+ detailVersion: nextDetailVersion
800
+ }
801
+ });
802
+ }
803
+ /** Decode a stored kind. A null kind comes from a writer of an older deploy. */
804
+ function conversationKindFromRow(row) {
805
+ const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
806
+ if (kind !== "root" && kind !== "thread" && kind !== "task") throw new Error("Conversation record kind is invalid");
807
+ return kind;
808
+ }
748
809
  // src/chat/conversations/sql/store.ts
749
810
  const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
750
811
  /** Serialize one conversation's durable mutations inside a SQL transaction. */
@@ -853,7 +914,9 @@ function conversationFromRow(readRow) {
853
914
  ...row.metricRunId ? { runId: row.metricRunId } : void 0,
854
915
  ...row.executionUsage ? { usage: row.executionUsage } : void 0
855
916
  },
917
+ kind: conversationKindFromRow(row),
856
918
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
919
+ ...row.childArchivedAt ? { childArchivedAtMs: row.childArchivedAt.getTime() } : void 0,
857
920
  ...destination ? { destination } : void 0,
858
921
  ...location ? { location } : void 0,
859
922
  ...actor ? { actor } : void 0,
@@ -862,6 +925,7 @@ function conversationFromRow(readRow) {
862
925
  ...sessionSource ? { sessionSource } : void 0,
863
926
  ...row.title ? { title: row.title } : void 0,
864
927
  ...msFromDate(row.transcriptPurgedAt) !== void 0 ? { transcriptPurgedAtMs: msFromDate(row.transcriptPurgedAt) } : void 0,
928
+ ...msFromDate(row.stoppedAt) !== void 0 ? { stoppedAtMs: msFromDate(row.stoppedAt) } : void 0,
865
929
  ...visibility ? { visibility } : void 0
866
930
  };
867
931
  }
@@ -870,6 +934,7 @@ function emptyConversation(args) {
870
934
  schemaVersion: 1,
871
935
  conversationId: args.conversationId,
872
936
  createdAtMs: args.nowMs,
937
+ kind: "root",
873
938
  lastActivityAtMs: args.nowMs,
874
939
  updatedAtMs: args.nowMs,
875
940
  ...args.destination ? { destination: args.destination } : void 0,
@@ -903,6 +968,7 @@ var SqlStore = class {
903
968
  const existing = await this.get({ conversationId: args.childConversationId });
904
969
  if (existing) {
905
970
  if (existing.parentConversationId !== args.parentConversationId) throw new Error(`Conversation parent changed for ${args.childConversationId}`);
971
+ if (existing.kind !== args.kind) throw new Error(`Conversation kind changed for ${args.childConversationId}`);
906
972
  return;
907
973
  }
908
974
  if (!await this.get({ conversationId: args.parentConversationId })) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
@@ -912,6 +978,7 @@ var SqlStore = class {
912
978
  nowMs,
913
979
  source: args.source
914
980
  }),
981
+ kind: args.kind,
915
982
  parentConversationId: args.parentConversationId
916
983
  };
917
984
  await this.upsertConversation({ conversation: child });
@@ -983,6 +1050,7 @@ var SqlStore = class {
983
1050
  schemaVersion: 1,
984
1051
  conversationId: args.conversationId,
985
1052
  createdAtMs: args.createdAtMs,
1053
+ kind: existing?.kind ?? "root",
986
1054
  lastActivityAtMs: args.lastActivityAtMs,
987
1055
  updatedAtMs: args.updatedAtMs,
988
1056
  ...existing?.parentConversationId ? { parentConversationId: existing.parentConversationId } : void 0,
@@ -1061,6 +1129,7 @@ var SqlStore = class {
1061
1129
  /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
1062
1130
  async upsertConversation(args) {
1063
1131
  const { conversation } = args;
1132
+ if (conversation.kind === "root" !== !conversation.parentConversationId) throw new Error(`Conversation ${conversation.conversationId} kind does not match its parent`);
1064
1133
  if (!conversation.parentConversationId && !conversation.destination) {
1065
1134
  if (!await this.get({ conversationId: conversation.conversationId })) throw new Error(`Conversation ${conversation.conversationId} requires a destination at create`);
1066
1135
  }
@@ -1108,6 +1177,7 @@ var SqlStore = class {
1108
1177
  lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
1109
1178
  lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs),
1110
1179
  parentConversationId: conversation.parentConversationId ?? null,
1180
+ kind: conversation.kind,
1111
1181
  rootConversationId
1112
1182
  }).onConflictDoUpdate({
1113
1183
  target: juniorConversations.conversationId,
@@ -1130,6 +1200,7 @@ var SqlStore = class {
1130
1200
  lastCheckpointAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_checkpoint_at, ${juniorConversations.lastCheckpointAt}) else ${juniorConversations.lastCheckpointAt} end`,
1131
1201
  lastEnqueuedAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_enqueued_at, ${juniorConversations.lastEnqueuedAt}) else ${juniorConversations.lastEnqueuedAt} end`,
1132
1202
  rootConversationId: sql`coalesce(${juniorConversations.rootConversationId}, excluded.root_conversation_id)`,
1203
+ kind: sql`coalesce(${juniorConversations.kind}, excluded.kind)`,
1133
1204
  detailVersion: nextDetailVersion
1134
1205
  }
1135
1206
  }).returning({
@@ -1138,6 +1209,7 @@ var SqlStore = class {
1138
1209
  rootConversationId: juniorConversations.rootConversationId
1139
1210
  }))[0];
1140
1211
  if (!row?.rootConversationId) throw new Error("Conversation parent is missing its persisted root");
1212
+ if (row.parentConversationId !== (conversation.parentConversationId ?? null)) throw new Error(`Conversation parent changed for ${conversation.conversationId}`);
1141
1213
  if (row.actorIdentityId && row.parentConversationId === null) await recordConversationParticipant(this.executor, {
1142
1214
  actorIdentityId: row.actorIdentityId,
1143
1215
  conversationId: conversation.conversationId,
@@ -1179,43 +1251,6 @@ var SqlStore = class {
1179
1251
  function createSqlStore(executor) {
1180
1252
  return new SqlStore(executor);
1181
1253
  }
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
1254
  // src/chat/conversations/sql/event-actor.ts
1220
1255
  function isRecord(value) {
1221
1256
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -1333,6 +1368,84 @@ function sanitizePostgresJson(value) {
1333
1368
  if (prototype !== Object.prototype && prototype !== null) return value;
1334
1369
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
1335
1370
  }
1371
+ // src/chat/conversations/sql/conversation-tree.ts
1372
+ /**
1373
+ * Read every Conversation in the trees of the given roots. Every descendant
1374
+ * shares `root_conversation_id`, so one indexed read covers any depth.
1375
+ */
1376
+ async function readConversationTrees(db, rootConversationIds) {
1377
+ if (rootConversationIds.length === 0) return /* @__PURE__ */ new Map();
1378
+ const rows = await db.select({
1379
+ childArchivedAt: juniorConversations.childArchivedAt,
1380
+ conversationId: juniorConversations.conversationId,
1381
+ kind: juniorConversations.kind,
1382
+ parentConversationId: juniorConversations.parentConversationId
1383
+ }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
1384
+ return new Map(rows.map((row) => [row.conversationId, {
1385
+ childArchivedAt: row.childArchivedAt,
1386
+ conversationId: row.conversationId,
1387
+ kind: conversationKindFromRow(row),
1388
+ ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
1389
+ }]));
1390
+ }
1391
+ /** List the ancestors of one Conversation, nearest first, root last. */
1392
+ function conversationAncestors(tree, conversationId) {
1393
+ const ancestors = [];
1394
+ const seen = /* @__PURE__ */ new Set([conversationId]);
1395
+ let parentId = tree.get(conversationId)?.parentConversationId;
1396
+ while (parentId && !seen.has(parentId)) {
1397
+ const parent = tree.get(parentId);
1398
+ if (!parent) break;
1399
+ ancestors.push(parent);
1400
+ seen.add(parentId);
1401
+ parentId = parent.parentConversationId;
1402
+ }
1403
+ return ancestors;
1404
+ }
1405
+ /** List every descendant of one Conversation, at any depth. */
1406
+ function conversationDescendants(tree, conversationId) {
1407
+ const childrenByParent = /* @__PURE__ */ new Map();
1408
+ for (const node of tree.values()) {
1409
+ if (!node.parentConversationId) continue;
1410
+ const siblings = childrenByParent.get(node.parentConversationId) ?? [];
1411
+ siblings.push(node);
1412
+ childrenByParent.set(node.parentConversationId, siblings);
1413
+ }
1414
+ const descendants = [];
1415
+ const seen = /* @__PURE__ */ new Set([conversationId]);
1416
+ const pending = [conversationId];
1417
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) for (const child of childrenByParent.get(id) ?? []) {
1418
+ if (seen.has(child.conversationId)) continue;
1419
+ seen.add(child.conversationId);
1420
+ descendants.push(child);
1421
+ pending.push(child.conversationId);
1422
+ }
1423
+ return descendants;
1424
+ }
1425
+ /** Set or clear the shared archive of the given child Conversations. */
1426
+ async function setChildArchivedAt(db, conversationIds, archivedAt) {
1427
+ if (conversationIds.length === 0) return;
1428
+ await db.update(juniorConversations).set({
1429
+ childArchivedAt: archivedAt,
1430
+ detailVersion: nextDetailVersion
1431
+ }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
1432
+ }
1433
+ /**
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.
1437
+ */
1438
+ async function restoreArchivedChildPath(db, conversationId) {
1439
+ const [row] = await db.select({
1440
+ parentConversationId: juniorConversations.parentConversationId,
1441
+ rootConversationId: juniorConversations.rootConversationId
1442
+ }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
1443
+ if (!row?.parentConversationId || !row.rootConversationId) return;
1444
+ const tree = await readConversationTrees(db, [row.rootConversationId]);
1445
+ const node = tree.get(conversationId);
1446
+ if (!node) return;
1447
+ await setChildArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.kind !== "root" && entry.childArchivedAt).map((entry) => entry.conversationId), null);
1448
+ }
1336
1449
  // src/chat/conversations/sql/event-lock.ts
1337
1450
  /** Serialize event sequence allocation with other conversation writes. */
1338
1451
  async function withConversationEventLock(executor, conversationId, callback) {
@@ -1464,16 +1577,20 @@ var SqlConversationEventStore = class {
1464
1577
  */
1465
1578
  async recordTurnInputParticipants(conversationId, inputMessageIds) {
1466
1579
  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;
1467
1581
  for (const row of rows) {
1468
1582
  const { data } = eventFromRow(row);
1469
1583
  if (!row.actorIdentityId || data.type !== "message") continue;
1470
- await recordConversationParticipant(this.executor, {
1584
+ const restoreArchive = eventUnarchivesConversation(data);
1585
+ const isPerson = await recordConversationParticipant(this.executor, {
1471
1586
  actorIdentityId: row.actorIdentityId,
1472
1587
  conversationId,
1473
1588
  atMs: row.createdAt.getTime(),
1474
- restoreArchive: eventUnarchivesConversation(data)
1589
+ restoreArchive
1475
1590
  });
1591
+ restoresChild ||= isPerson && restoreArchive;
1476
1592
  }
1593
+ if (restoresChild) await restoreArchivedChildPath(this.executor.db(), conversationId);
1477
1594
  }
1478
1595
  async replaceHistory(conversationId, replacement, options = {}) {
1479
1596
  const parsed = historyReplacementSchema.parse(replacement);
@@ -1809,6 +1926,7 @@ const AVATAR_CACHE_TTL_MS = 864e5;
1809
1926
  const AVATAR_FAILURE_TTL_MS = 3e5;
1810
1927
  const AVATAR_FETCH_TIMEOUT_MS = 5e3;
1811
1928
  const MAX_AVATAR_BYTES = 1048576;
1929
+ const AVATAR_EDGE_PX = 96;
1812
1930
  const MAX_AVATAR_REDIRECTS = 3;
1813
1931
  /**
1814
1932
  * Return the URL when it is HTTPS on a photo host of the provider or a
@@ -1914,16 +2032,35 @@ async function fetchAvatarImage(url, provider) {
1914
2032
  if (!data) return avatarFetchFailed(host, { "app.reason": "too_large" });
1915
2033
  const contentType = detectImageMediaType(data);
1916
2034
  if (!contentType) return avatarFetchFailed(host, { "app.reason": "not_an_image" });
1917
- return {
1918
- contentType,
1919
- data: Buffer.from(data).toString("base64")
1920
- };
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");
1921
2058
  }
1922
2059
  /**
1923
2060
  * 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.
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.
1927
2064
  */
1928
2065
  async function readAvatarImage(db, state, identityId) {
1929
2066
  const [row] = await db.select({
@@ -1932,7 +2069,7 @@ async function readAvatarImage(db, state, identityId) {
1932
2069
  }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
1933
2070
  const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
1934
2071
  if (!row?.avatarUrl || !url) return void 0;
1935
- const key = `avatar:${avatarUrlHash(url)}`;
2072
+ const key = `avatar:${AVATAR_EDGE_PX}:${avatarUrlHash(url)}`;
1936
2073
  const image = await createCache(state, "core").getOrLoad(key, async () => {
1937
2074
  const loaded = await fetchAvatarImage(url, row.provider);
1938
2075
  return {
@@ -2069,4 +2206,4 @@ async function readIdentityByIdFromSql(db, identityId) {
2069
2206
  async function readIdentityById(identityId) {
2070
2207
  return await readIdentityByIdFromSql(getDb(), identityId);
2071
2208
  }
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 };
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 };