@sentry/junior 0.310.0 → 0.312.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 (157) hide show
  1. package/dist/{adapter-context-BhKpjpGD.js → adapter-context-BRjEWRy1.js} +2 -2
  2. package/dist/adapter-iIq7ihf7.js +259 -0
  3. package/dist/{admin-tgZEZAk2.js → admin-DhInw5K9.js} +1 -2
  4. package/dist/{agent-runner-D9cvNlQl.js → agent-runner-C9iDurwX.js} +6507 -7721
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -6
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1625 -535
  9. package/dist/{app-B_7Wn0en.d.ts → app-DRFrC8Mw.d.ts} +14 -10
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +454 -994
  12. package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-DrKi7w3d.js} +10 -85
  13. package/dist/callback-mFlTUWWx.js +75 -0
  14. package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-D7xapBAX.js} +1 -1
  15. package/dist/channel-access-CJGfNTdn.js +221 -0
  16. package/dist/child-message-DcsritGf.js +179 -0
  17. package/dist/cli/chat.js +18 -19
  18. package/dist/cli/check.js +23 -29
  19. package/dist/cli/init.js +1 -7
  20. package/dist/cli/main.js +3 -7
  21. package/dist/cli/plugins.js +8 -7
  22. package/dist/cli/run.d.ts +1 -2
  23. package/dist/cli/run.js +1 -2
  24. package/dist/cli/snapshot-create.js +5 -5
  25. package/dist/cli/upgrade.d.ts +1 -1
  26. package/dist/cli/upgrade.js +3 -3
  27. package/dist/{config-Dkt2Le2b.js → config-kXB2Y5tl.js} +294 -28
  28. package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-O6pV5004.js} +7 -7
  29. package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-uNOv_x68.js} +87 -24
  30. package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-L4ja1_W6.js} +1 -1
  31. package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-CeLbHqdw.js} +56 -49
  32. package/dist/{credential-sync-vGnrB0BY.js → credential-sync-I8VBGk05.js} +16 -16
  33. package/dist/{projection-jZSlEAXG.js → credentialed-Cb6E2phL.js} +16268 -16821
  34. package/dist/{db-B4Hjxr-u.d.ts → db-BbC5stfa.d.ts} +13 -6
  35. package/dist/{db-CFZggNoy.js → db-LAyyX8tk.js} +1698 -1046
  36. package/dist/{executor-BPkZDx5-.js → executor-SCub-fAq.js} +552 -181
  37. package/dist/{html-2r2KmLwi.js → html-BCZ3Xtb_.js} +6 -6
  38. package/dist/{session-stop-BfY4rhJs.js → ingest-BDf3D50j.js} +2134 -2553
  39. package/dist/{install-C-oE6C_u.js → install-DCFJFkC0.js} +2 -2
  40. package/dist/instrumentation.js +4 -4
  41. package/dist/{lineage-CsvrEFQe.js → lineage-B_m-4TJw.js} +2 -2
  42. package/dist/{stop-DYzjRf2U.js → list-CN2QA2R9.js} +1656 -685
  43. package/dist/{logging-D5gkyvnK.js → logging-dQ9ZRGQ8.js} +47 -9
  44. package/dist/media-CYm1QD8T.js +2356 -0
  45. package/dist/{message-DwvJ-I3w.js → message-DSXGj1hM.js} +19 -29
  46. package/dist/{model-input-MAq2881y.js → model-input--TrP9hYV.js} +3 -3
  47. package/dist/nitro.d.ts +1 -1
  48. package/dist/nitro.js +4 -3
  49. package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-DHCZC6B4.js} +2 -2
  50. package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-pPMGnDZt.js} +1 -1
  51. package/dist/{registry-BBkWFCl8.js → registry-CZOzddwu.js} +5 -8
  52. package/dist/{resolve-B38MkHXE.js → resolve-cKOQ14Dh.js} +3 -3
  53. package/dist/{result-BaqSZcJb.js → result-DcvEOe1r.js} +119 -93
  54. package/dist/result-event-type-BdIJuZxg.js +48 -0
  55. package/dist/rule-DAxQY-1h.js +20 -0
  56. package/dist/{runner-11h8PrHh.js → runner-DBfUW44l.js} +14 -16
  57. package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
  58. package/dist/{schema-DriSvB40.d.ts → schema-BEHKxr4I.d.ts} +861 -298
  59. package/dist/{schema-obw5jvR4.js → schema-Bk9Nm2E8.js} +344 -153
  60. package/dist/{service-account-Bx93N1n1.js → service-account-CVYsFjty.js} +3 -3
  61. package/dist/{service-account-Zc5bUcIJ.js → service-account-Ts4ulcrV.js} +68 -68
  62. package/dist/{skills-C8Npu5zO.js → skills-VTnhAJWm.js} +2 -2
  63. package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -11
  64. package/dist/{spawn-CXr58R0x.js → spawn-vxAarlX5.js} +6 -6
  65. package/dist/start-conversation-CEn2KH1A.js +941 -0
  66. package/dist/{state-CGrGVeQC.js → state-C1P3_Ywk.js} +4 -4
  67. package/dist/statuses-_cRJHXK7.js +150 -0
  68. package/dist/store-DFZaN-Ix.js +492 -0
  69. package/dist/task-queue-Cx4Lmjyk.js +90 -0
  70. package/dist/task-runner-CbTwFA6k.js +1432 -0
  71. package/dist/{thread-context-Dyj1KWaY.js → thread-context-BkAZDTX2.js} +13 -11
  72. package/dist/thread-state-DhPndWi1.js +5625 -0
  73. package/dist/{validation-DxVNIxA0.js → validation-nIzMtAVJ.js} +1 -1
  74. package/dist/{task-queue-CaZffYaH.js → vercel-queue-hW90XzbG.js} +93 -172
  75. package/dist/{version-Cr7Z71yG.js → version-Brbtz4Qf.js} +1 -1
  76. package/dist/version.js +1 -1
  77. package/dist/{warmup-C6LOZ2d2.js → warmup-BDA5myRK.js} +5832 -4567
  78. package/dist/web-message-id-C6P83ans.js +10 -0
  79. package/dist/{worker-CUBtu1Li.js → worker-D63RcaVD.js} +20 -8
  80. package/migrations/0126_artifact_drop_public.sql +8 -0
  81. package/migrations/0127_artifact_path.sql +4 -0
  82. package/migrations/0128_artifact_path_index.sql +1 -0
  83. package/migrations/0129_review_item_answered_index.sql +1 -0
  84. package/migrations/0130_review_item_status_index.sql +1 -0
  85. package/migrations/0131_brief_outcome_status.sql +1 -0
  86. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  87. package/migrations/0133_brief_created_at_index.sql +1 -0
  88. package/migrations/0134_slack_person_search_index.sql +1 -0
  89. package/migrations/0135_code_change_size.sql +3 -0
  90. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  91. package/migrations/0137_inbox_snoozes.sql +27 -0
  92. package/migrations/0138_code_change_search_index.sql +2 -0
  93. package/migrations/0139_review_item_owner.sql +22 -0
  94. package/migrations/0140_review_item_owner_index.sql +1 -0
  95. package/migrations/0141_memory_core_adoption.sql +89 -0
  96. package/migrations/0142_memory_core_indexes.sql +17 -0
  97. package/migrations/0143_todos.sql +14 -0
  98. package/migrations/0144_inbox_items.sql +32 -0
  99. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  100. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  101. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  102. package/migrations/0148_authorization_request_index.sql +1 -0
  103. package/migrations/0149_conversation_metadata.sql +10 -0
  104. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  105. package/migrations/0151_conversation_search_index.sql +1 -0
  106. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  107. package/migrations/0153_artifact_expiry.sql +1 -0
  108. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  109. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  110. package/migrations/0156_conversation_kind_lead.sql +6 -0
  111. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  112. package/migrations/meta/0126_snapshot.json +5488 -0
  113. package/migrations/meta/0127_snapshot.json +5519 -0
  114. package/migrations/meta/0128_snapshot.json +5519 -0
  115. package/migrations/meta/0129_snapshot.json +5547 -0
  116. package/migrations/meta/0130_snapshot.json +5563 -0
  117. package/migrations/meta/0131_snapshot.json +5569 -0
  118. package/migrations/meta/0132_snapshot.json +5569 -0
  119. package/migrations/meta/0133_snapshot.json +5590 -0
  120. package/migrations/meta/0134_snapshot.json +5606 -0
  121. package/migrations/meta/0135_snapshot.json +5624 -0
  122. package/migrations/meta/0136_snapshot.json +5624 -0
  123. package/migrations/meta/0137_snapshot.json +5864 -0
  124. package/migrations/meta/0138_snapshot.json +5894 -0
  125. package/migrations/meta/0139_snapshot.json +5898 -0
  126. package/migrations/meta/0140_snapshot.json +5919 -0
  127. package/migrations/meta/0141_snapshot.json +6429 -0
  128. package/migrations/meta/0142_snapshot.json +6457 -0
  129. package/migrations/meta/0143_snapshot.json +6434 -0
  130. package/migrations/meta/0144_snapshot.json +6434 -0
  131. package/migrations/meta/0145_snapshot.json +6440 -0
  132. package/migrations/meta/0146_snapshot.json +6446 -0
  133. package/migrations/meta/0147_snapshot.json +6452 -0
  134. package/migrations/meta/0148_snapshot.json +6474 -0
  135. package/migrations/meta/0149_snapshot.json +6490 -0
  136. package/migrations/meta/0150_snapshot.json +6490 -0
  137. package/migrations/meta/0151_snapshot.json +6505 -0
  138. package/migrations/meta/0152_snapshot.json +6505 -0
  139. package/migrations/meta/0153_snapshot.json +6511 -0
  140. package/migrations/meta/0154_snapshot.json +6533 -0
  141. package/migrations/meta/0155_snapshot.json +6511 -0
  142. package/migrations/meta/0156_snapshot.json +6511 -0
  143. package/migrations/meta/0157_snapshot.json +6527 -0
  144. package/migrations/meta/_journal.json +224 -0
  145. package/package.json +7 -8
  146. package/skills/design-automation-skill/SKILL.md +108 -0
  147. package/dist/briefs-DKxkoruh.js +0 -395
  148. package/dist/conversation-M9KZ5JxF.js +0 -1024
  149. package/dist/prompt-CaMyeCpA.js +0 -910
  150. package/dist/schedule-DWxZ3kja.js +0 -1146
  151. package/dist/store-D4FQ1Nml.js +0 -335
  152. package/dist/task-runner-Dm7BHbGp.js +0 -287
  153. package/dist/turn-session-routing-CD0BRCex.js +0 -263
  154. package/dist/turn-user-message-9IxeEv5v.js +0 -364
  155. package/dist/users-CaUAYMb3.js +0 -181
  156. package/dist/viewer-AHldghAD.js +0 -212
  157. package/dist/web-message-id-BT8Mg8LL.js +0 -418
@@ -1,18 +1,17 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { i as getChatConfig } from "./config-Dkt2Le2b.js";
2
+ import { N as cacheKeyPrefix, P as createCache, r as getChatConfig } from "./config-kXB2Y5tl.js";
3
3
  import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-BsBdxDXQ.js";
4
- import { A as juniorConversationEvents, B as juniorUsers, D as CONVERSATION_METRICS, I as juniorAttachments, L as juniorMessageAttachments, M as juniorConversationAnnotations, O as juniorConversationMetrics, R as juniorConversations, S as juniorConversationBindings, V as juniorDestinations, k as isUserInstruction, p as juniorAutomationRuns, t as createJuniorSqlExecutor, x as juniorConversationParticipants, z as juniorIdentities } from "./executor-BPkZDx5-.js";
4
+ import { A as juniorConversationMetrics, B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, P as juniorConversationAnnotations, S as juniorConversationReadPositions, T as juniorConversationBriefs, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, f as juniorInboxItemAssignees, g as juniorAutomations, h as juniorInboxItems, j as isUserInstruction, k as CONVERSATION_METRICS, p as juniorInboxItemConversations, q as juniorDestinations, t as createJuniorSqlExecutor, w as juniorConversationBindings } from "./executor-SCub-fAq.js";
5
5
  import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-CYstOMKX.js";
6
- import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-D5gkyvnK.js";
6
+ import { t as canExposeConversationPayload } from "./conversation-privacy-L4ja1_W6.js";
7
7
  import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
8
+ import { J as normalizeIdentityEmail, K as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-dQ9ZRGQ8.js";
9
+ import { i as getStateAdapter } from "./adapter-iIq7ihf7.js";
8
10
  import * as z from "zod";
9
11
  import { createHash, randomUUID } from "node:crypto";
10
- import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
11
- import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
12
+ import { PluginToolInputError, destinationSchema, identitySchema, locationSchema, sourceSchema, userSchema } from "@sentry/junior-plugin-api";
13
+ import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, or, sql } from "drizzle-orm";
12
14
  import { alias } from "drizzle-orm/pg-core";
13
- import { createMemoryState } from "@chat-adapter/state-memory";
14
- import { createRedisState } from "@chat-adapter/state-redis";
15
- import { setTimeout } from "node:timers/promises";
16
15
  // src/chat/destination.ts
17
16
  /** Build Junior's canonical destination from Slack workspace and channel ids. */
18
17
  function createSlackDestination(input) {
@@ -223,1068 +222,1668 @@ function addAgentTurnUsage(...usages) {
223
222
  };
224
223
  return hasAgentTurnUsage(result) ? result : void 0;
225
224
  }
226
- // src/api/conversations/aggregate.ts
227
- function usageTokenValue(source, field) {
228
- return sql`CASE
229
- WHEN ${source.usage}->>${field} IS NOT NULL
230
- THEN (${source.usage}->>${field})::double precision
231
- ELSE NULL
232
- END`;
225
+ // src/api/conversations/membership.ts
226
+ /**
227
+ * Select the person's participant row on the outer `juniorConversations`
228
+ * root, with an optional extra condition.
229
+ */
230
+ function memberParticipantRow(member, condition) {
231
+ const rows = getDb().select({ rootConversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
232
+ const onRoot = eq(juniorConversationParticipants.rootConversationId, juniorConversations.conversationId);
233
+ return "userId" in member ? rows.where(and(onRoot, eq(juniorConversationParticipants.userId, member.userId), condition)) : rows.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(onRoot, eq(juniorUsers.primaryEmailNormalized, member.email), condition));
233
234
  }
234
- function tokenValue(source) {
235
- return sql`
236
- CASE
237
- WHEN COALESCE(
238
- ${source.usage}->>'inputTokens',
239
- ${source.usage}->>'outputTokens',
240
- ${source.usage}->>'cachedInputTokens',
241
- ${source.usage}->>'cacheCreationTokens'
242
- ) IS NOT NULL
243
- THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
244
- + COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
245
- + COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
246
- + COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
247
- WHEN ${source.usage}->>'totalTokens' IS NOT NULL
248
- THEN (${source.usage}->>'totalTokens')::double precision
249
- ELSE NULL
250
- END
251
- `;
235
+ /** True when the viewer is a materialized participant on this root conversation. */
236
+ function conversationHasParticipantUser(userId) {
237
+ return exists(memberParticipantRow({ userId }));
252
238
  }
253
- function costValue(source) {
254
- return conversationUsageCostExpr(source.usage);
239
+ /**
240
+ * True when the viewer may find the outer root conversation by a link to
241
+ * it: its Destination, joined as `juniorDestinations`, is public, or the
242
+ * viewer is a Participant.
243
+ */
244
+ function rootVisibleToViewer(viewerUserId) {
245
+ return or(eq(juniorDestinations.visibility, "public"), viewerUserId ? conversationHasParticipantUser(viewerUserId) : void 0);
255
246
  }
256
- /** Read one conversation row's usage cost as a SQL expression. */
257
- function conversationUsageCostExpr(usage) {
258
- return sql`
259
- CASE
260
- WHEN ${usage}->'cost'->>'total' IS NOT NULL
261
- THEN (${usage}->'cost'->>'total')::double precision
262
- WHEN COALESCE(
263
- ${usage}->'cost'->>'input',
264
- ${usage}->'cost'->>'output',
265
- ${usage}->'cost'->>'cacheRead',
266
- ${usage}->'cost'->>'cacheWrite'
267
- ) IS NOT NULL
268
- THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
269
- + COALESCE((${usage}->'cost'->>'output')::double precision, 0)
270
- + COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
271
- + COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
272
- ELSE NULL
273
- END
274
- `;
247
+ /**
248
+ * True when the person is a Participant of the conversation. Feeds filter
249
+ * with this id set instead of a per-row membership check, so Postgres reads
250
+ * only that person's conversations, not every root.
251
+ */
252
+ function conversationIsMemberRoot(member) {
253
+ const participating = getDb().select({ conversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
254
+ const memberRoots = "userId" in member ? participating.where(eq(juniorConversationParticipants.userId, member.userId)) : participating.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email));
255
+ return inArray(juniorConversations.conversationId, memberRoots);
275
256
  }
276
- /** Select complete conversation metrics inside the database instead of materializing source rows. */
277
- function conversationAggregateColumns(sources) {
278
- const metrics = sources?.metrics ?? juniorConversations;
279
- const roots = sources?.roots ?? juniorConversations;
280
- const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
281
- return {
282
- active: sql`${conversationCount} FILTER (
283
- WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
284
- )::integer`,
285
- conversations: sql`${conversationCount}::integer`,
286
- cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
287
- cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
288
- costUsd: sql`SUM(${costValue(metrics)})::double precision`,
289
- durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
290
- failed: sql`${conversationCount} FILTER (
291
- WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
292
- )::integer`,
293
- inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
294
- tokens: sql`SUM(${tokenValue(metrics)})::double precision`
295
- };
257
+ /**
258
+ * True when the person has not unsubscribed from the conversation. The
259
+ * active feed uses it, so a conversation that someone else carries on
260
+ * leaves the feed of a person who left it.
261
+ */
262
+ function conversationIsNotUnsubscribedRoot(member) {
263
+ return not(exists(memberParticipantRow(member, isNotNull(juniorConversationParticipants.unsubscribedAt))));
296
264
  }
297
- /** Select the complete first/last activity range for a grouped conversation aggregate. */
298
- function conversationRangeColumns() {
265
+ /**
266
+ * Read the roots among a bounded set where one person is a Participant, each
267
+ * with their pin marks. An unpinned root maps to empty marks.
268
+ */
269
+ async function readMemberParticipants(db, conversationIds, member) {
270
+ if (!member || conversationIds.length === 0) return /* @__PURE__ */ new Map();
271
+ const listed = inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]);
272
+ const query = db.select({
273
+ pinnedAt: juniorConversationParticipants.pinnedAt,
274
+ pinPosition: juniorConversationParticipants.pinPosition,
275
+ rootConversationId: juniorConversationParticipants.rootConversationId
276
+ }).from(juniorConversationParticipants);
277
+ const rows = "userId" in member ? await query.where(and(eq(juniorConversationParticipants.userId, member.userId), listed)) : await query.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorUsers.primaryEmailNormalized, member.email), listed));
278
+ return new Map(rows.map((row) => [row.rootConversationId, viewerMarksFromParticipant(row) ?? {}]));
279
+ }
280
+ /** Project one participant row into marks, or undefined when it has none. */
281
+ function viewerMarksFromParticipant(row) {
282
+ if (!row.pinnedAt) return void 0;
299
283
  return {
300
- firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
301
- lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
284
+ pinnedAtMs: row.pinnedAt.getTime(),
285
+ ...row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
302
286
  };
303
287
  }
304
- // src/db/micro-usd.ts
288
+ /** True when one user pinned this root. Feeds sort these rows first. */
289
+ function conversationPinnedForUser(userId) {
290
+ return exists(memberParticipantRow({ userId }, isNotNull(juniorConversationParticipants.pinnedAt)));
291
+ }
292
+ /** Find which of the supplied roots include the linked viewer as a participant. */
293
+ async function conversationIdsWithParticipantUser(db, conversationIds, userId) {
294
+ if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
295
+ const rows = await db.select({ rootConversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, userId), inArray(juniorConversationParticipants.rootConversationId, [...conversationIds])));
296
+ return new Set(rows.map((row) => row.rootConversationId));
297
+ }
298
+ // src/api/conversations/access.ts
299
+ const rootConversation = alias(juniorConversations, "access_root_conversation");
300
+ const rootDestination = alias(juniorDestinations, "access_root_destination");
301
+ /** Resolve viewer access for a bounded set of persisted conversations. */
302
+ async function readConversationAccessFromSql(db, conversationIds, viewer) {
303
+ const rows = await readConversationAccessRows(db, conversationIds);
304
+ const membershipConversationIds = /* @__PURE__ */ new Set();
305
+ for (const row of rows) {
306
+ membershipConversationIds.add(row.conversationId);
307
+ if (row.storedRootConversationId) membershipConversationIds.add(row.storedRootConversationId);
308
+ }
309
+ return conversationAccessFromRows(rows, viewer !== void 0 ? await conversationIdsWithParticipantUser(db, [...membershipConversationIds], viewer.id) : /* @__PURE__ */ new Set());
310
+ }
305
311
  /**
306
- * Postgres stores every money value as whole micro-USD, in a `bigint` column
307
- * or an integer metric value named `*_micro_usd`. Integer sums are exact and
308
- * do not depend on row order. Round once where a USD amount is stored, and
309
- * convert to USD once where the API returns it. `pnpm money-units:check`
310
- * keeps money scales in this file.
312
+ * Read the stored tree and root Destination of each conversation. A caller
313
+ * that reads the viewer's participant rows itself passes these rows to
314
+ * `conversationAccessFromRows`.
311
315
  */
312
- const MICRO_USD_PER_USD = 1e6;
313
- /** Round a USD amount to whole micro-USD for storage. */
314
- function usdToMicroUsd(usd) {
315
- return Math.round(usd * MICRO_USD_PER_USD);
316
- }
317
- /** Convert stored micro-USD to USD for an API response. */
318
- function microUsdToUsd(microUsd) {
319
- return microUsd / MICRO_USD_PER_USD;
316
+ async function readConversationAccessRows(db, conversationIds) {
317
+ if (conversationIds.length === 0) return [];
318
+ return await db.select({
319
+ conversationId: juniorConversations.conversationId,
320
+ parentConversationId: juniorConversations.parentConversationId,
321
+ storedRootConversationId: juniorConversations.rootConversationId,
322
+ rootConversationId: rootConversation.conversationId,
323
+ rootParentConversationId: rootConversation.parentConversationId,
324
+ rootRootConversationId: rootConversation.rootConversationId,
325
+ destinationId: rootDestination.id,
326
+ visibility: rootDestination.visibility,
327
+ provider: rootDestination.provider,
328
+ providerTenantId: rootDestination.providerTenantId
329
+ }).from(juniorConversations).leftJoin(rootConversation, eq(rootConversation.conversationId, juniorConversations.rootConversationId)).leftJoin(rootDestination, eq(rootDestination.id, rootConversation.destinationId)).where(inArray(juniorConversations.conversationId, [...conversationIds]));
320
330
  }
321
- /** SQL that rounds a USD amount to whole micro-USD. */
322
- function usdToMicroUsdSql(usd) {
323
- return sql`round(${usd} * 1000000)::bigint`;
331
+ /**
332
+ * Resolve access from `readConversationAccessRows`. `participantRootIds`
333
+ * holds the viewer's participant roots among the conversations and their
334
+ * stored roots, and is empty without a viewer.
335
+ */
336
+ function conversationAccessFromRows(rows, participantRootIds) {
337
+ return new Map(rows.map((row) => {
338
+ const validRootConversationId = row.rootConversationId !== null && row.rootConversationId === row.storedRootConversationId && row.rootRootConversationId === row.rootConversationId && row.rootParentConversationId === null && (row.parentConversationId !== null || row.storedRootConversationId === row.conversationId) ? row.rootConversationId ?? void 0 : void 0;
339
+ const visibility = validRootConversationId === void 0 ? null : row.visibility;
340
+ const isParticipant = row.parentConversationId === null && participantRootIds.has(row.conversationId) || validRootConversationId !== void 0 && participantRootIds.has(validRootConversationId);
341
+ const canViewPrivateContent = isParticipant || validRootConversationId !== void 0 && canExposeConversationPayload({ visibility: visibility ?? void 0 });
342
+ return [row.conversationId, {
343
+ canViewPrivateContent,
344
+ ...validRootConversationId !== void 0 && row.destinationId ? { destinationId: row.destinationId } : void 0,
345
+ isParticipant,
346
+ ...validRootConversationId !== void 0 ? { rootConversationId: validRootConversationId } : void 0,
347
+ visibility,
348
+ ...validRootConversationId !== void 0 && row.provider !== null && row.providerTenantId ? { tenant: {
349
+ provider: row.provider,
350
+ providerTenantId: row.providerTenantId
351
+ } } : void 0
352
+ }];
353
+ }));
324
354
  }
325
- /** SQL that converts micro-USD to USD, for usage JSON in USD. */
326
- function microUsdToUsdSql(microUsd) {
327
- return sql`(${microUsd}) / 1000000.0::double precision`;
355
+ /**
356
+ * Whether the viewer may add a Message to a Conversation. A signed-in person
357
+ * joins a public Conversation by posting in it, the same as a public Slack
358
+ * thread: their first Turn adds their Participant row. A private one takes
359
+ * Messages only from its Participants.
360
+ */
361
+ function canAddConversationMessages(access) {
362
+ return Boolean(access?.isParticipant || access?.visibility === "public");
328
363
  }
329
364
  /**
330
- * SQL that reads a micro-USD value or sum as an exact integer. Postgres
331
- * returns `bigint` as text, so this maps it to a number.
365
+ * The Slack workspace of a Conversation that the viewer can read. A mention
366
+ * in it must name a Slack user of that workspace.
332
367
  */
333
- function microUsdSql(microUsd) {
334
- return sql`(${microUsd})::bigint`.mapWith(Number);
368
+ function readableSlackTeamId(access) {
369
+ return access?.canViewPrivateContent && access.tenant?.provider === "slack" ? access.tenant.providerTenantId : void 0;
335
370
  }
336
- // src/chat/automations/run-cost.ts
337
371
  /**
338
- * SQL for a Conversation's usage cost in whole micro-USD, the unit of a run's
339
- * `cost_micro_usd`.
372
+ * Read access for one request. Each id is read at most once, so the parts of
373
+ * one response that need the same Conversation share a query.
340
374
  */
341
- function costMicroUsdExpr(usage) {
342
- return usdToMicroUsdSql(conversationUsageCostExpr(usage));
375
+ function createConversationAccessReader(db, viewer) {
376
+ const byId = /* @__PURE__ */ new Map();
377
+ return async (conversationIds) => {
378
+ const missing = [...new Set(conversationIds)].filter((id) => !byId.has(id));
379
+ if (missing.length > 0) {
380
+ const read = readConversationAccessFromSql(db, missing, viewer);
381
+ for (const id of missing) byId.set(id, read.then((access) => access.get(id)));
382
+ }
383
+ const entries = await Promise.all(conversationIds.map(async (id) => [id, await byId.get(id)]));
384
+ return new Map(entries.flatMap(([id, access]) => access ? [[id, access]] : []));
385
+ };
343
386
  }
344
387
  /**
345
- * SQL that reads the cost of one Conversation, for the `cost_micro_usd` of its
346
- * run. Set it in each run write that links a run to its Conversation, because
347
- * the Conversation can record usage before its run row exists.
388
+ * Apply `policies/conversation-access.md`: whether work in the `requester`
389
+ * Conversation may read or find the data of the `target` Conversation. The
390
+ * person of the Turn does not change the result. A public Conversation is
391
+ * reachable from any Conversation, on any surface and in any provider tenant.
392
+ * A private Conversation is reachable only from its own tree and from
393
+ * Conversations at the same Destination, which have the same audience.
348
394
  */
349
- function conversationCostOf(conversationId) {
350
- return sql`(select ${costMicroUsdExpr(juniorConversations.usage)} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
395
+ function canAccessConversation(args) {
396
+ const { requester, target } = args;
397
+ if (requester.rootConversationId !== void 0 && requester.rootConversationId === target.rootConversationId) return true;
398
+ if (requester.destinationId !== void 0 && requester.destinationId === target.destinationId) return true;
399
+ return target.visibility === "public";
351
400
  }
352
- // src/chat/conversations/metrics.ts
353
- function finite(value) {
354
- return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
401
+ /**
402
+ * Whether work in `requesterConversationId` may read `conversationId`, by
403
+ * `canAccessConversation`. A missing target is not readable. A requester that
404
+ * is not stored yet reaches only public targets.
405
+ */
406
+ async function canReadConversation(db, requesterConversationId, conversationId) {
407
+ const access = await readConversationAccessFromSql(db, [requesterConversationId, conversationId]);
408
+ const target = access.get(conversationId);
409
+ return target !== void 0 && canAccessConversation({
410
+ requester: access.get(requesterConversationId) ?? { visibility: null },
411
+ target
412
+ });
355
413
  }
356
- /** Convert one Run summary to metric rows. */
357
- function conversationMetricValues(args) {
358
- const usage = args.usage;
359
- const costUsd = agentTurnCostUsd(usage);
360
- return {
361
- duration_ms: Math.max(0, args.durationMs),
362
- total_tokens: agentTurnTotalTokens(usage),
363
- input_tokens: finite(usage?.inputTokens),
364
- output_tokens: finite(usage?.outputTokens),
365
- cached_input_tokens: finite(usage?.cachedInputTokens),
366
- cache_creation_tokens: finite(usage?.cacheCreationTokens),
367
- reasoning_tokens: finite(usage?.reasoningTokens),
368
- cost_micro_usd: costUsd === void 0 ? void 0 : usdToMicroUsd(costUsd)
369
- };
414
+ // src/chat/tool-support/tool-input-error.ts
415
+ /** Thrown when a tool fails due to invalid model/user input, not a system error. */
416
+ var ToolInputError = class extends Error {
417
+ constructor(message, options) {
418
+ super(message, options);
419
+ this.name = "ToolInputError";
420
+ }
421
+ };
422
+ /** Whether an error is an expected tool input failure that is not a Sentry exception. */
423
+ function isToolInputError(error) {
424
+ return error instanceof ToolInputError || error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
370
425
  }
426
+ // src/chat/identities/user-cache.ts
371
427
  /**
372
- * Read one Run's stored totals from its metric rows.
428
+ * Cache of each User and their user Identities. Every signed-in request
429
+ * resolves its viewer, and person cards read the people that a message
430
+ * links to, so these reads go to the state cache instead of the database.
373
431
  *
374
- * Returns undefined when the Run has no rows. Cost keeps only its total.
432
+ * Every write to a cached column or to a user Identity must call
433
+ * `clearCachedUser`. The other columns of a User, such as the timezone or
434
+ * the customization, are not in the cache.
375
435
  */
376
- async function readConversationRunMetrics(executor, args) {
377
- const rows = await executor.db().select({
378
- metric: juniorConversationMetrics.metric,
379
- value: juniorConversationMetrics.value
380
- }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
381
- const values = new Map(rows.map((row) => [row.metric, row.value]));
382
- const durationMs = values.get("duration_ms");
383
- if (durationMs === void 0) return void 0;
384
- const components = {
385
- inputTokens: values.get("input_tokens"),
386
- outputTokens: values.get("output_tokens"),
387
- cachedInputTokens: values.get("cached_input_tokens"),
388
- cacheCreationTokens: values.get("cache_creation_tokens")
436
+ const USER_TTL_MS = 864e5;
437
+ const MISSING_TTL_MS = 6e4;
438
+ const SETTLE_MS = 1e4;
439
+ /** The cache namespace of every key in this cache. */
440
+ const USER_CACHE_NAMESPACE = "identities";
441
+ const cachedUserSchema = z.object({
442
+ identities: z.array(z.object({
443
+ avatarUrl: z.string().nullable(),
444
+ displayName: z.string().nullable(),
445
+ handle: z.string().nullable(),
446
+ id: z.string(),
447
+ provider: z.string(),
448
+ providerSubjectId: z.string(),
449
+ providerTenantId: z.string(),
450
+ updatedAt: z.coerce.date()
451
+ })),
452
+ user: z.object({
453
+ displayName: z.string().nullable(),
454
+ id: z.string(),
455
+ isAdmin: z.boolean(),
456
+ primaryEmail: z.string()
457
+ })
458
+ });
459
+ const versionSchema = z.object({
460
+ token: z.string(),
461
+ writtenAtMs: z.number()
462
+ });
463
+ function versionKey(userId) {
464
+ return `${cacheKeyPrefix(USER_CACHE_NAMESPACE)}version:${userId}`;
465
+ }
466
+ function cache() {
467
+ return createCache(getStateAdapter(), USER_CACHE_NAMESPACE);
468
+ }
469
+ async function readVersion(userId) {
470
+ const state = getStateAdapter();
471
+ const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
472
+ if (stored.success) return stored.data;
473
+ const created = {
474
+ token: randomUUID(),
475
+ writtenAtMs: 0
389
476
  };
390
- const hasComponents = Object.values(components).some((value) => value !== void 0);
391
- const costMicroUsd = values.get("cost_micro_usd");
392
- const usage = Object.fromEntries(Object.entries({
393
- ...components,
394
- reasoningTokens: values.get("reasoning_tokens"),
395
- totalTokens: hasComponents ? void 0 : values.get("total_tokens"),
396
- cost: costMicroUsd === void 0 ? void 0 : { total: microUsdToUsd(costMicroUsd) }
397
- }).filter(([, value]) => value !== void 0));
477
+ if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
478
+ return versionSchema.parse(await state.get(versionKey(userId)));
479
+ }
480
+ async function loadUser(db, userId) {
481
+ const rows = await db.select({
482
+ avatarUrl: juniorIdentities.avatarUrl,
483
+ displayName: juniorIdentities.displayName,
484
+ handle: juniorIdentities.handle,
485
+ identityId: juniorIdentities.id,
486
+ provider: juniorIdentities.provider,
487
+ providerSubjectId: juniorIdentities.providerSubjectId,
488
+ providerTenantId: juniorIdentities.providerTenantId,
489
+ updatedAt: juniorIdentities.updatedAt,
490
+ userDisplayName: juniorUsers.displayName,
491
+ userId: juniorUsers.id,
492
+ userIsAdmin: juniorUsers.isAdmin,
493
+ userPrimaryEmail: juniorUsers.primaryEmail
494
+ }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.id, userId)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
495
+ const first = rows[0];
496
+ if (!first) return null;
398
497
  return {
399
- durationMs,
400
- ...Object.keys(usage).length > 0 ? { usage } : void 0
498
+ identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
499
+ avatarUrl: row.avatarUrl,
500
+ displayName: row.displayName,
501
+ handle: row.handle,
502
+ id: row.identityId,
503
+ provider: row.provider,
504
+ providerSubjectId: row.providerSubjectId,
505
+ providerTenantId: row.providerTenantId,
506
+ updatedAt: row.updatedAt
507
+ }] : []),
508
+ user: {
509
+ displayName: first.userDisplayName,
510
+ id: first.userId,
511
+ isAdmin: first.userIsAdmin,
512
+ primaryEmail: first.userPrimaryEmail
513
+ }
401
514
  };
402
515
  }
403
- /** Replace one Run's metric rows and refresh its Conversation totals. */
404
- async function replaceConversationMetrics(executor, args) {
405
- const [current] = await executor.db().select({ updatedAt: juniorConversationMetrics.updatedAt }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId))).limit(1);
406
- if (current && current.updatedAt.getTime() > args.updatedAtMs) return;
407
- await executor.db().delete(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
408
- const metricValues = conversationMetricValues({
409
- durationMs: args.durationMs,
410
- usage: args.usage
411
- });
412
- const values = CONVERSATION_METRICS.flatMap((metric) => {
413
- const value = metricValues[metric];
414
- return value === void 0 ? [] : [{
415
- actorIdentityId: args.actorIdentityId ?? null,
416
- conversationId: args.conversationId,
417
- runId: args.runId,
418
- metric,
516
+ /** Read one User and their user Identities by User id. */
517
+ async function readCachedUser(db, userId) {
518
+ const version = await readVersion(userId);
519
+ const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
520
+ const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
521
+ const value = await loadUser(db, userId);
522
+ if (!settled) return { value };
523
+ return {
419
524
  value,
420
- occurredAt: new Date(args.occurredAtMs),
421
- updatedAt: new Date(args.updatedAtMs)
422
- }];
525
+ ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
526
+ };
423
527
  });
424
- if (values.length > 0) await executor.db().insert(juniorConversationMetrics).values(values);
425
- const metric = (name) => sql`(
426
- select sum(${juniorConversationMetrics.value})
427
- from ${juniorConversationMetrics}
428
- where ${juniorConversationMetrics.conversationId} = ${args.conversationId}
429
- and ${juniorConversationMetrics.metric} = ${name}
430
- )`;
431
- const totalTokens = metric("total_tokens");
432
- const componentTokens = sql`
433
- coalesce(${metric("input_tokens")}, 0)
434
- + coalesce(${metric("output_tokens")}, 0)
435
- + coalesce(${metric("cached_input_tokens")}, 0)
436
- + coalesce(${metric("cache_creation_tokens")}, 0)
437
- `;
438
- const hasComponents = sql`
439
- ${metric("input_tokens")} is not null
440
- or ${metric("output_tokens")} is not null
441
- or ${metric("cached_input_tokens")} is not null
442
- or ${metric("cache_creation_tokens")} is not null
443
- `;
444
- const cost = sql`case when ${metric("cost_micro_usd")} is null then null
445
- else jsonb_build_object('total', ${microUsdToUsdSql(metric("cost_micro_usd"))}) end`;
446
- const db = executor.db();
447
- const usageUpdate = db.$with("conversation_usage_update").as(db.update(juniorConversations).set({
448
- durationMs: sql`coalesce(${metric("duration_ms")}, 0)`,
449
- usage: sql`case
450
- when ${totalTokens} is not null
451
- and (${hasComponents})
452
- and ${totalTokens} <> ${componentTokens}
453
- then jsonb_strip_nulls(jsonb_build_object(
454
- 'totalTokens', ${totalTokens},
455
- 'reasoningTokens', ${metric("reasoning_tokens")},
456
- 'cost', ${cost}
457
- ))
458
- else jsonb_strip_nulls(jsonb_build_object(
459
- 'totalTokens', ${totalTokens},
460
- 'inputTokens', ${metric("input_tokens")},
461
- 'outputTokens', ${metric("output_tokens")},
462
- 'cachedInputTokens', ${metric("cached_input_tokens")},
463
- 'cacheCreationTokens', ${metric("cache_creation_tokens")},
464
- 'reasoningTokens', ${metric("reasoning_tokens")},
465
- 'cost', ${cost}
466
- ))
467
- end`,
468
- detailVersion: nextDetailVersion
469
- }).where(eq(juniorConversations.conversationId, args.conversationId)).returning({ costMicroUsd: costMicroUsdExpr(juniorConversations.usage).as("cost_micro_usd") }));
470
- await db.with(usageUpdate).update(juniorAutomationRuns).set({ costMicroUsd: sql`(select ${usageUpdate.costMicroUsd} from ${usageUpdate})` }).where(eq(juniorAutomationRuns.conversationId, args.conversationId));
528
+ return cached ? cachedUserSchema.parse(cached) : void 0;
471
529
  }
472
- // src/chat/source.ts
473
530
  /**
474
- * Normalize a Turn Source into legacy provider fields stored on a Conversation.
475
- * System Sources do not contain a Conversation Location.
531
+ * Read one User and their user Identities by normalized primary email. A
532
+ * primary email never changes, so the email to User id entry stays valid.
533
+ * A missing User is not cached: a first sign-in can create it at any time.
476
534
  */
477
- function normalizeSessionSource(value) {
478
- if (!value) return;
479
- if (value.kind === "local") return {
480
- kind: "local",
481
- visibility: value.visibility,
482
- conversationId: value.conversationId
483
- };
484
- if (value.kind === "web") return {
485
- kind: "web",
486
- visibility: value.visibility,
487
- conversationId: value.conversationId
488
- };
489
- if (value.kind === "event" || value.kind === "scheduled_automation" || value.kind === "event_automation" || value.kind === "plugin_dispatch" || value.kind === "agent_invocation") return;
490
- const threadTs = value.threadTs?.trim();
491
- return {
492
- kind: "slack",
493
- visibility: value.visibility,
494
- teamId: value.teamId,
495
- channelId: value.channelId,
496
- ...threadTs ? { threadTs } : void 0
497
- };
535
+ async function readCachedUserByEmail(db, normalizedEmail) {
536
+ const userId = await cache().getOrLoad(emailKey(normalizedEmail), async () => {
537
+ const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
538
+ return id ? {
539
+ value: id,
540
+ ttlMs: USER_TTL_MS
541
+ } : { value: null };
542
+ });
543
+ return userId ? await readCachedUser(db, userId) : void 0;
498
544
  }
499
- /** Parse a serialized Source into legacy provider fields stored on a Conversation. */
500
- function parseSessionSource(value) {
501
- const parsed = sourceSchema.safeParse(value);
502
- return parsed.success ? normalizeSessionSource(parsed.data) : void 0;
545
+ function emailKey(normalizedEmail) {
546
+ return `email:${normalizedEmail}`;
503
547
  }
504
- // src/chat/conversations/sql/bindings.ts
505
- /** Resolve the durable conversation bound to provider-owned coordinates. */
506
- async function getConversationIdByProviderConversation(executor, args) {
507
- return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
548
+ /** Clear the cached User after a write to their row or user Identities. */
549
+ async function clearCachedUser(userId) {
550
+ await getStateAdapter().set(versionKey(userId), {
551
+ token: randomUUID(),
552
+ writtenAtMs: Date.now()
553
+ }, 2 * USER_TTL_MS);
508
554
  }
509
- /**
510
- * Bind provider coordinates to a durable conversation unless another
511
- * conversation has them. Return the conversation that has them.
512
- */
513
- async function claimProviderConversationOwner(executor, args) {
514
- const ownerId = (await executor.db().insert(juniorConversationBindings).values({
515
- ...args,
516
- createdAt: /* @__PURE__ */ new Date()
517
- }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args);
518
- if (!ownerId) throw new Error("Provider conversation binding disappeared during claim");
519
- return ownerId;
555
+ // src/chat/identities/sql.ts
556
+ function dateFromMs$1(ms) {
557
+ return new Date(ms);
520
558
  }
521
- /**
522
- * Bind provider coordinates to a durable conversation unless another
523
- * conversation has them. Return whether they belong to this conversation.
524
- */
525
- async function claimProviderConversation(executor, args) {
526
- return await claimProviderConversationOwner(executor, args) === args.conversationId;
559
+ function tenantId$1(value) {
560
+ return value ?? "";
527
561
  }
528
- /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
529
- async function bindProviderConversation(executor, args) {
530
- if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
562
+ async function upsertUser(executor, args) {
563
+ const id = (await executor.db().insert(juniorUsers).values({
564
+ id: randomUUID(),
565
+ primaryEmail: args.email,
566
+ primaryEmailNormalized: args.emailNormalized,
567
+ displayName: args.displayName ?? null,
568
+ createdAt: dateFromMs$1(args.nowMs),
569
+ updatedAt: dateFromMs$1(args.nowMs)
570
+ }).onConflictDoUpdate({
571
+ target: juniorUsers.primaryEmailNormalized,
572
+ set: {
573
+ displayName: sql`coalesce(${juniorUsers.displayName}, excluded.display_name)`,
574
+ updatedAt: sql`excluded.updated_at`
575
+ }
576
+ }).returning({ id: juniorUsers.id }))[0]?.id;
577
+ if (!id) throw new Error("User identity upsert returned no row");
578
+ return id;
531
579
  }
532
- // src/chat/state/locks.ts
533
- const ACTIVE_LOCK_TTL_MS = 9e4;
534
- const MUTATION_LOCK_TTL_MS = 1e4;
535
- /**
536
- * Acquire a lock for long-running work that the queued state adapter should
537
- * keep alive while the owning invocation is still making progress.
538
- */
539
- async function acquireActiveLock(state, threadId) {
540
- return await state.acquireLock(threadId, ACTIVE_LOCK_TTL_MS);
580
+ async function existingIdentity(executor, identity) {
581
+ return (await executor.db().select().from(juniorIdentities).where(and(eq(juniorIdentities.provider, identity.provider), eq(juniorIdentities.providerTenantId, tenantId$1(identity.providerTenantId)), eq(juniorIdentities.providerSubjectId, identity.providerSubjectId))))[0];
541
582
  }
542
- /**
543
- * Run work under one lock, optionally waiting for the current owner.
544
- * `keepAlive` is for multi-store mutations that must retain ownership until all
545
- * side effects finish; callers should still fence each blind write.
546
- */
547
- async function withLock(state, key, run, options = {}) {
548
- const ttlMs = options.ttlMs ?? 9e4;
549
- const startedAtMs = Date.now();
550
- let lock;
551
- while (true) {
552
- lock = await state.acquireLock(key, ttlMs);
553
- if (lock) break;
554
- if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
555
- await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
556
- }
557
- const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
558
- heartbeat?.unref();
559
- try {
560
- return {
561
- acquired: true,
562
- value: await run(lock)
563
- };
564
- } finally {
565
- if (heartbeat) clearInterval(heartbeat);
566
- await state.releaseLock(lock);
583
+ async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
584
+ const emailNormalized = normalizeIdentityEmail(identity.email);
585
+ const email = emailNormalized ? identity.email?.trim() || emailNormalized : void 0;
586
+ const existing = await existingIdentity(executor, identity);
587
+ const userEmailNormalized = existing?.emailVerified && existing.emailNormalized ? existing.emailNormalized : identity.emailVerified ? emailNormalized : void 0;
588
+ const userEmail = existing?.emailVerified && existing.email ? existing.email : email ?? userEmailNormalized;
589
+ const verifiedUserId = identity.kind === "user" && userEmailNormalized ? await upsertUser(executor, {
590
+ email: userEmail ?? userEmailNormalized,
591
+ emailNormalized: userEmailNormalized,
592
+ nowMs,
593
+ ...existing?.displayName || identity.displayName ? { displayName: existing?.displayName ?? identity.displayName } : void 0
594
+ }) : void 0;
595
+ if (existing?.userId && verifiedUserId && existing.userId !== verifiedUserId) throw new Error("Identity verified email conflicts with linked user");
596
+ if (linkedUserId && verifiedUserId && linkedUserId !== verifiedUserId) throw new Error("Linked identity conflicts with verified email user");
597
+ if (existing?.userId && linkedUserId && existing.userId !== linkedUserId) throw new Error("Identity conflicts with linked user");
598
+ const userId = existing?.userId ?? linkedUserId ?? verifiedUserId;
599
+ const row = (await executor.db().insert(juniorIdentities).values({
600
+ id: randomUUID(),
601
+ userId: userId ?? null,
602
+ kind: identity.kind,
603
+ provider: identity.provider,
604
+ providerTenantId: tenantId$1(identity.providerTenantId),
605
+ providerSubjectId: identity.providerSubjectId,
606
+ displayName: identity.displayName ?? null,
607
+ handle: identity.handle ?? null,
608
+ email: email ?? null,
609
+ emailNormalized: emailNormalized ?? null,
610
+ emailVerified: Boolean(identity.emailVerified && emailNormalized),
611
+ avatarUrl: identity.avatarUrl ?? null,
612
+ metadata: identity.metadata ?? null,
613
+ createdAt: dateFromMs$1(nowMs),
614
+ updatedAt: dateFromMs$1(nowMs)
615
+ }).onConflictDoUpdate({
616
+ target: [
617
+ juniorIdentities.provider,
618
+ juniorIdentities.providerTenantId,
619
+ juniorIdentities.providerSubjectId
620
+ ],
621
+ set: {
622
+ kind: sql`excluded.kind`,
623
+ userId: sql`coalesce(${juniorIdentities.userId}, excluded.user_id)`,
624
+ displayName: linkedUserId ? sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})` : sql`coalesce(${juniorIdentities.displayName}, excluded.display_name)`,
625
+ handle: linkedUserId ? sql`coalesce(excluded.handle, ${juniorIdentities.handle})` : sql`coalesce(${juniorIdentities.handle}, excluded.handle)`,
626
+ email: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.email}, excluded.email) when excluded.email_verified then excluded.email else coalesce(${juniorIdentities.email}, excluded.email) end`,
627
+ emailNormalized: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) when excluded.email_verified then excluded.email_normalized else coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) end`,
628
+ emailVerified: sql`${juniorIdentities.emailVerified} OR excluded.email_verified`,
629
+ avatarUrl: identity.avatarUrl === void 0 ? sql`${juniorIdentities.avatarUrl}` : sql`excluded.avatar_url`,
630
+ metadata: sql`coalesce(${juniorIdentities.metadata}, excluded.metadata_json)`,
631
+ updatedAt: sql`excluded.updated_at`
632
+ },
633
+ ...linkedUserId ? { setWhere: sql`${juniorIdentities.userId} IS NULL OR ${juniorIdentities.userId} = excluded.user_id` } : void 0
634
+ }).returning({
635
+ id: juniorIdentities.id,
636
+ userId: juniorIdentities.userId
637
+ }))[0];
638
+ if (!row) {
639
+ if (linkedUserId) throw new Error("Identity conflicts with linked user");
640
+ throw new Error("Identity upsert returned no row");
567
641
  }
568
- }
569
- /**
570
- * Prove lock ownership immediately before a blind write.
571
- *
572
- * Whole-record mutations must stop if their lock expired rather than overwrite
573
- * state committed by a newer owner.
574
- */
575
- async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
576
- if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
577
- }
578
- // src/chat/state/adapter.ts
579
- const ACTIVE_LOCK_HEARTBEAT_MS = 3e4;
580
- const REDIS_STATE_KEY_PREFIX = "chat-sdk";
581
- let stateAdapter;
582
- let redisStateAdapter;
583
- /** Lazily connect state operations, including queued-adapter lock heartbeats. */
584
- function createConnectingStateAdapter(base) {
585
- const connected = async (operation) => {
586
- await base.connect();
587
- return await operation();
588
- };
589
- return {
590
- appendToList: (key, value, options) => connected(() => base.appendToList(key, value, options)),
591
- connect: () => base.connect(),
592
- disconnect: () => base.disconnect(),
593
- subscribe: (threadId) => connected(() => base.subscribe(threadId)),
594
- unsubscribe: (threadId) => connected(() => base.unsubscribe(threadId)),
595
- isSubscribed: (threadId) => connected(() => base.isSubscribed(threadId)),
596
- acquireLock: (threadId, ttlMs) => connected(() => base.acquireLock(threadId, ttlMs)),
597
- releaseLock: (lock) => connected(() => base.releaseLock(lock)),
598
- extendLock: (lock, ttlMs) => connected(() => base.extendLock(lock, ttlMs)),
599
- forceReleaseLock: (threadId) => connected(() => base.forceReleaseLock(threadId)),
600
- enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
601
- dequeue: (threadId) => connected(() => base.dequeue(threadId)),
602
- queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
603
- get: (key) => connected(() => base.get(key)),
604
- getList: (key) => connected(() => base.getList(key)),
605
- set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
606
- setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
607
- delete: (key) => connected(() => base.delete(key))
608
- };
609
- }
610
- function createPrefixedStateAdapter(base, prefix) {
611
- const prefixed = (value) => `${prefix}:${value}`;
612
- const unprefixed = (value) => value.startsWith(`${prefix}:`) ? value.slice(prefix.length + 1) : value;
613
- const prefixLock = (lock) => ({
614
- ...lock,
615
- threadId: prefixed(lock.threadId)
616
- });
617
- const unprefixLock = (lock) => ({
618
- ...lock,
619
- threadId: unprefixed(lock.threadId)
642
+ const previousUserId = existing?.userId;
643
+ await Promise.all([row.userId ? clearCachedUser(row.userId) : void 0, previousUserId && previousUserId !== row.userId ? clearCachedUser(previousUserId) : void 0]);
644
+ if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
645
+ identityId: row.id,
646
+ userId: row.userId
620
647
  });
621
648
  return {
622
- appendToList: (key, value, options) => base.appendToList(prefixed(key), value, options),
623
- connect: () => base.connect(),
624
- disconnect: () => base.disconnect(),
625
- subscribe: (threadId) => base.subscribe(prefixed(threadId)),
626
- unsubscribe: (threadId) => base.unsubscribe(prefixed(threadId)),
627
- isSubscribed: (threadId) => base.isSubscribed(prefixed(threadId)),
628
- acquireLock: async (threadId, ttlMs) => {
629
- const lock = await base.acquireLock(prefixed(threadId), ttlMs);
630
- return lock ? unprefixLock(lock) : null;
631
- },
632
- releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
633
- extendLock: async (lock, ttlMs) => {
634
- const prefixedLock = prefixLock(lock);
635
- const extended = await base.extendLock(prefixedLock, ttlMs);
636
- if (extended) lock.expiresAt = prefixedLock.expiresAt;
637
- return extended;
638
- },
639
- forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
640
- enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
641
- dequeue: (threadId) => base.dequeue(prefixed(threadId)),
642
- queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
643
- get: (key) => base.get(prefixed(key)),
644
- getList: (key) => base.getList(prefixed(key)),
645
- set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
646
- setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
647
- delete: (key) => base.delete(prefixed(key))
649
+ id: row.id,
650
+ ...row.userId ? { userId: row.userId } : void 0
648
651
  };
649
652
  }
650
- function createQueuedStateAdapter(base, options) {
651
- const heartbeats = /* @__PURE__ */ new Map();
652
- const shouldHeartbeatLock = (ttlMs) => ttlMs === ACTIVE_LOCK_TTL_MS;
653
- const heartbeatKey = (lock) => `${lock.threadId}:${lock.token}`;
654
- const stopHeartbeatByKey = (key) => {
655
- const heartbeat = heartbeats.get(key);
656
- if (!heartbeat) return;
657
- clearInterval(heartbeat.timer);
658
- heartbeats.delete(key);
659
- };
660
- const stopHeartbeat = (lock) => {
661
- stopHeartbeatByKey(heartbeatKey(lock));
662
- };
663
- const stopHeartbeatsForThread = (threadId) => {
664
- for (const [key, heartbeat] of heartbeats) if (heartbeat.lock.threadId === threadId) stopHeartbeatByKey(key);
665
- };
666
- const stopAllHeartbeats = () => {
667
- for (const key of heartbeats.keys()) stopHeartbeatByKey(key);
668
- };
669
- const runHeartbeat = async (key) => {
670
- const heartbeat = heartbeats.get(key);
671
- if (!heartbeat || heartbeat.inFlight) return;
672
- heartbeat.inFlight = true;
673
- try {
674
- if (Date.now() - heartbeat.startedAtMs >= options.activeLockMaxAgeMs) {
675
- stopHeartbeatByKey(key);
676
- return;
677
- }
678
- if (!await base.extendLock(heartbeat.lock, heartbeat.ttlMs)) {
679
- stopHeartbeatByKey(key);
680
- return;
681
- }
682
- heartbeat.lock.expiresAt = Date.now() + heartbeat.ttlMs;
683
- } catch {} finally {
684
- const current = heartbeats.get(key);
685
- if (current === heartbeat) current.inFlight = false;
686
- }
687
- };
688
- const startOrUpdateHeartbeat = (lock, ttlMs) => {
689
- const key = heartbeatKey(lock);
690
- const existing = heartbeats.get(key);
691
- if (existing) {
692
- existing.ttlMs = ttlMs;
693
- return;
694
- }
695
- const timer = setInterval(() => {
696
- runHeartbeat(key);
697
- }, ACTIVE_LOCK_HEARTBEAT_MS);
698
- timer.unref?.();
699
- heartbeats.set(key, {
700
- inFlight: false,
701
- lock,
702
- startedAtMs: Date.now(),
703
- timer,
704
- ttlMs
705
- });
706
- };
707
- const acquireLock = async (threadId, ttlMs) => {
708
- const lock = await base.acquireLock(threadId, ttlMs);
709
- if (lock && shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
710
- return lock;
711
- };
712
- return {
713
- appendToList: (key, value, options) => base.appendToList(key, value, options),
714
- connect: () => base.connect(),
715
- disconnect: async () => {
716
- stopAllHeartbeats();
717
- await base.disconnect();
718
- },
719
- subscribe: (threadId) => base.subscribe(threadId),
720
- unsubscribe: (threadId) => base.unsubscribe(threadId),
721
- isSubscribed: (threadId) => base.isSubscribed(threadId),
722
- acquireLock,
723
- releaseLock: async (lock) => {
724
- stopHeartbeat(lock);
725
- await base.releaseLock(lock);
726
- },
727
- extendLock: async (lock, ttlMs) => {
728
- const extended = await base.extendLock(lock, ttlMs);
729
- if (extended) {
730
- lock.expiresAt = Date.now() + ttlMs;
731
- if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
732
- else stopHeartbeat(lock);
733
- } else stopHeartbeat(lock);
734
- return extended;
735
- },
736
- forceReleaseLock: async (threadId) => {
737
- stopHeartbeatsForThread(threadId);
738
- await base.forceReleaseLock(threadId);
739
- },
740
- enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
741
- dequeue: (threadId) => base.dequeue(threadId),
742
- queueDepth: (threadId) => base.queueDepth(threadId),
743
- get: (key) => base.get(key),
744
- getList: (key) => base.getList(key),
745
- set: (key, value, ttlMs) => base.set(key, value, ttlMs),
746
- setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
747
- delete: (key) => base.delete(key)
748
- };
749
- }
750
- function withOptionalPrefix(base, prefix) {
751
- return prefix ? createPrefixedStateAdapter(base, prefix) : base;
752
- }
753
- function createStateAdapter() {
754
- const config = getChatConfig();
755
- const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
756
- if (config.state.adapter === "memory") {
757
- redisStateAdapter = void 0;
758
- return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
759
- }
760
- if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
761
- const redisState = createRedisState({
762
- keyPrefix: REDIS_STATE_KEY_PREFIX,
763
- url: config.state.redisUrl
764
- });
765
- redisStateAdapter = redisState;
766
- return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
767
- }
768
- function getOptionalRedisStateAdapter() {
769
- getStateAdapter();
770
- return redisStateAdapter;
653
+ /** Read the saved timezone for one user. */
654
+ async function readUserTimezone(db, userId) {
655
+ return (await db.select({ timezone: juniorUsers.timezone }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1))[0]?.timezone ?? void 0;
771
656
  }
772
- async function getConnectedStateContext() {
773
- const adapter = getStateAdapter();
774
- await adapter.connect();
775
- return {
776
- redisStateAdapter: getOptionalRedisStateAdapter(),
777
- stateAdapter: adapter
778
- };
657
+ /** Save the IANA timezone for one user. */
658
+ async function saveUserTimezone(db, userId, timezone, nowMs) {
659
+ await db.update(juniorUsers).set({
660
+ timezone,
661
+ updatedAt: dateFromMs$1(nowMs)
662
+ }).where(and(eq(juniorUsers.id, userId), sql`${juniorUsers.timezone} is distinct from ${timezone}`));
779
663
  }
780
- /** Return the Redis adapter only when the caller is using the default state adapter. */
781
- async function getDefaultRedisStateAdapterFor(adapter) {
782
- if (adapter !== stateAdapter) return;
783
- const context = await getConnectedStateContext();
784
- return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
785
- }
786
- /** The Redis key that the default Redis adapter uses for one state value key. */
787
- function redisStateKey(key) {
788
- const prefix = getChatConfig().state.keyPrefix;
789
- return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
790
- }
791
- /** Read state values in one Redis round trip. Other adapters read each key. */
792
- async function getStateValues(state, keys) {
793
- if (keys.length === 0) return [];
794
- const redis = await getDefaultRedisStateAdapterFor(state);
795
- if (!redis) return await mapBounded(keys, (key) => state.get(key));
796
- return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
797
- if (value === null) return null;
798
- try {
799
- return JSON.parse(value);
800
- } catch {
801
- return value;
802
- }
803
- });
664
+ /** Return the Slack user most recently linked to a Junior user. */
665
+ async function linkedSlackUser(db, userId) {
666
+ const row = (await db.select({
667
+ teamId: juniorIdentities.providerTenantId,
668
+ slackUserId: juniorIdentities.providerSubjectId
669
+ }).from(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"))).orderBy(desc(juniorIdentities.updatedAt)).limit(1))[0];
670
+ return row?.teamId ? {
671
+ teamId: row.teamId,
672
+ userId: row.slackUserId
673
+ } : void 0;
804
674
  }
805
- /** Write state values with one TTL in one Redis round trip. */
806
- async function setStateValues(state, entries, ttlMs) {
807
- if (entries.length === 0) return;
808
- const redis = await getDefaultRedisStateAdapterFor(state);
809
- if (!redis) {
810
- await mapBounded(entries, ({ key, value }) => state.set(key, value, ttlMs));
811
- return;
812
- }
813
- const pipeline = redis.getClient().multi();
814
- for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
815
- await pipeline.execAsPipeline();
816
- }
817
- function getStateAdapter() {
818
- if (!stateAdapter) stateAdapter = createStateAdapter();
819
- return stateAdapter;
820
- }
821
- async function disconnectStateAdapter() {
822
- if (!stateAdapter) return;
823
- try {
824
- await stateAdapter.disconnect();
825
- } finally {
826
- stateAdapter = void 0;
827
- redisStateAdapter = void 0;
828
- }
829
- }
830
- // src/chat/state/cache.ts
831
- const MAX_CACHE_KEY_LENGTH = 512;
832
- const LOAD_WAIT_MS = 1e4;
833
- /** The prefix of every state key of one cache namespace. */
834
- function cacheKeyPrefix(namespace) {
835
- return `junior:cache:${namespace}:`;
836
- }
837
- /**
838
- * Create a cache in the state adapter under `junior:cache:{namespace}:`.
839
- * Entries are wrapped, so `null` and `false` values are cache hits.
840
- */
841
- function createCache(state, namespace) {
842
- return { async getOrLoad(key, load, options) {
843
- if (!key.trim()) throw new Error("Cache key is required");
844
- if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
845
- const cacheKey = `${cacheKeyPrefix(namespace)}${key}`;
846
- const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
847
- await state.connect();
848
- const hit = await cached();
849
- if (hit) return hit.value;
850
- const attempt = await withLock(state, `${cacheKey}:load`, async () => {
851
- const loadedMeanwhile = await cached();
852
- if (loadedMeanwhile) return loadedMeanwhile.value;
853
- const entry = await load();
854
- if (entry.ttlMs !== void 0) {
855
- if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
856
- await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
857
- }
858
- return entry.value;
859
- }, {
860
- keepAlive: true,
861
- waitMs: LOAD_WAIT_MS
862
- });
863
- if (attempt.acquired) return attempt.value;
864
- return (await load()).value;
865
- } };
675
+ /** Persist one provider identity observation and link verified emails to users. */
676
+ async function upsertIdentity(executor, identity, nowMs = Date.now()) {
677
+ return await upsertIdentityRecord(executor, identity, void 0, nowMs);
866
678
  }
867
- // src/chat/identities/user-cache.ts
868
679
  /**
869
- * Cache of each User and their user Identities. Every signed-in request
870
- * resolves its viewer, and person cards read the people that a message
871
- * links to, so these reads go to the state cache instead of the database.
872
- *
873
- * Every write to a cached column or to a user Identity must call
874
- * `clearCachedUser`. The other columns of a User, such as the timezone or
875
- * the customization, are not in the cache.
680
+ * Persist one provider identity after a trusted account-linking flow.
681
+ * Callers must use provider-verified account data, such as GitHub's authenticated
682
+ * user response, never identity claims inferred from content such as Git commits.
876
683
  */
877
- const USER_TTL_MS = 864e5;
878
- const MISSING_TTL_MS = 6e4;
879
- const SETTLE_MS = 1e4;
880
- /** The cache namespace of every key in this cache. */
881
- const USER_CACHE_NAMESPACE = "identities";
882
- const cachedUserSchema = z.object({
883
- identities: z.array(z.object({
884
- avatarUrl: z.string().nullable(),
885
- displayName: z.string().nullable(),
886
- handle: z.string().nullable(),
887
- id: z.string(),
888
- provider: z.string(),
889
- providerSubjectId: z.string(),
890
- providerTenantId: z.string(),
891
- updatedAt: z.coerce.date()
892
- })),
893
- user: z.object({
894
- displayName: z.string().nullable(),
895
- id: z.string(),
896
- isAdmin: z.boolean(),
897
- primaryEmail: z.string()
898
- })
899
- });
900
- const versionSchema = z.object({
901
- token: z.string(),
902
- writtenAtMs: z.number()
903
- });
904
- function versionKey(userId) {
905
- return `${cacheKeyPrefix(USER_CACHE_NAMESPACE)}version:${userId}`;
906
- }
907
- function cache() {
908
- return createCache(getStateAdapter(), USER_CACHE_NAMESPACE);
684
+ async function upsertLinkedIdentity(executor, userId, identity, nowMs = Date.now()) {
685
+ return await upsertIdentityRecord(executor, identity, userId, nowMs);
909
686
  }
910
- async function readVersion(userId) {
911
- const state = getStateAdapter();
912
- const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
913
- if (stored.success) return stored.data;
914
- const created = {
915
- token: randomUUID(),
916
- writtenAtMs: 0
917
- };
918
- if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
919
- return versionSchema.parse(await state.get(versionKey(userId)));
687
+ /**
688
+ * Find the one user whose primary email is in a provider-verified email list.
689
+ * Return undefined when no user or more than one user matches.
690
+ */
691
+ async function findUserByVerifiedEmails(executor, emails) {
692
+ const normalized = new Set(emails.map((email) => normalizeIdentityEmail(email) ?? ""));
693
+ normalized.delete("");
694
+ if (normalized.size === 0) return void 0;
695
+ const rows = await executor.db().select({
696
+ email: juniorUsers.primaryEmail,
697
+ userId: juniorUsers.id
698
+ }).from(juniorUsers).where(inArray(juniorUsers.primaryEmailNormalized, Array.from(normalized))).limit(2);
699
+ return rows.length === 1 ? rows[0] : void 0;
920
700
  }
921
- async function loadUser(db, userId) {
922
- const rows = await db.select({
923
- avatarUrl: juniorIdentities.avatarUrl,
924
- displayName: juniorIdentities.displayName,
925
- handle: juniorIdentities.handle,
926
- identityId: juniorIdentities.id,
927
- provider: juniorIdentities.provider,
928
- providerSubjectId: juniorIdentities.providerSubjectId,
929
- providerTenantId: juniorIdentities.providerTenantId,
930
- updatedAt: juniorIdentities.updatedAt,
931
- userDisplayName: juniorUsers.displayName,
932
- userId: juniorUsers.id,
933
- userIsAdmin: juniorUsers.isAdmin,
934
- userPrimaryEmail: juniorUsers.primaryEmail
935
- }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.id, userId)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
936
- const first = rows[0];
937
- if (!first) return null;
701
+ const linkedSlackIdentity = alias(juniorIdentities, "linked_slack_identity");
702
+ const linkedSlackUserColumns = {
703
+ displayName: juniorUsers.displayName,
704
+ email: juniorUsers.primaryEmail,
705
+ slackUserId: linkedSlackIdentity.providerSubjectId,
706
+ userId: juniorUsers.id
707
+ };
708
+ function singleLinkedSlackUser(rows) {
709
+ const [row] = rows;
710
+ if (rows.length !== 1 || !row) return void 0;
938
711
  return {
939
- identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
940
- avatarUrl: row.avatarUrl,
941
- displayName: row.displayName,
942
- handle: row.handle,
943
- id: row.identityId,
944
- provider: row.provider,
945
- providerSubjectId: row.providerSubjectId,
946
- providerTenantId: row.providerTenantId,
947
- updatedAt: row.updatedAt
948
- }] : []),
712
+ slackUserId: row.slackUserId,
949
713
  user: {
950
- displayName: first.userDisplayName,
951
- id: first.userId,
952
- isAdmin: first.userIsAdmin,
953
- primaryEmail: first.userPrimaryEmail
714
+ id: row.userId,
715
+ email: row.email,
716
+ ...row.displayName ? { displayName: row.displayName } : void 0
954
717
  }
955
718
  };
956
719
  }
957
- /** Read one User and their user Identities by User id. */
958
- async function readCachedUser(db, userId) {
959
- const version = await readVersion(userId);
960
- const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
961
- const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
962
- const value = await loadUser(db, userId);
963
- if (!settled) return { value };
964
- return {
965
- value,
966
- ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
967
- };
968
- });
969
- return cached ? cachedUserSchema.parse(cached) : void 0;
970
- }
971
720
  /**
972
- * Read one User and their user Identities by normalized primary email. A
973
- * primary email never changes, so the email to User id entry stays valid.
974
- * A missing User is not cached: a first sign-in can create it at any time.
721
+ * Find the one Slack user in a workspace who is linked to an exact provider
722
+ * Identity, and the User behind both.
723
+ *
724
+ * Only the provider account id from an account-linking flow matches. Handles,
725
+ * emails, and display names never match. Return undefined when no Slack user
726
+ * or more than one Slack user matches.
975
727
  */
976
- async function readCachedUserByEmail(db, normalizedEmail) {
977
- const userId = await cache().getOrLoad(emailKey(normalizedEmail), async () => {
978
- const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
979
- return id ? {
980
- value: id,
981
- ttlMs: USER_TTL_MS
982
- } : { value: null };
983
- });
984
- return userId ? await readCachedUser(db, userId) : void 0;
728
+ async function findLinkedSlackUser(executor, args) {
729
+ return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorIdentities).innerJoin(linkedSlackIdentity, and(eq(linkedSlackIdentity.userId, juniorIdentities.userId), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, args.providerSubjectId))).limit(2));
985
730
  }
986
- function emailKey(normalizedEmail) {
987
- return `email:${normalizedEmail}`;
731
+ /**
732
+ * Find the one Slack user in a workspace whose User has this primary email.
733
+ *
734
+ * The caller must have verified that the person sent from this address.
735
+ * Return undefined when no Slack user or more than one Slack user matches.
736
+ */
737
+ async function findSlackUserByPrimaryEmail(executor, args) {
738
+ return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorUsers).innerJoin(linkedSlackIdentity, eq(linkedSlackIdentity.userId, juniorUsers.id)).where(and(eq(juniorUsers.primaryEmailNormalized, args.normalizedEmail), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).limit(2));
988
739
  }
989
- /** Clear the cached User after a write to their row or user Identities. */
990
- async function clearCachedUser(userId) {
991
- await getStateAdapter().set(versionKey(userId), {
992
- token: randomUUID(),
993
- writtenAtMs: Date.now()
994
- }, 2 * USER_TTL_MS);
740
+ /** Remove one exact provider identity owned by a workspace Slack user. */
741
+ async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUserId, provider, providerSubjectId) {
742
+ const userId = (await executor.db().select({ userId: juniorIdentities.userId }).from(juniorIdentities).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"), eq(juniorIdentities.providerTenantId, slackTeamId), eq(juniorIdentities.providerSubjectId, slackUserId))).limit(1))[0]?.userId;
743
+ if (!userId) return;
744
+ await deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId);
995
745
  }
996
- // src/chat/identities/sql.ts
997
- function dateFromMs$1(ms) {
998
- return new Date(ms);
746
+ /** Remove one exact provider identity owned by a user. */
747
+ async function deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId) {
748
+ await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
749
+ await clearCachedUser(userId);
999
750
  }
1000
- function tenantId$1(value) {
1001
- return value ?? "";
751
+ /**
752
+ * Save one Google sign-in. Link the Google identity to the user of its
753
+ * verified email, and set its sign-in time. Return the previous sign-in
754
+ * time, if any.
755
+ */
756
+ async function recordGoogleSignIn(executor, account, nowMs = Date.now()) {
757
+ const stored = await upsertIdentity(executor, {
758
+ kind: "user",
759
+ provider: GOOGLE_IDENTITY_PROVIDER,
760
+ providerSubjectId: account.subject,
761
+ email: account.email,
762
+ emailVerified: true,
763
+ displayName: account.displayName,
764
+ avatarUrl: account.avatarUrl ?? null
765
+ }, nowMs);
766
+ const [previous] = await executor.db().select({ signedInAt: juniorIdentities.signedInAt }).from(juniorIdentities).where(eq(juniorIdentities.id, stored.id)).limit(1);
767
+ await executor.db().update(juniorIdentities).set({ signedInAt: dateFromMs$1(nowMs) }).where(eq(juniorIdentities.id, stored.id));
768
+ return previous?.signedInAt?.getTime();
1002
769
  }
1003
- async function upsertUser(executor, args) {
1004
- const id = (await executor.db().insert(juniorUsers).values({
1005
- id: randomUUID(),
1006
- primaryEmail: args.email,
1007
- primaryEmailNormalized: args.emailNormalized,
1008
- displayName: args.displayName ?? null,
1009
- createdAt: dateFromMs$1(args.nowMs),
1010
- updatedAt: dateFromMs$1(args.nowMs)
1011
- }).onConflictDoUpdate({
1012
- target: juniorUsers.primaryEmailNormalized,
1013
- set: {
1014
- displayName: sql`coalesce(${juniorUsers.displayName}, excluded.display_name)`,
1015
- updatedAt: sql`excluded.updated_at`
770
+ // src/chat/identities/actor.ts
771
+ /**
772
+ * Resolve runtime Actors to the Identity rows that Junior stores for them.
773
+ *
774
+ * The Conversation store, OAuth, the viewer, and message events use this
775
+ * module, so they agree on one Identity per person. The key for each Actor
776
+ * stays private here, so it can change without changing callers.
777
+ */
778
+ /**
779
+ * The fixed id of the one system Identity: kind `system`, provider `junior`,
780
+ * an empty tenant, and subject `system`. A migration creates the row, so
781
+ * callers use this id without a database read.
782
+ */
783
+ const SYSTEM_IDENTITY_ID = "system";
784
+ /**
785
+ * Return whether an Actor uses the system Identity.
786
+ *
787
+ * `SystemActor.name` is provenance, not part of the Identity. A LocalActor
788
+ * uses the system Identity because the local runner has no per-person user id.
789
+ */
790
+ function usesSystemIdentity(actor) {
791
+ return actor.platform === "local" || actor.platform === "system";
792
+ }
793
+ /** Return the Identity key for one Slack or web Actor. */
794
+ function identityKey(actor) {
795
+ switch (actor.platform) {
796
+ case "slack": return {
797
+ kind: "user",
798
+ provider: "slack",
799
+ providerTenantId: actor.teamId,
800
+ providerSubjectId: actor.userId,
801
+ ...actor.fullName ? { displayName: actor.fullName } : void 0,
802
+ ...actor.userName ? { handle: actor.userName } : void 0,
803
+ ...actor.email ? {
804
+ email: actor.email,
805
+ emailVerified: true
806
+ } : void 0,
807
+ metadata: { platform: "slack" }
808
+ };
809
+ case "web": {
810
+ const email = normalizeIdentityEmail(actor.email);
811
+ if (!email) return;
812
+ return {
813
+ kind: "user",
814
+ provider: "junior",
815
+ providerSubjectId: email,
816
+ email,
817
+ emailVerified: true,
818
+ ...actor.fullName ? { displayName: actor.fullName } : void 0,
819
+ metadata: { platform: "web" }
820
+ };
1016
821
  }
1017
- }).returning({ id: juniorUsers.id }))[0]?.id;
1018
- if (!id) throw new Error("User identity upsert returned no row");
1019
- return id;
822
+ }
1020
823
  }
1021
- async function existingIdentity(executor, identity) {
1022
- return (await executor.db().select().from(juniorIdentities).where(and(eq(juniorIdentities.provider, identity.provider), eq(juniorIdentities.providerTenantId, tenantId$1(identity.providerTenantId)), eq(juniorIdentities.providerSubjectId, identity.providerSubjectId))))[0];
824
+ /**
825
+ * Return the Identity id for one Actor. Save a Slack or web Identity first.
826
+ * Return undefined only for a web Actor without a verified email.
827
+ */
828
+ async function resolveActorIdentityId(executor, actor, nowMs = Date.now()) {
829
+ if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
830
+ const key = identityKey(actor);
831
+ return key ? (await upsertIdentity(executor, key, nowMs)).id : void 0;
1023
832
  }
1024
- async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
1025
- const emailNormalized = normalizeIdentityEmail(identity.email);
1026
- const email = emailNormalized ? identity.email?.trim() || emailNormalized : void 0;
1027
- const existing = await existingIdentity(executor, identity);
1028
- const userEmailNormalized = existing?.emailVerified && existing.emailNormalized ? existing.emailNormalized : identity.emailVerified ? emailNormalized : void 0;
1029
- const userEmail = existing?.emailVerified && existing.email ? existing.email : email ?? userEmailNormalized;
1030
- const verifiedUserId = identity.kind === "user" && userEmailNormalized ? await upsertUser(executor, {
1031
- email: userEmail ?? userEmailNormalized,
1032
- emailNormalized: userEmailNormalized,
1033
- nowMs,
1034
- ...existing?.displayName || identity.displayName ? { displayName: existing?.displayName ?? identity.displayName } : void 0
1035
- }) : void 0;
1036
- if (existing?.userId && verifiedUserId && existing.userId !== verifiedUserId) throw new Error("Identity verified email conflicts with linked user");
1037
- if (linkedUserId && verifiedUserId && linkedUserId !== verifiedUserId) throw new Error("Linked identity conflicts with verified email user");
1038
- if (existing?.userId && linkedUserId && existing.userId !== linkedUserId) throw new Error("Identity conflicts with linked user");
1039
- const userId = existing?.userId ?? linkedUserId ?? verifiedUserId;
1040
- const row = (await executor.db().insert(juniorIdentities).values({
833
+ /** Save the profile photo on the Identity of one Slack Actor. Null clears it. */
834
+ async function saveActorAvatar(executor, actor, avatarUrl, nowMs = Date.now()) {
835
+ const key = identityKey(actor);
836
+ if (key) await upsertIdentity(executor, {
837
+ ...key,
838
+ avatarUrl
839
+ }, nowMs);
840
+ }
841
+ /** Find the stored Identity id for one Actor without writing. */
842
+ async function findActorIdentityId(db, actor) {
843
+ if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
844
+ const key = identityKey(actor);
845
+ if (!key) return;
846
+ return (await db.select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, key.provider), eq(juniorIdentities.providerTenantId, key.providerTenantId ?? ""), eq(juniorIdentities.providerSubjectId, key.providerSubjectId))).limit(1))[0]?.id;
847
+ }
848
+ // src/chat/identities/avatar.ts
849
+ /**
850
+ * Profile photos of people, saved on their native Slack and Google
851
+ * identities. `/api/people/avatars/:identityId` serves each photo through
852
+ * the shared image route code, so browsers never load a photo from Slack or
853
+ * Google.
854
+ */
855
+ const AVATAR_HOSTS = {
856
+ slack: ["avatars.slack-edge.com"],
857
+ [GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
858
+ };
859
+ const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
860
+ /**
861
+ * Return the URL when it is HTTPS on a photo host of the provider or a
862
+ * subdomain. Junior fetches only these URLs.
863
+ */
864
+ function parseAvatarUrl(value, provider) {
865
+ const hosts = AVATAR_HOSTS[provider];
866
+ if (!hosts || !value || !URL.canParse(value)) return void 0;
867
+ const url = new URL(value);
868
+ if (url.protocol !== "https:" || url.username || url.password) return;
869
+ const host = url.hostname.toLowerCase();
870
+ return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
871
+ }
872
+ function avatarVersion(url) {
873
+ return createHash("sha256").update(url).digest("hex").slice(0, 16);
874
+ }
875
+ function avatarPath(identityId, avatarUrl) {
876
+ return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
877
+ }
878
+ /**
879
+ * Match the user Identities that hold a photo, for a read that joins them to
880
+ * the Identities of other rows.
881
+ */
882
+ function hasUserPhoto(identities) {
883
+ return and(eq(identities.kind, "user"), inArray(identities.provider, AVATAR_PROVIDERS), isNotNull(identities.avatarUrl));
884
+ }
885
+ /**
886
+ * Read the photo path of each user: the Slack photo, then the Google photo.
887
+ * Users without a photo are not in the map.
888
+ */
889
+ async function readUserAvatarUrls(db, userIds) {
890
+ if (userIds.length === 0) return /* @__PURE__ */ new Map();
891
+ return userAvatarUrlsFromIdentities(await db.select({
892
+ avatarUrl: juniorIdentities.avatarUrl,
893
+ identityId: juniorIdentities.id,
894
+ provider: juniorIdentities.provider,
895
+ updatedAt: juniorIdentities.updatedAt,
896
+ userId: juniorIdentities.userId
897
+ }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), hasUserPhoto(juniorIdentities))));
898
+ }
899
+ /**
900
+ * Pick the photo path of each user from their user Identities, for a caller
901
+ * that already read them: the Slack photo, then the Google photo.
902
+ */
903
+ function userAvatarUrlsFromIdentities(rows) {
904
+ const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
905
+ const ranked = rows.filter((row) => rank(row) >= 0).sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
906
+ const avatars = /* @__PURE__ */ new Map();
907
+ for (const row of ranked) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
908
+ return avatars;
909
+ }
910
+ /**
911
+ * Pick the photo path of each user from rows that joined their photo
912
+ * Identities with `hasUserPhoto`: the Slack photo, then the Google photo.
913
+ */
914
+ function userAvatarUrlsFromJoinedPhotos(rows) {
915
+ return userAvatarUrlsFromIdentities(rows.flatMap(({ photo, userId }) => photo?.identityId && photo.provider && photo.updatedAt ? [{
916
+ avatarUrl: photo.avatarUrl,
917
+ identityId: photo.identityId,
918
+ provider: photo.provider,
919
+ updatedAt: photo.updatedAt,
920
+ userId
921
+ }] : []));
922
+ }
923
+ /**
924
+ * Return the photo path for one Identity row. A linked Identity uses the
925
+ * photo of its user. An Identity without a user uses its own photo.
926
+ */
927
+ function identityAvatarUrl(row, userAvatarUrls) {
928
+ if (row.userId) return userAvatarUrls.get(row.userId);
929
+ return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
930
+ }
931
+ /**
932
+ * Return how to fetch the photo of one user Identity, or nothing when it has
933
+ * no photo on a photo host of its provider. A redirect cannot leave the
934
+ * photo hosts of the provider.
935
+ */
936
+ async function readAvatarFetch(db, identityId) {
937
+ const [row] = await db.select({
938
+ avatarUrl: juniorIdentities.avatarUrl,
939
+ provider: juniorIdentities.provider
940
+ }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
941
+ const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
942
+ const hosts = row && AVATAR_HOSTS[row.provider];
943
+ return url && hosts ? {
944
+ hosts,
945
+ url
946
+ } : void 0;
947
+ }
948
+ // src/chat/plugins/viewer.ts
949
+ function identityFromRow(row) {
950
+ return identitySchema.parse({
951
+ id: row.id,
952
+ provider: row.provider,
953
+ providerSubjectId: row.providerSubjectId,
954
+ ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
955
+ ...row.displayName ? { displayName: row.displayName } : void 0,
956
+ ...row.handle ? { handle: row.handle } : void 0
957
+ });
958
+ }
959
+ async function readUserById(db, userRow) {
960
+ 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)));
961
+ }
962
+ function userFromRows(userRow, identityRows) {
963
+ return userSchema.parse({
964
+ email: userRow.primaryEmail,
965
+ id: userRow.id,
966
+ identities: identityRows.map(identityFromRow),
967
+ ...userRow.displayName ? { displayName: userRow.displayName } : void 0,
968
+ ...userRow.isAdmin ? { isAdmin: true } : void 0
969
+ });
970
+ }
971
+ async function readUserByNormalizedEmail(db, normalizedEmail) {
972
+ const cached = await readCachedUserByEmail(db, normalizedEmail);
973
+ return cached ? userFromRows(cached.user, cached.identities) : void 0;
974
+ }
975
+ /** Resolve or create the canonical user for one verified viewer email. */
976
+ async function resolveViewerUserFromSql(db, email) {
977
+ const normalizedEmail = normalizeIdentityEmail(email);
978
+ if (!normalizedEmail) return void 0;
979
+ const existing = await readUserByNormalizedEmail(db, normalizedEmail);
980
+ if (existing) return existing;
981
+ const now = /* @__PURE__ */ new Date();
982
+ const userRow = (await db.insert(juniorUsers).values({
1041
983
  id: randomUUID(),
1042
- userId: userId ?? null,
1043
- kind: identity.kind,
1044
- provider: identity.provider,
1045
- providerTenantId: tenantId$1(identity.providerTenantId),
1046
- providerSubjectId: identity.providerSubjectId,
1047
- displayName: identity.displayName ?? null,
1048
- handle: identity.handle ?? null,
1049
- email: email ?? null,
1050
- emailNormalized: emailNormalized ?? null,
1051
- emailVerified: Boolean(identity.emailVerified && emailNormalized),
1052
- avatarUrl: identity.avatarUrl ?? null,
1053
- metadata: identity.metadata ?? null,
1054
- createdAt: dateFromMs$1(nowMs),
1055
- updatedAt: dateFromMs$1(nowMs)
1056
- }).onConflictDoUpdate({
1057
- target: [
1058
- juniorIdentities.provider,
1059
- juniorIdentities.providerTenantId,
1060
- juniorIdentities.providerSubjectId
1061
- ],
1062
- set: {
1063
- kind: sql`excluded.kind`,
1064
- userId: sql`coalesce(${juniorIdentities.userId}, excluded.user_id)`,
1065
- displayName: linkedUserId ? sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})` : sql`coalesce(${juniorIdentities.displayName}, excluded.display_name)`,
1066
- handle: linkedUserId ? sql`coalesce(excluded.handle, ${juniorIdentities.handle})` : sql`coalesce(${juniorIdentities.handle}, excluded.handle)`,
1067
- email: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.email}, excluded.email) when excluded.email_verified then excluded.email else coalesce(${juniorIdentities.email}, excluded.email) end`,
1068
- emailNormalized: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) when excluded.email_verified then excluded.email_normalized else coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) end`,
1069
- emailVerified: sql`${juniorIdentities.emailVerified} OR excluded.email_verified`,
1070
- avatarUrl: identity.avatarUrl === void 0 ? sql`${juniorIdentities.avatarUrl}` : sql`excluded.avatar_url`,
1071
- metadata: sql`coalesce(${juniorIdentities.metadata}, excluded.metadata_json)`,
1072
- updatedAt: sql`excluded.updated_at`
984
+ primaryEmail: email.trim(),
985
+ primaryEmailNormalized: normalizedEmail,
986
+ displayName: null,
987
+ createdAt: now,
988
+ updatedAt: now
989
+ }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
990
+ return userRow ? await readUserById(db, userRow) : void 0;
991
+ }
992
+ /** Resolve or create the canonical user for one authenticated viewer. */
993
+ async function resolveViewerUser(email) {
994
+ return await resolveViewerUserFromSql(getDb(), email);
995
+ }
996
+ /** Read one existing canonical user by verified email without creating a row. */
997
+ async function findUserByEmailFromSql(db, email) {
998
+ const normalizedEmail = normalizeIdentityEmail(email);
999
+ if (!normalizedEmail) return void 0;
1000
+ return await readUserByNormalizedEmail(db, normalizedEmail);
1001
+ }
1002
+ /** Read one existing canonical user by verified email without creating a row. */
1003
+ async function findUserByEmail(email) {
1004
+ return await findUserByEmailFromSql(getDb(), email);
1005
+ }
1006
+ /** Update one canonical user's display name in SQL. */
1007
+ async function updateViewerDisplayNameFromSql(db, userId, displayName) {
1008
+ const rows = await db.update(juniorUsers).set({
1009
+ displayName,
1010
+ updatedAt: /* @__PURE__ */ new Date()
1011
+ }).where(eq(juniorUsers.id, userId)).returning();
1012
+ await clearCachedUser(userId);
1013
+ const userRow = rows[0];
1014
+ return userRow ? await readUserById(db, userRow) : void 0;
1015
+ }
1016
+ /** Read the photo path of one canonical user: Slack, then Google. */
1017
+ async function readViewerAvatarUrl(userId) {
1018
+ return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
1019
+ }
1020
+ /** Update one canonical user's display name. */
1021
+ async function updateViewerDisplayName(userId, displayName) {
1022
+ return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
1023
+ }
1024
+ /**
1025
+ * Grant or revoke the Junior-wide admin role for one email.
1026
+ *
1027
+ * Granting creates the canonical user when needed, so an operator can grant
1028
+ * admin before that person first signs in. Revoking never creates a user.
1029
+ */
1030
+ async function setUserAdminFromSql(db, email, isAdmin) {
1031
+ const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
1032
+ if (!user) return void 0;
1033
+ const rows = await db.update(juniorUsers).set({
1034
+ isAdmin,
1035
+ updatedAt: /* @__PURE__ */ new Date()
1036
+ }).where(eq(juniorUsers.id, user.id)).returning();
1037
+ await clearCachedUser(user.id);
1038
+ const userRow = rows[0];
1039
+ return userRow ? await readUserById(db, userRow) : void 0;
1040
+ }
1041
+ /** List every Junior admin by primary email. */
1042
+ async function listAdminUsersFromSql(db) {
1043
+ const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
1044
+ if (rows.length === 0) return [];
1045
+ const identityRows = await db.select().from(juniorIdentities).where(and(inArray(juniorIdentities.userId, rows.map((row) => row.id)), eq(juniorIdentities.kind, "user"))).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
1046
+ return rows.map((row) => userFromRows(row, identityRows.filter((identity) => identity.userId === row.id)));
1047
+ }
1048
+ /** Resolve the stored identity and linked user for one runtime actor. */
1049
+ async function readActorIdentityFromSql(db, actor) {
1050
+ const identityId = await findActorIdentityId(db, actor);
1051
+ return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
1052
+ }
1053
+ /** Resolve the stored identity and linked user for one runtime actor. */
1054
+ async function readActorIdentity(actor) {
1055
+ return await readActorIdentityFromSql(getDb(), actor);
1056
+ }
1057
+ /** Read one stored identity and its linked user by identity id. */
1058
+ async function readIdentityByIdFromSql(db, identityId) {
1059
+ const row = (await db.select({
1060
+ identity: juniorIdentities,
1061
+ user: juniorUsers
1062
+ }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
1063
+ if (!row) return void 0;
1064
+ return {
1065
+ identity: identityFromRow(row.identity),
1066
+ ...row.user ? { user: await readUserById(db, row.user) } : void 0
1067
+ };
1068
+ }
1069
+ /** Read one stored identity and its linked user by identity id. */
1070
+ async function readIdentityById(identityId) {
1071
+ return await readIdentityByIdFromSql(getDb(), identityId);
1072
+ }
1073
+ // src/chat/inbox-items/assignees.ts
1074
+ /** Text that the agent writes to assign Everyone. */
1075
+ const EVERYONE_ASSIGNEE = "everyone";
1076
+ /**
1077
+ * Resolve one assignee: Everyone, an email, or a mention. A mention must be
1078
+ * in the tenant of the item.
1079
+ */
1080
+ async function resolveAssignee(db, value, tenant, findMentionedUserId) {
1081
+ const text = value.trim();
1082
+ if (text.toLowerCase() === "everyone") return { everyone: true };
1083
+ const mentionedUserId = await findMentionedUserId(text, tenant);
1084
+ if (mentionedUserId) return { userId: mentionedUserId };
1085
+ if (text.includes("@")) {
1086
+ const user = await findUserByEmailFromSql(db, text);
1087
+ if (!user) throw new ToolInputError(`No User has the email ${text}.`);
1088
+ return { userId: user.id };
1089
+ }
1090
+ throw new ToolInputError(`Unknown assignee ${JSON.stringify(text)}. Use ${EVERYONE_ASSIGNEE}, an email, or a mention such as <@U123>.`);
1091
+ }
1092
+ /** Resolve the assignees of an Inbox item. One is required. */
1093
+ async function resolveAssignees(db, values, tenant, findMentionedUserId) {
1094
+ if (values.length === 0) throw new ToolInputError("An inbox item needs at least one assignee.");
1095
+ const resolved = await mapBounded(values, (value) => resolveAssignee(db, value, tenant, findMentionedUserId));
1096
+ return {
1097
+ everyone: resolved.some((assignee) => "everyone" in assignee),
1098
+ userIds: [...new Set(resolved.flatMap((assignee) => "userId" in assignee ? [assignee.userId] : []))]
1099
+ };
1100
+ }
1101
+ async function participantUserIds(db, conversationIds, condition) {
1102
+ return (await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorConversations, eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), condition))).map((row) => row.userId);
1103
+ }
1104
+ /** Return which of the Users are Participants of any of the Conversations. */
1105
+ async function conversationParticipantUserIds(db, conversationIds, userIds) {
1106
+ if (conversationIds.length === 0 || userIds.length === 0) return /* @__PURE__ */ new Set();
1107
+ return new Set(await participantUserIds(db, conversationIds, inArray(juniorConversationParticipants.userId, [...userIds])));
1108
+ }
1109
+ /**
1110
+ * Return the active Participants of a Conversation: the people who have not
1111
+ * unsubscribed from it.
1112
+ */
1113
+ async function activeParticipantUserIds(db, conversationId) {
1114
+ return await participantUserIds(db, [conversationId], isNull(juniorConversationParticipants.unsubscribedAt));
1115
+ }
1116
+ /** Return the User who created an Automation, if Junior knows them. */
1117
+ async function automationCreatorUserId(db, automationId) {
1118
+ const [row] = await db.select({ userId: juniorIdentities.userId }).from(juniorAutomations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorAutomations.creatorIdentityId)).where(eq(juniorAutomations.id, automationId)).limit(1);
1119
+ return row?.userId ?? void 0;
1120
+ }
1121
+ // src/chat/inbox-items/access.ts
1122
+ /** Return whether two tenants are the same. Two missing tenants match. */
1123
+ function isSameTenant(a, b) {
1124
+ return a?.provider === b?.provider && a?.providerTenantId === b?.providerTenantId;
1125
+ }
1126
+ /**
1127
+ * The reader for one person: items assigned to them, and public items in the
1128
+ * provider tenants of their identities.
1129
+ */
1130
+ function inboxItemReaderForUser(user) {
1131
+ return {
1132
+ tenants: user.identities.flatMap((identity) => identity.providerTenantId ? [{
1133
+ provider: identity.provider,
1134
+ providerTenantId: identity.providerTenantId
1135
+ }] : []),
1136
+ userId: user.id
1137
+ };
1138
+ }
1139
+ /**
1140
+ * SQL: a Conversation owns the Inbox item. The Conversation status and
1141
+ * feeds read the items that each Conversation owns.
1142
+ */
1143
+ function inboxItemOwnedByConversation(conversationId) {
1144
+ return and(eq(juniorInboxItems.ownerKind, "conversation"), eq(juniorInboxItems.ownerId, conversationId));
1145
+ }
1146
+ /** SQL: the Inbox item has this assigned User. */
1147
+ function inboxItemAssignedTo(userId) {
1148
+ return sql`exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id} and ${juniorInboxItemAssignees.userId} = ${userId})`;
1149
+ }
1150
+ /**
1151
+ * SQL: the Inbox item needs this User. Only an open `action` item that is
1152
+ * assigned to the User needs them. A notice, an item for Everyone, and an
1153
+ * item without assignees need no one. An assigned User can always see the
1154
+ * item, so this rule needs no visibility check. The nav count and the
1155
+ * "Waiting on you" marker use this rule.
1156
+ */
1157
+ function inboxItemNeedsUser(userId) {
1158
+ return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId));
1159
+ }
1160
+ /**
1161
+ * SQL: the Inbox item needs some person: an open `action` item with an
1162
+ * assigned User. It is `inboxItemNeedsUser` for any User.
1163
+ */
1164
+ function inboxItemNeedsSomeone() {
1165
+ return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), sql`exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`);
1166
+ }
1167
+ /**
1168
+ * SQL: the Inbox item waits for a person's input: an open `action` item,
1169
+ * whoever it is assigned to. An item with no assignees still waits for
1170
+ * anyone who can answer it. The Conversation that added it shows
1171
+ * `needs_input`. `junior_inbox_items_open_action_added_by_idx` has this
1172
+ * predicate.
1173
+ */
1174
+ function inboxItemNeedsInput() {
1175
+ return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"));
1176
+ }
1177
+ /**
1178
+ * SQL: the Inbox item is not assigned only to other people. It is assigned
1179
+ * to this User, to Everyone, or to no one. This is the assignee rule of
1180
+ * `canActOnInboxItem`; keep the two the same.
1181
+ */
1182
+ function inboxItemForUser(userId) {
1183
+ return or(eq(juniorInboxItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`, inboxItemAssignedTo(userId));
1184
+ }
1185
+ /** SQL: the Inbox item links this Conversation. */
1186
+ function inboxItemLinkedTo(conversationId) {
1187
+ return sql`exists (select 1 from ${juniorInboxItemConversations} where ${juniorInboxItemConversations.itemId} = ${juniorInboxItems.id} and ${juniorInboxItemConversations.conversationId} = ${conversationId})`;
1188
+ }
1189
+ function publicIn(tenants) {
1190
+ return tenants.map((tenant) => and(eq(juniorInboxItems.visibility, "public"), eq(juniorInboxItems.provider, tenant.provider), eq(juniorInboxItems.providerTenantId, tenant.providerTenantId)));
1191
+ }
1192
+ /**
1193
+ * SQL form of `canReadInboxItem`, for search. Keep the two the same; the
1194
+ * Inbox item access test checks that they agree.
1195
+ */
1196
+ function inboxItemVisibleTo(reader) {
1197
+ return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [inboxItemAssignedTo(reader.userId)] : [], ...reader.conversationId ? [inboxItemLinkedTo(reader.conversationId)] : [], ...reader.automationId ? [eq(juniorInboxItems.automationId, reader.automationId)] : []) ?? sql`false`;
1198
+ }
1199
+ /** Return whether a reader can see one Inbox item. */
1200
+ function canReadInboxItem(item, reader) {
1201
+ return item.visibility === "public" && item.tenant !== void 0 && (reader.tenants ?? []).some((tenant) => isSameTenant(tenant, item.tenant)) || reader.userId !== void 0 && item.assignees.some((assignee) => assignee.userId === reader.userId) || reader.conversationId !== void 0 && item.conversationIds.includes(reader.conversationId) || reader.automationId !== void 0 && item.automationId === reader.automationId;
1202
+ }
1203
+ /**
1204
+ * Return whether a person can read one Inbox item: by the reader rule, or
1205
+ * because they take part in a Conversation that the item links. The second
1206
+ * part is the person rule of `policies/conversation-access.md`; it lets the
1207
+ * Conversation view show its items. Viewing a public Conversation is not
1208
+ * enough: a private item stays private when its Conversation becomes public.
1209
+ */
1210
+ async function canUserReadInboxItem(item, user) {
1211
+ if (canReadInboxItem(item, inboxItemReaderForUser(user))) return true;
1212
+ const access = await readConversationAccessFromSql(getDb(), item.conversationIds, user);
1213
+ return item.conversationIds.some((id) => access.get(id)?.isParticipant === true);
1214
+ }
1215
+ /**
1216
+ * The reader for one person who looks at one Conversation: the person's
1217
+ * reader, plus the items linked to the Conversation when they take part in
1218
+ * it. It is the list form of `canUserReadInboxItem`.
1219
+ */
1220
+ async function inboxItemReaderForUserInConversation(user, conversationId) {
1221
+ const reader = inboxItemReaderForUser(user);
1222
+ return (await readConversationAccessFromSql(getDb(), [conversationId], user)).get(conversationId)?.isParticipant ? {
1223
+ ...reader,
1224
+ conversationId
1225
+ } : reader;
1226
+ }
1227
+ /**
1228
+ * Read the scope of an agent. The agent reads as its Conversation and
1229
+ * Automation, not as its Actor: an assignment lets a person see the item on
1230
+ * the Inbox, not let an agent read it into another Conversation.
1231
+ */
1232
+ async function readInboxItemAgentScope(context) {
1233
+ const actor = await context.resolveActorIdentity?.();
1234
+ const user = actor?.user;
1235
+ const automationId = context.source.kind === "scheduled_automation" || context.source.kind === "event_automation" ? context.source.automationId : void 0;
1236
+ const current = (await readConversationAccessFromSql(getDb(), [context.conversationId], user)).get(context.conversationId);
1237
+ const tenant = current?.tenant;
1238
+ return {
1239
+ actorIsPerson: actor !== void 0,
1240
+ inPrivateConversation: current?.visibility !== "public",
1241
+ reader: {
1242
+ conversationId: context.conversationId,
1243
+ ...automationId ? { automationId } : void 0,
1244
+ ...tenant ? { tenants: [tenant] } : void 0
1073
1245
  },
1074
- ...linkedUserId ? { setWhere: sql`${juniorIdentities.userId} IS NULL OR ${juniorIdentities.userId} = excluded.user_id` } : void 0
1075
- }).returning({
1076
- id: juniorIdentities.id,
1077
- userId: juniorIdentities.userId
1078
- }))[0];
1079
- if (!row) {
1080
- if (linkedUserId) throw new Error("Identity conflicts with linked user");
1081
- throw new Error("Identity upsert returned no row");
1246
+ ...tenant ? { tenant } : void 0,
1247
+ ...user ? { user } : void 0
1248
+ };
1249
+ }
1250
+ /**
1251
+ * Dedupe keys with this prefix belong to plugins. Only the plugin that added
1252
+ * the item, or a person, can change it. An agent cannot use the prefix.
1253
+ */
1254
+ const PLUGIN_INBOX_ITEM_KEY_PREFIX = "plugin:";
1255
+ /**
1256
+ * Dedupe keys with this prefix belong to Automation alerts, which core adds
1257
+ * and closes. An agent cannot use the prefix.
1258
+ */
1259
+ const AUTOMATION_INBOX_ITEM_KEY_PREFIX = "automation:";
1260
+ /** Return the plugin that owns a dedupe key, or undefined for an agent's key. */
1261
+ function inboxItemPlugin(dedupeKey) {
1262
+ if (!dedupeKey.startsWith("plugin:")) return void 0;
1263
+ return dedupeKey.slice(7).split(":", 1)[0] || void 0;
1264
+ }
1265
+ /** Return whether the item is an Automation alert. Core takes its answer. */
1266
+ function isAutomationAlertItem(item) {
1267
+ return item.dedupeKey.startsWith(AUTOMATION_INBOX_ITEM_KEY_PREFIX);
1268
+ }
1269
+ /** Return whether a plugin added the item. Its answer goes to the plugin. */
1270
+ function isPluginInboxItem(item) {
1271
+ return inboxItemPlugin(item.dedupeKey) !== void 0;
1272
+ }
1273
+ /**
1274
+ * Whether an agent can change an item. Only an agent in the tenant of the
1275
+ * item can change it. A public item changes only from a public
1276
+ * Conversation, so private content never reaches its readers. A private
1277
+ * item changes only from the Conversation or Automation that added it. An
1278
+ * agent never changes an item that a plugin added, or an item that another
1279
+ * owner kind, such as an Automation, owns.
1280
+ */
1281
+ function canAgentChangeInboxItem(item, scope) {
1282
+ if (item.dedupeKey.startsWith("plugin:")) return false;
1283
+ if (item.owner.kind !== "conversation") return false;
1284
+ if (!isSameTenant(item.tenant, scope.tenant)) return false;
1285
+ if (item.visibility === "public") return !scope.inPrivateConversation;
1286
+ return item.owner.id === scope.reader.conversationId || scope.reader.automationId !== void 0 && item.automationId === scope.reader.automationId;
1287
+ }
1288
+ /**
1289
+ * Check the Conversations that an agent links. Every link must be in the
1290
+ * tenant of the item. `allowedIds` (the current Conversation and the links
1291
+ * that the item already has) always pass. A private item gets no other
1292
+ * links. A public item can get other links only to public Conversations.
1293
+ */
1294
+ async function requireInboxItemLinks(args) {
1295
+ const access = await readConversationAccessFromSql(getDb(), args.conversationIds, args.scope.user);
1296
+ for (const conversationId of args.conversationIds) {
1297
+ const conversation = access.get(conversationId);
1298
+ if (!conversation || !isSameTenant(conversation.tenant, args.tenant)) throw new ToolInputError(`Conversation ${conversationId} is not found.`);
1299
+ if (args.allowedIds.has(conversationId)) continue;
1300
+ if (args.visibility === "private") throw new ToolInputError("A private item links only to the Conversation that added it.");
1301
+ if (conversation.visibility !== "public") throw new ToolInputError(conversation.canViewPrivateContent ? `Conversation ${conversationId} is private. Only public Conversations can be linked.` : `Conversation ${conversationId} is not found.`);
1082
1302
  }
1083
- const previousUserId = existing?.userId;
1084
- await Promise.all([row.userId ? clearCachedUser(row.userId) : void 0, previousUserId && previousUserId !== row.userId ? clearCachedUser(previousUserId) : void 0]);
1085
- if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
1086
- identityId: row.id,
1087
- userId: row.userId
1303
+ }
1304
+ /**
1305
+ * Check who an agent assigns a private item to. It cannot go to Everyone.
1306
+ * Each User must be the current Actor, a Participant of one of the given
1307
+ * Conversations (the current one and, for an existing item, the one that
1308
+ * added it), or the creator of the Automation that added the item. An
1309
+ * Automation run often has no Actor and no people yet, and its creator wrote
1310
+ * the work. A public item can go to anyone.
1311
+ */
1312
+ async function requireInboxItemAssignees(args) {
1313
+ if (args.visibility === "public") return;
1314
+ if (args.assignees.everyone) throw new ToolInputError("A private item cannot be assigned to Everyone. Assign Users instead.");
1315
+ const creatorId = args.automationId ? await automationCreatorUserId(getDb(), args.automationId) : void 0;
1316
+ const others = args.assignees.userIds.filter((id) => id !== args.scope.user?.id && id !== creatorId);
1317
+ const inConversation = await conversationParticipantUserIds(getDb(), args.conversationIds, others);
1318
+ if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation.");
1319
+ }
1320
+ /**
1321
+ * Return whether a User can act on an open Inbox item: an assigned User,
1322
+ * anyone for an item assigned to Everyone, and anyone for an item with no
1323
+ * assignees. The caller checks that the User can see the item.
1324
+ * `inboxItemForUser` is the SQL form of the assignee rule.
1325
+ */
1326
+ function canActOnInboxItem(item, userId) {
1327
+ if (item.status !== "open") return false;
1328
+ if (item.assignedToEveryone) return true;
1329
+ if (item.assignees.length === 0) return true;
1330
+ return item.assignees.some((assignee) => assignee.userId === userId);
1331
+ }
1332
+ /**
1333
+ * Return whether an Inbox item needs a User: an open `action` item that is
1334
+ * assigned to them. `inboxItemNeedsUser` is the SQL form; keep the two the
1335
+ * same.
1336
+ */
1337
+ function itemNeedsUser(item, userId) {
1338
+ return item.status === "open" && item.kind === "action" && item.assignees.some((assignee) => assignee.userId === userId);
1339
+ }
1340
+ /** Return whether a User is already the only assignee, so take does nothing. */
1341
+ function isOnlyAssignee(item, userId) {
1342
+ return !item.assignedToEveryone && item.assignees.length === 1 && item.assignees[0]?.userId === userId;
1343
+ }
1344
+ // src/chat/conversations/sql/authorization-wait.ts
1345
+ /**
1346
+ * How long a person can finish an authorization. The MCP auth session and the
1347
+ * dashboard connect prompt expire after this time, so the parked Turn cannot
1348
+ * resume after it.
1349
+ */
1350
+ const AUTHORIZATION_WAIT_MS = 864e5;
1351
+ /**
1352
+ * The request and the events that end its wait: the person connected, or a
1353
+ * Turn started or ended after the request. A stop or new input ends the
1354
+ * parked Turn with `turn_completed`. A child agent invocation that needs a
1355
+ * connection abandons its Turn and ends it as `blocked`, so nothing resumes
1356
+ * it and its parent gets the result instead.
1357
+ */
1358
+ const AUTHORIZATION_WAIT_EVENT_TYPES = [
1359
+ "authorization_requested",
1360
+ "authorization_completed",
1361
+ "turn_started",
1362
+ "turn_completed",
1363
+ "turn_failed"
1364
+ ];
1365
+ /** The oldest request that still waits, on the app clock. */
1366
+ function authorizationWaitStart() {
1367
+ return (/* @__PURE__ */ new Date(Date.now() - AUTHORIZATION_WAIT_MS)).toISOString();
1368
+ }
1369
+ /**
1370
+ * SQL: the Conversation waits on a person to finish an authorization. A Turn
1371
+ * that needs a connection parks with execution `idle`, so only the durable
1372
+ * `authorization_requested` event shows the wait: it is the newest of these
1373
+ * events and has not expired. Build it for each query: it binds the app
1374
+ * clock, which also dated the request.
1375
+ */
1376
+ function awaitsAuthorization(conversationId) {
1377
+ return authorizationWait(conversationId, sql`true`);
1378
+ }
1379
+ /**
1380
+ * SQL: the Conversation waits on this User to finish an authorization. The
1381
+ * request names the person by their User id, or by the Slack user id of
1382
+ * one of their Identities. Build it for each query, as `awaitsAuthorization`.
1383
+ */
1384
+ function awaitsAuthorizationFrom(conversationId, userId) {
1385
+ const actorId = sql`${juniorConversationEvents.payload}->>'actorId'`;
1386
+ return authorizationWait(conversationId, sql`(${actorId} = ${userId} or ${actorId} in (select ${juniorIdentities.providerSubjectId} from ${juniorIdentities} where ${and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, "slack"))}))`);
1387
+ }
1388
+ /** SQL: the newest wait event is a live request that `requester` matches. */
1389
+ function authorizationWait(conversationId, requester) {
1390
+ const events = juniorConversationEvents;
1391
+ const start = authorizationWaitStart();
1392
+ const recentRequest = sql`(select true from ${events} where ${events.conversationId} = ${conversationId} and ${events.type} = 'authorization_requested' and ${events.createdAt} > ${start}::timestamptz limit 1)`;
1393
+ return sql`(coalesce(${recentRequest}, false) and coalesce((
1394
+ select ${events.type} = 'authorization_requested'
1395
+ and ${events.createdAt} > ${start}::timestamptz
1396
+ and ${requester}
1397
+ from ${events}
1398
+ where ${events.conversationId} = ${conversationId}
1399
+ and ${events.type} in (${sql.join(AUTHORIZATION_WAIT_EVENT_TYPES.map((type) => sql`${type}`), sql`, `)})
1400
+ order by ${events.seq} desc
1401
+ limit 1
1402
+ ), false))`;
1403
+ }
1404
+ /**
1405
+ * SQL: the root or a child Conversation of `rootConversationId` waits on a
1406
+ * person to finish an authorization.
1407
+ */
1408
+ function treeAwaitsAuthorization(rootConversationId) {
1409
+ const tree = alias(juniorConversations, "authorization_tree");
1410
+ return sql`exists (
1411
+ select 1 from ${juniorConversations} as ${tree}
1412
+ where (${tree.conversationId} = ${rootConversationId}
1413
+ or ${tree.rootConversationId} = ${rootConversationId})
1414
+ and ${awaitsAuthorization(tree.conversationId)}
1415
+ )`;
1416
+ }
1417
+ // src/chat/conversations/sql/conversation-row.ts
1418
+ /**
1419
+ * Establish the conversation metadata row on first contact for content writes
1420
+ * (conversation events, visible transcript) that can land before activity has
1421
+ * created the row, and whose tables FK to it.
1422
+ *
1423
+ * First contact creates the row; every later content write advances the
1424
+ * activity clock so retention mirrors append-refresh semantics (each content
1425
+ * append refreshes the retention window). Background observations may opt out
1426
+ * and leave an existing row unchanged. The timestamp is content-intrinsic (the
1427
+ * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
1428
+ * imported historical write — which carries an old timestamp — can never
1429
+ * regress `last_activity_at`.
1430
+ */
1431
+ async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
1432
+ const at = new Date(atMs);
1433
+ const insert = executor.db().insert(juniorConversations).values({
1434
+ conversationId,
1435
+ createdAt: at,
1436
+ lastActivityAt: at,
1437
+ updatedAt: at,
1438
+ executionStatus: "idle",
1439
+ kind: "root"
1088
1440
  });
1441
+ if (options.activity === "preserve") {
1442
+ await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
1443
+ return;
1444
+ }
1445
+ await insert.onConflictDoUpdate({
1446
+ target: juniorConversations.conversationId,
1447
+ set: {
1448
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
1449
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
1450
+ transcriptPurgedAt: null,
1451
+ detailVersion: nextDetailVersion
1452
+ }
1453
+ });
1454
+ }
1455
+ const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
1456
+ "root",
1457
+ "automation",
1458
+ "lead",
1459
+ "thread",
1460
+ "task"
1461
+ ]);
1462
+ /** Decode a stored kind. A null kind comes from a writer of an older deploy. */
1463
+ function conversationKindFromRow(row) {
1464
+ const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
1465
+ if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
1466
+ return kind;
1467
+ }
1468
+ /** SQL for the kind of a row, with the same null fallback as `conversationKindFromRow`. */
1469
+ function conversationKindSql(conversation) {
1470
+ return sql`coalesce(${conversation.kind}, case when ${conversation.parentConversationId} is null then 'root' else 'task' end)`;
1471
+ }
1472
+ // src/chat/conversations/sql/status.ts
1473
+ const ACTIVE_EXECUTION_STATUSES = [
1474
+ "pending",
1475
+ "running",
1476
+ "paused",
1477
+ "awaiting_resume"
1478
+ ];
1479
+ /** SQL: a Turn of the Conversation is queued or running. */
1480
+ function conversationIsActiveSql(conversation) {
1481
+ return sql`${conversation.executionStatus} in (${sql.raw(ACTIVE_EXECUTION_STATUSES.map((status) => `'${status}'`).join(", "))})`;
1482
+ }
1483
+ /**
1484
+ * Whether a Turn is queued or running, for a row that is already read. It
1485
+ * matches `conversationIsActiveSql`. Live views poll on it; `status` can
1486
+ * read `needs_input` meanwhile.
1487
+ */
1488
+ function executionIsActive(executionStatus) {
1489
+ return ACTIVE_EXECUTION_STATUSES.includes(executionStatus);
1490
+ }
1491
+ /**
1492
+ * SQL: the latest Turn of the Conversation failed with no newer input.
1493
+ * Execution is `failed`, or the newest Turn lifecycle Event is
1494
+ * `turn_failed`. Events are durable; the Redis Turn record expires. Stats
1495
+ * count it; the status reads it as input that the starter needs to give.
1496
+ */
1497
+ function conversationTurnFailedSql(conversation) {
1498
+ const newestSeq = (type) => sql`(select max(${juniorConversationEvents.seq}) from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, conversation.conversationId), eq(juniorConversationEvents.type, type))})`;
1499
+ return sql`(${conversation.executionStatus} = 'failed' or ${newestSeq("turn_failed")} > coalesce(greatest(${newestSeq("turn_started")}, ${newestSeq("turn_completed")}), -1))`;
1500
+ }
1501
+ const DELIVERY_PAUSE_START = sql.raw(`'2026-11-10T02:48:39Z'::timestamptz`);
1502
+ const starterRoot = alias(juniorConversations, "status_starter_root");
1503
+ const starterIdentity = alias(juniorIdentities, "status_starter_identity");
1504
+ const replyReader = alias(juniorIdentities, "status_reply_reader");
1505
+ /** SQL: the User id of the Conversation's starter, the User of its root's actor. */
1506
+ function conversationStarterUserIdSql(conversation) {
1507
+ return sql`(select ${starterIdentity.userId} from ${juniorConversations} as ${starterRoot} join ${juniorIdentities} as ${starterIdentity} on ${eq(starterIdentity.id, starterRoot.actorIdentityId)} where ${eq(starterRoot.conversationId, sql`coalesce(${conversation.rootConversationId}, ${conversation.conversationId})`)})`;
1508
+ }
1509
+ /**
1510
+ * SQL: the work of the Conversation waits on its starter. The starter is
1511
+ * the User of the root's actor: the person whose message started the root,
1512
+ * or the creator of an Automation run. A Task reports to its parent, so
1513
+ * only a root, an Automation run, or a Thread waits on its starter. A stop
1514
+ * ends what the Conversation waits on, and a queued or running Turn is
1515
+ * `working`, not waiting. One of these applies:
1516
+ *
1517
+ * - The latest Turn failed.
1518
+ * - The latest Brief outcome is `partial` or `blocked`, and that Brief
1519
+ * covers the latest assistant Message. Turns no longer store Briefs, so a
1520
+ * legacy Brief stops deciding once the Conversation moves on.
1521
+ * - The latest assistant Message is an answer that the starter has not
1522
+ * read. It is an answer when the latest Brief is `answered` or does not
1523
+ * cover it. A `done` Brief that covers it needs no read. The starter read
1524
+ * it when Slack accepted it for a root's Location, when the starter
1525
+ * wrote a later Message, or when their dashboard read position reaches it.
1526
+ * With no starter, nobody reads it, so an answer does not wait.
1527
+ */
1528
+ function conversationWaitsOnStarterSql(conversation) {
1529
+ const id = conversation.conversationId;
1530
+ const starter = sql.identifier("status_starter");
1531
+ const brief = sql.identifier("status_brief");
1532
+ const reply = sql.identifier("status_reply");
1533
+ const starterUserId = sql`${starter}.user_id`;
1534
+ const briefStatus = sql`${brief}.status`;
1535
+ const briefThroughSeq = sql`${brief}.through_seq`;
1536
+ const replySeq = sql`${reply}.seq`;
1537
+ const replyInSlack = sql`${reply}.in_slack`;
1538
+ const latestBrief = sql`(select ${juniorConversationBriefs.content}->'outcome'->>'status' as status, ${juniorConversationBriefs.throughSeq} as through_seq from ${juniorConversationBriefs} where ${eq(juniorConversationBriefs.conversationId, id)} order by ${desc(juniorConversationBriefs.version)} limit 1)`;
1539
+ const latestReply = sql`(select ${juniorConversationEvents.seq} as seq, coalesce(${juniorConversationEvents.payload}->'meta'->>'source' = 'slack', ${juniorConversationEvents.createdAt} < ${DELIVERY_PAUSE_START}) as in_slack from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`)} order by ${desc(juniorConversationEvents.seq)} limit 1)`;
1540
+ const readByStarter = or(and(sql`${conversation.parentConversationId} is null`, sql`${conversation.location} is not null`, sql`coalesce(${replyInSlack}, false)`), sql`exists (select 1 from ${juniorConversationEvents} join ${juniorIdentities} as ${replyReader} on ${eq(replyReader.id, juniorConversationEvents.actorIdentityId)} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), gt(juniorConversationEvents.seq, replySeq), eq(replyReader.userId, starterUserId))})`, sql`exists (select 1 from ${juniorConversationReadPositions} where ${and(eq(juniorConversationReadPositions.conversationId, id), eq(juniorConversationReadPositions.userId, starterUserId), gte(juniorConversationReadPositions.lastReadSeq, replySeq))})`);
1541
+ const unreadAnswer = sql`${replySeq} is not null and ${starterUserId} is not null and (coalesce(${briefStatus}, 'answered') = 'answered' or ${briefThroughSeq} < ${replySeq}) and not (${readByStarter})`;
1542
+ const waitsOnFacts = sql`(select (${briefStatus} in ('partial', 'blocked') and (${replySeq} is null or ${briefThroughSeq} >= ${replySeq})) or (${unreadAnswer})
1543
+ from (select ${conversationStarterUserIdSql(conversation)} as user_id offset 0) as ${starter}
1544
+ left join lateral ${latestBrief} as ${brief} on true
1545
+ left join lateral ${latestReply} as ${reply} on true)`;
1546
+ return sql`(${conversation.stoppedAt} is null
1547
+ and ${conversationKindSql(conversation)} <> 'task'
1548
+ and not ${conversationIsActiveSql(conversation)}
1549
+ and (
1550
+ ${conversationTurnFailedSql(conversation)}
1551
+ or ${waitsOnFacts}
1552
+ ))`;
1553
+ }
1554
+ /**
1555
+ * SQL for the status of one Conversation's own work, shared by everyone.
1556
+ * This is the only place that derives it; readers, counts, and feed tokens
1557
+ * select it. When more than one applies: `needs_input` > `working` > `done`.
1558
+ *
1559
+ * - `needs_input`: an open action Inbox item that this Conversation added
1560
+ * waits on its assignees or Everyone, a Turn waits on a person to sign in
1561
+ * (`awaitsAuthorization`), or the work waits on its starter
1562
+ * (`conversationWaitsOnStarterSql`).
1563
+ * - `working`: a Turn is queued or running (`conversationIsActiveSql`).
1564
+ * - `done`: anything else, such as a `done` Brief, a read answer, a stop,
1565
+ * or an idle Conversation.
1566
+ */
1567
+ function conversationStatusSql(conversation) {
1568
+ const needsInput = sql`exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(conversation.conversationId), inboxItemNeedsInput())})`;
1569
+ return sql`case
1570
+ when ${needsInput} or ${awaitsAuthorization(conversation.conversationId)} or ${conversationWaitsOnStarterSql(conversation)} then 'needs_input'
1571
+ when ${conversationIsActiveSql(conversation)} then 'working'
1572
+ else 'done'
1573
+ end`;
1574
+ }
1575
+ /**
1576
+ * SQL: the Conversation's work waits on this User as its starter. See
1577
+ * `conversationWaitsOnStarterSql`.
1578
+ */
1579
+ function conversationWaitsOnUserSql(conversation, userId) {
1580
+ return sql`(${conversationStarterUserIdSql(conversation)} = ${userId} and ${conversationWaitsOnStarterSql(conversation)})`;
1581
+ }
1582
+ // src/api/conversations/aggregate.ts
1583
+ function usageTokenValue(source, field) {
1584
+ return sql`CASE
1585
+ WHEN ${source.usage}->>${field} IS NOT NULL
1586
+ THEN (${source.usage}->>${field})::double precision
1587
+ ELSE NULL
1588
+ END`;
1589
+ }
1590
+ function tokenValue(source) {
1591
+ return sql`
1592
+ CASE
1593
+ WHEN COALESCE(
1594
+ ${source.usage}->>'inputTokens',
1595
+ ${source.usage}->>'outputTokens',
1596
+ ${source.usage}->>'cachedInputTokens',
1597
+ ${source.usage}->>'cacheCreationTokens'
1598
+ ) IS NOT NULL
1599
+ THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
1600
+ + COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
1601
+ + COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
1602
+ + COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
1603
+ WHEN ${source.usage}->>'totalTokens' IS NOT NULL
1604
+ THEN (${source.usage}->>'totalTokens')::double precision
1605
+ ELSE NULL
1606
+ END
1607
+ `;
1608
+ }
1609
+ function costValue(source) {
1610
+ return conversationUsageCostExpr(source.usage);
1611
+ }
1612
+ /** Read one conversation row's usage cost as a SQL expression. */
1613
+ function conversationUsageCostExpr(usage) {
1614
+ return sql`
1615
+ CASE
1616
+ WHEN ${usage}->'cost'->>'total' IS NOT NULL
1617
+ THEN (${usage}->'cost'->>'total')::double precision
1618
+ WHEN COALESCE(
1619
+ ${usage}->'cost'->>'input',
1620
+ ${usage}->'cost'->>'output',
1621
+ ${usage}->'cost'->>'cacheRead',
1622
+ ${usage}->'cost'->>'cacheWrite'
1623
+ ) IS NOT NULL
1624
+ THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
1625
+ + COALESCE((${usage}->'cost'->>'output')::double precision, 0)
1626
+ + COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
1627
+ + COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
1628
+ ELSE NULL
1629
+ END
1630
+ `;
1631
+ }
1632
+ /** Select complete conversation metrics inside the database instead of materializing source rows. */
1633
+ function conversationAggregateColumns(sources) {
1634
+ const metrics = sources?.metrics ?? juniorConversations;
1635
+ const roots = sources?.roots ?? juniorConversations;
1636
+ const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
1089
1637
  return {
1090
- id: row.id,
1091
- ...row.userId ? { userId: row.userId } : void 0
1638
+ active: sql`${conversationCount} FILTER (
1639
+ WHERE ${conversationIsActiveSql(roots)}
1640
+ )::integer`,
1641
+ conversations: sql`${conversationCount}::integer`,
1642
+ cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
1643
+ cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
1644
+ costUsd: sql`SUM(${costValue(metrics)})::double precision`,
1645
+ durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
1646
+ failed: sql`${conversationCount} FILTER (
1647
+ WHERE ${conversationTurnFailedSql(roots)} AND ${roots.stoppedAt} IS NULL
1648
+ )::integer`,
1649
+ inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
1650
+ tokens: sql`SUM(${tokenValue(metrics)})::double precision`
1092
1651
  };
1093
1652
  }
1094
- /** Read the saved timezone for one user. */
1095
- async function readUserTimezone(db, userId) {
1096
- return (await db.select({ timezone: juniorUsers.timezone }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1))[0]?.timezone ?? void 0;
1653
+ /** Select the complete first/last activity range for a grouped conversation aggregate. */
1654
+ function conversationRangeColumns() {
1655
+ return {
1656
+ firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
1657
+ lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
1658
+ };
1097
1659
  }
1098
- /** Save the IANA timezone for one user. */
1099
- async function saveUserTimezone(db, userId, timezone, nowMs) {
1100
- await db.update(juniorUsers).set({
1101
- timezone,
1102
- updatedAt: dateFromMs$1(nowMs)
1103
- }).where(and(eq(juniorUsers.id, userId), sql`${juniorUsers.timezone} is distinct from ${timezone}`));
1660
+ // src/db/micro-usd.ts
1661
+ /**
1662
+ * Postgres stores every money value as whole micro-USD, in a `bigint` column
1663
+ * or an integer metric value named `*_micro_usd`. Integer sums are exact and
1664
+ * do not depend on row order. Round once where a USD amount is stored, and
1665
+ * convert to USD once where the API returns it. `pnpm money-units:check`
1666
+ * keeps money scales in this file.
1667
+ */
1668
+ const MICRO_USD_PER_USD = 1e6;
1669
+ /** Round a USD amount to whole micro-USD for storage. */
1670
+ function usdToMicroUsd(usd) {
1671
+ return Math.round(usd * MICRO_USD_PER_USD);
1104
1672
  }
1105
- /** Return the Slack user most recently linked to a Junior user. */
1106
- async function linkedSlackUser(db, userId) {
1107
- const row = (await db.select({
1108
- teamId: juniorIdentities.providerTenantId,
1109
- slackUserId: juniorIdentities.providerSubjectId
1110
- }).from(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"))).orderBy(desc(juniorIdentities.updatedAt)).limit(1))[0];
1111
- return row?.teamId ? {
1112
- teamId: row.teamId,
1113
- userId: row.slackUserId
1114
- } : void 0;
1673
+ /** Convert stored micro-USD to USD for an API response. */
1674
+ function microUsdToUsd(microUsd) {
1675
+ return microUsd / MICRO_USD_PER_USD;
1115
1676
  }
1116
- /** Persist one provider identity observation and link verified emails to users. */
1117
- async function upsertIdentity(executor, identity, nowMs = Date.now()) {
1118
- return await upsertIdentityRecord(executor, identity, void 0, nowMs);
1677
+ /** SQL that rounds a USD amount to whole micro-USD. */
1678
+ function usdToMicroUsdSql(usd) {
1679
+ return sql`round(${usd} * 1000000)::bigint`;
1680
+ }
1681
+ /** SQL that converts micro-USD to USD, for usage JSON in USD. */
1682
+ function microUsdToUsdSql(microUsd) {
1683
+ return sql`(${microUsd}) / 1000000.0::double precision`;
1119
1684
  }
1120
1685
  /**
1121
- * Persist one provider identity after a trusted account-linking flow.
1122
- * Callers must use provider-verified account data, such as GitHub's authenticated
1123
- * user response, never identity claims inferred from content such as Git commits.
1686
+ * SQL that reads a micro-USD value or sum as an exact integer. Postgres
1687
+ * returns `bigint` as text, so this maps it to a number.
1124
1688
  */
1125
- async function upsertLinkedIdentity(executor, userId, identity, nowMs = Date.now()) {
1126
- return await upsertIdentityRecord(executor, identity, userId, nowMs);
1689
+ function microUsdSql(microUsd) {
1690
+ return sql`(${microUsd})::bigint`.mapWith(Number);
1127
1691
  }
1692
+ // src/chat/automations/run-cost.ts
1128
1693
  /**
1129
- * Find the one user whose primary email is in a provider-verified email list.
1130
- * Return undefined when no user or more than one user matches.
1694
+ * SQL for a Conversation's usage cost in whole micro-USD, the unit of a run's
1695
+ * `cost_micro_usd`.
1131
1696
  */
1132
- async function findUserByVerifiedEmails(executor, emails) {
1133
- const normalized = new Set(emails.map((email) => normalizeIdentityEmail(email) ?? ""));
1134
- normalized.delete("");
1135
- if (normalized.size === 0) return void 0;
1136
- const rows = await executor.db().select({
1137
- email: juniorUsers.primaryEmail,
1138
- userId: juniorUsers.id
1139
- }).from(juniorUsers).where(inArray(juniorUsers.primaryEmailNormalized, Array.from(normalized))).limit(2);
1140
- return rows.length === 1 ? rows[0] : void 0;
1697
+ function costMicroUsdExpr(usage) {
1698
+ return usdToMicroUsdSql(conversationUsageCostExpr(usage));
1141
1699
  }
1142
- const linkedSlackIdentity = alias(juniorIdentities, "linked_slack_identity");
1143
- const linkedSlackUserColumns = {
1144
- displayName: juniorUsers.displayName,
1145
- email: juniorUsers.primaryEmail,
1146
- slackUserId: linkedSlackIdentity.providerSubjectId,
1147
- userId: juniorUsers.id
1148
- };
1149
- function singleLinkedSlackUser(rows) {
1150
- const [row] = rows;
1151
- if (rows.length !== 1 || !row) return void 0;
1700
+ /**
1701
+ * SQL that reads the cost of one Conversation, for the `cost_micro_usd` of its
1702
+ * run. Set it in each run write that links a run to its Conversation, because
1703
+ * the Conversation can record usage before its run row exists.
1704
+ */
1705
+ function conversationCostOf(conversationId) {
1706
+ return sql`(select ${costMicroUsdExpr(juniorConversations.usage)} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
1707
+ }
1708
+ // src/chat/conversations/metrics.ts
1709
+ function finite(value) {
1710
+ return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
1711
+ }
1712
+ /** Convert one Run summary to metric rows. */
1713
+ function conversationMetricValues(args) {
1714
+ const usage = args.usage;
1715
+ const costUsd = agentTurnCostUsd(usage);
1152
1716
  return {
1153
- slackUserId: row.slackUserId,
1154
- user: {
1155
- id: row.userId,
1156
- email: row.email,
1157
- ...row.displayName ? { displayName: row.displayName } : void 0
1158
- }
1717
+ duration_ms: Math.max(0, args.durationMs),
1718
+ total_tokens: agentTurnTotalTokens(usage),
1719
+ input_tokens: finite(usage?.inputTokens),
1720
+ output_tokens: finite(usage?.outputTokens),
1721
+ cached_input_tokens: finite(usage?.cachedInputTokens),
1722
+ cache_creation_tokens: finite(usage?.cacheCreationTokens),
1723
+ reasoning_tokens: finite(usage?.reasoningTokens),
1724
+ cost_micro_usd: costUsd === void 0 ? void 0 : usdToMicroUsd(costUsd)
1159
1725
  };
1160
1726
  }
1161
1727
  /**
1162
- * Find the one Slack user in a workspace who is linked to an exact provider
1163
- * Identity, and the User behind both.
1728
+ * Read one Run's stored totals from its metric rows.
1164
1729
  *
1165
- * Only the provider account id from an account-linking flow matches. Handles,
1166
- * emails, and display names never match. Return undefined when no Slack user
1167
- * or more than one Slack user matches.
1730
+ * Returns undefined when the Run has no rows. Cost keeps only its total.
1168
1731
  */
1169
- async function findLinkedSlackUser(executor, args) {
1170
- return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorIdentities).innerJoin(linkedSlackIdentity, and(eq(linkedSlackIdentity.userId, juniorIdentities.userId), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, args.providerSubjectId))).limit(2));
1732
+ async function readConversationRunMetrics(executor, args) {
1733
+ const rows = await executor.db().select({
1734
+ metric: juniorConversationMetrics.metric,
1735
+ value: juniorConversationMetrics.value
1736
+ }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
1737
+ const values = new Map(rows.map((row) => [row.metric, row.value]));
1738
+ const durationMs = values.get("duration_ms");
1739
+ if (durationMs === void 0) return void 0;
1740
+ const components = {
1741
+ inputTokens: values.get("input_tokens"),
1742
+ outputTokens: values.get("output_tokens"),
1743
+ cachedInputTokens: values.get("cached_input_tokens"),
1744
+ cacheCreationTokens: values.get("cache_creation_tokens")
1745
+ };
1746
+ const hasComponents = Object.values(components).some((value) => value !== void 0);
1747
+ const costMicroUsd = values.get("cost_micro_usd");
1748
+ const usage = Object.fromEntries(Object.entries({
1749
+ ...components,
1750
+ reasoningTokens: values.get("reasoning_tokens"),
1751
+ totalTokens: hasComponents ? void 0 : values.get("total_tokens"),
1752
+ cost: costMicroUsd === void 0 ? void 0 : { total: microUsdToUsd(costMicroUsd) }
1753
+ }).filter(([, value]) => value !== void 0));
1754
+ return {
1755
+ durationMs,
1756
+ ...Object.keys(usage).length > 0 ? { usage } : void 0
1757
+ };
1758
+ }
1759
+ /** Replace one Run's metric rows and refresh its Conversation totals. */
1760
+ async function replaceConversationMetrics(executor, args) {
1761
+ const [current] = await executor.db().select({ updatedAt: juniorConversationMetrics.updatedAt }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId))).limit(1);
1762
+ if (current && current.updatedAt.getTime() > args.updatedAtMs) return;
1763
+ await executor.db().delete(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
1764
+ const metricValues = conversationMetricValues({
1765
+ durationMs: args.durationMs,
1766
+ usage: args.usage
1767
+ });
1768
+ const values = CONVERSATION_METRICS.flatMap((metric) => {
1769
+ const value = metricValues[metric];
1770
+ return value === void 0 ? [] : [{
1771
+ actorIdentityId: args.actorIdentityId ?? null,
1772
+ conversationId: args.conversationId,
1773
+ runId: args.runId,
1774
+ metric,
1775
+ value,
1776
+ occurredAt: new Date(args.occurredAtMs),
1777
+ updatedAt: new Date(args.updatedAtMs)
1778
+ }];
1779
+ });
1780
+ if (values.length > 0) await executor.db().insert(juniorConversationMetrics).values(values);
1781
+ const metric = (name) => sql`(
1782
+ select sum(${juniorConversationMetrics.value})
1783
+ from ${juniorConversationMetrics}
1784
+ where ${juniorConversationMetrics.conversationId} = ${args.conversationId}
1785
+ and ${juniorConversationMetrics.metric} = ${name}
1786
+ )`;
1787
+ const totalTokens = metric("total_tokens");
1788
+ const componentTokens = sql`
1789
+ coalesce(${metric("input_tokens")}, 0)
1790
+ + coalesce(${metric("output_tokens")}, 0)
1791
+ + coalesce(${metric("cached_input_tokens")}, 0)
1792
+ + coalesce(${metric("cache_creation_tokens")}, 0)
1793
+ `;
1794
+ const hasComponents = sql`
1795
+ ${metric("input_tokens")} is not null
1796
+ or ${metric("output_tokens")} is not null
1797
+ or ${metric("cached_input_tokens")} is not null
1798
+ or ${metric("cache_creation_tokens")} is not null
1799
+ `;
1800
+ const cost = sql`case when ${metric("cost_micro_usd")} is null then null
1801
+ else jsonb_build_object('total', ${microUsdToUsdSql(metric("cost_micro_usd"))}) end`;
1802
+ const db = executor.db();
1803
+ const usageUpdate = db.$with("conversation_usage_update").as(db.update(juniorConversations).set({
1804
+ durationMs: sql`coalesce(${metric("duration_ms")}, 0)`,
1805
+ usage: sql`case
1806
+ when ${totalTokens} is not null
1807
+ and (${hasComponents})
1808
+ and ${totalTokens} <> ${componentTokens}
1809
+ then jsonb_strip_nulls(jsonb_build_object(
1810
+ 'totalTokens', ${totalTokens},
1811
+ 'reasoningTokens', ${metric("reasoning_tokens")},
1812
+ 'cost', ${cost}
1813
+ ))
1814
+ else jsonb_strip_nulls(jsonb_build_object(
1815
+ 'totalTokens', ${totalTokens},
1816
+ 'inputTokens', ${metric("input_tokens")},
1817
+ 'outputTokens', ${metric("output_tokens")},
1818
+ 'cachedInputTokens', ${metric("cached_input_tokens")},
1819
+ 'cacheCreationTokens', ${metric("cache_creation_tokens")},
1820
+ 'reasoningTokens', ${metric("reasoning_tokens")},
1821
+ 'cost', ${cost}
1822
+ ))
1823
+ end`,
1824
+ detailVersion: nextDetailVersion
1825
+ }).where(eq(juniorConversations.conversationId, args.conversationId)).returning({ costMicroUsd: costMicroUsdExpr(juniorConversations.usage).as("cost_micro_usd") }));
1826
+ await db.with(usageUpdate).update(juniorAutomationRuns).set({ costMicroUsd: sql`(select ${usageUpdate.costMicroUsd} from ${usageUpdate})` }).where(eq(juniorAutomationRuns.conversationId, args.conversationId));
1171
1827
  }
1828
+ // src/chat/source.ts
1172
1829
  /**
1173
- * Find the one Slack user in a workspace whose User has this primary email.
1174
- *
1175
- * The caller must have verified that the person sent from this address.
1176
- * Return undefined when no Slack user or more than one Slack user matches.
1830
+ * Normalize a Turn Source into legacy provider fields stored on a Conversation.
1831
+ * System Sources do not contain a Conversation Location.
1177
1832
  */
1178
- async function findSlackUserByPrimaryEmail(executor, args) {
1179
- return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorUsers).innerJoin(linkedSlackIdentity, eq(linkedSlackIdentity.userId, juniorUsers.id)).where(and(eq(juniorUsers.primaryEmailNormalized, args.normalizedEmail), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).limit(2));
1180
- }
1181
- /** Remove one exact provider identity owned by a workspace Slack user. */
1182
- async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUserId, provider, providerSubjectId) {
1183
- const userId = (await executor.db().select({ userId: juniorIdentities.userId }).from(juniorIdentities).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"), eq(juniorIdentities.providerTenantId, slackTeamId), eq(juniorIdentities.providerSubjectId, slackUserId))).limit(1))[0]?.userId;
1184
- if (!userId) return;
1185
- await deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId);
1833
+ function normalizeSessionSource(value) {
1834
+ if (!value) return;
1835
+ if (value.kind === "local") return {
1836
+ kind: "local",
1837
+ visibility: value.visibility,
1838
+ conversationId: value.conversationId
1839
+ };
1840
+ if (value.kind === "web") return {
1841
+ kind: "web",
1842
+ visibility: value.visibility,
1843
+ conversationId: value.conversationId
1844
+ };
1845
+ if (value.kind === "event" || value.kind === "scheduled_automation" || value.kind === "event_automation" || value.kind === "plugin_dispatch" || value.kind === "agent_invocation") return;
1846
+ const threadTs = value.threadTs?.trim();
1847
+ return {
1848
+ kind: "slack",
1849
+ visibility: value.visibility,
1850
+ teamId: value.teamId,
1851
+ channelId: value.channelId,
1852
+ ...threadTs ? { threadTs } : void 0
1853
+ };
1186
1854
  }
1187
- /** Remove one exact provider identity owned by a user. */
1188
- async function deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId) {
1189
- await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
1190
- await clearCachedUser(userId);
1855
+ /** Parse a serialized Source into legacy provider fields stored on a Conversation. */
1856
+ function parseSessionSource(value) {
1857
+ const parsed = sourceSchema.safeParse(value);
1858
+ return parsed.success ? normalizeSessionSource(parsed.data) : void 0;
1191
1859
  }
1192
- /**
1193
- * Save one Google sign-in. Link the Google identity to the user of its
1194
- * verified email, and set its sign-in time. Return the previous sign-in
1195
- * time, if any.
1196
- */
1197
- async function recordGoogleSignIn(executor, account, nowMs = Date.now()) {
1198
- const stored = await upsertIdentity(executor, {
1199
- kind: "user",
1200
- provider: GOOGLE_IDENTITY_PROVIDER,
1201
- providerSubjectId: account.subject,
1202
- email: account.email,
1203
- emailVerified: true,
1204
- displayName: account.displayName,
1205
- avatarUrl: account.avatarUrl ?? null
1206
- }, nowMs);
1207
- const [previous] = await executor.db().select({ signedInAt: juniorIdentities.signedInAt }).from(juniorIdentities).where(eq(juniorIdentities.id, stored.id)).limit(1);
1208
- await executor.db().update(juniorIdentities).set({ signedInAt: dateFromMs$1(nowMs) }).where(eq(juniorIdentities.id, stored.id));
1209
- return previous?.signedInAt?.getTime();
1860
+ // src/chat/conversations/sql/bindings.ts
1861
+ /** Resolve the durable conversation bound to provider-owned coordinates. */
1862
+ async function getConversationIdByProviderConversation(executor, args) {
1863
+ return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
1210
1864
  }
1211
- // src/chat/identities/actor.ts
1212
- /**
1213
- * Resolve runtime Actors to the Identity rows that Junior stores for them.
1214
- *
1215
- * The Conversation store, OAuth, the viewer, and message events use this
1216
- * module, so they agree on one Identity per person. The key for each Actor
1217
- * stays private here, so it can change without changing callers.
1218
- */
1219
- /**
1220
- * The fixed id of the one system Identity: kind `system`, provider `junior`,
1221
- * an empty tenant, and subject `system`. A migration creates the row, so
1222
- * callers use this id without a database read.
1223
- */
1224
- const SYSTEM_IDENTITY_ID = "system";
1225
1865
  /**
1226
- * Return whether an Actor uses the system Identity.
1227
- *
1228
- * `SystemActor.name` is provenance, not part of the Identity. A LocalActor
1229
- * uses the system Identity because the local runner has no per-person user id.
1866
+ * Bind provider coordinates to a durable conversation unless another
1867
+ * conversation has them. Return the conversation that has them.
1230
1868
  */
1231
- function usesSystemIdentity(actor) {
1232
- return actor.platform === "local" || actor.platform === "system";
1233
- }
1234
- /** Return the Identity key for one Slack or web Actor. */
1235
- function identityKey(actor) {
1236
- switch (actor.platform) {
1237
- case "slack": return {
1238
- kind: "user",
1239
- provider: "slack",
1240
- providerTenantId: actor.teamId,
1241
- providerSubjectId: actor.userId,
1242
- ...actor.fullName ? { displayName: actor.fullName } : void 0,
1243
- ...actor.userName ? { handle: actor.userName } : void 0,
1244
- ...actor.email ? {
1245
- email: actor.email,
1246
- emailVerified: true
1247
- } : void 0,
1248
- metadata: { platform: "slack" }
1249
- };
1250
- case "web": {
1251
- const email = normalizeIdentityEmail(actor.email);
1252
- if (!email) return;
1253
- return {
1254
- kind: "user",
1255
- provider: "junior",
1256
- providerSubjectId: email,
1257
- email,
1258
- emailVerified: true,
1259
- ...actor.fullName ? { displayName: actor.fullName } : void 0,
1260
- metadata: { platform: "web" }
1261
- };
1262
- }
1263
- }
1869
+ async function claimProviderConversationOwner(executor, args) {
1870
+ const ownerId = (await executor.db().insert(juniorConversationBindings).values({
1871
+ ...args,
1872
+ createdAt: /* @__PURE__ */ new Date()
1873
+ }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args);
1874
+ if (!ownerId) throw new Error("Provider conversation binding disappeared during claim");
1875
+ return ownerId;
1264
1876
  }
1265
1877
  /**
1266
- * Return the Identity id for one Actor. Save a Slack or web Identity first.
1267
- * Return undefined only for a web Actor without a verified email.
1878
+ * Bind provider coordinates to a durable conversation unless another
1879
+ * conversation has them. Return whether they belong to this conversation.
1268
1880
  */
1269
- async function resolveActorIdentityId(executor, actor, nowMs = Date.now()) {
1270
- if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
1271
- const key = identityKey(actor);
1272
- return key ? (await upsertIdentity(executor, key, nowMs)).id : void 0;
1273
- }
1274
- /** Save the profile photo on the Identity of one Slack Actor. Null clears it. */
1275
- async function saveActorAvatar(executor, actor, avatarUrl, nowMs = Date.now()) {
1276
- const key = identityKey(actor);
1277
- if (key) await upsertIdentity(executor, {
1278
- ...key,
1279
- avatarUrl
1280
- }, nowMs);
1881
+ async function claimProviderConversation(executor, args) {
1882
+ return await claimProviderConversationOwner(executor, args) === args.conversationId;
1281
1883
  }
1282
- /** Find the stored Identity id for one Actor without writing. */
1283
- async function findActorIdentityId(db, actor) {
1284
- if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
1285
- const key = identityKey(actor);
1286
- if (!key) return;
1287
- return (await db.select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, key.provider), eq(juniorIdentities.providerTenantId, key.providerTenantId ?? ""), eq(juniorIdentities.providerSubjectId, key.providerSubjectId))).limit(1))[0]?.id;
1884
+ /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
1885
+ async function bindProviderConversation(executor, args) {
1886
+ if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
1288
1887
  }
1289
1888
  // src/chat/conversations/sql/actor-identity.ts
1290
1889
  /**
@@ -1460,56 +2059,6 @@ async function startLocationThread(executor, binding) {
1460
2059
  detailVersion: nextDetailVersion
1461
2060
  }).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'`)));
1462
2061
  }
1463
- // src/chat/conversations/sql/conversation-row.ts
1464
- /**
1465
- * Establish the conversation metadata row on first contact for content writes
1466
- * (conversation events, visible transcript) that can land before activity has
1467
- * created the row, and whose tables FK to it.
1468
- *
1469
- * First contact creates the row; every later content write advances the
1470
- * activity clock so retention mirrors append-refresh semantics (each content
1471
- * append refreshes the retention window). Background observations may opt out
1472
- * and leave an existing row unchanged. The timestamp is content-intrinsic (the
1473
- * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
1474
- * imported historical write — which carries an old timestamp — can never
1475
- * regress `last_activity_at`.
1476
- */
1477
- async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
1478
- const at = new Date(atMs);
1479
- const insert = executor.db().insert(juniorConversations).values({
1480
- conversationId,
1481
- createdAt: at,
1482
- lastActivityAt: at,
1483
- updatedAt: at,
1484
- executionStatus: "idle",
1485
- kind: "root"
1486
- });
1487
- if (options.activity === "preserve") {
1488
- await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
1489
- return;
1490
- }
1491
- await insert.onConflictDoUpdate({
1492
- target: juniorConversations.conversationId,
1493
- set: {
1494
- lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
1495
- updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
1496
- transcriptPurgedAt: null,
1497
- detailVersion: nextDetailVersion
1498
- }
1499
- });
1500
- }
1501
- const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
1502
- "root",
1503
- "automation",
1504
- "thread",
1505
- "task"
1506
- ]);
1507
- /** Decode a stored kind. A null kind comes from a writer of an older deploy. */
1508
- function conversationKindFromRow(row) {
1509
- const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
1510
- if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
1511
- return kind;
1512
- }
1513
2062
  // src/chat/conversations/kind-behavior.ts
1514
2063
  const ROOT = {
1515
2064
  delivery: "location",
@@ -1519,9 +2068,10 @@ const ROOT = {
1519
2068
  gated: false,
1520
2069
  failureNotice: "none",
1521
2070
  sessionTasks: true,
2071
+ relatedConversations: true,
1522
2072
  tools: {
1523
2073
  agents: "children",
1524
- reviewDesk: true,
2074
+ inbox: true,
1525
2075
  subscriptions: true,
1526
2076
  userCustomization: true,
1527
2077
  reply: "none",
@@ -1529,11 +2079,16 @@ const ROOT = {
1529
2079
  noReply: true
1530
2080
  }
1531
2081
  };
2082
+ const ROOT_RUNTIME_TURN = {
2083
+ ...ROOT,
2084
+ relatedConversations: false
2085
+ };
1532
2086
  const PERSON_IN_THREAD = {
1533
2087
  ...ROOT,
1534
2088
  promptMode: "thread",
1535
2089
  sender: "person",
1536
2090
  sessionTasks: false,
2091
+ relatedConversations: false,
1537
2092
  tools: {
1538
2093
  ...ROOT.tools,
1539
2094
  agents: "none"
@@ -1547,9 +2102,10 @@ const CHILD_AGENT_TURN = {
1547
2102
  gated: true,
1548
2103
  failureNotice: "none",
1549
2104
  sessionTasks: false,
2105
+ relatedConversations: false,
1550
2106
  tools: {
1551
2107
  agents: "children_and_parent",
1552
- reviewDesk: false,
2108
+ inbox: false,
1553
2109
  subscriptions: false,
1554
2110
  userCustomization: false,
1555
2111
  reply: "parent",
@@ -1564,7 +2120,7 @@ const AGENT_IN_THREAD = {
1564
2120
  };
1565
2121
  const THREAD_TOOLS = {
1566
2122
  ...AGENT_IN_THREAD.tools,
1567
- reviewDesk: PERSON_IN_THREAD.tools.reviewDesk,
2123
+ inbox: PERSON_IN_THREAD.tools.inbox,
1568
2124
  subscriptions: PERSON_IN_THREAD.tools.subscriptions,
1569
2125
  userCustomization: PERSON_IN_THREAD.tools.userCustomization
1570
2126
  };
@@ -1582,6 +2138,7 @@ const AUTOMATION_RUN = {
1582
2138
  gated: true,
1583
2139
  failureNotice: "none",
1584
2140
  sessionTasks: true,
2141
+ relatedConversations: false,
1585
2142
  tools: {
1586
2143
  ...ROOT.tools,
1587
2144
  reply: "automation",
@@ -1591,15 +2148,47 @@ const AUTOMATION_RUN = {
1591
2148
  const PERSON_IN_AUTOMATION = {
1592
2149
  ...ROOT,
1593
2150
  promptMode: "automation",
1594
- sender: "person"
2151
+ sender: "person",
2152
+ relatedConversations: false
2153
+ };
2154
+ const LEAD_TOOLS = [
2155
+ "startConversation",
2156
+ "messageAgent",
2157
+ "searchConversations",
2158
+ "searchConversationEvents",
2159
+ "readConversationEvent",
2160
+ "searchInboxItems",
2161
+ "searchEventTypes",
2162
+ "watchEvents",
2163
+ "watchTimer",
2164
+ "listWatches",
2165
+ "stopWatchingResources",
2166
+ "systemTime",
2167
+ "updateUserCustomization",
2168
+ "noReply"
2169
+ ];
2170
+ const LEAD = {
2171
+ ...ROOT,
2172
+ promptMode: "lead",
2173
+ sessionTasks: false,
2174
+ tools: {
2175
+ ...ROOT.tools,
2176
+ agents: "lead",
2177
+ subscriptions: false,
2178
+ only: LEAD_TOOLS
2179
+ }
1595
2180
  };
1596
2181
  /** Return the behavior of one Turn. */
1597
2182
  function turnBehavior(args) {
1598
- if (args.kind === "root") return ROOT;
1599
- if (args.kind === "automation") return args.personInput ? PERSON_IN_AUTOMATION : AUTOMATION_RUN;
1600
- if (args.kind === "thread") return args.personInput ? PERSON_IN_THREAD : AGENT_IN_THREAD;
1601
- if (!args.personInput) return AGENT_IN_TASK;
1602
- throw new Error("A task Conversation cannot have a person's input");
2183
+ switch (args.kind) {
2184
+ case "root": return args.personInput ? ROOT : ROOT_RUNTIME_TURN;
2185
+ case "automation": return args.personInput ? PERSON_IN_AUTOMATION : AUTOMATION_RUN;
2186
+ case "thread": return args.personInput ? PERSON_IN_THREAD : AGENT_IN_THREAD;
2187
+ case "task":
2188
+ if (!args.personInput) return AGENT_IN_TASK;
2189
+ throw new Error("A task Conversation cannot have a person's input");
2190
+ case "lead": return LEAD;
2191
+ }
1603
2192
  }
1604
2193
  /**
1605
2194
  * Return the tools that every Turn of one Prompt mode lists. A Turn of a mode
@@ -1607,19 +2196,69 @@ function turnBehavior(args) {
1607
2196
  * cannot use are disabled.
1608
2197
  */
1609
2198
  function promptModeTurnTools(mode) {
1610
- if (mode === "automation") return AUTOMATION_RUN.tools;
1611
- if (mode === "child_agent") return AGENT_IN_TASK.tools;
1612
- if (mode === "thread") return THREAD_TOOLS;
1613
- return ROOT.tools;
2199
+ switch (mode) {
2200
+ case "automation": return AUTOMATION_RUN.tools;
2201
+ case "child_agent": return AGENT_IN_TASK.tools;
2202
+ case "thread": return THREAD_TOOLS;
2203
+ case "conversation": return ROOT.tools;
2204
+ case "lead": return LEAD.tools;
2205
+ }
2206
+ }
2207
+ /**
2208
+ * Return whether Turns update the Conversation metadata of this kind. Only
2209
+ * its parent reads a Task, so a Task has no summary.
2210
+ */
2211
+ function hasConversationMetadata(kind) {
2212
+ return kind !== "task";
1614
2213
  }
1615
2214
  /** Return whether a Conversation of this kind has no parent. */
1616
2215
  function isTopLevelKind(kind) {
1617
- return kind === "root" || kind === "automation";
2216
+ return kind === "root" || kind === "automation" || kind === "lead";
2217
+ }
2218
+ /**
2219
+ * Return whether a Watch on this Conversation would repeat what already
2220
+ * reaches the watcher: a child agent's results and messages go to its parent.
2221
+ */
2222
+ function watchRepeatsChildResults(target, watcherConversationId) {
2223
+ return target.parentConversationId === watcherConversationId;
1618
2224
  }
1619
2225
  /** Return whether a person sent input from this Source. */
1620
2226
  function isPersonInput(source) {
1621
2227
  return source === "web" || source === "slack";
1622
2228
  }
2229
+ /** Narrow a Source to one that a person sent input from. */
2230
+ function isPersonSource(source) {
2231
+ return isPersonInput(source.kind);
2232
+ }
2233
+ /**
2234
+ * Return the chat platform of a Source that a person writes from, or
2235
+ * undefined for a runtime Source, such as an event or an Automation.
2236
+ */
2237
+ function personSourcePlatform(source) {
2238
+ switch (source.kind) {
2239
+ case "slack":
2240
+ case "local":
2241
+ case "web": return source.kind;
2242
+ case "event":
2243
+ case "scheduled_automation":
2244
+ case "event_automation":
2245
+ case "plugin_dispatch":
2246
+ case "agent_invocation": return;
2247
+ }
2248
+ }
2249
+ /** Return a short label that names a Source, such as `slack:T1:C1`. */
2250
+ function sourceLabel(source) {
2251
+ switch (source.kind) {
2252
+ case "slack": return `slack:${source.teamId}:${source.channelId}`;
2253
+ case "web":
2254
+ case "local": return `${source.kind}:${source.conversationId}`;
2255
+ case "event": return `event:${source.namespace}:${source.eventKey}`;
2256
+ case "scheduled_automation":
2257
+ case "event_automation":
2258
+ case "plugin_dispatch":
2259
+ case "agent_invocation": return source.kind;
2260
+ }
2261
+ }
1623
2262
  /**
1624
2263
  * Return whether the runtime delivers the final response of a Slack or
1625
2264
  * dispatch run. Only root Conversations reach these paths, so only an
@@ -1753,6 +2392,7 @@ function conversationFromRow(readRow) {
1753
2392
  },
1754
2393
  kind: conversationKindFromRow(row),
1755
2394
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
2395
+ ...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0,
1756
2396
  ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
1757
2397
  ...destination ? { destination } : void 0,
1758
2398
  ...location ? { location } : void 0,
@@ -1761,6 +2401,7 @@ function conversationFromRow(readRow) {
1761
2401
  ...source ? { source } : void 0,
1762
2402
  ...sessionSource ? { sessionSource } : void 0,
1763
2403
  ...row.title ? { title: row.title } : void 0,
2404
+ ...row.summary ? { summary: row.summary } : void 0,
1764
2405
  ...msFromDate(row.transcriptPurgedAt) !== void 0 ? { transcriptPurgedAtMs: msFromDate(row.transcriptPurgedAt) } : void 0,
1765
2406
  ...msFromDate(row.stoppedAt) !== void 0 ? { stoppedAtMs: msFromDate(row.stoppedAt) } : void 0,
1766
2407
  ...msFromDate(row.deliveryPausedAt) !== void 0 ? { deliveryPausedAtMs: msFromDate(row.deliveryPausedAt) } : void 0,
@@ -2149,19 +2790,15 @@ async function refreshLastMessageAt(executor, conversationId) {
2149
2790
  await db.update(juniorConversations).set({ lastMessageAt: lastMessageAtSql(db) }).where(eq(juniorConversations.conversationId, conversationId));
2150
2791
  }
2151
2792
  // src/chat/conversations/sql/event-actor.ts
2152
- function isRecord(value) {
2153
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2154
- }
2793
+ const authorMetaSchema = z.object({ author: z.object({
2794
+ email: z.string().optional().catch(void 0),
2795
+ fullName: z.string().optional().catch(void 0),
2796
+ isBot: z.boolean().optional().catch(void 0),
2797
+ userId: z.string().optional().catch(void 0),
2798
+ userName: z.string().optional().catch(void 0)
2799
+ }) });
2155
2800
  function readAuthor(meta) {
2156
- if (!isRecord(meta) || !isRecord(meta["author"])) return {};
2157
- const author = meta["author"];
2158
- return {
2159
- ...typeof author["email"] === "string" ? { email: author["email"] } : void 0,
2160
- ...typeof author["fullName"] === "string" ? { fullName: author["fullName"] } : void 0,
2161
- ...typeof author["isBot"] === "boolean" ? { isBot: author["isBot"] } : void 0,
2162
- ...typeof author["userId"] === "string" ? { userId: author["userId"] } : void 0,
2163
- ...typeof author["userName"] === "string" ? { userName: author["userName"] } : void 0
2164
- };
2801
+ return authorMetaSchema.safeParse(meta).data?.author ?? {};
2165
2802
  }
2166
2803
  /** Read the Slack workspace that owns a conversation, when it has one. */
2167
2804
  async function loadConversationSlackTenantId(executor, conversationId) {
@@ -2177,12 +2814,19 @@ async function loadConversationSlackTenantIds(executor, conversationIds) {
2177
2814
  }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(inArray(juniorConversations.conversationId, [...conversationIds]));
2178
2815
  const tenants = /* @__PURE__ */ new Map();
2179
2816
  for (const row of rows) {
2180
- const sessionSource = parseSessionSource(row.sessionSource);
2181
- const tenantId = row.providerTenantId?.trim() || (sessionSource?.kind === "slack" ? sessionSource.teamId : void 0);
2817
+ const tenantId = conversationSlackTenantId(row);
2182
2818
  if (tenantId) tenants.set(row.conversationId, tenantId);
2183
2819
  }
2184
2820
  return tenants;
2185
2821
  }
2822
+ /**
2823
+ * Return the Slack workspace that owns a conversation, from its Destination
2824
+ * tenant or its stored Slack session source.
2825
+ */
2826
+ function conversationSlackTenantId(row) {
2827
+ const sessionSource = parseSessionSource(row.sessionSource);
2828
+ return row.providerTenantId?.trim() || (sessionSource?.kind === "slack" ? sessionSource.teamId : void 0);
2829
+ }
2186
2830
  async function findIdentityIdByProviderSubject(executor, args) {
2187
2831
  return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerSubjectId, args.providerSubjectId), args.providerTenantId === void 0 ? void 0 : eq(juniorIdentities.providerTenantId, args.providerTenantId))).limit(1))[0]?.id;
2188
2832
  }
@@ -2276,13 +2920,15 @@ async function readConversationTrees(db, rootConversationIds) {
2276
2920
  archivedAt: juniorConversations.archivedAt,
2277
2921
  conversationId: juniorConversations.conversationId,
2278
2922
  kind: juniorConversations.kind,
2279
- parentConversationId: juniorConversations.parentConversationId
2923
+ parentConversationId: juniorConversations.parentConversationId,
2924
+ rootConversationId: juniorConversations.rootConversationId
2280
2925
  }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
2281
2926
  return new Map(rows.map((row) => [row.conversationId, {
2282
2927
  archivedAt: row.archivedAt,
2283
2928
  conversationId: row.conversationId,
2284
2929
  kind: conversationKindFromRow(row),
2285
- ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
2930
+ ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
2931
+ ...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0
2286
2932
  }]));
2287
2933
  }
2288
2934
  /** List the ancestors of one Conversation, nearest first, root last. */
@@ -2685,7 +3331,8 @@ var SqlConversationEventStore = class {
2685
3331
  await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(insertFromEvent(conversationId, cursor.nextSeq, historyVersion, parsed));
2686
3332
  return {
2687
3333
  status: "replaced",
2688
- historyVersion
3334
+ historyVersion,
3335
+ seq: cursor.nextSeq
2689
3336
  };
2690
3337
  });
2691
3338
  }
@@ -2733,6 +3380,11 @@ var SqlConversationEventStore = class {
2733
3380
  async loadEventsOfType(conversationId, type) {
2734
3381
  return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
2735
3382
  }
3383
+ async loadCurrentEventsOfType(conversationId, type) {
3384
+ const db = this.executor.db();
3385
+ const currentHistoryVersion = db.select({ historyVersion: sql`max(${juniorConversationEvents.historyVersion})` }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
3386
+ return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersion), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
3387
+ }
2736
3388
  async query(conversationId, query) {
2737
3389
  if (query.limit < 1) throw new Error("Conversation event query limit must be at least 1");
2738
3390
  if (query.afterSeq !== void 0 && query.beforeSeq !== void 0 && query.afterSeq >= query.beforeSeq) return {
@@ -2954,4 +3606,4 @@ async function closeDb() {
2954
3606
  current = void 0;
2955
3607
  await previous?.db.close();
2956
3608
  }
2957
- export { disconnectStateAdapter as $, turnBehavior as A, requireSlackDestination as At, deleteProviderIdentityForUser as B, withConversationMutationLock as C, resolveRootConversationId as Ct, isTopLevelKind as D, touchConversationDetail as Dt, isPersonInput as E, nextDetailVersion as Et, SYSTEM_IDENTITY_ID as F, readUserTimezone as G, findSlackUserByPrimaryEmail as H, findActorIdentityId as I, upsertLinkedIdentity as J, recordGoogleSignIn as K, resolveActorIdentityId as L, locationFromRow as M, setFirstConversationLocation as N, postsRunNotices as O, createSlackDestination as Ot, startLocationThread as P, createCache as Q, saveActorAvatar as R, createSqlStore as S, hasAgentTurnUsage as St, dispatchInstructionsInvokeSkills as T, conversationDetailTouch as Tt, findUserByVerifiedEmails as U, findLinkedSlackUser as V, linkedSlackUser as W, readCachedUserByEmail as X, clearCachedUser as Y, cacheKeyPrefix as Z, readConversationTrees as _, conversationUsageCostExpr as _t, getConversationStore as a, acquireActiveLock as at, lastMessageAtSql as b, agentTurnTotalTokens as bt, hasAnnotationKey as c, claimProviderConversation as ct, eventFromRow as d, conversationCostOf as dt, getDefaultRedisStateAdapterFor as et, copyMessageLinks as f, microUsdSql as ft, conversationDescendants as g, conversationRangeColumns as gt, conversationAncestors as h, conversationAggregateColumns as ht, getConversationMessageSearchStore as i, MUTATION_LOCK_TTL_MS as it, conversationKindFromRow as j, sameDestination as jt, promptModeTurnTools as k, parseDestination as kt, treeHasAnnotationKey as l, getConversationIdByProviderConversation as lt, withConversationEventLock as m, usdToMicroUsd as mt, db_exports as n, getStateValues as nt, getDb as o, fenceLock as ot, deleteMessageLinks as p, microUsdToUsd as pt, saveUserTimezone as q, getConversationEventStore as r, setStateValues as rt, getSqlExecutor as s, withLock as st, closeDb as t, getStateAdapter as tt, createSqlConversationEventStore as u, parseSessionSource as ut, setArchivedAt as v, addAgentTurnUsage as vt, deliversFinalText as w, rootConversationIsArchived as wt, userMessageQueries as x, agentTurnUsageSchema as xt, loadConversationSlackTenantIds as y, agentTurnCostUsd as yt, deleteProviderIdentityForSlackUser as z };
3609
+ export { conversationWaitsOnUserSql as $, resolveActorIdentityId as $t, isTopLevelKind as A, agentTurnTotalTokens as An, activeParticipantUserIds as At, claimProviderConversation as B, requireSlackDestination as Bn, readIdentityByIdFromSql as Bt, createSqlStore as C, conversationIsNotUnsubscribedRoot as Cn, isOnlyAssignee as Ct, hasConversationMetadata as D, viewerMarksFromParticipant as Dn, requireInboxItemAssignees as Dt, dispatchInstructionsInvokeSkills as E, rootVisibleToViewer as En, readInboxItemAgentScope as Et, turnBehavior as F, conversationDetailTouch as Fn, findUserByEmailFromSql as Ft, microUsdToUsd as G, hasUserPhoto as Gt, parseSessionSource as H, resolveViewerUser as Ht, watchRepeatsChildResults as I, nextDetailVersion as In, listAdminUsersFromSql as It, conversationRangeColumns as J, readAvatarFetch as Jt, usdToMicroUsd as K, identityAvatarUrl as Kt, locationFromRow as L, touchConversationDetail as Ln, readActorIdentity as Lt, postsRunNotices as M, hasAgentTurnUsage as Mn, resolveAssignee as Mt, promptModeTurnTools as N, resolveRootConversationId as Nn, resolveAssignees as Nt, isPersonInput as O, addAgentTurnUsage as On, requireInboxItemLinks as Ot, sourceLabel as P, rootConversationIsArchived as Pn, findUserByEmail as Pt, conversationTurnFailedSql as Q, SYSTEM_IDENTITY_ID as Qt, setFirstConversationLocation as R, createSlackDestination as Rn, readActorIdentityFromSql as Rt, userMessageQueries as S, conversationIsMemberRoot as Sn, isAutomationAlertItem as St, deliversFinalText as T, readMemberParticipants as Tn, itemNeedsUser as Tt, conversationCostOf as U, setUserAdminFromSql as Ut, getConversationIdByProviderConversation as V, sameDestination as Vn, readViewerAvatarUrl as Vt, microUsdSql as W, updateViewerDisplayName as Wt, conversationIsActiveSql as X, userAvatarUrlsFromIdentities as Xt, conversationUsageCostExpr as Y, readUserAvatarUrls as Yt, conversationStatusSql as Z, userAvatarUrlsFromJoinedPhotos as Zt, readConversationTrees as _, conversationAccessFromRows as _n, inboxItemOwnedByConversation as _t, getConversationStore as a, findUserByVerifiedEmails as an, AUTOMATION_INBOX_ITEM_KEY_PREFIX as at, loadConversationSlackTenantIds as b, readConversationAccessRows as bn, inboxItemReaderForUserInConversation as bt, hasAnnotationKey as c, recordGoogleSignIn as cn, canAgentChangeInboxItem as ct, eventFromRow as d, readCachedUserByEmail as dn, inboxItemAssignedTo as dt, saveActorAvatar as en, executionIsActive as et, copyMessageLinks as f, ToolInputError as fn, inboxItemForUser as ft, conversationDescendants as g, canReadConversation as gn, inboxItemNeedsUser as gt, conversationAncestors as h, canAddConversationMessages as hn, inboxItemNeedsSomeone as ht, getConversationMessageSearchStore as i, findSlackUserByPrimaryEmail as in, treeAwaitsAuthorization as it, personSourcePlatform as j, agentTurnUsageSchema as jn, automationCreatorUserId as jt, isPersonSource as k, agentTurnCostUsd as kn, EVERYONE_ASSIGNEE as kt, treeHasAnnotationKey as l, saveUserTimezone as ln, canReadInboxItem as lt, withConversationEventLock as m, canAccessConversation as mn, inboxItemNeedsInput as mt, db_exports as n, deleteProviderIdentityForUser as nn, conversationKindSql as nt, getDb as o, linkedSlackUser as on, PLUGIN_INBOX_ITEM_KEY_PREFIX as ot, deleteMessageLinks as p, isToolInputError as pn, inboxItemLinkedTo as pt, conversationAggregateColumns as q, parseAvatarUrl as qt, getConversationEventStore as r, findLinkedSlackUser as rn, awaitsAuthorizationFrom as rt, getSqlExecutor as s, readUserTimezone as sn, canActOnInboxItem as st, closeDb as t, deleteProviderIdentityForSlackUser as tn, conversationKindFromRow as tt, createSqlConversationEventStore as u, upsertLinkedIdentity as un, canUserReadInboxItem as ut, setArchivedAt as v, createConversationAccessReader as vn, inboxItemPlugin as vt, withConversationMutationLock as w, conversationPinnedForUser as wn, isPluginInboxItem as wt, lastMessageAtSql as x, readableSlackTeamId as xn, inboxItemVisibleTo as xt, conversationSlackTenantId as y, readConversationAccessFromSql as yn, inboxItemReaderForUser as yt, startLocationThread as z, parseDestination as zn, readIdentityById as zt };