@sentry/junior 0.203.0 → 0.205.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 (174) hide show
  1. package/dist/agent-D4nu8MQV.js +17521 -0
  2. package/dist/agent-hooks-DXHpTJ4m.js +4042 -0
  3. package/dist/agent-runner-C04colea.js +678 -0
  4. package/dist/api/schema.d.ts +2736 -2639
  5. package/dist/api/schema.js +4 -169
  6. package/dist/api.d.ts +23 -17
  7. package/dist/api.js +3881 -5326
  8. package/dist/app-Cb776lL8.d.ts +247 -0
  9. package/dist/app.d.ts +4 -520
  10. package/dist/app.js +9524 -11875
  11. package/dist/auth-pause-state-C2P3guS1.js +168 -0
  12. package/dist/catalog-runtime-CXw3asJD.js +7 -0
  13. package/dist/checkpoint-CrViJ8Ps.js +2450 -0
  14. package/dist/cli/chat.d.ts +20 -0
  15. package/dist/cli/chat.js +229 -336
  16. package/dist/cli/check.d.ts +8 -0
  17. package/dist/cli/check.js +513 -806
  18. package/dist/cli/env.d.ts +13 -0
  19. package/dist/cli/env.js +63 -12
  20. package/dist/cli/init.d.ts +3 -0
  21. package/dist/cli/init.js +90 -159
  22. package/dist/cli/main.d.ts +6 -0
  23. package/dist/cli/main.js +43 -64
  24. package/dist/cli/plugins.d.ts +13 -0
  25. package/dist/cli/plugins.js +148 -227
  26. package/dist/cli/run.d.ts +16 -0
  27. package/dist/cli/run.js +52 -8
  28. package/dist/cli/snapshot-create.d.ts +4 -0
  29. package/dist/cli/snapshot-create.js +71 -125
  30. package/dist/cli/upgrade.d.ts +15 -0
  31. package/dist/cli/upgrade.js +232 -335
  32. package/dist/config-BOtJQ7Pc.js +941 -0
  33. package/dist/context-B45_WqVX.js +298 -0
  34. package/dist/conversation-privacy-BZRA6Pes.js +182 -0
  35. package/dist/conversation-work-C6y3T5Hx.js +51 -0
  36. package/dist/credential-sync-Bep34IB_.js +2661 -0
  37. package/dist/db-BeyXKJOI.d.ts +5 -0
  38. package/dist/destinations-BeBiJeEM.js +29 -0
  39. package/dist/execution-stats-B6lgWxCK.js +373 -0
  40. package/dist/executor-BlUhFL7_.js +721 -0
  41. package/dist/experimental-CIXf7Uye.js +46 -0
  42. package/dist/history-ClE4toxe.d.ts +32 -0
  43. package/dist/history-CqTuSAdI.js +441 -0
  44. package/dist/instrumentation.d.ts +3 -3
  45. package/dist/instrumentation.js +130 -176
  46. package/dist/job-queue-DLMqIK74.js +63 -0
  47. package/dist/logging-BMJzdDlP.js +1210 -0
  48. package/dist/model-profile-CZmVoGdX.js +49 -0
  49. package/dist/nitro.d.ts +31 -36
  50. package/dist/nitro.js +275 -456
  51. package/dist/oauth-callback-server-WwG5_Zgm.js +130 -0
  52. package/dist/oauth-relay-CdCnu80W.js +62 -0
  53. package/dist/package-discovery-7a9YqLhE.js +455 -0
  54. package/dist/pending-auth-CUbXq06G.js +185 -0
  55. package/dist/plugin-module-BKGOXca2.js +81 -0
  56. package/dist/plugins-BI9A1vKA.d.ts +95 -0
  57. package/dist/plugins-egKWjgue.js +99 -0
  58. package/dist/private-trace-result-BLvBjy_e.js +16 -0
  59. package/dist/profile-T0tXE4zu.js +861 -0
  60. package/dist/registry-BA0__8ai.js +1419 -0
  61. package/dist/reporting-schema-DosTN__Q.js +105 -0
  62. package/dist/resolve-bvD1ORdv.js +546 -0
  63. package/dist/rolldown-runtime-B4FMCO8f.js +28 -0
  64. package/dist/runner-BXYxfIUL.js +392 -0
  65. package/dist/sandbox-egress-signals-ngEPjSEW.js +46 -0
  66. package/dist/schema-Rn8-XEaN.js +1140 -0
  67. package/dist/sentry-CD3SdJl-.js +26 -0
  68. package/dist/skills-DJOlYdBs.js +316 -0
  69. package/dist/spawn-h0R1bTEo.js +29 -0
  70. package/dist/stats-3YZn-Swi.js +2648 -0
  71. package/dist/store-C5qxF2ac.d.ts +208 -0
  72. package/dist/task-queue-CoXwd2eq.js +136 -0
  73. package/dist/task-runner-B2_mJZj0.js +639 -0
  74. package/dist/thread-state-CqZ1m-es.js +431 -0
  75. package/dist/turn-execution-fI6PZ0iI.js +47 -0
  76. package/dist/turn-lifecycle-CcnwrOcp.js +54 -0
  77. package/dist/usage-B5SfMb3H.js +296 -0
  78. package/dist/usage-schema-CKaDkH_j.js +20 -0
  79. package/dist/validation-DfWcvhuS.js +40 -0
  80. package/dist/vercel-queue-DIkVcfK4.js +167 -0
  81. package/dist/vercel.d.ts +6 -6
  82. package/dist/vercel.js +14 -6
  83. package/dist/version-CnXZ614E.d.ts +5 -0
  84. package/dist/version-oD-oPrbO.js +8 -0
  85. package/dist/version.d.ts +2 -4
  86. package/dist/version.js +2 -6
  87. package/dist/web-authorization-Crbzlmzo.js +76 -0
  88. package/dist/web-input-BOuq3oKK.js +494 -0
  89. package/dist/work-B91LQKHr.js +509 -0
  90. package/dist/worker-BcRRTe6k.js +625 -0
  91. package/package.json +9 -9
  92. package/dist/agent-hooks-GB2VPTNA.js +0 -51
  93. package/dist/catalog-runtime-UBLIWD3O.js +0 -14
  94. package/dist/chunk-2LYHWMR4.js +0 -46
  95. package/dist/chunk-352OWAZH.js +0 -320
  96. package/dist/chunk-3Y47VMHV.js +0 -6
  97. package/dist/chunk-3YJSKOWF.js +0 -164
  98. package/dist/chunk-4KSSKTQ5.js +0 -229
  99. package/dist/chunk-4UO6FK4G.js +0 -64
  100. package/dist/chunk-5AHX53NQ.js +0 -717
  101. package/dist/chunk-5J3E5FWA.js +0 -700
  102. package/dist/chunk-5PDAG6O3.js +0 -206
  103. package/dist/chunk-6Y5B5PEX.js +0 -80
  104. package/dist/chunk-7GWQ5S5R.js +0 -2086
  105. package/dist/chunk-7H2VZTWN.js +0 -103
  106. package/dist/chunk-7NL7T6VU.js +0 -406
  107. package/dist/chunk-A5L27LE4.js +0 -387
  108. package/dist/chunk-ADIAWL34.js +0 -81
  109. package/dist/chunk-ASTEMBKJ.js +0 -519
  110. package/dist/chunk-CEMMLV5L.js +0 -98
  111. package/dist/chunk-CM5HNV2W.js +0 -131
  112. package/dist/chunk-CRTRBBRI.js +0 -105
  113. package/dist/chunk-DA2KGZZI.js +0 -13
  114. package/dist/chunk-DIB4GX3G.js +0 -8
  115. package/dist/chunk-DKIJ2RP5.js +0 -68
  116. package/dist/chunk-DWPN6SCH.js +0 -172
  117. package/dist/chunk-EDKUFGPL.js +0 -64
  118. package/dist/chunk-ENY6SKIU.js +0 -1228
  119. package/dist/chunk-F4MGCZOX.js +0 -2943
  120. package/dist/chunk-FA6POGLH.js +0 -70
  121. package/dist/chunk-FSUR7GTG.js +0 -20475
  122. package/dist/chunk-GKEOHJL5.js +0 -1856
  123. package/dist/chunk-GMCB6W5Y.js +0 -333
  124. package/dist/chunk-IE2VPG7O.js +0 -1135
  125. package/dist/chunk-IZ5B5IHQ.js +0 -3656
  126. package/dist/chunk-JAL3CH4G.js +0 -27
  127. package/dist/chunk-KIIEUXD3.js +0 -1764
  128. package/dist/chunk-KXU4NIL7.js +0 -692
  129. package/dist/chunk-MTM5IFCY.js +0 -1190
  130. package/dist/chunk-N7TMSOZH.js +0 -235
  131. package/dist/chunk-NCEBK6PH.js +0 -36
  132. package/dist/chunk-NHJU2ZAL.js +0 -56
  133. package/dist/chunk-P6KTRNVC.js +0 -321
  134. package/dist/chunk-PDO5BLNM.js +0 -22
  135. package/dist/chunk-PDRNLLFT.js +0 -3295
  136. package/dist/chunk-PEQXYSSE.js +0 -45
  137. package/dist/chunk-PKEX2AQX.js +0 -198
  138. package/dist/chunk-PSJCGIGO.js +0 -1163
  139. package/dist/chunk-PZUSUL55.js +0 -506
  140. package/dist/chunk-R45M4TUS.js +0 -37
  141. package/dist/chunk-RC745GGZ.js +0 -122
  142. package/dist/chunk-SP3QKZXJ.js +0 -820
  143. package/dist/chunk-TXKUKMVO.js +0 -417
  144. package/dist/chunk-UE4GPWSD.js +0 -931
  145. package/dist/chunk-UIE3R5XU.js +0 -17
  146. package/dist/chunk-UXPG6ZIN.js +0 -84
  147. package/dist/chunk-VFUK3X5B.js +0 -50
  148. package/dist/chunk-VNMJWREK.js +0 -787
  149. package/dist/chunk-VZ7CSOX2.js +0 -706
  150. package/dist/chunk-WCNQJKFT.js +0 -10
  151. package/dist/chunk-WDZR3QQM.js +0 -135
  152. package/dist/chunk-WLYVJCHV.js +0 -1433
  153. package/dist/chunk-WS7NAFTM.js +0 -1520
  154. package/dist/chunk-X6GDDWQH.js +0 -60
  155. package/dist/chunk-XPDEYNQI.js +0 -102
  156. package/dist/chunk-XRW44VGM.js +0 -58
  157. package/dist/chunk-Y2CM7HXH.js +0 -111
  158. package/dist/chunk-Y7X25LFY.js +0 -15
  159. package/dist/conversation-work-VIOQ5ZF3.js +0 -54
  160. package/dist/db-NGDJV7YH.js +0 -26
  161. package/dist/discovery-DWVDM7UK.js +0 -44
  162. package/dist/experimental-P5FZM4CU.js +0 -12
  163. package/dist/oauth-callback-server-YFY7YEGK.js +0 -243
  164. package/dist/oauth-relay-5XPVRPYB.js +0 -8
  165. package/dist/plugins-YTYJMMJF.js +0 -14
  166. package/dist/runner-ORTNSB2Q.js +0 -522
  167. package/dist/sandbox-egress-signals-FIL7EGPR.js +0 -73
  168. package/dist/sentry-MB3NL3IR.js +0 -42
  169. package/dist/skills-H376WQOH.js +0 -27
  170. package/dist/spawn-T43WHLOS.js +0 -42
  171. package/dist/task-runner-LBZWF32V.js +0 -36
  172. package/dist/validation-REJLRKI6.js +0 -17
  173. package/dist/work-3KJ3RE76.js +0 -51
  174. package/dist/worker-QFEBU72E.js +0 -24
@@ -0,0 +1,4042 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
+ import { _ as completeObject, i as getChatConfig, n as botConfig, o as getSlackBotToken, y as embedTexts } from "./config-BOtJQ7Pc.js";
3
+ import { C as withSpan, P as normalizeIdentityEmail, _ as setSpanAttributes, d as logInfo, f as logWarn, u as logException, v as setSpanStatus } from "./logging-BMJzdDlP.js";
4
+ import { n as defaultModelId } from "./model-profile-CZmVoGdX.js";
5
+ import { _ as parseSlackMessageTs, c as isActorUserId, h as parseSlackTeamId, m as parseSlackChannelReferenceId, u as parseActorUserId } from "./context-B45_WqVX.js";
6
+ import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
7
+ import { C as juniorConversations, S as conversationReadColumns, T as juniorUsers, b as juniorCodeRepositories, g as juniorConversationEvents, h as juniorConversationBindings, i as juniorWorkspaces, m as juniorConversationParticipants, n as juniorSnapshots, r as juniorWorkspaceRepos, t as createJuniorSqlExecutor, v as juniorConversationAnnotations, w as juniorIdentities, y as juniorCodeChanges } from "./executor-BlUhFL7_.js";
8
+ import { c as newConversationEventSchema, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-CqTuSAdI.js";
9
+ import { A as sleep$1, P as SANDBOX_WORKSPACE_ROOT, l as isSandboxMissingError, n as hash, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand } from "./profile-T0tXE4zu.js";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
11
+ import { z } from "zod";
12
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
13
+ import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
14
+ import { codeChangeInputSchema, conversationAnnotationInputSchema, destinationSchema, identitySchema, locationSchema, missingToolAnnotationKeys, normalizeResourceEventIdentifier, pluginResourceEventsSchema, promptContextSchema, promptMessageSchema, resourceEventInputSchema, resourceEventMatchSchema, resourceEventMatches, resourceEventTypeSchema, sourceSchema, stableResourceEventMatchKey, userSchema } from "@sentry/junior-plugin-api";
15
+ import { WebClient } from "@slack/web-api";
16
+ import { Sandbox } from "@vercel/sandbox";
17
+ //#region src/chat/destination.ts
18
+ /** Build Junior's canonical destination from Slack workspace and channel ids. */
19
+ function createSlackDestination(input) {
20
+ const channelId = parseSlackChannelReferenceId(input.channelId);
21
+ const teamId = parseSlackTeamId(input.teamId);
22
+ if (!channelId || !teamId) return;
23
+ return {
24
+ platform: "slack",
25
+ teamId,
26
+ channelId
27
+ };
28
+ }
29
+ /** Parse and validate a serialized destination that crossed a runtime boundary. */
30
+ function parseDestination(value) {
31
+ const parsed = destinationSchema.safeParse(value);
32
+ return parsed.success ? parsed.data : void 0;
33
+ }
34
+ /** Require a Slack destination at a Slack-only runtime boundary. */
35
+ function requireSlackDestination(destination, action) {
36
+ if (destination?.platform === "slack") return destination;
37
+ throw new Error(`${action} requires a Slack destination`);
38
+ }
39
+ /** Compare two destinations without relying on object identity. */
40
+ function sameDestination(left, right) {
41
+ if (left.platform !== right.platform) return false;
42
+ if (left.platform === "local" && right.platform === "local") return left.conversationId === right.conversationId;
43
+ if (left.platform === "slack" && right.platform === "slack") return left.teamId === right.teamId && left.channelId === right.channelId;
44
+ return false;
45
+ }
46
+ //#endregion
47
+ //#region src/chat/identities/sql.ts
48
+ function dateFromMs$1(ms) {
49
+ return new Date(ms);
50
+ }
51
+ function tenantId$1(value) {
52
+ return value ?? "";
53
+ }
54
+ async function upsertUser(executor, args) {
55
+ const id = (await executor.db().insert(juniorUsers).values({
56
+ id: randomUUID(),
57
+ primaryEmail: args.email,
58
+ primaryEmailNormalized: args.emailNormalized,
59
+ displayName: args.displayName ?? null,
60
+ createdAt: dateFromMs$1(args.nowMs),
61
+ updatedAt: dateFromMs$1(args.nowMs)
62
+ }).onConflictDoUpdate({
63
+ target: juniorUsers.primaryEmailNormalized,
64
+ set: {
65
+ displayName: sql`coalesce(${juniorUsers.displayName}, excluded.display_name)`,
66
+ updatedAt: sql`excluded.updated_at`
67
+ }
68
+ }).returning({ id: juniorUsers.id }))[0]?.id;
69
+ if (!id) throw new Error("User identity upsert returned no row");
70
+ return id;
71
+ }
72
+ async function existingIdentity(executor, identity) {
73
+ 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];
74
+ }
75
+ async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
76
+ const emailNormalized = normalizeIdentityEmail(identity.email);
77
+ const email = emailNormalized ? identity.email?.trim() || emailNormalized : void 0;
78
+ const existing = await existingIdentity(executor, identity);
79
+ const userEmailNormalized = existing?.emailVerified && existing.emailNormalized ? existing.emailNormalized : identity.emailVerified ? emailNormalized : void 0;
80
+ const userEmail = existing?.emailVerified && existing.email ? existing.email : email ?? userEmailNormalized;
81
+ const verifiedUserId = identity.kind === "user" && userEmailNormalized ? await upsertUser(executor, {
82
+ email: userEmail ?? userEmailNormalized,
83
+ emailNormalized: userEmailNormalized,
84
+ nowMs,
85
+ ...existing?.displayName || identity.displayName ? { displayName: existing?.displayName ?? identity.displayName } : void 0
86
+ }) : void 0;
87
+ if (existing?.userId && verifiedUserId && existing.userId !== verifiedUserId) throw new Error("Identity verified email conflicts with linked user");
88
+ if (linkedUserId && verifiedUserId && linkedUserId !== verifiedUserId) throw new Error("Linked identity conflicts with verified email user");
89
+ if (existing?.userId && linkedUserId && existing.userId !== linkedUserId) throw new Error("Identity conflicts with linked user");
90
+ const userId = existing?.userId ?? linkedUserId ?? verifiedUserId;
91
+ const row = (await executor.db().insert(juniorIdentities).values({
92
+ id: randomUUID(),
93
+ userId: userId ?? null,
94
+ kind: identity.kind,
95
+ provider: identity.provider,
96
+ providerTenantId: tenantId$1(identity.providerTenantId),
97
+ providerSubjectId: identity.providerSubjectId,
98
+ displayName: identity.displayName ?? null,
99
+ handle: identity.handle ?? null,
100
+ email: email ?? null,
101
+ emailNormalized: emailNormalized ?? null,
102
+ emailVerified: Boolean(identity.emailVerified && emailNormalized),
103
+ avatarUrl: null,
104
+ metadata: identity.metadata ?? null,
105
+ createdAt: dateFromMs$1(nowMs),
106
+ updatedAt: dateFromMs$1(nowMs)
107
+ }).onConflictDoUpdate({
108
+ target: [
109
+ juniorIdentities.provider,
110
+ juniorIdentities.providerTenantId,
111
+ juniorIdentities.providerSubjectId
112
+ ],
113
+ set: {
114
+ kind: sql`excluded.kind`,
115
+ userId: sql`coalesce(${juniorIdentities.userId}, excluded.user_id)`,
116
+ displayName: linkedUserId ? sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})` : sql`coalesce(${juniorIdentities.displayName}, excluded.display_name)`,
117
+ handle: linkedUserId ? sql`coalesce(excluded.handle, ${juniorIdentities.handle})` : sql`coalesce(${juniorIdentities.handle}, excluded.handle)`,
118
+ 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`,
119
+ 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`,
120
+ emailVerified: sql`${juniorIdentities.emailVerified} OR excluded.email_verified`,
121
+ avatarUrl: sql`coalesce(${juniorIdentities.avatarUrl}, excluded.avatar_url)`,
122
+ metadata: sql`coalesce(${juniorIdentities.metadata}, excluded.metadata_json)`,
123
+ updatedAt: sql`excluded.updated_at`
124
+ },
125
+ ...linkedUserId ? { setWhere: sql`${juniorIdentities.userId} IS NULL OR ${juniorIdentities.userId} = excluded.user_id` } : void 0
126
+ }).returning({
127
+ id: juniorIdentities.id,
128
+ userId: juniorIdentities.userId
129
+ }))[0];
130
+ if (!row) {
131
+ if (linkedUserId) throw new Error("Identity conflicts with linked user");
132
+ throw new Error("Identity upsert returned no row");
133
+ }
134
+ return {
135
+ id: row.id,
136
+ ...row.userId ? { userId: row.userId } : void 0
137
+ };
138
+ }
139
+ /** Persist one provider identity observation and link verified emails to users. */
140
+ async function upsertIdentity(executor, identity, nowMs = Date.now()) {
141
+ return await upsertIdentityRecord(executor, identity, void 0, nowMs);
142
+ }
143
+ /**
144
+ * Persist one provider identity after a trusted account-linking flow.
145
+ * Callers must use provider-verified account data, such as GitHub's authenticated
146
+ * user response, never identity claims inferred from content such as Git commits.
147
+ */
148
+ async function upsertLinkedIdentity(executor, userId, identity, nowMs = Date.now()) {
149
+ return await upsertIdentityRecord(executor, identity, userId, nowMs);
150
+ }
151
+ /** Remove one exact provider identity owned by a workspace Slack user. */
152
+ async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUserId, provider, providerSubjectId) {
153
+ 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;
154
+ if (!userId) return;
155
+ await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
156
+ }
157
+ //#endregion
158
+ //#region src/chat/conversations/sql/participants.ts
159
+ /** Resolve the root conversation id that owns personal-feed membership. */
160
+ async function resolveRootConversationId(executor, conversationId) {
161
+ const [row] = await executor.db().select({ rootConversationId: juniorConversations.rootConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
162
+ return row?.rootConversationId ?? conversationId;
163
+ }
164
+ /**
165
+ * Upsert one linked user as a participant on a root conversation.
166
+ * No-ops when the identity is missing, unlinked, or not a user.
167
+ */
168
+ async function recordConversationParticipant(executor, args) {
169
+ const [identity] = await executor.db().select({
170
+ kind: juniorIdentities.kind,
171
+ userId: juniorIdentities.userId
172
+ }).from(juniorIdentities).where(eq(juniorIdentities.id, args.actorIdentityId)).limit(1);
173
+ if (!identity?.userId || identity.kind !== "user") return;
174
+ const rootConversationId = await resolveRootConversationId(executor, args.conversationId);
175
+ const at = new Date(args.atMs);
176
+ await executor.db().insert(juniorConversationParticipants).values({
177
+ userId: identity.userId,
178
+ rootConversationId,
179
+ lastMessageAt: at
180
+ }).onConflictDoUpdate({
181
+ target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
182
+ set: {
183
+ lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`,
184
+ ...args.restoreArchive ? { archivedAt: null } : void 0
185
+ }
186
+ });
187
+ }
188
+ //#endregion
189
+ //#region src/chat/source.ts
190
+ /**
191
+ * Normalize a Turn Source into legacy provider fields stored on a Conversation.
192
+ * System Sources do not contain a Conversation Location.
193
+ */
194
+ function normalizeSessionSource(value) {
195
+ if (!value) return;
196
+ if (value.kind === "local") return {
197
+ kind: "local",
198
+ visibility: value.visibility,
199
+ conversationId: value.conversationId
200
+ };
201
+ if (value.kind === "web") return {
202
+ kind: "web",
203
+ visibility: value.visibility,
204
+ conversationId: value.conversationId
205
+ };
206
+ if (value.kind === "resource_event" || value.kind === "scheduled_task" || value.kind === "event_task" || value.kind === "plugin_dispatch" || value.kind === "agent_invocation") return;
207
+ const threadTs = value.threadTs?.trim();
208
+ return {
209
+ kind: "slack",
210
+ visibility: value.visibility,
211
+ teamId: value.teamId,
212
+ channelId: value.channelId,
213
+ ...threadTs ? { threadTs } : void 0
214
+ };
215
+ }
216
+ /** Parse a serialized Source into legacy provider fields stored on a Conversation. */
217
+ function parseSessionSource(value) {
218
+ const parsed = sourceSchema.safeParse(value);
219
+ return parsed.success ? normalizeSessionSource(parsed.data) : void 0;
220
+ }
221
+ //#endregion
222
+ //#region src/chat/conversations/sql/bindings.ts
223
+ /** Resolve the durable conversation bound to provider-owned coordinates. */
224
+ async function getConversationIdByProviderConversation(executor, args) {
225
+ 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;
226
+ }
227
+ /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
228
+ async function bindProviderConversation(executor, args) {
229
+ if (((await executor.db().insert(juniorConversationBindings).values({
230
+ ...args,
231
+ createdAt: /* @__PURE__ */ new Date()
232
+ }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args)) !== args.conversationId) throw new Error("Provider conversation is already bound to another conversation");
233
+ }
234
+ //#endregion
235
+ //#region src/chat/conversations/sql/actor-identity.ts
236
+ /** Build a durable identity observation from a stored conversation actor. */
237
+ function identityFromActor(actor) {
238
+ if (actor?.slackUserId) return {
239
+ kind: "user",
240
+ provider: "slack",
241
+ providerTenantId: actor.teamId,
242
+ providerSubjectId: actor.slackUserId,
243
+ ...actor.fullName ? { displayName: actor.fullName } : void 0,
244
+ ...actor.slackUserName ? { handle: actor.slackUserName } : void 0,
245
+ ...actor.email ? {
246
+ email: actor.email,
247
+ emailVerified: true
248
+ } : void 0,
249
+ metadata: { platform: "slack" }
250
+ };
251
+ const email = actor?.email?.trim().toLowerCase();
252
+ if (!email) return;
253
+ return {
254
+ kind: "user",
255
+ provider: "junior",
256
+ providerSubjectId: email,
257
+ email,
258
+ emailVerified: true,
259
+ ...actor?.fullName ? { displayName: actor.fullName } : void 0,
260
+ metadata: { platform: "web" }
261
+ };
262
+ }
263
+ /** Build a system identity when a conversation has no user actor. */
264
+ function systemIdentityFromSource(source) {
265
+ if (source === "scheduler") return {
266
+ kind: "system",
267
+ provider: "junior",
268
+ providerSubjectId: "scheduler",
269
+ displayName: "Junior Scheduler"
270
+ };
271
+ if (source === "local") return {
272
+ kind: "system",
273
+ provider: "junior",
274
+ providerSubjectId: "local-cli",
275
+ displayName: "Local CLI"
276
+ };
277
+ if (source === "resource_event") return {
278
+ kind: "system",
279
+ provider: "junior",
280
+ providerSubjectId: "resource-event",
281
+ displayName: "Resource Event"
282
+ };
283
+ }
284
+ /** Prefer the user actor identity, else a source-derived system identity. */
285
+ function actorIdentityForConversation(conversation) {
286
+ return identityFromActor(conversation.actor) ?? systemIdentityFromSource(conversation.source);
287
+ }
288
+ /**
289
+ * Reconstruct a stored actor with the linked user name and identity-scoped
290
+ * provider fields.
291
+ */
292
+ function actorFromIdentityRow(identity, userDisplayName) {
293
+ if (!identity) return;
294
+ const fullName = userDisplayName?.trim() ? userDisplayName : identity.displayName;
295
+ const email = identity.emailNormalized ?? identity.email ?? void 0;
296
+ if (identity.provider === "slack") return {
297
+ ...email ? { email } : void 0,
298
+ ...fullName ? { fullName } : void 0,
299
+ platform: "slack",
300
+ slackUserId: identity.providerSubjectId,
301
+ ...identity.handle ? { slackUserName: identity.handle } : void 0,
302
+ ...identity.providerTenantId ? { teamId: identity.providerTenantId } : void 0
303
+ };
304
+ if (identity.provider === "junior" && email) return {
305
+ email,
306
+ ...fullName ? { fullName } : void 0
307
+ };
308
+ }
309
+ /** Merge later actor observations without replacing a durable Slack subject. */
310
+ function mergeActor(current, next) {
311
+ if (!current) return next;
312
+ if (!next) return current;
313
+ if (current.slackUserId && next.slackUserId && current.slackUserId !== next.slackUserId) return current;
314
+ return {
315
+ ...current,
316
+ ...current.email ?? next.email ? { email: current.email ?? next.email } : void 0,
317
+ ...current.fullName ?? next.fullName ? { fullName: current.fullName ?? next.fullName } : void 0,
318
+ ...current.platform ?? next.platform ? { platform: current.platform ?? next.platform } : void 0,
319
+ ...current.slackUserId ?? next.slackUserId ? { slackUserId: current.slackUserId ?? next.slackUserId } : void 0,
320
+ ...current.slackUserName ?? next.slackUserName ? { slackUserName: current.slackUserName ?? next.slackUserName } : void 0,
321
+ ...current.teamId ?? next.teamId ? { teamId: current.teamId ?? next.teamId } : void 0
322
+ };
323
+ }
324
+ //#endregion
325
+ //#region src/chat/conversations/sql/location.ts
326
+ /** Build the complete Location for one Conversation SQL write. */
327
+ function locationForWrite(args) {
328
+ const location = args.location ? locationSchema.parse(args.location) : void 0;
329
+ const destination = args.destination?.platform === "slack" ? args.destination : void 0;
330
+ const source = args.sessionSource?.kind === "slack" ? args.sessionSource : void 0;
331
+ if (location) {
332
+ if (destination && (location.id !== args.destinationId || location.teamId !== destination.teamId || location.channelId !== destination.channelId) || source && (location.teamId !== source.teamId || location.channelId !== source.channelId)) throw new Error("Conversation Location changed");
333
+ const threadTs = location.threadTs ?? destination?.threadTs ?? source?.threadTs;
334
+ return threadTs === location.threadTs ? location : {
335
+ ...location,
336
+ threadTs
337
+ };
338
+ }
339
+ if (destination && source && (destination.teamId !== source.teamId || destination.channelId !== source.channelId)) throw new Error("Conversation Location does not match its session Source");
340
+ if (!destination || !args.destinationId) return;
341
+ const threadTs = destination.threadTs ?? source?.threadTs;
342
+ return locationSchema.parse({
343
+ id: args.destinationId,
344
+ provider: "slack",
345
+ teamId: destination.teamId,
346
+ channelId: destination.channelId,
347
+ ...threadTs ? { threadTs } : void 0
348
+ });
349
+ }
350
+ /** Read one complete Location from SQL. */
351
+ function locationFromRow(value, row, sessionSource) {
352
+ if (value !== void 0 && value !== null) {
353
+ const location = locationSchema.parse(value);
354
+ const slackSource = !location.threadTs && sessionSource?.kind === "slack" && sessionSource.teamId === location.teamId && sessionSource.channelId === location.channelId ? sessionSource : void 0;
355
+ return slackSource?.threadTs ? {
356
+ ...location,
357
+ threadTs: slackSource.threadTs
358
+ } : location;
359
+ }
360
+ if (!row || row.provider === "local") return;
361
+ if (row.provider !== "slack") throw new Error("Conversation Location provider is not supported");
362
+ const slackSource = sessionSource?.kind === "slack" && sessionSource.teamId === row.providerTenantId && sessionSource.channelId === row.providerDestinationId ? sessionSource : void 0;
363
+ return locationSchema.parse({
364
+ id: row.id,
365
+ provider: "slack",
366
+ teamId: row.providerTenantId,
367
+ channelId: row.providerDestinationId,
368
+ ...slackSource?.threadTs ? { threadTs: slackSource.threadTs } : void 0
369
+ });
370
+ }
371
+ /** Read confirmed visibility from one linked Location row. */
372
+ function visibilityFromLocationRow(row) {
373
+ if (!row) return;
374
+ if (row.visibility === "public" || row.visibility === "private") return row.visibility;
375
+ }
376
+ //#endregion
377
+ //#region src/chat/conversations/sql/store.ts
378
+ const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
379
+ /** Serialize one conversation's durable mutations inside a SQL transaction. */
380
+ async function withConversationMutationLock(executor, conversationId, callback) {
381
+ return await executor.withLock(`${CONVERSATION_MUTATION_LOCK_PREFIX}:${conversationId}`, async () => await executor.transaction(callback));
382
+ }
383
+ function now() {
384
+ return Date.now();
385
+ }
386
+ function dateFromMs(ms) {
387
+ return new Date(ms);
388
+ }
389
+ function msFromDate(value) {
390
+ if (value === null || value === void 0) return;
391
+ return (value instanceof Date ? value : new Date(value)).getTime();
392
+ }
393
+ function requiredMsFromDate(value) {
394
+ const ms = msFromDate(value);
395
+ if (typeof ms !== "number" || Number.isNaN(ms)) throw new Error("Conversation record timestamp is invalid");
396
+ return ms;
397
+ }
398
+ function tenantId(value) {
399
+ return value ?? "";
400
+ }
401
+ function sourceFromValue(value) {
402
+ if (value === "api" || value === "internal" || value === "local" || value === "plugin" || value === "resource_event" || value === "scheduler" || value === "slack" || value === "web") return value;
403
+ }
404
+ function originTypeFromSource(source) {
405
+ return source;
406
+ }
407
+ function localWorkspaceFromConversationId(conversationId) {
408
+ return /^local:([^:]+):/.exec(conversationId)?.[1];
409
+ }
410
+ function destinationUpsertFromDestination(args) {
411
+ const { destination } = args;
412
+ if (!destination) return;
413
+ if (destination.platform === "slack") {
414
+ const channelId = destination.channelId;
415
+ return {
416
+ kind: channelId.startsWith("D") ? "dm" : channelId.startsWith("G") ? "group" : "channel",
417
+ provider: "slack",
418
+ providerTenantId: destination.teamId,
419
+ providerDestinationId: channelId,
420
+ refreshVisibility: args.visibility !== void 0,
421
+ visibility: args.visibility ?? "unknown",
422
+ ...args.channelName ? { displayName: args.channelName } : void 0,
423
+ metadata: { platform: "slack" }
424
+ };
425
+ }
426
+ return {
427
+ kind: "local_conversation",
428
+ provider: "local",
429
+ providerTenantId: localWorkspaceFromConversationId(destination.conversationId) ?? localWorkspaceFromConversationId(args.conversationId ?? ""),
430
+ providerDestinationId: destination.conversationId,
431
+ refreshVisibility: args.visibility !== void 0,
432
+ visibility: args.visibility ?? "direct",
433
+ metadata: { platform: "local" }
434
+ };
435
+ }
436
+ function executionStatusFromValue(value) {
437
+ if (value === "awaiting_resume" || value === "paused") return "paused";
438
+ if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
439
+ throw new Error("Conversation record execution status is invalid");
440
+ }
441
+ function executionStatusToSql(status) {
442
+ return status === "paused" ? "awaiting_resume" : status;
443
+ }
444
+ function destinationFromRow(destination) {
445
+ return parseDestination(destination?.provider === "slack" ? {
446
+ platform: "slack",
447
+ teamId: destination.providerTenantId,
448
+ channelId: destination.providerDestinationId
449
+ } : destination?.provider === "local" ? {
450
+ platform: "local",
451
+ conversationId: destination.providerDestinationId
452
+ } : void 0);
453
+ }
454
+ /** Decode one SQL row and reject invalid durable conversation records. */
455
+ function conversationFromRow(readRow) {
456
+ const row = readRow.conversation;
457
+ const visibility = visibilityFromLocationRow(readRow.destination);
458
+ if (row.schemaVersion !== 1) throw new Error("Conversation record schema version is invalid");
459
+ if (row.destination !== null && readRow.destination === null) throw new Error("Conversation legacy destination is not migrated");
460
+ if (row.actor !== null && readRow.actorIdentity === null) throw new Error("Conversation legacy actor is not migrated");
461
+ const destination = destinationFromRow(readRow.destination);
462
+ const actor = actorFromIdentityRow(readRow.actorIdentity, readRow.actorUserDisplayName);
463
+ if (readRow.destination !== null && !destination) throw new Error("Conversation record destination is invalid");
464
+ const source = row.source === void 0 || row.source === null ? void 0 : sourceFromValue(row.source);
465
+ if (row.source !== void 0 && row.source !== null && !source) throw new Error("Conversation record source is invalid");
466
+ const sessionSource = row.sessionSource === void 0 || row.sessionSource === null ? void 0 : parseSessionSource(row.sessionSource);
467
+ if (row.sessionSource !== void 0 && row.sessionSource !== null && !sessionSource) throw new Error("Conversation record session source is invalid");
468
+ const execution = {
469
+ status: executionStatusFromValue(row.executionStatus),
470
+ lastCheckpointAtMs: msFromDate(row.lastCheckpointAt),
471
+ lastEnqueuedAtMs: msFromDate(row.lastEnqueuedAt),
472
+ ...row.runId ? { runId: row.runId } : void 0,
473
+ updatedAtMs: msFromDate(row.executionUpdatedAt) ?? requiredMsFromDate(row.updatedAt)
474
+ };
475
+ const location = locationFromRow(row.location, readRow.destination, sessionSource);
476
+ return {
477
+ schemaVersion: 1,
478
+ conversationId: row.conversationId,
479
+ createdAtMs: requiredMsFromDate(row.createdAt),
480
+ lastActivityAtMs: requiredMsFromDate(row.lastActivityAt),
481
+ updatedAtMs: requiredMsFromDate(row.updatedAt),
482
+ execution,
483
+ executionMetrics: {
484
+ durationMs: row.executionDurationMs,
485
+ ...row.metricRunId ? { runId: row.metricRunId } : void 0,
486
+ ...row.executionUsage ? { usage: row.executionUsage } : void 0
487
+ },
488
+ ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
489
+ ...destination ? { destination } : void 0,
490
+ ...location ? { location } : void 0,
491
+ ...actor ? { actor } : void 0,
492
+ ...row.channelName ? { channelName: row.channelName } : void 0,
493
+ ...source ? { source } : void 0,
494
+ ...sessionSource ? { sessionSource } : void 0,
495
+ ...row.title ? { title: row.title } : void 0,
496
+ ...msFromDate(row.transcriptPurgedAt) !== void 0 ? { transcriptPurgedAtMs: msFromDate(row.transcriptPurgedAt) } : void 0,
497
+ ...visibility ? { visibility } : void 0
498
+ };
499
+ }
500
+ function emptyConversation(args) {
501
+ return {
502
+ schemaVersion: 1,
503
+ conversationId: args.conversationId,
504
+ createdAtMs: args.nowMs,
505
+ lastActivityAtMs: args.nowMs,
506
+ updatedAtMs: args.nowMs,
507
+ ...args.destination ? { destination: args.destination } : void 0,
508
+ ...args.source ? { source: args.source } : void 0,
509
+ ...args.sessionSource ? { sessionSource: args.sessionSource } : void 0,
510
+ execution: {
511
+ status: "idle",
512
+ updatedAtMs: args.nowMs
513
+ }
514
+ };
515
+ }
516
+ function assertSameConversationDestination(args) {
517
+ if (!args.current || sameDestination(args.current, args.next)) return;
518
+ throw new Error(`Conversation destination changed for ${args.conversationId}`);
519
+ }
520
+ function tokenTotal(usage) {
521
+ if (!usage) return 0;
522
+ if (usage.totalTokens !== void 0) return usage.totalTokens;
523
+ return (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0) + (usage.cachedInputTokens ?? 0) + (usage.cacheCreationTokens ?? 0);
524
+ }
525
+ function updateConversationUsage(args) {
526
+ const usage = { totalTokens: tokenTotal(args.current) - tokenTotal(args.previousExecution) + tokenTotal(args.nextExecution) };
527
+ if (args.current?.reasoningTokens !== void 0 || args.previousExecution?.reasoningTokens !== void 0 || args.nextExecution.reasoningTokens !== void 0) usage.reasoningTokens = (args.current?.reasoningTokens ?? 0) - (args.previousExecution?.reasoningTokens ?? 0) + (args.nextExecution.reasoningTokens ?? 0);
528
+ const costFields = [
529
+ "input",
530
+ "output",
531
+ "cacheRead",
532
+ "cacheWrite",
533
+ "total"
534
+ ];
535
+ const cost = {};
536
+ for (const field of costFields) {
537
+ if (args.current?.cost?.[field] === void 0 && args.previousExecution?.cost?.[field] === void 0 && args.nextExecution.cost?.[field] === void 0) continue;
538
+ cost[field] = Math.round(((args.current?.cost?.[field] ?? 0) - (args.previousExecution?.cost?.[field] ?? 0) + (args.nextExecution.cost?.[field] ?? 0)) * 0xe8d4a51000) / 0xe8d4a51000;
539
+ }
540
+ if (Object.keys(cost).length > 0) usage.cost = cost;
541
+ return usage;
542
+ }
543
+ var SqlStore = class {
544
+ executor;
545
+ constructor(executor) {
546
+ this.executor = executor;
547
+ }
548
+ async getConversationIdByProviderConversation(args) {
549
+ return await getConversationIdByProviderConversation(this.executor, args);
550
+ }
551
+ async bindProviderConversation(args) {
552
+ await bindProviderConversation(this.executor, args);
553
+ }
554
+ async createChild(args) {
555
+ const nowMs = args.nowMs ?? now();
556
+ await this.withConversationMutation(args.parentConversationId, async () => {
557
+ await this.withConversationMutation(args.childConversationId, async () => {
558
+ const existing = await this.get({ conversationId: args.childConversationId });
559
+ if (existing) {
560
+ if (existing.parentConversationId !== args.parentConversationId) throw new Error(`Conversation parent changed for ${args.childConversationId}`);
561
+ return;
562
+ }
563
+ const parent = await this.get({ conversationId: args.parentConversationId });
564
+ if (!parent) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
565
+ if (parent.parentConversationId) throw new Error("Recursive agent delegation is not enabled");
566
+ const child = {
567
+ ...emptyConversation({
568
+ conversationId: args.childConversationId,
569
+ nowMs,
570
+ source: args.source
571
+ }),
572
+ parentConversationId: args.parentConversationId
573
+ };
574
+ await this.upsertConversation({ conversation: child });
575
+ });
576
+ });
577
+ }
578
+ async get(args) {
579
+ const row = await this.readConversationRow(args.conversationId);
580
+ if (!row) return;
581
+ return conversationFromRow(row);
582
+ }
583
+ async recordActivity(args) {
584
+ const nowMs = args.nowMs ?? now();
585
+ const activityAtMs = args.activityAtMs ?? nowMs;
586
+ const sessionSource = normalizeSessionSource(args.sessionSource);
587
+ await this.withConversationMutation(args.conversationId, async () => {
588
+ const existing = await this.get({ conversationId: args.conversationId });
589
+ if (existing && args.destination) assertSameConversationDestination({
590
+ conversationId: args.conversationId,
591
+ current: existing.destination,
592
+ next: args.destination
593
+ });
594
+ const current = existing ?? emptyConversation({
595
+ conversationId: args.conversationId,
596
+ destination: args.destination,
597
+ nowMs,
598
+ source: args.source,
599
+ ...sessionSource ? { sessionSource } : void 0
600
+ });
601
+ const { sessionSource: _persistedSessionSource, visibility: _persistedVisibility, ...currentWithoutPersistedSignals } = current;
602
+ await this.upsertConversation({ conversation: {
603
+ ...currentWithoutPersistedSignals,
604
+ destination: current.destination ?? args.destination,
605
+ source: current.source ?? args.source,
606
+ ...sessionSource ? { sessionSource } : void 0,
607
+ channelName: current.channelName ?? args.channelName,
608
+ actor: mergeActor(current.actor, args.actor),
609
+ title: current.title ?? args.title,
610
+ lastActivityAtMs: Math.max(current.lastActivityAtMs, activityAtMs),
611
+ updatedAtMs: nowMs,
612
+ execution: {
613
+ ...current.execution,
614
+ updatedAtMs: current.execution.updatedAtMs ?? nowMs
615
+ },
616
+ ...args.visibility ? { visibility: args.visibility } : void 0
617
+ } });
618
+ });
619
+ }
620
+ async recordExecution(args) {
621
+ await this.withConversationMutation(args.conversationId, async () => {
622
+ const existingRow = await this.readConversationRow(args.conversationId);
623
+ const existing = existingRow ? conversationFromRow(existingRow) : void 0;
624
+ if (!existing && !args.destination) return;
625
+ const incomingIsFresh = (args.execution.updatedAtMs ?? args.updatedAtMs) >= (existing?.execution.updatedAtMs ?? existing?.updatedAtMs ?? 0);
626
+ const metricRunId = existingRow?.conversation.metricRunId;
627
+ const sameRun = Boolean(metricRunId) && metricRunId === args.execution.runId;
628
+ const execution = incomingIsFresh ? args.execution : existing?.execution ?? args.execution;
629
+ await this.upsertConversation({ conversation: {
630
+ schemaVersion: 1,
631
+ conversationId: args.conversationId,
632
+ createdAtMs: args.createdAtMs,
633
+ lastActivityAtMs: args.lastActivityAtMs,
634
+ updatedAtMs: args.updatedAtMs,
635
+ ...existing?.parentConversationId ? { parentConversationId: existing.parentConversationId } : void 0,
636
+ ...existing?.location ? { location: existing.location } : void 0,
637
+ ...args.channelName ? { channelName: args.channelName } : void 0,
638
+ ...args.destination ? { destination: args.destination } : void 0,
639
+ ...args.actor ? { actor: args.actor } : void 0,
640
+ ...args.source ? { source: args.source } : void 0,
641
+ ...args.title ? { title: args.title } : void 0,
642
+ ...args.visibility ? { visibility: args.visibility } : void 0,
643
+ execution
644
+ } });
645
+ if (incomingIsFresh && args.metrics) {
646
+ const row = existingRow?.conversation;
647
+ const usage = args.metrics.usage ? updateConversationUsage({
648
+ current: row?.usage ?? void 0,
649
+ previousExecution: sameRun ? row?.executionUsage ?? void 0 : void 0,
650
+ nextExecution: args.metrics.usage
651
+ }) : row?.usage ?? void 0;
652
+ await this.executor.db().update(juniorConversations).set({
653
+ durationMs: (row?.durationMs ?? 0) - (sameRun ? row?.executionDurationMs ?? 0 : 0) + args.metrics.durationMs,
654
+ usage: usage ?? null,
655
+ metricRunId: args.execution.runId ?? null,
656
+ executionDurationMs: args.metrics.durationMs,
657
+ executionUsage: args.metrics.usage ?? (sameRun ? row?.executionUsage ?? null : null)
658
+ }).where(eq(juniorConversations.conversationId, args.conversationId));
659
+ }
660
+ });
661
+ }
662
+ async listByActivity(args = {}) {
663
+ const rows = await this.executor.db().select({
664
+ conversation: conversationReadColumns(),
665
+ destination: juniorDestinations,
666
+ actorIdentity: juniorIdentities,
667
+ actorUserDisplayName: juniorUsers.displayName
668
+ }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(isNull(juniorConversations.parentConversationId)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(Math.max(0, args.limit ?? 1e4)).offset(Math.max(0, args.offset ?? 0));
669
+ const conversations = [];
670
+ for (const row of rows) conversations.push(conversationFromRow(row));
671
+ return conversations;
672
+ }
673
+ async getDestinationVisibility(args) {
674
+ const row = (await this.executor.db().select({ visibility: juniorDestinations.visibility }).from(juniorDestinations).where(and(eq(juniorDestinations.provider, args.provider), eq(juniorDestinations.providerTenantId, tenantId(args.providerTenantId)), eq(juniorDestinations.providerDestinationId, args.providerDestinationId))))[0];
675
+ if (!row) return;
676
+ if (row.visibility === "public" || row.visibility === "private") return row.visibility;
677
+ }
678
+ async findSlackDestinationByName(args) {
679
+ const normalized = args.channelName.trim().replace(/^#/, "").toLowerCase();
680
+ if (!normalized) return;
681
+ const rows = await this.executor.db().select({
682
+ channelId: juniorDestinations.providerDestinationId,
683
+ channelName: juniorDestinations.displayName
684
+ }).from(juniorDestinations).where(and(eq(juniorDestinations.provider, "slack"), eq(juniorDestinations.providerTenantId, tenantId(args.teamId)), eq(juniorDestinations.kind, "channel"), sql`lower(ltrim(${juniorDestinations.displayName}, '#')) = ${normalized}`)).limit(2);
685
+ if (rows.length !== 1) return;
686
+ const row = rows[0];
687
+ if (!row?.channelId) return;
688
+ return {
689
+ channelId: row.channelId,
690
+ ...row.channelName ? { channelName: row.channelName } : void 0
691
+ };
692
+ }
693
+ /** Serialize all durable mutations for one conversation inside a SQL transaction. */
694
+ async withConversationMutation(conversationId, callback) {
695
+ return await withConversationMutationLock(this.executor, conversationId, callback);
696
+ }
697
+ async readConversationRow(conversationId) {
698
+ return (await this.executor.db().select({
699
+ conversation: conversationReadColumns(),
700
+ destination: juniorDestinations,
701
+ actorIdentity: juniorIdentities,
702
+ actorUserDisplayName: juniorUsers.displayName
703
+ }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(eq(juniorConversations.conversationId, conversationId)))[0];
704
+ }
705
+ /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
706
+ async upsertConversation(args) {
707
+ const { conversation } = args;
708
+ if (!conversation.parentConversationId && !conversation.destination) {
709
+ if (!await this.get({ conversationId: conversation.conversationId })) throw new Error(`Conversation ${conversation.conversationId} requires a destination at create`);
710
+ }
711
+ const incomingExecutionVersion = sql`coalesce(excluded.execution_updated_at, excluded.updated_at)`;
712
+ const currentExecutionVersion = sql`coalesce(${juniorConversations.executionUpdatedAt}, ${juniorConversations.updatedAt})`;
713
+ const incomingExecutionIsFresh = sql`${incomingExecutionVersion} >= ${currentExecutionVersion}`;
714
+ const destinationId = await this.upsertDestination(destinationUpsertFromDestination({
715
+ channelName: conversation.channelName,
716
+ conversationId: conversation.conversationId,
717
+ destination: conversation.destination,
718
+ ...conversation.visibility ? { visibility: conversation.visibility } : void 0
719
+ }), conversation.updatedAtMs);
720
+ const location = locationForWrite({
721
+ destination: conversation.destination,
722
+ destinationId,
723
+ location: conversation.location,
724
+ sessionSource: conversation.sessionSource
725
+ });
726
+ const actorIdentityObservation = actorIdentityForConversation(conversation);
727
+ const actorIdentity = actorIdentityObservation ? await upsertIdentity(this.executor, actorIdentityObservation, conversation.updatedAtMs) : void 0;
728
+ const rootConversationId = conversation.parentConversationId ? sql`(
729
+ select parent.root_conversation_id
730
+ from junior_conversations parent
731
+ where parent.conversation_id = ${conversation.parentConversationId}
732
+ )` : conversation.conversationId;
733
+ const row = (await this.executor.db().insert(juniorConversations).values({
734
+ conversationId: conversation.conversationId,
735
+ schemaVersion: 1,
736
+ source: conversation.source ?? null,
737
+ sessionSource: conversation.sessionSource ?? null,
738
+ originType: originTypeFromSource(conversation.source) ?? null,
739
+ originId: null,
740
+ originRunId: null,
741
+ location: location ?? null,
742
+ destinationId: destinationId ?? null,
743
+ destination: null,
744
+ actorIdentityId: actorIdentity?.id ?? null,
745
+ creatorIdentityId: null,
746
+ credentialSubjectIdentityId: null,
747
+ actor: null,
748
+ channelName: conversation.channelName ?? null,
749
+ title: conversation.title ?? null,
750
+ createdAt: dateFromMs(conversation.createdAtMs),
751
+ lastActivityAt: dateFromMs(conversation.lastActivityAtMs),
752
+ updatedAt: dateFromMs(conversation.updatedAtMs),
753
+ executionUpdatedAt: conversation.execution.updatedAtMs === void 0 ? null : dateFromMs(conversation.execution.updatedAtMs),
754
+ executionStatus: executionStatusToSql(conversation.execution.status),
755
+ runId: conversation.execution.runId ?? null,
756
+ lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
757
+ lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs),
758
+ parentConversationId: conversation.parentConversationId ?? null,
759
+ rootConversationId
760
+ }).onConflictDoUpdate({
761
+ target: juniorConversations.conversationId,
762
+ set: {
763
+ source: sql`coalesce(${juniorConversations.source}, excluded.source)`,
764
+ sessionSource: sql`coalesce(${juniorConversations.sessionSource}, excluded.source_json)`,
765
+ originType: sql`coalesce(excluded.origin_type, ${juniorConversations.originType})`,
766
+ originId: sql`coalesce(excluded.origin_id, ${juniorConversations.originId})`,
767
+ originRunId: sql`coalesce(excluded.origin_run_id, ${juniorConversations.originRunId})`,
768
+ location: sql`coalesce(excluded.location_json, ${juniorConversations.location})`,
769
+ destinationId: sql`coalesce(excluded.destination_id, ${juniorConversations.destinationId})`,
770
+ actorIdentityId: sql`coalesce(excluded.actor_identity_id, ${juniorConversations.actorIdentityId})`,
771
+ creatorIdentityId: sql`coalesce(excluded.creator_identity_id, ${juniorConversations.creatorIdentityId})`,
772
+ credentialSubjectIdentityId: sql`coalesce(excluded.credential_subject_identity_id, ${juniorConversations.credentialSubjectIdentityId})`,
773
+ channelName: sql`coalesce(excluded.channel_name, ${juniorConversations.channelName})`,
774
+ title: sql`coalesce(excluded.title, ${juniorConversations.title})`,
775
+ createdAt: sql`least(${juniorConversations.createdAt}, excluded.created_at)`,
776
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
777
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
778
+ executionUpdatedAt: sql`case when ${incomingExecutionIsFresh} then excluded.execution_updated_at else ${juniorConversations.executionUpdatedAt} end`,
779
+ executionStatus: sql`case when ${incomingExecutionIsFresh} then excluded.execution_status else ${juniorConversations.executionStatus} end`,
780
+ runId: sql`case when ${incomingExecutionIsFresh} then excluded.run_id else ${juniorConversations.runId} end`,
781
+ lastCheckpointAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_checkpoint_at, ${juniorConversations.lastCheckpointAt}) else ${juniorConversations.lastCheckpointAt} end`,
782
+ lastEnqueuedAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_enqueued_at, ${juniorConversations.lastEnqueuedAt}) else ${juniorConversations.lastEnqueuedAt} end`,
783
+ rootConversationId: sql`coalesce(${juniorConversations.rootConversationId}, excluded.root_conversation_id)`
784
+ }
785
+ }).returning({
786
+ actorIdentityId: juniorConversations.actorIdentityId,
787
+ parentConversationId: juniorConversations.parentConversationId,
788
+ rootConversationId: juniorConversations.rootConversationId
789
+ }))[0];
790
+ if (!row?.rootConversationId) throw new Error("Conversation parent is missing its persisted root");
791
+ if (row.actorIdentityId && row.parentConversationId === null) await recordConversationParticipant(this.executor, {
792
+ actorIdentityId: row.actorIdentityId,
793
+ conversationId: conversation.conversationId,
794
+ atMs: conversation.lastActivityAtMs
795
+ });
796
+ }
797
+ async upsertDestination(destination, nowMs) {
798
+ if (!destination) return;
799
+ const visibilityUpdate = destination.refreshVisibility ? sql`excluded.visibility` : juniorDestinations.visibility;
800
+ return (await this.executor.db().insert(juniorDestinations).values({
801
+ id: randomUUID(),
802
+ provider: destination.provider,
803
+ providerTenantId: tenantId(destination.providerTenantId),
804
+ providerDestinationId: destination.providerDestinationId,
805
+ kind: destination.kind,
806
+ parentDestinationId: null,
807
+ displayName: destination.displayName ?? null,
808
+ visibility: destination.visibility,
809
+ metadata: destination.metadata ?? null,
810
+ createdAt: dateFromMs(nowMs),
811
+ updatedAt: dateFromMs(nowMs)
812
+ }).onConflictDoUpdate({
813
+ target: [
814
+ juniorDestinations.provider,
815
+ juniorDestinations.providerTenantId,
816
+ juniorDestinations.providerDestinationId
817
+ ],
818
+ set: {
819
+ kind: sql`excluded.kind`,
820
+ displayName: sql`coalesce(excluded.display_name, ${juniorDestinations.displayName})`,
821
+ visibility: visibilityUpdate,
822
+ metadata: sql`coalesce(excluded.metadata_json, ${juniorDestinations.metadata})`,
823
+ updatedAt: sql`excluded.updated_at`
824
+ }
825
+ }).returning({ id: juniorDestinations.id }))[0]?.id;
826
+ }
827
+ };
828
+ /** Create a SQL-backed conversation store. */
829
+ function createSqlStore(executor) {
830
+ return new SqlStore(executor);
831
+ }
832
+ //#endregion
833
+ //#region src/chat/conversations/sql/conversation-row.ts
834
+ /**
835
+ * Establish the conversation metadata row on first contact for content writes
836
+ * (conversation events, visible transcript) that can land before activity has
837
+ * created the row, and whose tables FK to it.
838
+ *
839
+ * First contact creates the row; every later content write advances the
840
+ * activity clock so retention mirrors append-refresh semantics (each content
841
+ * append refreshes the retention window). Background observations may opt out
842
+ * and leave an existing row unchanged. The timestamp is content-intrinsic (the
843
+ * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
844
+ * imported historical write — which carries an old timestamp — can never
845
+ * regress `last_activity_at`.
846
+ */
847
+ async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
848
+ const at = new Date(atMs);
849
+ const insert = executor.db().insert(juniorConversations).values({
850
+ conversationId,
851
+ createdAt: at,
852
+ lastActivityAt: at,
853
+ updatedAt: at,
854
+ executionStatus: "idle"
855
+ });
856
+ if (options.activity === "preserve") {
857
+ await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
858
+ return;
859
+ }
860
+ await insert.onConflictDoUpdate({
861
+ target: juniorConversations.conversationId,
862
+ set: {
863
+ lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
864
+ updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
865
+ transcriptPurgedAt: null
866
+ }
867
+ });
868
+ }
869
+ //#endregion
870
+ //#region src/chat/conversations/sql/event-actor.ts
871
+ const SLACK_USER_ID_PATTERN = /^[UW][A-Z0-9]{5,}$/;
872
+ function isRecord$1(value) {
873
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
874
+ }
875
+ function readAuthor(meta) {
876
+ if (!isRecord$1(meta) || !isRecord$1(meta.author)) return {};
877
+ const author = meta.author;
878
+ return {
879
+ ...typeof author.email === "string" ? { email: author.email } : void 0,
880
+ ...typeof author.fullName === "string" ? { fullName: author.fullName } : void 0,
881
+ ...typeof author.isBot === "boolean" ? { isBot: author.isBot } : void 0,
882
+ ...typeof author.userId === "string" ? { userId: author.userId } : void 0,
883
+ ...typeof author.userName === "string" ? { userName: author.userName } : void 0
884
+ };
885
+ }
886
+ async function loadConversationSlackTenantId(executor, conversationId) {
887
+ const [row] = await executor.db().select({
888
+ providerTenantId: juniorDestinations.providerTenantId,
889
+ sessionSource: juniorConversations.sessionSource
890
+ }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
891
+ const destinationTenant = row?.providerTenantId?.trim();
892
+ if (destinationTenant) return destinationTenant;
893
+ const sessionSource = parseSessionSource(row?.sessionSource);
894
+ if (sessionSource?.kind === "slack") return sessionSource.teamId;
895
+ }
896
+ async function findIdentityIdByProviderSubject(executor, args) {
897
+ 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;
898
+ }
899
+ async function findJuniorIdentityIdByEmail(executor, email) {
900
+ const normalized = email.trim().toLowerCase();
901
+ if (!normalized) return void 0;
902
+ return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, "junior"), eq(juniorIdentities.kind, "user"), or(eq(juniorIdentities.providerSubjectId, normalized), and(eq(juniorIdentities.emailNormalized, normalized), eq(juniorIdentities.emailVerified, true))))).limit(1))[0]?.id;
903
+ }
904
+ /**
905
+ * Resolve a dashboard:<hash> author against junior identities keyed by email.
906
+ * Web actors store userId as dashboard:${sha256(email).slice(0,24)} while the
907
+ * durable identity subject remains the verified email.
908
+ */
909
+ async function findJuniorIdentityIdByDashboardAuthorId(executor, dashboardAuthorId) {
910
+ if (!dashboardAuthorId.startsWith("dashboard:")) return;
911
+ return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, "junior"), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.emailVerified, true), sql`${juniorIdentities.emailNormalized} is not null`, sql`concat(
912
+ 'dashboard:',
913
+ left(encode(digest(${juniorIdentities.emailNormalized}, 'sha256'), 'hex'), 24)
914
+ ) = ${dashboardAuthorId}`)).limit(1))[0]?.id;
915
+ }
916
+ /**
917
+ * Resolve the durable actor identity for one event payload.
918
+ * Human user messages get an identity when author data is enough; other events
919
+ * keep a null actor.
920
+ */
921
+ async function resolveEventActorIdentityId(executor, args) {
922
+ const data = args.data;
923
+ if (data.type !== "message" && data.type !== "message_updated") return;
924
+ if (typeof data.authorIdentityId === "string" && data.authorIdentityId) return data.authorIdentityId;
925
+ if (data.role !== "user") return;
926
+ const author = readAuthor(data.meta);
927
+ if (author.isBot === true) return;
928
+ const userId = parseActorUserId(author.userId);
929
+ if (!userId) return;
930
+ if (SLACK_USER_ID_PATTERN.test(userId)) {
931
+ const tenantId = await loadConversationSlackTenantId(executor, args.conversationId);
932
+ const observation = {
933
+ kind: "user",
934
+ provider: "slack",
935
+ providerSubjectId: userId,
936
+ ...tenantId ? { providerTenantId: tenantId } : void 0,
937
+ ...author.fullName ? { displayName: author.fullName } : void 0,
938
+ ...author.userName ? { handle: author.userName } : void 0,
939
+ ...author.email ? {
940
+ email: author.email,
941
+ emailVerified: true
942
+ } : void 0
943
+ };
944
+ if (tenantId) return (await upsertIdentity(executor, observation, args.nowMs)).id;
945
+ return await findIdentityIdByProviderSubject(executor, {
946
+ provider: "slack",
947
+ providerSubjectId: userId
948
+ }) ?? void 0;
949
+ }
950
+ const email = typeof author.email === "string" && author.email.includes("@") ? author.email.trim().toLowerCase() : userId.includes("@") ? userId.trim().toLowerCase() : void 0;
951
+ if (email) return (await upsertIdentity(executor, {
952
+ kind: "user",
953
+ provider: "junior",
954
+ providerSubjectId: email,
955
+ email,
956
+ emailVerified: true,
957
+ ...author.fullName ? { displayName: author.fullName } : void 0,
958
+ metadata: { platform: "web" }
959
+ }, args.nowMs)).id;
960
+ if (userId.startsWith("dashboard:")) return findJuniorIdentityIdByDashboardAuthorId(executor, userId);
961
+ return findJuniorIdentityIdByEmail(executor, userId);
962
+ }
963
+ /** Drop payload-only authorIdentityId after lifting it onto the event column. */
964
+ function stripPayloadAuthorIdentityId(data) {
965
+ if (data.type !== "message" && data.type !== "message_updated" || data.authorIdentityId === void 0) return data;
966
+ const { authorIdentityId: _authorIdentityId, ...rest } = data;
967
+ return rest;
968
+ }
969
+ //#endregion
970
+ //#region src/db/postgres-json.ts
971
+ /**
972
+ * Replace actual NUL characters that PostgreSQL cannot store in JSONB.
973
+ * Literal `\\u0000` text is preserved because it contains no NUL character.
974
+ */
975
+ function sanitizePostgresJson(value) {
976
+ if (typeof value === "string") return value.replaceAll("\0", " ");
977
+ if (Array.isArray(value)) return value.map((item) => sanitizePostgresJson(item));
978
+ if (value === null || typeof value !== "object") return value;
979
+ const prototype = Object.getPrototypeOf(value);
980
+ if (prototype !== Object.prototype && prototype !== null) return value;
981
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
982
+ }
983
+ //#endregion
984
+ //#region src/chat/conversations/sql/event-lock.ts
985
+ /** Serialize event sequence allocation with other conversation writes. */
986
+ async function withConversationEventLock(executor, conversationId, callback) {
987
+ return executor.withLock(`junior_conversation:${conversationId}`, callback);
988
+ }
989
+ //#endregion
990
+ //#region src/chat/conversations/sql/history.ts
991
+ const messageHistoryEventTypes = [
992
+ "message",
993
+ "message_updated",
994
+ "message_handled"
995
+ ];
996
+ const HUMAN_INSTRUCTION_PLATFORMS = /* @__PURE__ */ new Set([
997
+ "slack",
998
+ "local",
999
+ "web"
1000
+ ]);
1001
+ /**
1002
+ * Whether one event should restore an archived conversation to the feed.
1003
+ *
1004
+ * Archive hides finished noise until a human comes back. Resource events,
1005
+ * turn lifecycle, compaction, and other system writes may still refresh
1006
+ * activity clocks, but they must not unarchive on their own.
1007
+ */
1008
+ function eventUnarchivesConversation(data) {
1009
+ if (data.type === "user_message") {
1010
+ const provenance = data.provenance;
1011
+ if (provenance.authority !== "instruction") return false;
1012
+ const platform = provenance.actor?.platform;
1013
+ return platform === void 0 || HUMAN_INSTRUCTION_PLATFORMS.has(platform);
1014
+ }
1015
+ if (data.type !== "message") return false;
1016
+ if (data.role !== "user") return false;
1017
+ const meta = data.meta;
1018
+ if (!meta) return true;
1019
+ if (typeof meta.eventType === "string" && meta.eventType.length > 0) return false;
1020
+ const author = meta.author;
1021
+ if (author && typeof author === "object" && !Array.isArray(author) && author.isBot === true) return false;
1022
+ return true;
1023
+ }
1024
+ /** Split validated event data into column-lifted and JSON payload fields. */
1025
+ function insertFromEvent(conversationId, seq, historyVersion, event, actorIdentityId) {
1026
+ const stripped = stripPayloadAuthorIdentityId(event.data);
1027
+ const { type, ...payload } = conversationEventDataSchema.parse(stripped);
1028
+ return {
1029
+ conversationId,
1030
+ seq,
1031
+ historyVersion,
1032
+ schemaVersion: 1,
1033
+ idempotencyKey: event.idempotencyKey ?? null,
1034
+ type,
1035
+ payload: sanitizePostgresJson(payload),
1036
+ actorIdentityId: actorIdentityId ?? null,
1037
+ createdAt: new Date(event.createdAtMs)
1038
+ };
1039
+ }
1040
+ /** Parse one physical event row into the storage-compatible domain envelope. */
1041
+ function eventFromRow(row) {
1042
+ const payload = row.actorIdentityId && typeof row.payload === "object" && row.payload !== null && !Array.isArray(row.payload) && (row.type === "message" || row.type === "message_updated") && !("authorIdentityId" in row.payload) ? {
1043
+ ...row.payload,
1044
+ authorIdentityId: row.actorIdentityId
1045
+ } : row.payload;
1046
+ return decodeStoredConversationEvent({
1047
+ schemaVersion: row.schemaVersion,
1048
+ seq: row.seq,
1049
+ historyVersion: row.historyVersion,
1050
+ ...row.idempotencyKey ? { idempotencyKey: row.idempotencyKey } : void 0,
1051
+ createdAtMs: row.createdAt.getTime(),
1052
+ type: row.type,
1053
+ payload
1054
+ });
1055
+ }
1056
+ /** Decode the summary row that defines a readable message-history suffix. */
1057
+ function messagesSummarizedEventFromRow(row) {
1058
+ const event = eventFromRow(row);
1059
+ if (event.schemaVersion !== 1 || event.data.type !== "messages_summarized") throw new Error("Message compaction row did not decode as messages_summarized");
1060
+ return {
1061
+ ...event,
1062
+ schemaVersion: 1,
1063
+ data: event.data
1064
+ };
1065
+ }
1066
+ var SqlConversationEventStore = class {
1067
+ executor;
1068
+ constructor(executor) {
1069
+ this.executor = executor;
1070
+ }
1071
+ async append(conversationId, events, options = {}) {
1072
+ const parsed = events.map((event) => newConversationEventSchema.parse(event));
1073
+ if (parsed.length === 0) return [];
1074
+ return withConversationEventLock(this.executor, conversationId, async () => {
1075
+ const existingKeys = parsed.map((event) => event.idempotencyKey).filter((key) => key !== void 0);
1076
+ const persistedKeys = existingKeys.length === 0 ? /* @__PURE__ */ new Set() : new Set((await this.executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, existingKeys)))).flatMap((row) => row.key ? [row.key] : []));
1077
+ const acceptedKeys = new Set(persistedKeys);
1078
+ const pending = parsed.filter((event) => {
1079
+ if (event.idempotencyKey === void 0) return true;
1080
+ if (acceptedKeys.has(event.idempotencyKey)) return false;
1081
+ acceptedKeys.add(event.idempotencyKey);
1082
+ return true;
1083
+ });
1084
+ if (pending.length === 0) return [];
1085
+ const newestCreatedAtMs = Math.max(...pending.map((event) => event.createdAtMs));
1086
+ await ensureConversationRow(this.executor, conversationId, newestCreatedAtMs, options);
1087
+ const cursor = await this.readCursor(conversationId);
1088
+ const historyVersion = cursor.maxHistoryVersion ?? 0;
1089
+ let seq = cursor.nextSeq;
1090
+ const rows = [];
1091
+ for (const event of pending) {
1092
+ const actorIdentityId = await resolveEventActorIdentityId(this.executor, {
1093
+ conversationId,
1094
+ data: event.data,
1095
+ nowMs: event.createdAtMs
1096
+ });
1097
+ rows.push(insertFromEvent(conversationId, seq++, historyVersion, event, actorIdentityId));
1098
+ if (actorIdentityId) await recordConversationParticipant(this.executor, {
1099
+ actorIdentityId,
1100
+ conversationId,
1101
+ atMs: event.createdAtMs,
1102
+ restoreArchive: eventUnarchivesConversation(event.data)
1103
+ });
1104
+ }
1105
+ await this.executor.db().insert(juniorConversationEvents).values(rows);
1106
+ return rows.map((row) => ({
1107
+ seq: row.seq,
1108
+ historyVersion: row.historyVersion
1109
+ }));
1110
+ });
1111
+ }
1112
+ async replaceHistory(conversationId, replacement) {
1113
+ const parsed = historyReplacementSchema.parse(replacement);
1114
+ await withConversationEventLock(this.executor, conversationId, async () => {
1115
+ await ensureConversationRow(this.executor, conversationId, Date.now());
1116
+ const cursor = await this.readCursor(conversationId);
1117
+ const historyVersion = (cursor.maxHistoryVersion ?? 0) + 1;
1118
+ await this.executor.db().insert(juniorConversationEvents).values(insertFromEvent(conversationId, cursor.nextSeq, historyVersion, parsed));
1119
+ });
1120
+ }
1121
+ async loadCurrentHistoryVersion(conversationId) {
1122
+ return (await this.readCursor(conversationId)).maxHistoryVersion ?? 0;
1123
+ }
1124
+ async loadCurrentHistory(conversationId) {
1125
+ const cursor = await this.readCursor(conversationId);
1126
+ if (cursor.maxHistoryVersion === null) return [];
1127
+ return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, cursor.maxHistoryVersion))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1128
+ }
1129
+ async loadByIdempotencyKey(conversationId, idempotencyKey) {
1130
+ const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.idempotencyKey, idempotencyKey))).limit(1);
1131
+ return row ? eventFromRow(row) : void 0;
1132
+ }
1133
+ async loadHistoryContaining(conversationId, seq, throughSeq) {
1134
+ const [boundary] = await this.executor.db().select({ historyVersion: juniorConversationEvents.historyVersion }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, seq))).limit(1);
1135
+ if (!boundary) return void 0;
1136
+ return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, boundary.historyVersion), throughSeq === void 0 ? void 0 : lte(juniorConversationEvents.seq, throughSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1137
+ }
1138
+ async loadLatestStructuredEvent(conversationId, namespace, name) {
1139
+ const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${namespace}`, sql`${juniorConversationEvents.payload}->>'name' = ${name}`)).orderBy(desc(juniorConversationEvents.seq)).limit(1);
1140
+ return row ? eventFromRow(row) : void 0;
1141
+ }
1142
+ async loadLatestInstruction(conversationId) {
1143
+ const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "user_message"), sql`${juniorConversationEvents.payload}->'provenance'->>'authority' = 'instruction'`)).orderBy(desc(juniorConversationEvents.seq)).limit(1);
1144
+ return row ? eventFromRow(row) : void 0;
1145
+ }
1146
+ async loadMessageHistory(conversationId) {
1147
+ const [compactionRow] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "messages_summarized"))).orderBy(desc(juniorConversationEvents.seq)).limit(1);
1148
+ const compaction = compactionRow ? messagesSummarizedEventFromRow(compactionRow) : void 0;
1149
+ const historyFromSeq = compaction?.data.historyFromSeq ?? 0;
1150
+ return {
1151
+ events: (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.type, messageHistoryEventTypes), gte(juniorConversationEvents.seq, historyFromSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow),
1152
+ compaction,
1153
+ historyFromSeq
1154
+ };
1155
+ }
1156
+ async loadHistory(conversationId) {
1157
+ return (await this.executor.db().select().from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId)).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
1158
+ }
1159
+ async query(conversationId, query) {
1160
+ if (query.limit < 1) throw new Error("Conversation event query limit must be at least 1");
1161
+ if (query.afterSeq !== void 0 && query.beforeSeq !== void 0 && query.afterSeq >= query.beforeSeq) return {
1162
+ events: [],
1163
+ hasOlder: false,
1164
+ hasNewer: false
1165
+ };
1166
+ const typeFilter = query.types && query.types.length > 0 ? inArray(juniorConversationEvents.type, [...query.types]) : void 0;
1167
+ const bounds = and(eq(juniorConversationEvents.conversationId, conversationId), query.afterSeq === void 0 ? void 0 : gt(juniorConversationEvents.seq, query.afterSeq), query.beforeSeq === void 0 ? void 0 : lt(juniorConversationEvents.seq, query.beforeSeq), typeFilter);
1168
+ const newestFirst = query.afterSeq === void 0;
1169
+ const rows = await this.executor.db().select().from(juniorConversationEvents).where(bounds).orderBy(newestFirst ? desc(juniorConversationEvents.seq) : asc(juniorConversationEvents.seq)).limit(query.limit + 1);
1170
+ const overflow = rows.length > query.limit;
1171
+ const pageRows = overflow ? rows.slice(0, query.limit) : rows;
1172
+ const events = (newestFirst ? [...pageRows].reverse() : pageRows).map(eventFromRow);
1173
+ if (events.length === 0) return {
1174
+ events,
1175
+ hasOlder: false,
1176
+ hasNewer: false
1177
+ };
1178
+ const firstSeq = events[0].seq;
1179
+ const lastSeq = events[events.length - 1].seq;
1180
+ return {
1181
+ events,
1182
+ hasOlder: newestFirst && overflow ? true : await this.hasMatchingEvent({
1183
+ conversationId,
1184
+ beforeSeq: firstSeq,
1185
+ typeFilter
1186
+ }),
1187
+ hasNewer: !newestFirst && overflow ? true : await this.hasMatchingEvent({
1188
+ conversationId,
1189
+ afterSeq: lastSeq,
1190
+ typeFilter
1191
+ })
1192
+ };
1193
+ }
1194
+ /** Return whether any matching event exists inside the exclusive seq window. */
1195
+ async hasMatchingEvent(args) {
1196
+ if (args.afterSeq !== void 0 && args.beforeSeq !== void 0 && args.afterSeq >= args.beforeSeq) return false;
1197
+ const [row] = await this.executor.db().select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, args.conversationId), args.afterSeq === void 0 ? void 0 : gt(juniorConversationEvents.seq, args.afterSeq), args.beforeSeq === void 0 ? void 0 : lt(juniorConversationEvents.seq, args.beforeSeq), args.typeFilter)).limit(1);
1198
+ return row !== void 0;
1199
+ }
1200
+ /** Read the next sequence and active model-history version. */
1201
+ async readCursor(conversationId) {
1202
+ const rows = await this.executor.db().select({
1203
+ maxSeq: sql`max(${juniorConversationEvents.seq})`,
1204
+ maxHistoryVersion: sql`max(${juniorConversationEvents.historyVersion})`
1205
+ }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
1206
+ const maxSeq = rows[0]?.maxSeq;
1207
+ const maxHistoryVersion = rows[0]?.maxHistoryVersion;
1208
+ return {
1209
+ maxHistoryVersion: maxHistoryVersion === null || maxHistoryVersion === void 0 ? null : Number(maxHistoryVersion),
1210
+ nextSeq: maxSeq === null || maxSeq === void 0 ? 0 : Number(maxSeq) + 1
1211
+ };
1212
+ }
1213
+ };
1214
+ /** Create a SQL-backed canonical conversation event store. */
1215
+ function createSqlConversationEventStore(executor) {
1216
+ return new SqlConversationEventStore(executor);
1217
+ }
1218
+ //#endregion
1219
+ //#region src/chat/conversations/sql/message-search.ts
1220
+ const EXCERPT_WITHOUT_QUERY_CHARS = 240;
1221
+ var SqlConversationMessageSearchStore = class {
1222
+ executor;
1223
+ constructor(executor) {
1224
+ this.executor = executor;
1225
+ }
1226
+ async search(args) {
1227
+ const db = this.executor.db();
1228
+ const query = args.filters.query?.trim() || void 0;
1229
+ const text = sql`${juniorConversationEvents.payload}->>'text'`;
1230
+ const role = sql`${juniorConversationEvents.payload}->>'role'`;
1231
+ const messageId = sql`${juniorConversationEvents.payload}->>'messageId'`;
1232
+ const tsquery = query ? sql`websearch_to_tsquery('english', ${query})` : void 0;
1233
+ const rank = tsquery ? sql`ts_rank_cd(to_tsvector('english', ${text}), ${tsquery})` : sql`1`;
1234
+ const excerpt = tsquery ? sql`ts_headline('english', ${text}, ${tsquery}, 'MaxFragments=2, MinWords=8, MaxWords=40, FragmentDelimiter=" … ", StartSel=**, StopSel=**')` : sql`left(${text}, ${EXCERPT_WITHOUT_QUERY_CHARS})`;
1235
+ const conditions = [
1236
+ eq(juniorConversations.source, "slack"),
1237
+ isNull(juniorConversations.parentConversationId),
1238
+ isNull(juniorConversations.transcriptPurgedAt),
1239
+ ne(juniorConversations.conversationId, args.currentConversationId),
1240
+ eq(juniorDestinations.provider, args.scope.provider),
1241
+ eq(juniorDestinations.providerTenantId, args.scope.providerTenantId),
1242
+ eq(juniorDestinations.visibility, "public"),
1243
+ eq(juniorConversationEvents.type, "message"),
1244
+ sql`${role} in ('user', 'assistant')`
1245
+ ];
1246
+ if (tsquery) conditions.push(sql`to_tsvector('english', ${text}) @@ ${tsquery}`);
1247
+ if (args.filters.channelId) conditions.push(eq(juniorDestinations.providerDestinationId, args.filters.channelId));
1248
+ if (args.filters.afterMs !== void 0 && Number.isFinite(args.filters.afterMs)) conditions.push(gte(juniorConversations.lastActivityAt, new Date(args.filters.afterMs)));
1249
+ if (args.filters.beforeMs !== void 0 && Number.isFinite(args.filters.beforeMs)) conditions.push(lt(juniorConversations.lastActivityAt, new Date(args.filters.beforeMs)));
1250
+ if (args.filters.annotation) {
1251
+ const annotation = args.filters.annotation.toLowerCase();
1252
+ const nestedAnnotationPrefix = `${annotation}#`;
1253
+ conditions.push(sql`exists (
1254
+ select 1
1255
+ from ${juniorConversationAnnotations}
1256
+ where ${and(eq(juniorConversationAnnotations.conversationId, juniorConversations.conversationId), sql`(
1257
+ lower(${juniorConversationAnnotations.key}) = ${annotation}
1258
+ or starts_with(
1259
+ lower(${juniorConversationAnnotations.key}),
1260
+ ${nestedAnnotationPrefix}
1261
+ )
1262
+ )`)}
1263
+ )`);
1264
+ }
1265
+ const bestPerConversation = db.selectDistinctOn([juniorConversations.conversationId], {
1266
+ channelName: juniorDestinations.displayName,
1267
+ conversationId: juniorConversations.conversationId,
1268
+ excerpt: excerpt.as("excerpt"),
1269
+ lastActivityAt: juniorConversations.lastActivityAt,
1270
+ messageCreatedAt: juniorConversationEvents.createdAt,
1271
+ messageId: messageId.as("message_id"),
1272
+ providerDestinationId: juniorDestinations.providerDestinationId,
1273
+ rank: rank.as("rank"),
1274
+ role: role.as("role")
1275
+ }).from(juniorConversationEvents).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorConversationEvents.conversationId)).innerJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(...conditions)).orderBy(juniorConversations.conversationId, desc(rank), desc(juniorConversationEvents.createdAt)).as("best_conversation_matches");
1276
+ return (await db.select().from(bestPerConversation).orderBy(desc(bestPerConversation.rank), desc(bestPerConversation.lastActivityAt), desc(bestPerConversation.messageCreatedAt)).limit(args.limit)).map((row) => ({
1277
+ conversationId: row.conversationId,
1278
+ excerpt: row.excerpt,
1279
+ messageCreatedAtMs: row.messageCreatedAt.getTime(),
1280
+ messageId: row.messageId,
1281
+ providerDestinationId: row.providerDestinationId,
1282
+ role: row.role,
1283
+ ...row.channelName ? { channelName: row.channelName } : void 0
1284
+ }));
1285
+ }
1286
+ };
1287
+ /** Create a SQL-backed public workspace message search store. */
1288
+ function createSqlConversationMessageSearchStore(executor) {
1289
+ return new SqlConversationMessageSearchStore(executor);
1290
+ }
1291
+ //#endregion
1292
+ //#region src/chat/db.ts
1293
+ var db_exports = /* @__PURE__ */ __exportAll({
1294
+ closeDb: () => closeDb,
1295
+ getConversationEventStore: () => getConversationEventStore,
1296
+ getConversationMessageSearchStore: () => getConversationMessageSearchStore,
1297
+ getConversationStore: () => getConversationStore,
1298
+ getDb: () => getDb,
1299
+ getSqlExecutor: () => getSqlExecutor
1300
+ });
1301
+ let current;
1302
+ function createDb(args) {
1303
+ return createJuniorSqlExecutor({
1304
+ connectionString: args.databaseUrl,
1305
+ driver: args.driver,
1306
+ statementTimeoutMs: args.statementTimeoutMs
1307
+ });
1308
+ }
1309
+ /** Return the process SQL executor for SQL-specific queries and transactions. */
1310
+ function getSqlExecutor() {
1311
+ const { sql } = getChatConfig();
1312
+ if (current?.databaseUrl !== sql.databaseUrl || current.driver !== sql.driver || current.statementTimeoutMs !== sql.statementTimeoutMs) {
1313
+ if (current) {
1314
+ const previous = current;
1315
+ current = void 0;
1316
+ previous.db.close().catch(() => void 0);
1317
+ }
1318
+ const db = createDb({
1319
+ databaseUrl: sql.databaseUrl,
1320
+ driver: sql.driver,
1321
+ statementTimeoutMs: sql.statementTimeoutMs
1322
+ });
1323
+ current = {
1324
+ databaseUrl: sql.databaseUrl,
1325
+ driver: sql.driver,
1326
+ statementTimeoutMs: sql.statementTimeoutMs,
1327
+ db,
1328
+ store: createSqlStore(db),
1329
+ eventStore: createSqlConversationEventStore(db),
1330
+ searchStore: createSqlConversationMessageSearchStore(db)
1331
+ };
1332
+ }
1333
+ return current.db;
1334
+ }
1335
+ /** Return the process Drizzle database. */
1336
+ function getDb() {
1337
+ return getSqlExecutor().db();
1338
+ }
1339
+ /** Return the SQL-backed conversation store. */
1340
+ function getConversationStore() {
1341
+ getSqlExecutor();
1342
+ return current.store;
1343
+ }
1344
+ /** Return the canonical SQL-backed conversation event store. */
1345
+ function getConversationEventStore() {
1346
+ getSqlExecutor();
1347
+ return current.eventStore;
1348
+ }
1349
+ /** Return the SQL-backed public provider-tenant conversation search store. */
1350
+ function getConversationMessageSearchStore() {
1351
+ getSqlExecutor();
1352
+ return current.searchStore;
1353
+ }
1354
+ /** Close the process SQL database when it has been opened. */
1355
+ async function closeDb() {
1356
+ const previous = current;
1357
+ current = void 0;
1358
+ await previous?.db.close();
1359
+ }
1360
+ //#endregion
1361
+ //#region src/chat/plugins/annotations.ts
1362
+ function annotationFromRow(row) {
1363
+ const parsed = conversationAnnotationInputSchema.safeParse(row.annotation);
1364
+ if (!parsed.success) return void 0;
1365
+ return {
1366
+ ...parsed.data,
1367
+ plugin: row.plugin,
1368
+ createdAt: row.createdAt.toISOString(),
1369
+ updatedAt: row.updatedAt.toISOString()
1370
+ };
1371
+ }
1372
+ function createPluginAnnotations(args) {
1373
+ return {
1374
+ async upsert(input) {
1375
+ const annotation = conversationAnnotationInputSchema.parse(input);
1376
+ const now = /* @__PURE__ */ new Date();
1377
+ await args.db.insert(juniorConversationAnnotations).values({
1378
+ annotation,
1379
+ conversationId: args.conversationId,
1380
+ createdAt: now,
1381
+ key: annotation.key,
1382
+ kind: annotation.kind,
1383
+ plugin: args.plugin,
1384
+ updatedAt: now
1385
+ }).onConflictDoUpdate({
1386
+ target: [
1387
+ juniorConversationAnnotations.conversationId,
1388
+ juniorConversationAnnotations.plugin,
1389
+ juniorConversationAnnotations.kind,
1390
+ juniorConversationAnnotations.key
1391
+ ],
1392
+ set: {
1393
+ annotation,
1394
+ updatedAt: now
1395
+ }
1396
+ });
1397
+ },
1398
+ async remove(kind, key) {
1399
+ await args.db.delete(juniorConversationAnnotations).where(and(eq(juniorConversationAnnotations.conversationId, args.conversationId), eq(juniorConversationAnnotations.plugin, args.plugin), eq(juniorConversationAnnotations.kind, kind), eq(juniorConversationAnnotations.key, key)));
1400
+ },
1401
+ async list() {
1402
+ return (await listConversationAnnotations(args.db, args.conversationId)).filter((a) => a.plugin === args.plugin);
1403
+ }
1404
+ };
1405
+ }
1406
+ /** Load stored annotations for one conversation, newest update first. */
1407
+ async function listConversationAnnotations(db, conversationId) {
1408
+ return (await listConversationAnnotationsById(db, [conversationId])).get(conversationId) ?? [];
1409
+ }
1410
+ /** Load stored annotations for a bounded set of conversations. */
1411
+ async function listConversationAnnotationsById(db, conversationIds) {
1412
+ const byConversation = /* @__PURE__ */ new Map();
1413
+ if (conversationIds.length === 0) return byConversation;
1414
+ const rows = await db.select().from(juniorConversationAnnotations).where(inArray(juniorConversationAnnotations.conversationId, [...conversationIds])).orderBy(desc(juniorConversationAnnotations.updatedAt));
1415
+ for (const row of rows) {
1416
+ const annotation = annotationFromRow(row);
1417
+ if (!annotation) continue;
1418
+ const current = byConversation.get(row.conversationId);
1419
+ if (current) current.push(annotation);
1420
+ else byConversation.set(row.conversationId, [annotation]);
1421
+ }
1422
+ return byConversation;
1423
+ }
1424
+ //#endregion
1425
+ //#region src/chat/plugins/conversation-events.ts
1426
+ function registeredDefinition(plugin, value) {
1427
+ return plugin.conversationEvents?.find((definition) => definition === value.definition);
1428
+ }
1429
+ /** Keep operation idempotency stable when a registered event schema advances. */
1430
+ function eventIdentityVersion(plugin, definition) {
1431
+ let version = definition.version;
1432
+ for (const candidate of plugin.conversationEvents ?? []) if (candidate.eventName === definition.eventName) version = Math.min(version, candidate.version);
1433
+ return version;
1434
+ }
1435
+ /** Create a conversation-bound writer for one plugin operation. */
1436
+ function createPluginConversationEvents(args) {
1437
+ return { async emit(value) {
1438
+ const definition = registeredDefinition(args.plugin, value);
1439
+ if (!definition) throw new Error(`Plugin "${args.plugin.manifest.name}" cannot emit an unregistered conversation event.`);
1440
+ const content = definition.parse(value.data);
1441
+ const identityVersion = eventIdentityVersion(args.plugin, definition);
1442
+ await getConversationEventStore().append(args.conversationId, [{
1443
+ createdAtMs: Date.now(),
1444
+ idempotencyKey: `plugin:${args.plugin.manifest.name}:operation:${args.operationId}:event:${definition.eventName}@${identityVersion}`,
1445
+ data: {
1446
+ type: "structured_event",
1447
+ namespace: args.plugin.manifest.name,
1448
+ name: definition.eventName,
1449
+ version: definition.version,
1450
+ turnId: args.turnId,
1451
+ content
1452
+ }
1453
+ }], { activity: "preserve" });
1454
+ } };
1455
+ }
1456
+ /** Render a stored plugin event through its currently registered definition. */
1457
+ function renderPluginConversationEvent(args) {
1458
+ const definition = getPlugins().find((candidate) => candidate.manifest.name === args.namespace)?.conversationEvents?.find((candidate) => candidate.eventName === args.name && candidate.version === args.version);
1459
+ if (!definition) return void 0;
1460
+ return definition.renderEvent(definition.parse(args.content));
1461
+ }
1462
+ //#endregion
1463
+ //#region src/chat/plugins/conversation-event-stats.ts
1464
+ const DAY_MS = 864e5;
1465
+ const costRowSchema = z.object({
1466
+ costUsd: z.number().finite().nonnegative(),
1467
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),
1468
+ events: z.number().int().nonnegative()
1469
+ }).strict();
1470
+ function startOfUtcDay(value) {
1471
+ const date = new Date(value);
1472
+ date.setUTCHours(0, 0, 0, 0);
1473
+ return date;
1474
+ }
1475
+ function registeredEventName(plugin, eventName) {
1476
+ if (!plugin.conversationEvents?.some((definition) => definition.eventName === eventName)) throw new TypeError(`Plugin "${plugin.manifest.name}" did not register event "${eventName}"`);
1477
+ return eventName;
1478
+ }
1479
+ /** Create aggregate event-cost reads bound to one plugin's registered namespace. */
1480
+ function createPluginConversationEventStats(plugin, now = Date.now) {
1481
+ return {
1482
+ async costsByHour(input) {
1483
+ const eventName = registeredEventName(plugin, input.eventName);
1484
+ const hourCount = input.hours ?? 24;
1485
+ const end = new Date(now());
1486
+ end.setUTCMinutes(0, 0, 0);
1487
+ const start = /* @__PURE__ */ new Date(end.getTime() - (hourCount - 1) * 60 * 60 * 1e3);
1488
+ const endExclusive = new Date(end.getTime() + 36e5);
1489
+ const date = sql`TO_CHAR(
1490
+ ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
1491
+ 'YYYY-MM-DD"T"HH24'
1492
+ )`;
1493
+ const cost = sql`CASE
1494
+ WHEN jsonb_typeof(${juniorConversationEvents.payload}->'content'->'costUsd') = 'number'
1495
+ THEN (${juniorConversationEvents.payload}->'content'->>'costUsd')::double precision
1496
+ ELSE 0
1497
+ END`;
1498
+ const rows = await getDb().select({
1499
+ costUsd: sql`SUM(${cost})::double precision`.mapWith(Number),
1500
+ date,
1501
+ events: sql`COUNT(*)::integer`.mapWith(Number)
1502
+ }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${plugin.manifest.name}`, sql`${juniorConversationEvents.payload}->>'name' = ${eventName}`, gte(juniorConversationEvents.createdAt, start), lt(juniorConversationEvents.createdAt, endExclusive))).groupBy(date);
1503
+ const byHour = new Map(z.array(costRowSchema).parse(rows).map((row) => [row.date, row]));
1504
+ return Array.from({ length: hourCount }, (_, index) => {
1505
+ const key = new Date(start.getTime() + index * 60 * 60 * 1e3).toISOString().slice(0, 13);
1506
+ return byHour.get(key) ?? {
1507
+ costUsd: 0,
1508
+ date: key,
1509
+ events: 0
1510
+ };
1511
+ });
1512
+ },
1513
+ async costsByDay(input) {
1514
+ const eventName = registeredEventName(plugin, input.eventName);
1515
+ const end = startOfUtcDay(now());
1516
+ const start = /* @__PURE__ */ new Date(end.getTime() - (input.days - 1) * DAY_MS);
1517
+ const endExclusive = new Date(end.getTime() + DAY_MS);
1518
+ const date = sql`TO_CHAR(
1519
+ ${juniorConversationEvents.createdAt} AT TIME ZONE 'UTC',
1520
+ 'YYYY-MM-DD'
1521
+ )`;
1522
+ const cost = sql`CASE
1523
+ WHEN jsonb_typeof(${juniorConversationEvents.payload}->'content'->'costUsd') = 'number'
1524
+ THEN (${juniorConversationEvents.payload}->'content'->>'costUsd')::double precision
1525
+ ELSE 0
1526
+ END`;
1527
+ const rows = await getDb().select({
1528
+ costUsd: sql`SUM(${cost})::double precision`.mapWith(Number),
1529
+ date,
1530
+ events: sql`COUNT(*)::integer`.mapWith(Number)
1531
+ }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${plugin.manifest.name}`, sql`${juniorConversationEvents.payload}->>'name' = ${eventName}`, gte(juniorConversationEvents.createdAt, start), lt(juniorConversationEvents.createdAt, endExclusive))).groupBy(date);
1532
+ const byDate = new Map(z.array(costRowSchema).parse(rows).map((row) => [row.date, row]));
1533
+ return Array.from({ length: input.days }, (_, index) => {
1534
+ const date = new Date(start.getTime() + index * DAY_MS).toISOString().slice(0, 10);
1535
+ return byDate.get(date) ?? {
1536
+ costUsd: 0,
1537
+ date,
1538
+ events: 0
1539
+ };
1540
+ });
1541
+ }
1542
+ };
1543
+ }
1544
+ //#endregion
1545
+ //#region src/chat/plugins/logging.ts
1546
+ /** Create the host logger exposed to plugin hooks. */
1547
+ function createPluginLogger(plugin) {
1548
+ return {
1549
+ info(message, metadata) {
1550
+ logInfo("plugin.log.info", {
1551
+ "app.log.message": message,
1552
+ "app.plugin.name": plugin,
1553
+ ...metadata
1554
+ });
1555
+ },
1556
+ warn(message, metadata) {
1557
+ logWarn("plugin.log.warn", {
1558
+ "app.log.message": message,
1559
+ "app.plugin.name": plugin,
1560
+ ...metadata
1561
+ });
1562
+ },
1563
+ error(message, metadata) {
1564
+ logException(new Error(message), "plugin.log.error", {
1565
+ "app.plugin.name": plugin,
1566
+ ...metadata
1567
+ });
1568
+ }
1569
+ };
1570
+ }
1571
+ //#endregion
1572
+ //#region src/chat/plugins/model.ts
1573
+ /** Create the host-owned structured model capability exposed to plugins. */
1574
+ function createPluginModel(pluginName, options = {}, runtime = {}) {
1575
+ return { async completeObject(input) {
1576
+ const modelId = options.structuredModelId ?? (options.structuredModel === "default" ? defaultModelId(botConfig) : botConfig.fastModelId);
1577
+ const result = await completeObject({
1578
+ modelId,
1579
+ schema: input.schema,
1580
+ prompt: input.prompt,
1581
+ ...input.system !== void 0 ? { system: input.system } : void 0,
1582
+ ...input.maxTokens !== void 0 ? { maxTokens: input.maxTokens } : void 0,
1583
+ signal: runtime.signal,
1584
+ promptName: `${pluginName}.structured_completion`,
1585
+ metadata: {
1586
+ pluginName,
1587
+ pluginModelRole: "structured"
1588
+ }
1589
+ });
1590
+ return {
1591
+ object: result.object,
1592
+ ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0
1593
+ };
1594
+ } };
1595
+ }
1596
+ /** Create the host-owned embedding capability exposed to prompt hooks. */
1597
+ function createPluginEmbedder(pluginName, runtime = {}) {
1598
+ return { async embedTexts(input) {
1599
+ return await embedTexts({
1600
+ modelId: botConfig.embeddingModelId,
1601
+ texts: input.texts,
1602
+ signal: runtime.signal,
1603
+ metadata: {
1604
+ pluginName,
1605
+ pluginModelRole: "embedding"
1606
+ }
1607
+ });
1608
+ } };
1609
+ }
1610
+ //#endregion
1611
+ //#region src/chat/plugins/state.ts
1612
+ const MAX_PLUGIN_STATE_KEY_LENGTH = 512;
1613
+ function hashKeyPart(value) {
1614
+ return createHash("sha256").update(value).digest("hex").slice(0, 32);
1615
+ }
1616
+ function pluginStateKey(plugin, key) {
1617
+ const pluginPrefix = `junior:${plugin}`;
1618
+ if (key === pluginPrefix || key.startsWith(`${pluginPrefix}:`)) return key;
1619
+ return `junior:plugin_state:${hashKeyPart(plugin)}:${hashKeyPart(key)}`;
1620
+ }
1621
+ function validatePluginStateKey(key) {
1622
+ if (!key.trim()) throw new Error("Plugin state key is required");
1623
+ if (key.length > MAX_PLUGIN_STATE_KEY_LENGTH) throw new Error("Plugin state key exceeds the maximum length");
1624
+ }
1625
+ /** Create a durable state namespace scoped to one plugin. */
1626
+ function createPluginState(plugin, adapter) {
1627
+ const getAdapter = () => adapter ?? getStateAdapter();
1628
+ return {
1629
+ async delete(key) {
1630
+ validatePluginStateKey(key);
1631
+ const state = getAdapter();
1632
+ await state.connect();
1633
+ await state.delete(pluginStateKey(plugin, key));
1634
+ },
1635
+ async get(key) {
1636
+ validatePluginStateKey(key);
1637
+ const state = getAdapter();
1638
+ await state.connect();
1639
+ return await state.get(pluginStateKey(plugin, key)) ?? void 0;
1640
+ },
1641
+ async set(key, value, ttlMs) {
1642
+ validatePluginStateKey(key);
1643
+ const state = getAdapter();
1644
+ await state.connect();
1645
+ await state.set(pluginStateKey(plugin, key), value, ttlMs);
1646
+ },
1647
+ async setIfNotExists(key, value, ttlMs) {
1648
+ validatePluginStateKey(key);
1649
+ const state = getAdapter();
1650
+ await state.connect();
1651
+ return await state.setIfNotExists(pluginStateKey(plugin, key), value, ttlMs);
1652
+ },
1653
+ async withLock(key, ttlMs, callback) {
1654
+ validatePluginStateKey(key);
1655
+ const state = getAdapter();
1656
+ await state.connect();
1657
+ const lockKey = pluginStateKey(plugin, key);
1658
+ const lock = await state.acquireLock(lockKey, ttlMs);
1659
+ if (!lock) throw new Error(`Could not acquire plugin state lock for ${key}`);
1660
+ try {
1661
+ return await callback();
1662
+ } finally {
1663
+ await state.releaseLock(lock);
1664
+ }
1665
+ }
1666
+ };
1667
+ }
1668
+ //#endregion
1669
+ //#region src/chat/slack/dashboard-link.ts
1670
+ let dashboardConversationLinkOptions;
1671
+ function withHttps(host) {
1672
+ return /^https?:\/\//.test(host) ? host : `https://${host}`;
1673
+ }
1674
+ function stripTrailingSlashes(value) {
1675
+ let end = value.length;
1676
+ while (end > 1 && value.charCodeAt(end - 1) === 47) end -= 1;
1677
+ return end === value.length ? value : value.slice(0, end);
1678
+ }
1679
+ function normalizeDashboardPath(path, fallback) {
1680
+ const value = path?.trim() || fallback;
1681
+ return stripTrailingSlashes(value.startsWith("/") ? value : `/${value}`);
1682
+ }
1683
+ function resolveDashboardBaseURL(config) {
1684
+ const explicit = config.baseURL ?? process.env.JUNIOR_BASE_URL;
1685
+ if (explicit?.trim()) return stripTrailingSlashes(withHttps(explicit.trim()));
1686
+ const vercelProd = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim();
1687
+ if (vercelProd) return stripTrailingSlashes(withHttps(vercelProd));
1688
+ const vercelUrl = process.env.VERCEL_URL?.trim();
1689
+ if (vercelUrl) return stripTrailingSlashes(withHttps(vercelUrl));
1690
+ return "http://localhost:3000";
1691
+ }
1692
+ /** Configure core dashboard links used in Slack footers. */
1693
+ function setDashboardConversationLinkOptions(options) {
1694
+ const previous = dashboardConversationLinkOptions;
1695
+ dashboardConversationLinkOptions = options?.disabled ? void 0 : options;
1696
+ return previous;
1697
+ }
1698
+ function resolveDashboardPath(segmentPath) {
1699
+ if (!dashboardConversationLinkOptions) return;
1700
+ const baseURL = resolveDashboardBaseURL(dashboardConversationLinkOptions);
1701
+ const basePath = normalizeDashboardPath(dashboardConversationLinkOptions.basePath, "/");
1702
+ return `${baseURL}${basePath === "/" ? segmentPath : `${basePath}${segmentPath}`}`;
1703
+ }
1704
+ /** Build the dashboard conversation URL when the core dashboard is enabled. */
1705
+ function getDashboardConversationLink(conversationId) {
1706
+ return resolveDashboardPath(`/conversations/${encodeURIComponent(conversationId)}`);
1707
+ }
1708
+ /** Build the dashboard task detail URL when the core dashboard is enabled. */
1709
+ function getDashboardTaskLink(taskId) {
1710
+ return resolveDashboardPath(`/tasks/${encodeURIComponent(taskId)}`);
1711
+ }
1712
+ //#endregion
1713
+ //#region src/chat/state/ttl.ts
1714
+ /** Retain expiring conversation/runtime state long enough for resume and dashboard history. */
1715
+ const JUNIOR_THREAD_STATE_TTL_MS = 6048e5;
1716
+ //#endregion
1717
+ //#region src/chat/resource-events/store.ts
1718
+ const RESOURCE_EVENT_PREFIX = "junior:resource_event_subscription:v5";
1719
+ const INDEX_LOCK_TTL_MS = 1e4;
1720
+ const SUBSCRIPTION_LOCK_TTL_MS = 1e4;
1721
+ const SUBSCRIPTION_LOCK_WAIT_MS = 1e4;
1722
+ const SUBSCRIPTION_LOCK_RETRY_MS = 25;
1723
+ const SUBSCRIPTION_LOCK_HEARTBEAT_MS = 3e3;
1724
+ const subscriptionStatusSchema = z.enum([
1725
+ "active",
1726
+ "cancelled",
1727
+ "completed"
1728
+ ]);
1729
+ const subscriptionIdIndexSchema = z.array(z.string().min(1));
1730
+ const subscriptionSchema = z.object({
1731
+ conversationId: z.string().min(1),
1732
+ createdAtMs: z.number().finite(),
1733
+ events: z.array(resourceEventTypeSchema).min(1),
1734
+ expiresAtMs: z.number().finite(),
1735
+ id: z.string().min(1),
1736
+ intent: z.string().min(1),
1737
+ label: z.string().min(1),
1738
+ match: resourceEventMatchSchema.optional(),
1739
+ namespace: z.string().min(1),
1740
+ identifier: z.string().min(1),
1741
+ resourceType: z.string().min(1),
1742
+ status: subscriptionStatusSchema,
1743
+ updatedAtMs: z.number().finite()
1744
+ }).strict();
1745
+ function digest(value) {
1746
+ return createHash("sha256").update(value).digest("hex").slice(0, 32);
1747
+ }
1748
+ function subscriptionKey(id) {
1749
+ return `${RESOURCE_EVENT_PREFIX}:record:${id}`;
1750
+ }
1751
+ function subscriptionLockKey(id) {
1752
+ return `${RESOURCE_EVENT_PREFIX}:lock:${id}`;
1753
+ }
1754
+ function resourceIndexKey(namespace, identifier) {
1755
+ return `${RESOURCE_EVENT_PREFIX}:resource:${digest(`${namespace}\0${identifier}`)}`;
1756
+ }
1757
+ function conversationIndexKey(conversationId) {
1758
+ return `${RESOURCE_EVENT_PREFIX}:conversation:${digest(conversationId)}`;
1759
+ }
1760
+ function indexLockKey(key) {
1761
+ return `${key}:lock`;
1762
+ }
1763
+ async function sleep(ms) {
1764
+ await new Promise((resolve) => {
1765
+ setTimeout(resolve, ms).unref?.();
1766
+ });
1767
+ }
1768
+ async function acquireSubscriptionLock(state, subscriptionId, waitDeadlineMs = Date.now() + SUBSCRIPTION_LOCK_WAIT_MS) {
1769
+ while (true) {
1770
+ const lock = await state.acquireLock(subscriptionLockKey(subscriptionId), SUBSCRIPTION_LOCK_TTL_MS);
1771
+ if (lock) return lock;
1772
+ if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire resource event subscription lock for ${subscriptionId}`);
1773
+ await sleep(SUBSCRIPTION_LOCK_RETRY_MS);
1774
+ }
1775
+ }
1776
+ /** Run one subscription lifecycle transition while keeping its lease alive. */
1777
+ async function withSubscriptionLock(state, subscriptionId, callback, waitDeadlineMs) {
1778
+ const lock = await acquireSubscriptionLock(state, subscriptionId, waitDeadlineMs);
1779
+ let lockLostError;
1780
+ let heartbeatError;
1781
+ let heartbeat;
1782
+ const timer = setInterval(() => {
1783
+ if (heartbeat) return;
1784
+ heartbeat = state.extendLock(lock, SUBSCRIPTION_LOCK_TTL_MS).then((extended) => {
1785
+ if (extended) heartbeatError = void 0;
1786
+ else lockLostError = /* @__PURE__ */ new Error(`Resource event subscription lock was lost for ${subscriptionId}`);
1787
+ }).catch((error) => {
1788
+ heartbeatError = error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to extend subscription lock: ${String(error)}`);
1789
+ }).finally(() => {
1790
+ heartbeat = void 0;
1791
+ });
1792
+ }, SUBSCRIPTION_LOCK_HEARTBEAT_MS);
1793
+ timer.unref?.();
1794
+ let result;
1795
+ try {
1796
+ result = await callback();
1797
+ } finally {
1798
+ clearInterval(timer);
1799
+ await heartbeat;
1800
+ await state.releaseLock(lock);
1801
+ }
1802
+ const lockError = lockLostError ?? heartbeatError;
1803
+ if (lockError) throw lockError;
1804
+ return result;
1805
+ }
1806
+ function ttlUntil(expiresAtMs, nowMs) {
1807
+ return Math.max(1, expiresAtMs - nowMs);
1808
+ }
1809
+ async function readSubscriptionIdIndex(state, key) {
1810
+ const value = await state.get(key);
1811
+ if (value === void 0 || value === null) return [];
1812
+ return subscriptionIdIndexSchema.parse(value);
1813
+ }
1814
+ function buildSubscriptionId(input) {
1815
+ const eventKey = [...new Set(input.events)].sort().join("\0");
1816
+ const matchKey = stableResourceEventMatchKey(input.match);
1817
+ return `resub_${digest(matchKey ? `${input.namespace}\0${input.identifier}\0${input.conversationId}\0${eventKey}\0${matchKey}` : `${input.namespace}\0${input.identifier}\0${input.conversationId}\0${eventKey}`)}`;
1818
+ }
1819
+ async function withIndexLock(state, key, callback) {
1820
+ const lock = await state.acquireLock(indexLockKey(key), INDEX_LOCK_TTL_MS);
1821
+ if (!lock) throw new Error(`Could not acquire resource event index lock for ${key}`);
1822
+ try {
1823
+ return await callback();
1824
+ } finally {
1825
+ await state.releaseLock(lock);
1826
+ }
1827
+ }
1828
+ async function addToIndex(state, key, subscriptionId, nowMs) {
1829
+ await withIndexLock(state, key, async () => {
1830
+ const ids = [...new Set(await readSubscriptionIdIndex(state, key))];
1831
+ const next = ids.includes(subscriptionId) ? ids : [...ids, subscriptionId];
1832
+ await state.set(key, next, await indexTtlMs(state, next, nowMs));
1833
+ });
1834
+ }
1835
+ async function removeFromIndex(state, key, subscriptionId, nowMs) {
1836
+ await withIndexLock(state, key, async () => {
1837
+ const next = (await readSubscriptionIdIndex(state, key)).filter((id) => id !== subscriptionId);
1838
+ await state.set(key, next, await indexTtlMs(state, next, nowMs));
1839
+ });
1840
+ }
1841
+ async function indexTtlMs(state, subscriptionIds, nowMs) {
1842
+ const records = await Promise.all(subscriptionIds.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))));
1843
+ return ttlUntil(Math.max(nowMs, ...records.filter((record) => record !== void 0 && activeAt(record, nowMs)).map((record) => record.expiresAtMs)), nowMs);
1844
+ }
1845
+ function parseSubscription(value) {
1846
+ if (value === void 0 || value === null) return;
1847
+ return subscriptionSchema.parse(value);
1848
+ }
1849
+ function activeAt(subscription, nowMs) {
1850
+ return subscription.status === "active" && subscription.expiresAtMs > nowMs;
1851
+ }
1852
+ function matchesEvent(subscription, input) {
1853
+ return subscription.namespace === input.namespace && subscription.identifier === input.identifier && subscription.events.includes(input.eventType) && activeAt(subscription, input.nowMs) && resourceEventMatches(subscription.match, input.data);
1854
+ }
1855
+ /** Create or replace the active subscription for one conversation/resource/event set. */
1856
+ async function createResourceEventSubscription(input, options = {}) {
1857
+ const state = options.state ?? getStateAdapter();
1858
+ await state.connect();
1859
+ const nowMs = options.nowMs ?? Date.now();
1860
+ const events = [...new Set(input.events.map((event) => event.trim()))].filter(Boolean);
1861
+ if (events.length === 0) throw new Error("Resource event subscription requires at least one event");
1862
+ if (input.expiresAtMs <= nowMs) throw new Error("Resource event subscription expiry must be in the future");
1863
+ const match = input.match && Object.keys(input.match).length > 0 ? input.match : void 0;
1864
+ const id = buildSubscriptionId({
1865
+ conversationId: input.conversationId,
1866
+ events,
1867
+ match,
1868
+ namespace: input.namespace,
1869
+ identifier: input.identifier
1870
+ });
1871
+ const record = {
1872
+ conversationId: input.conversationId,
1873
+ createdAtMs: nowMs,
1874
+ events,
1875
+ expiresAtMs: input.expiresAtMs,
1876
+ id,
1877
+ intent: input.intent,
1878
+ label: input.label,
1879
+ ...match ? { match } : void 0,
1880
+ namespace: input.namespace,
1881
+ identifier: input.identifier,
1882
+ resourceType: input.resourceType,
1883
+ status: "active",
1884
+ updatedAtMs: nowMs
1885
+ };
1886
+ const parsed = subscriptionSchema.parse(record);
1887
+ await state.set(subscriptionKey(id), parsed, ttlUntil(parsed.expiresAtMs, nowMs));
1888
+ await addToIndex(state, resourceIndexKey(input.namespace, input.identifier), id, nowMs);
1889
+ await addToIndex(state, conversationIndexKey(input.conversationId), id, nowMs);
1890
+ return parsed;
1891
+ }
1892
+ /** List active subscriptions bound to one conversation. */
1893
+ async function listResourceEventSubscriptions(input) {
1894
+ const state = input.state ?? getStateAdapter();
1895
+ await state.connect();
1896
+ const nowMs = input.nowMs ?? Date.now();
1897
+ const ids = await readSubscriptionIdIndex(state, conversationIndexKey(input.conversationId));
1898
+ return (await Promise.all(ids.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))))).filter((record) => record !== void 0 && record.conversationId === input.conversationId && activeAt(record, nowMs)).sort((left, right) => left.createdAtMs - right.createdAtMs);
1899
+ }
1900
+ /** Cancel a current-conversation subscription and remove it from match indexes. */
1901
+ async function cancelResourceEventSubscription(input) {
1902
+ const state = input.state ?? getStateAdapter();
1903
+ await state.connect();
1904
+ return await withSubscriptionLock(state, input.id, async () => {
1905
+ const current = parseSubscription(await state.get(subscriptionKey(input.id)));
1906
+ if (!current || current.conversationId !== input.conversationId) return;
1907
+ const nowMs = input.nowMs ?? Date.now();
1908
+ const next = {
1909
+ ...current,
1910
+ status: "cancelled",
1911
+ updatedAtMs: nowMs
1912
+ };
1913
+ await state.set(subscriptionKey(input.id), next, JUNIOR_THREAD_STATE_TTL_MS);
1914
+ await removeFromIndex(state, resourceIndexKey(current.namespace, current.identifier), input.id, nowMs);
1915
+ await removeFromIndex(state, conversationIndexKey(current.conversationId), input.id, nowMs);
1916
+ return next;
1917
+ });
1918
+ }
1919
+ /** Cancel every active resource event subscription bound to one conversation. */
1920
+ async function cancelSubscriptions(input) {
1921
+ const subscriptions = await listResourceEventSubscriptions(input);
1922
+ for (const subscription of subscriptions) await cancelResourceEventSubscription({
1923
+ conversationId: input.conversationId,
1924
+ id: subscription.id,
1925
+ nowMs: input.nowMs,
1926
+ state: input.state
1927
+ });
1928
+ }
1929
+ /**
1930
+ * Collect match keys from active watches for these identifiers and event types.
1931
+ * Does not evaluate match values — only reports keys that filters use.
1932
+ */
1933
+ async function collectResourceEventMatchKeys(input) {
1934
+ const state = input.state ?? getStateAdapter();
1935
+ await state.connect();
1936
+ const nowMs = input.nowMs ?? Date.now();
1937
+ const eventTypes = new Set(input.eventTypes.map((eventType) => eventType.trim()).filter(Boolean));
1938
+ if (eventTypes.size === 0) return [];
1939
+ const keys = /* @__PURE__ */ new Set();
1940
+ const identifiers = new Set(input.identifiers.map((value) => value.trim()).filter(Boolean));
1941
+ for (const identifier of identifiers) {
1942
+ const ids = await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, identifier));
1943
+ const records = await Promise.all(ids.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))));
1944
+ for (const record of records) {
1945
+ if (!record) continue;
1946
+ if (record.namespace !== input.namespace) continue;
1947
+ if (record.identifier !== identifier) continue;
1948
+ if (!activeAt(record, nowMs)) continue;
1949
+ if (!record.events.some((eventType) => eventTypes.has(eventType))) continue;
1950
+ for (const key of Object.keys(record.match ?? {})) keys.add(key);
1951
+ }
1952
+ }
1953
+ return [...keys].sort();
1954
+ }
1955
+ /** Find active subscriptions interested in a normalized resource event. */
1956
+ async function findMatchingResourceEventSubscriptions(input) {
1957
+ const state = input.state ?? getStateAdapter();
1958
+ await state.connect();
1959
+ const nowMs = input.nowMs ?? Date.now();
1960
+ const ids = await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, input.identifier));
1961
+ return (await Promise.all(ids.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))))).filter((record) => record !== void 0 && matchesEvent(record, {
1962
+ data: input.data,
1963
+ eventType: input.eventType,
1964
+ nowMs,
1965
+ namespace: input.namespace,
1966
+ identifier: input.identifier
1967
+ }));
1968
+ }
1969
+ /** Recheck and deliver a matched subscription while holding its status lock. */
1970
+ async function deliverResourceEventSubscription(input) {
1971
+ const state = input.state ?? getStateAdapter();
1972
+ await state.connect();
1973
+ return await withSubscriptionLock(state, input.subscription.id, async () => {
1974
+ const nowMs = input.nowMs ?? Date.now();
1975
+ const current = parseSubscription(await state.get(subscriptionKey(input.subscription.id)));
1976
+ if (!current || !matchesEvent(current, {
1977
+ data: input.data,
1978
+ eventType: input.eventType,
1979
+ nowMs,
1980
+ namespace: input.namespace,
1981
+ identifier: input.identifier
1982
+ })) return false;
1983
+ const delivered = await input.deliver(current);
1984
+ if (input.terminal) {
1985
+ const latest = parseSubscription(await state.get(subscriptionKey(current.id)));
1986
+ if (!latest || latest.status !== current.status || latest.updatedAtMs !== current.updatedAtMs) return delivered;
1987
+ const next = {
1988
+ ...current,
1989
+ status: "completed",
1990
+ updatedAtMs: nowMs
1991
+ };
1992
+ await state.set(subscriptionKey(current.id), next, JUNIOR_THREAD_STATE_TTL_MS);
1993
+ await removeFromIndex(state, resourceIndexKey(current.namespace, current.identifier), current.id, nowMs);
1994
+ await removeFromIndex(state, conversationIndexKey(current.conversationId), current.id, nowMs);
1995
+ }
1996
+ return delivered;
1997
+ }, input.waitDeadlineMs);
1998
+ }
1999
+ //#endregion
2000
+ //#region src/chat/resource-events/tool-support.ts
2001
+ /** Default lifetime for temporary resource subscriptions. */
2002
+ const RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS = 12096e5;
2003
+ /** Hard upper bound for temporary resource subscriptions. */
2004
+ const RESOURCE_SUBSCRIPTION_MAX_TTL_MS = 2592e6;
2005
+ const STOP_WATCHING_TOOL_NAME = "stopWatchingResources";
2006
+ const RESOURCE_WATCH_TOOL_SOURCE = {
2007
+ id: "resource-watches",
2008
+ description: "Inspect or stop resource watches for the current conversation."
2009
+ };
2010
+ //#endregion
2011
+ //#region src/chat/slack/tool-support/context.ts
2012
+ /** Resolve Slack tool context from the Conversation Location. */
2013
+ function getSlackToolContext(context) {
2014
+ const source = context.source.kind === "slack" ? context.source : void 0;
2015
+ const location = context.location?.provider === "slack" ? context.location : source ? {
2016
+ provider: "slack",
2017
+ teamId: source.teamId,
2018
+ channelId: source.channelId,
2019
+ threadTs: source.threadTs
2020
+ } : void 0;
2021
+ if (!location) return void 0;
2022
+ const destinationChannelId = parseSlackChannelReferenceId(context.destination.platform === "slack" ? context.destination.channelId : location.channelId);
2023
+ const locationChannelId = parseSlackChannelReferenceId(location.channelId);
2024
+ const teamId = parseSlackTeamId(location.teamId);
2025
+ if (!destinationChannelId || !locationChannelId || !teamId) return;
2026
+ return {
2027
+ actor: context.actor?.platform === "slack" ? context.actor : void 0,
2028
+ destinationChannelId,
2029
+ locationChannelId,
2030
+ messageChannelId: source ? parseSlackChannelReferenceId(source.channelId) : void 0,
2031
+ messageTs: parseSlackMessageTs(source?.messageTs),
2032
+ teamId,
2033
+ threadTs: parseSlackMessageTs(location.threadTs)
2034
+ };
2035
+ }
2036
+ //#endregion
2037
+ //#region src/chat/plugins/viewer.ts
2038
+ function identityFromRow(row) {
2039
+ return identitySchema.parse({
2040
+ id: row.id,
2041
+ provider: row.provider,
2042
+ providerSubjectId: row.providerSubjectId,
2043
+ ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
2044
+ ...row.displayName ? { displayName: row.displayName } : void 0,
2045
+ ...row.handle ? { handle: row.handle } : void 0
2046
+ });
2047
+ }
2048
+ async function readUserById(db, userRow) {
2049
+ const identityRows = 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));
2050
+ return userSchema.parse({
2051
+ email: userRow.primaryEmail,
2052
+ id: userRow.id,
2053
+ identities: identityRows.map(identityFromRow),
2054
+ ...userRow.displayName ? { displayName: userRow.displayName } : void 0
2055
+ });
2056
+ }
2057
+ /** Resolve or create the canonical user for one verified viewer email. */
2058
+ async function resolveViewerUserFromSql(db, email) {
2059
+ const normalizedEmail = normalizeIdentityEmail(email);
2060
+ if (!normalizedEmail) return void 0;
2061
+ const now = /* @__PURE__ */ new Date();
2062
+ const userRow = (await db.insert(juniorUsers).values({
2063
+ id: randomUUID(),
2064
+ primaryEmail: email.trim(),
2065
+ primaryEmailNormalized: normalizedEmail,
2066
+ displayName: null,
2067
+ createdAt: now,
2068
+ updatedAt: now
2069
+ }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
2070
+ return userRow ? await readUserById(db, userRow) : void 0;
2071
+ }
2072
+ /** Resolve or create the canonical user for one authenticated viewer. */
2073
+ async function resolveViewerUser(email) {
2074
+ return await resolveViewerUserFromSql(getDb(), email);
2075
+ }
2076
+ /** Read one existing canonical user by verified email without creating a row. */
2077
+ async function findUserByEmailFromSql(db, email) {
2078
+ const normalizedEmail = normalizeIdentityEmail(email);
2079
+ if (!normalizedEmail) return void 0;
2080
+ const userRow = (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
2081
+ return userRow ? await readUserById(db, userRow) : void 0;
2082
+ }
2083
+ /** Read one existing canonical user by verified email without creating a row. */
2084
+ async function findUserByEmail(email) {
2085
+ return await findUserByEmailFromSql(getDb(), email);
2086
+ }
2087
+ /** Update one canonical user's display name in SQL. */
2088
+ async function updateViewerDisplayNameFromSql(db, userId, displayName) {
2089
+ const userRow = (await db.update(juniorUsers).set({
2090
+ displayName,
2091
+ updatedAt: /* @__PURE__ */ new Date()
2092
+ }).where(eq(juniorUsers.id, userId)).returning())[0];
2093
+ return userRow ? await readUserById(db, userRow) : void 0;
2094
+ }
2095
+ /** Update one canonical user's display name. */
2096
+ async function updateViewerDisplayName(userId, displayName) {
2097
+ return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
2098
+ }
2099
+ /** Resolve the stored identity and linked user for one runtime actor. */
2100
+ async function readActorIdentityFromSql(db, actor) {
2101
+ if (actor.platform === "system") return void 0;
2102
+ const providerTenantId = actor.platform === "slack" ? actor.teamId : "";
2103
+ const row = (await db.select({
2104
+ identity: juniorIdentities,
2105
+ user: juniorUsers
2106
+ }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, actor.platform), eq(juniorIdentities.providerTenantId, providerTenantId), eq(juniorIdentities.providerSubjectId, actor.userId))).limit(1))[0];
2107
+ if (!row) return void 0;
2108
+ return {
2109
+ identity: identityFromRow(row.identity),
2110
+ ...row.user ? { user: await readUserById(db, row.user) } : void 0
2111
+ };
2112
+ }
2113
+ /** Resolve the stored identity and linked user for one runtime actor. */
2114
+ async function readActorIdentity(actor) {
2115
+ return await readActorIdentityFromSql(getDb(), actor);
2116
+ }
2117
+ //#endregion
2118
+ //#region src/chat/slack/workspace-context.ts
2119
+ const workspaceTeamIdStorage = new AsyncLocalStorage();
2120
+ /** Run a callback with the Slack workspace team ID for the inbound webhook. */
2121
+ function runWithWorkspaceTeamId(teamId, fn) {
2122
+ if (!teamId) return fn();
2123
+ return workspaceTeamIdStorage.run(teamId, fn);
2124
+ }
2125
+ /** Return the Slack workspace team ID for the current inbound webhook. */
2126
+ function getWorkspaceTeamId() {
2127
+ return workspaceTeamIdStorage.getStore();
2128
+ }
2129
+ //#endregion
2130
+ //#region src/chat/slack/client.ts
2131
+ var SlackActionError = class extends Error {
2132
+ code;
2133
+ apiError;
2134
+ needed;
2135
+ provided;
2136
+ statusCode;
2137
+ requestId;
2138
+ errorData;
2139
+ retryAfterSeconds;
2140
+ detail;
2141
+ detailLine;
2142
+ detailRule;
2143
+ constructor(message, code, options = {}) {
2144
+ super(message);
2145
+ this.name = "SlackActionError";
2146
+ this.code = code;
2147
+ this.apiError = options.apiError;
2148
+ this.needed = options.needed;
2149
+ this.provided = options.provided;
2150
+ this.statusCode = options.statusCode;
2151
+ this.requestId = options.requestId;
2152
+ this.errorData = options.errorData;
2153
+ this.retryAfterSeconds = options.retryAfterSeconds;
2154
+ this.detail = options.detail;
2155
+ this.detailLine = options.detailLine;
2156
+ this.detailRule = options.detailRule;
2157
+ }
2158
+ };
2159
+ function serializeSlackErrorData(data) {
2160
+ if (!data || typeof data !== "object") return;
2161
+ const filtered = Object.fromEntries(Object.entries(data).filter(([key]) => key !== "error"));
2162
+ if (Object.keys(filtered).length === 0) return;
2163
+ try {
2164
+ const serialized = JSON.stringify(filtered);
2165
+ return serialized.length <= 600 ? serialized : `${serialized.slice(0, 597)}...`;
2166
+ } catch {
2167
+ return;
2168
+ }
2169
+ }
2170
+ /** Extract a header value by case-insensitive name from a raw headers object. */
2171
+ function getHeaderString(headers, name) {
2172
+ if (!headers || typeof headers !== "object") return;
2173
+ const key = name.toLowerCase();
2174
+ const entries = headers;
2175
+ for (const [entryKey, value] of Object.entries(entries)) {
2176
+ if (entryKey.toLowerCase() !== key) continue;
2177
+ if (typeof value === "string") return value;
2178
+ if (Array.isArray(value)) {
2179
+ const first = value.find((entry) => typeof entry === "string");
2180
+ return typeof first === "string" ? first : void 0;
2181
+ }
2182
+ }
2183
+ }
2184
+ function parseSlackCanvasDetail(detail) {
2185
+ if (typeof detail !== "string") return {};
2186
+ const trimmed = detail.trim();
2187
+ if (!trimmed) return {};
2188
+ const parsed = { detail: trimmed };
2189
+ const lineMatch = trimmed.match(/line\s+(\d+):/i);
2190
+ if (lineMatch) {
2191
+ const line = Number.parseInt(lineMatch[1] ?? "", 10);
2192
+ if (Number.isFinite(line)) parsed.detailLine = line;
2193
+ }
2194
+ if (/unsupported heading depth/i.test(trimmed)) parsed.detailRule = "unsupported_heading_depth";
2195
+ return parsed;
2196
+ }
2197
+ /**
2198
+ * Ambient destination-installation token for Slack outbound calls, bound by
2199
+ * installation-scoped entry points so writes carry the destination
2200
+ * workspace's credentials instead of the process-global env token.
2201
+ */
2202
+ const installationTokenStorage = new AsyncLocalStorage();
2203
+ const clientsByToken = /* @__PURE__ */ new Map();
2204
+ /**
2205
+ * Bind a workspace installation token for all Slack Web API calls inside
2206
+ * `fn`, so multi-workspace outbound writes use the destination workspace's
2207
+ * credentials rather than the env fallback token.
2208
+ */
2209
+ function runWithSlackInstallationToken(token, fn) {
2210
+ const trimmed = token.trim();
2211
+ if (!trimmed) throw new SlackActionError("Slack installation token binding requires a non-empty token", "missing_token");
2212
+ return installationTokenStorage.run({ token: trimmed }, fn);
2213
+ }
2214
+ /**
2215
+ * Token precedence: ambient installation token, then env token, then a hard
2216
+ * failure for team-scoped calls — a call scoped to one workspace must never
2217
+ * silently fall through to another workspace's credentials.
2218
+ */
2219
+ function resolveSlackToken() {
2220
+ const ambientToken = installationTokenStorage.getStore()?.token;
2221
+ if (ambientToken) return ambientToken;
2222
+ const envToken = getSlackBotToken();
2223
+ if (envToken) return envToken;
2224
+ const teamId = getWorkspaceTeamId();
2225
+ if (teamId) throw new SlackActionError(`Slack call is scoped to workspace ${teamId} but no installation token is bound and no default bot token is configured`, "missing_token");
2226
+ throw new SlackActionError("SLACK_BOT_TOKEN (or SLACK_BOT_USER_TOKEN) is required for Slack Web API actions in this service", "missing_token");
2227
+ }
2228
+ /** Normalize Junior Slack references to native Slack conversation IDs. */
2229
+ function normalizeSlackConversationId(channelId) {
2230
+ return parseSlackChannelReferenceId(channelId);
2231
+ }
2232
+ /**
2233
+ * Return the per-token cached WebClient. `withSlackRetries` owns retry
2234
+ * classification for this boundary: the WebClient's built-in policy would
2235
+ * re-post timed-out writes (a duplicate-message hazard) and sleep for the
2236
+ * full unbounded Retry-After inside the request, so both internal behaviors
2237
+ * are disabled here.
2238
+ */
2239
+ function getClient() {
2240
+ const token = resolveSlackToken();
2241
+ let cached = clientsByToken.get(token);
2242
+ if (!cached) {
2243
+ cached = new WebClient(token, {
2244
+ retryConfig: { retries: 0 },
2245
+ rejectRateLimitedCalls: true
2246
+ });
2247
+ clientsByToken.set(token, cached);
2248
+ }
2249
+ return cached;
2250
+ }
2251
+ function mapSlackError(error) {
2252
+ if (error instanceof SlackActionError) return error;
2253
+ const candidate = error;
2254
+ const apiError = candidate.data?.error;
2255
+ const message = candidate.message ?? "Slack action failed";
2256
+ const baseOptions = {
2257
+ apiError,
2258
+ statusCode: candidate.statusCode,
2259
+ requestId: getHeaderString(candidate.headers, "x-slack-req-id"),
2260
+ errorData: serializeSlackErrorData(candidate.data),
2261
+ ...parseSlackCanvasDetail(candidate.data?.detail)
2262
+ };
2263
+ if (apiError === "missing_scope") return new SlackActionError(message, "missing_scope", {
2264
+ ...baseOptions,
2265
+ needed: candidate.data?.needed,
2266
+ provided: candidate.data?.provided
2267
+ });
2268
+ if (apiError === "not_in_channel") return new SlackActionError(message, "not_in_channel", baseOptions);
2269
+ if (apiError === "restricted_action_read_only_channel") return new SlackActionError(message, "read_only_channel", baseOptions);
2270
+ if (apiError === "already_reacted") return new SlackActionError(message, "already_reacted", baseOptions);
2271
+ if (apiError === "no_reaction") return new SlackActionError(message, "no_reaction", baseOptions);
2272
+ if (apiError === "invalid_arguments") return new SlackActionError(message, "invalid_arguments", baseOptions);
2273
+ if (apiError === "invalid_cursor") return new SlackActionError(message, "invalid_arguments", baseOptions);
2274
+ if (apiError === "invalid_name") return new SlackActionError(message, "invalid_arguments", baseOptions);
2275
+ if (apiError === "not_found" || apiError === "channel_not_found" || apiError === "message_not_found") return new SlackActionError(message, "not_found", baseOptions);
2276
+ if (apiError === "feature_not_enabled" || apiError === "not_allowed_token_type") return new SlackActionError(message, "feature_unavailable", baseOptions);
2277
+ if (apiError === "canvas_creation_failed") return new SlackActionError(message, "canvas_creation_failed", baseOptions);
2278
+ if (apiError === "canvas_editing_failed") return new SlackActionError(message, "canvas_editing_failed", baseOptions);
2279
+ if (candidate.code === "slack_webapi_rate_limited_error" || candidate.statusCode === 429) return new SlackActionError(message, "rate_limited", {
2280
+ ...baseOptions,
2281
+ retryAfterSeconds: candidate.retryAfter
2282
+ });
2283
+ return new SlackActionError(message, "internal_error", baseOptions);
2284
+ }
2285
+ const MAX_RETRY_DELAY_MS = 1e4;
2286
+ const MAX_TOTAL_RETRY_DELAY_MS = 2e4;
2287
+ const CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
2288
+ "ECONNREFUSED",
2289
+ "ECONNRESET",
2290
+ "ENOTFOUND",
2291
+ "EAI_AGAIN"
2292
+ ]);
2293
+ const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
2294
+ "ETIMEDOUT",
2295
+ "ECONNABORTED",
2296
+ "ESOCKETTIMEDOUT"
2297
+ ]);
2298
+ function findNetworkErrorCode(error, depth = 0) {
2299
+ if (!error || typeof error !== "object" || depth > 4) return;
2300
+ const candidate = error;
2301
+ if (typeof candidate.code === "string" && (CONNECTION_ERROR_CODES.has(candidate.code) || TIMEOUT_ERROR_CODES.has(candidate.code))) return candidate.code;
2302
+ return findNetworkErrorCode(candidate.original, depth + 1) ?? findNetworkErrorCode(candidate.cause, depth + 1);
2303
+ }
2304
+ function hasSocketHangUpMessage(error) {
2305
+ return error instanceof Error && error.message.toLowerCase().includes("socket hang up");
2306
+ }
2307
+ /**
2308
+ * Classify a failed Slack call for retry: rate limits, Slack 5xx, and
2309
+ * connection-phase failures are always retryable; timeouts are retried only
2310
+ * for idempotent operations because Slack may already have accepted the
2311
+ * request.
2312
+ */
2313
+ function classifySlackRetry(raw, mapped) {
2314
+ if (mapped.code === "rate_limited") return "rate_limited";
2315
+ if (mapped.statusCode !== void 0 && mapped.statusCode >= 500) return "server_error";
2316
+ const networkCode = findNetworkErrorCode(raw);
2317
+ if (networkCode && CONNECTION_ERROR_CODES.has(networkCode)) return "connection";
2318
+ if (networkCode && TIMEOUT_ERROR_CODES.has(networkCode)) return "timeout";
2319
+ if (hasSocketHangUpMessage(raw)) return "connection";
2320
+ return "none";
2321
+ }
2322
+ /**
2323
+ * Run a Slack Web API call with bounded retries so transient platform
2324
+ * failures do not surface as turn failures, while non-idempotent posts are
2325
+ * never re-sent when Slack may already have accepted them.
2326
+ *
2327
+ * Retry classes: rate limits (bounded Retry-After), connection-phase network
2328
+ * failures, and Slack 5xx responses always retry; request timeouts retry only
2329
+ * when the caller marks the operation `idempotent`.
2330
+ */
2331
+ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
2332
+ let attempt = 0;
2333
+ let totalDelayMs = 0;
2334
+ const action = context.action ?? "unknown";
2335
+ while (attempt < maxAttempts) {
2336
+ attempt += 1;
2337
+ const attemptNumber = attempt;
2338
+ try {
2339
+ return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
2340
+ try {
2341
+ return await task();
2342
+ } catch (error) {
2343
+ const mapped = mapSlackError(error);
2344
+ const errorAttrs = { "error.type": mapped.code };
2345
+ if (mapped.apiError) errorAttrs["app.slack.api_error_code"] = mapped.apiError;
2346
+ if (mapped.code === "rate_limited") {
2347
+ errorAttrs["http.response.status_code"] = 429;
2348
+ if (mapped.retryAfterSeconds) errorAttrs["app.slack.retry_after_ms"] = mapped.retryAfterSeconds * 1e3;
2349
+ } else if (mapped.statusCode != null) errorAttrs["http.response.status_code"] = mapped.statusCode;
2350
+ setSpanAttributes(errorAttrs);
2351
+ setSpanStatus("error");
2352
+ throw error;
2353
+ }
2354
+ }, {
2355
+ "http.request.method": "POST",
2356
+ "server.address": "slack.com",
2357
+ "url.scheme": "https",
2358
+ "url.path": `/api/${action}`,
2359
+ "app.slack.method": action,
2360
+ "app.retry.max_attempts": maxAttempts,
2361
+ ...attemptNumber > 1 ? { "http.request.resend_count": attemptNumber - 1 } : void 0,
2362
+ ...context.attributes ?? {},
2363
+ ...context.spanAttributes ?? {}
2364
+ });
2365
+ } catch (error) {
2366
+ const mapped = mapSlackError(error);
2367
+ const retryClass = classifySlackRetry(error, mapped);
2368
+ const isRetryable = retryClass === "rate_limited" || retryClass === "connection" || retryClass === "server_error" || retryClass === "timeout" && context.idempotent === true;
2369
+ const remainingDelayBudgetMs = MAX_TOTAL_RETRY_DELAY_MS - totalDelayMs;
2370
+ const baseLogAttributes = {
2371
+ "app.slack.action": action,
2372
+ "app.slack.error_code": mapped.code,
2373
+ ...mapped.apiError ? { "app.slack.api_error": mapped.apiError } : void 0,
2374
+ ...mapped.detail ? { "app.slack.detail": mapped.detail } : void 0,
2375
+ ...mapped.detailLine !== void 0 ? { "app.slack.detail_line": mapped.detailLine } : void 0,
2376
+ ...mapped.detailRule ? { "app.slack.detail_rule": mapped.detailRule } : void 0,
2377
+ ...mapped.requestId ? { "app.slack.request_id": mapped.requestId } : void 0,
2378
+ ...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
2379
+ ...context.attributes ?? {}
2380
+ };
2381
+ if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
2382
+ logWarn("slack.action.failed", {
2383
+ ...baseLogAttributes,
2384
+ ...mapped.errorData ? { "app.slack.error_data": mapped.errorData } : void 0
2385
+ });
2386
+ throw mapped;
2387
+ }
2388
+ logWarn("slack.action.retrying", {
2389
+ ...baseLogAttributes,
2390
+ "app.slack.retry_attempt": attempt,
2391
+ "app.slack.retry_class": retryClass
2392
+ });
2393
+ const retryAfterMs = retryClass === "rate_limited" && mapped.retryAfterSeconds && mapped.retryAfterSeconds > 0 ? mapped.retryAfterSeconds * 1e3 : void 0;
2394
+ const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
2395
+ const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
2396
+ totalDelayMs += delayMs;
2397
+ await sleep$1(delayMs);
2398
+ }
2399
+ }
2400
+ throw new SlackActionError("Slack action exhausted retries", "internal_error");
2401
+ }
2402
+ /**
2403
+ * Slack Web API client for the current destination workspace: the ambient
2404
+ * installation token when one is bound, otherwise the env bot token for
2405
+ * single-workspace deployments. Fails instead of falling back when the call
2406
+ * is workspace-scoped and no installation token can be resolved, so a write
2407
+ * never goes out with another workspace's credentials.
2408
+ */
2409
+ function getSlackClient() {
2410
+ return getClient();
2411
+ }
2412
+ /**
2413
+ * Slack channel ID prefixes:
2414
+ * - C: channel — modern private channels also use C, so the prefix never
2415
+ * proves a channel is public
2416
+ * - G: legacy private channel / group DM
2417
+ * - D: direct message (1:1)
2418
+ */
2419
+ function isDmChannel(channelId) {
2420
+ const normalized = normalizeSlackConversationId(channelId);
2421
+ return Boolean(normalized && normalized.startsWith("D"));
2422
+ }
2423
+ /**
2424
+ * Conversation-scoped Slack contexts backed by a concrete conversation ID.
2425
+ * Includes channels/groups/DMs (C/G/D).
2426
+ */
2427
+ function isConversationScopedChannel(channelId) {
2428
+ const normalized = normalizeSlackConversationId(channelId);
2429
+ if (!normalized) return false;
2430
+ return normalized.startsWith("C") || normalized.startsWith("G") || normalized.startsWith("D");
2431
+ }
2432
+ function isConversationChannel(channelId) {
2433
+ const normalized = normalizeSlackConversationId(channelId);
2434
+ if (!normalized) return false;
2435
+ return normalized.startsWith("C") || normalized.startsWith("G");
2436
+ }
2437
+ async function getFilePermalink(fileId) {
2438
+ const client = getClient();
2439
+ return (await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
2440
+ action: "files.info",
2441
+ idempotent: true,
2442
+ spanAttributes: { "app.slack.file_id": fileId }
2443
+ })).file?.permalink;
2444
+ }
2445
+ async function downloadPrivateSlackFile(url) {
2446
+ const token = resolveSlackToken();
2447
+ return withSpan("GET files.slack.com", "http.client", {}, async () => {
2448
+ const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
2449
+ setSpanAttributes({ "http.response.status_code": response.status });
2450
+ if (!response.ok) {
2451
+ setSpanAttributes({ "error.type": String(response.status) });
2452
+ setSpanStatus("error");
2453
+ throw new Error(`Slack file download failed: ${response.status}`);
2454
+ }
2455
+ return Buffer.from(await response.arrayBuffer());
2456
+ }, {
2457
+ "http.request.method": "GET",
2458
+ "server.address": "files.slack.com",
2459
+ "url.scheme": "https",
2460
+ "app.slack.method": "files.download"
2461
+ });
2462
+ }
2463
+ //#endregion
2464
+ //#region src/chat/credentials/subject.ts
2465
+ const CREDENTIAL_SUBJECT_HMAC_CONTEXT = "junior.credential_subject.v1";
2466
+ const CREDENTIAL_SUBJECT_SIGNATURE_VERSION = "v1";
2467
+ function getCredentialSubjectSecret() {
2468
+ return process.env.JUNIOR_SECRET?.trim() || void 0;
2469
+ }
2470
+ /** Encode ordered signing fields without allowing delimiter ambiguity. */
2471
+ function buildPayload(parts) {
2472
+ return [CREDENTIAL_SUBJECT_HMAC_CONTEXT, ...parts].join("\0");
2473
+ }
2474
+ function signPayload(secret, payload) {
2475
+ const digest = createHmac("sha256", secret).update(payload).digest("hex");
2476
+ return `${CREDENTIAL_SUBJECT_SIGNATURE_VERSION}=${digest}`;
2477
+ }
2478
+ function timingSafeMatch(expected, actual) {
2479
+ const expectedBuffer = Buffer.from(expected);
2480
+ const actualBuffer = Buffer.from(actual);
2481
+ if (expectedBuffer.length !== actualBuffer.length) return false;
2482
+ return timingSafeEqual(expectedBuffer, actualBuffer);
2483
+ }
2484
+ /** Create a delegated user credential subject for a verified Slack DM turn. */
2485
+ function createSlackDirectCredentialSubject(input) {
2486
+ const channelId = normalizeSlackConversationId(input.channelId);
2487
+ const teamId = input.teamId?.trim();
2488
+ const userId = parseActorUserId(input.userId);
2489
+ if (!channelId || !teamId || !userId || !isDmChannel(channelId)) return;
2490
+ return {
2491
+ type: "user",
2492
+ userId,
2493
+ allowedWhen: "private-direct-conversation"
2494
+ };
2495
+ }
2496
+ /** Bind a delegated user subject to the Slack DM destination being dispatched. */
2497
+ function bindSlackDirectCredentialSubject(input) {
2498
+ const channelId = normalizeSlackConversationId(input.channelId);
2499
+ const teamId = input.teamId.trim();
2500
+ const secret = getCredentialSubjectSecret();
2501
+ const { subject } = input;
2502
+ const userId = parseActorUserId(subject.userId);
2503
+ if (!channelId || !teamId || !secret || !isDmChannel(channelId) || subject.type !== "user" || !userId || subject.allowedWhen !== "private-direct-conversation") return;
2504
+ return {
2505
+ type: "user",
2506
+ userId,
2507
+ allowedWhen: subject.allowedWhen,
2508
+ binding: {
2509
+ type: "slack-direct-conversation",
2510
+ teamId,
2511
+ channelId,
2512
+ signature: signPayload(secret, buildPayload([
2513
+ subject.allowedWhen,
2514
+ teamId,
2515
+ channelId,
2516
+ userId
2517
+ ]))
2518
+ }
2519
+ };
2520
+ }
2521
+ /** Verify that a delegated subject was signed for the dispatch destination. */
2522
+ function verifySlackDirectCredentialSubject(input) {
2523
+ const channelId = normalizeSlackConversationId(input.channelId);
2524
+ const secret = getCredentialSubjectSecret();
2525
+ if (!channelId || !secret) return false;
2526
+ const { subject } = input;
2527
+ const binding = subject.binding;
2528
+ if (subject.type !== "user" || !isActorUserId(subject.userId) || subject.allowedWhen !== "private-direct-conversation" || !binding || binding.type !== "slack-direct-conversation" || typeof binding.signature !== "string" || !binding.signature || binding.teamId !== input.teamId || binding.channelId !== channelId) return false;
2529
+ return timingSafeMatch(signPayload(secret, buildPayload([
2530
+ subject.allowedWhen,
2531
+ binding.teamId,
2532
+ binding.channelId,
2533
+ subject.userId
2534
+ ])), binding.signature);
2535
+ }
2536
+ /** Bind a delegated user subject to one scheduler task dispatch. */
2537
+ function bindScheduledTaskCredentialSubject(input) {
2538
+ const secret = getCredentialSubjectSecret();
2539
+ const plugin = input.plugin.trim();
2540
+ const userId = parseActorUserId(input.subject.userId);
2541
+ if (!secret || plugin !== "scheduler" || !userId || input.subject.allowedWhen !== "scheduled-task") return;
2542
+ const taskId = input.subject.taskId;
2543
+ if (!taskId || taskId !== taskId.trim()) return;
2544
+ return {
2545
+ type: "user",
2546
+ userId,
2547
+ allowedWhen: "scheduled-task",
2548
+ taskId,
2549
+ binding: {
2550
+ type: "scheduled-task",
2551
+ plugin,
2552
+ taskId,
2553
+ signature: signPayload(secret, buildPayload([
2554
+ "scheduled-task",
2555
+ plugin,
2556
+ taskId,
2557
+ userId
2558
+ ]))
2559
+ }
2560
+ };
2561
+ }
2562
+ /** Verify that a delegated subject was signed for one scheduler task. */
2563
+ function verifyScheduledTaskCredentialSubject(input) {
2564
+ const secret = getCredentialSubjectSecret();
2565
+ const { subject } = input;
2566
+ const binding = subject.binding;
2567
+ if (!secret || input.plugin !== "scheduler" || subject.type !== "user" || !isActorUserId(subject.userId) || subject.allowedWhen !== "scheduled-task" || !subject.taskId || binding.type !== "scheduled-task" || binding.plugin !== input.plugin || binding.taskId !== subject.taskId) return false;
2568
+ return timingSafeMatch(signPayload(secret, buildPayload([
2569
+ "scheduled-task",
2570
+ binding.plugin,
2571
+ binding.taskId,
2572
+ subject.userId
2573
+ ])), binding.signature);
2574
+ }
2575
+ /** Bind a delegated user subject to one event task dispatch. */
2576
+ function bindEventTaskCredentialSubject(input) {
2577
+ const secret = getCredentialSubjectSecret();
2578
+ const plugin = input.plugin.trim();
2579
+ const userId = parseActorUserId(input.subject.userId);
2580
+ if (!secret || plugin !== "junior" || !userId || input.subject.allowedWhen !== "event-task") return;
2581
+ const taskId = input.subject.taskId;
2582
+ if (!taskId || taskId !== taskId.trim()) return;
2583
+ return {
2584
+ type: "user",
2585
+ userId,
2586
+ allowedWhen: "event-task",
2587
+ taskId,
2588
+ binding: {
2589
+ type: "event-task",
2590
+ plugin,
2591
+ taskId,
2592
+ signature: signPayload(secret, buildPayload([
2593
+ "event-task",
2594
+ plugin,
2595
+ taskId,
2596
+ userId
2597
+ ]))
2598
+ }
2599
+ };
2600
+ }
2601
+ /** Verify that a delegated subject was signed for one event task. */
2602
+ function verifyEventTaskCredentialSubject(input) {
2603
+ const secret = getCredentialSubjectSecret();
2604
+ const { subject } = input;
2605
+ const binding = subject.binding;
2606
+ if (!secret || input.plugin !== "junior" || subject.type !== "user" || !isActorUserId(subject.userId) || subject.allowedWhen !== "event-task" || !subject.taskId || binding.type !== "event-task" || binding.plugin !== input.plugin || binding.taskId !== subject.taskId) return false;
2607
+ return timingSafeMatch(signPayload(secret, buildPayload([
2608
+ "event-task",
2609
+ binding.plugin,
2610
+ binding.taskId,
2611
+ subject.userId
2612
+ ])), binding.signature);
2613
+ }
2614
+ //#endregion
2615
+ //#region src/chat/slack/tool-support/channel-capabilities.ts
2616
+ /** Resolve channel capabilities from a Slack channel ID. */
2617
+ function resolveChannelCapabilities(channelId) {
2618
+ return {
2619
+ canCreateCanvas: isConversationScopedChannel(channelId),
2620
+ canSendFiles: isConversationScopedChannel(channelId),
2621
+ canPostToChannel: isConversationChannel(channelId),
2622
+ canAddReactions: isConversationScopedChannel(channelId)
2623
+ };
2624
+ }
2625
+ //#endregion
2626
+ //#region src/chat/workspaces/checkout-path.ts
2627
+ /** Derive the fixed sandbox checkout path for one repository, or undefined when invalid. */
2628
+ function tryWorkspaceRepoCheckoutPath(repo) {
2629
+ const name = repo.split("/").filter(Boolean).at(-1);
2630
+ if (!name || name === "." || name === ".." || !/^[A-Za-z0-9._-]+$/.test(name)) return;
2631
+ return `repos/${name}`;
2632
+ }
2633
+ /** Derive the fixed sandbox checkout path for one repository. */
2634
+ function workspaceRepoCheckoutPath(repo) {
2635
+ const path = tryWorkspaceRepoCheckoutPath(repo);
2636
+ if (!path) throw new Error(`Invalid repository name for checkout path: ${repo}`);
2637
+ return path;
2638
+ }
2639
+ //#endregion
2640
+ //#region src/chat/sandbox/snapshot/builder-sandbox.ts
2641
+ /** Resume the named Sandbox that owns one Workspace snapshot build. */
2642
+ async function getWorkspaceSnapshotBuilder(name, signal) {
2643
+ const credentials = getVercelSandboxCredentials();
2644
+ return await Sandbox.get({
2645
+ name,
2646
+ resume: true,
2647
+ signal,
2648
+ ...credentials ?? {}
2649
+ });
2650
+ }
2651
+ /** Permanently delete named Workspace snapshot builders without resuming them. */
2652
+ async function deleteWorkspaceSnapshotBuilders(names) {
2653
+ const credentials = getVercelSandboxCredentials();
2654
+ let hasError = false;
2655
+ let firstError;
2656
+ for (const name of new Set(names)) try {
2657
+ await (await Sandbox.get({
2658
+ name,
2659
+ resume: false,
2660
+ ...credentials ?? {}
2661
+ })).delete();
2662
+ } catch (error) {
2663
+ if (!isSandboxMissingError(error)) {
2664
+ if (!hasError) firstError = error;
2665
+ hasError = true;
2666
+ }
2667
+ }
2668
+ if (hasError) throw firstError;
2669
+ }
2670
+ //#endregion
2671
+ //#region src/chat/sandbox/snapshot/runtime.ts
2672
+ /** Runtime used to build and start reusable Sandbox snapshots. */
2673
+ const SANDBOX_RUNTIME = "node22";
2674
+ //#endregion
2675
+ //#region src/chat/sandbox/snapshot/store.ts
2676
+ function builderNames(rows) {
2677
+ return [...new Set(rows.map((row) => row.sandboxName).filter((name) => Boolean(name)))];
2678
+ }
2679
+ function sameWorkspaceRecipe(stored, expected) {
2680
+ if (stored.setupScript !== expected.setupScript || stored.repos.length !== expected.repos.length) return false;
2681
+ const expectedRepos = new Set(expected.repos.map((repo) => JSON.stringify([repo.provider, repo.repo])));
2682
+ return stored.repos.every((repo) => expectedRepos.has(JSON.stringify([repo.provider, repo.repo])));
2683
+ }
2684
+ function snapshotFromRow(row) {
2685
+ if (row.status !== "ready" || !row.snapshotId || !row.generatedAt || row.buildDurationMs == null) throw new Error(`Invalid ready Workspace snapshot row: ${row.id}`);
2686
+ return {
2687
+ id: row.snapshotId,
2688
+ generatedAt: row.generatedAt,
2689
+ buildDurationMs: row.buildDurationMs,
2690
+ sizeBytes: row.sizeBytes,
2691
+ profileHash: row.profileHash
2692
+ };
2693
+ }
2694
+ function snapshotBuildFromRow(row) {
2695
+ if (row.status === "ready" || !row.buildStartedAt || !row.buildPhase) throw new Error(`Invalid Workspace snapshot build row: ${row.id}`);
2696
+ return {
2697
+ id: row.id,
2698
+ status: row.status,
2699
+ phase: row.buildPhase,
2700
+ profileHash: row.profileHash,
2701
+ startedAt: row.buildStartedAt,
2702
+ sandboxName: row.buildSandboxName,
2703
+ commandId: row.buildCommandId,
2704
+ error: row.buildError
2705
+ };
2706
+ }
2707
+ /** Load bounded ready and build views for one Workspace profile hash. */
2708
+ async function loadSnapshotsForProfile(db, workspaceId, profileHash) {
2709
+ const profile = and(eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, profileHash));
2710
+ const order = [
2711
+ desc(juniorSnapshots.updatedAt),
2712
+ desc(juniorSnapshots.createdAt),
2713
+ desc(juniorSnapshots.id)
2714
+ ];
2715
+ const [readyRows, buildRows] = await Promise.all([db.select().from(juniorSnapshots).where(and(profile, eq(juniorSnapshots.status, "ready"))).orderBy(...order).limit(1), db.select().from(juniorSnapshots).where(and(profile, ne(juniorSnapshots.status, "ready"))).orderBy(asc(juniorSnapshots.status), ...order).limit(1)]);
2716
+ return {
2717
+ ready: readyRows[0] ? snapshotFromRow(readyRows[0]) : null,
2718
+ build: buildRows[0] ? snapshotBuildFromRow(buildRows[0]) : null
2719
+ };
2720
+ }
2721
+ /** Drop every snapshot row before its Workspace is deleted. */
2722
+ async function clearWorkspaceSnapshots(db, workspaceId) {
2723
+ await db.select({ id: juniorWorkspaces.id }).from(juniorWorkspaces).where(eq(juniorWorkspaces.id, workspaceId)).for("update");
2724
+ return builderNames(await db.delete(juniorSnapshots).where(eq(juniorSnapshots.workspaceId, workspaceId)).returning({ sandboxName: juniorSnapshots.buildSandboxName }));
2725
+ }
2726
+ /** Drop one ready snapshot and return the name of its provider owner. */
2727
+ async function invalidateReadySnapshot(params) {
2728
+ const executor = getSqlExecutor();
2729
+ return await executor.transaction(async () => {
2730
+ return (await executor.db().delete(juniorSnapshots).where(and(eq(juniorSnapshots.workspaceId, params.workspaceId), eq(juniorSnapshots.profileHash, params.profileHash), eq(juniorSnapshots.status, "ready"), eq(juniorSnapshots.snapshotId, params.snapshotId))).returning({ sandboxName: juniorSnapshots.buildSandboxName }))[0]?.sandboxName ?? null;
2731
+ });
2732
+ }
2733
+ /** Complete one owned build and report provider owners that it replaced. */
2734
+ async function setWorkspaceSnapshot(workspaceId, snapshot, options) {
2735
+ const executor = getSqlExecutor();
2736
+ return await executor.transaction(async () => {
2737
+ const db = executor.db();
2738
+ const now = /* @__PURE__ */ new Date();
2739
+ if ((await db.update(juniorSnapshots).set({
2740
+ status: "ready",
2741
+ snapshotId: snapshot.id,
2742
+ buildDurationMs: snapshot.buildDurationMs,
2743
+ sizeBytes: snapshot.sizeBytes,
2744
+ generatedAt: snapshot.generatedAt,
2745
+ buildStartedAt: null,
2746
+ buildPhase: null,
2747
+ buildCommandId: null,
2748
+ buildError: null,
2749
+ updatedAt: now
2750
+ }).where(and(eq(juniorSnapshots.id, options.buildId), eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, snapshot.profileHash), eq(juniorSnapshots.status, "building"))).returning({ id: juniorSnapshots.id })).length === 0) return {
2751
+ written: false,
2752
+ replacedBuilderNames: []
2753
+ };
2754
+ return {
2755
+ written: true,
2756
+ replacedBuilderNames: builderNames(await db.delete(juniorSnapshots).where(and(eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, snapshot.profileHash), ne(juniorSnapshots.id, options.buildId), or(eq(juniorSnapshots.status, "failed"), eq(juniorSnapshots.status, "ready")))).returning({ sandboxName: juniorSnapshots.buildSandboxName }))
2757
+ };
2758
+ });
2759
+ }
2760
+ /** Update an owned build row. Initial creation locks and verifies its Workspace. */
2761
+ async function setWorkspaceSnapshotBuild(workspaceId, build, options = {}) {
2762
+ const executor = getSqlExecutor();
2763
+ return await executor.transaction(async () => {
2764
+ const db = executor.db();
2765
+ const now = /* @__PURE__ */ new Date();
2766
+ if ((await db.update(juniorSnapshots).set({
2767
+ status: build.status,
2768
+ buildStartedAt: build.startedAt,
2769
+ buildPhase: build.phase,
2770
+ buildSandboxName: build.sandboxName,
2771
+ buildCommandId: build.commandId,
2772
+ buildError: build.error,
2773
+ updatedAt: now
2774
+ }).where(and(eq(juniorSnapshots.id, build.id), eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, build.profileHash), eq(juniorSnapshots.status, "building"))).returning({ id: juniorSnapshots.id })).length > 0) return true;
2775
+ if (!options.insertIfMissing) return false;
2776
+ const workspace = (await db.select({ setupScript: juniorWorkspaces.setupScript }).from(juniorWorkspaces).where(eq(juniorWorkspaces.id, workspaceId)).for("update"))[0];
2777
+ if (!workspace) return false;
2778
+ if (options.expectedRecipe) {
2779
+ const repos = await db.select({
2780
+ provider: juniorWorkspaceRepos.provider,
2781
+ repo: juniorWorkspaceRepos.repo
2782
+ }).from(juniorWorkspaceRepos).where(eq(juniorWorkspaceRepos.workspaceId, workspaceId));
2783
+ if (!sameWorkspaceRecipe({
2784
+ ...workspace,
2785
+ repos
2786
+ }, options.expectedRecipe)) return false;
2787
+ }
2788
+ return (await db.insert(juniorSnapshots).values({
2789
+ id: build.id,
2790
+ workspaceId,
2791
+ profileHash: build.profileHash,
2792
+ status: build.status,
2793
+ snapshotId: null,
2794
+ buildDurationMs: null,
2795
+ sizeBytes: null,
2796
+ generatedAt: null,
2797
+ buildStartedAt: build.startedAt,
2798
+ buildPhase: build.phase,
2799
+ buildSandboxName: build.sandboxName,
2800
+ buildCommandId: build.commandId,
2801
+ buildError: build.error,
2802
+ createdAt: now,
2803
+ updatedAt: now
2804
+ }).onConflictDoNothing().returning({ id: juniorSnapshots.id })).length > 0;
2805
+ });
2806
+ }
2807
+ //#endregion
2808
+ //#region src/chat/workspaces/validation.ts
2809
+ const WORKSPACE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
2810
+ const PROVIDER_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
2811
+ const REPO_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
2812
+ const MAX_SETUP_SCRIPT_BYTES = 65536;
2813
+ const MAX_REPOS = 32;
2814
+ /** Validation failure for one Workspace recipe write. */
2815
+ var WorkspaceValidationError = class extends Error {
2816
+ constructor(message) {
2817
+ super(message);
2818
+ this.name = "WorkspaceValidationError";
2819
+ }
2820
+ };
2821
+ /** Normalize and validate one Workspace recipe write payload. */
2822
+ function normalizeWorkspaceRecipe(input) {
2823
+ const name = input.name.trim().toLowerCase();
2824
+ if (!WORKSPACE_NAME_PATTERN.test(name)) throw new WorkspaceValidationError("Workspace name must start with a letter and use only lowercase letters, digits, underscores, or hyphens.");
2825
+ const setupScript = input.setupScript ?? "";
2826
+ if (typeof setupScript !== "string") throw new WorkspaceValidationError("Setup script must be a string.");
2827
+ if (Buffer.byteLength(setupScript, "utf8") > MAX_SETUP_SCRIPT_BYTES) throw new WorkspaceValidationError(`Setup script must be at most ${MAX_SETUP_SCRIPT_BYTES} bytes.`);
2828
+ if (!Array.isArray(input.repos)) throw new WorkspaceValidationError("Repositories must be an array.");
2829
+ if (input.repos.length > MAX_REPOS) throw new WorkspaceValidationError(`A Workspace can include at most ${MAX_REPOS} repositories.`);
2830
+ const repos = input.repos.map((entry, index) => {
2831
+ const provider = entry.provider.trim().toLowerCase();
2832
+ if (!PROVIDER_PATTERN.test(provider)) throw new WorkspaceValidationError(`Repository ${index + 1} provider is invalid.`);
2833
+ const repo = entry.repo.trim();
2834
+ if (!REPO_PATTERN.test(repo)) throw new WorkspaceValidationError(`Repository ${index + 1} must use owner/name format.`);
2835
+ if (!tryWorkspaceRepoCheckoutPath(repo)) throw new WorkspaceValidationError(`Repository ${index + 1} name cannot be used as a checkout path.`);
2836
+ return {
2837
+ provider,
2838
+ repo
2839
+ };
2840
+ });
2841
+ const identities = /* @__PURE__ */ new Set();
2842
+ for (const repo of repos) {
2843
+ const identity = `${repo.provider}:${repo.repo.toLowerCase()}`;
2844
+ if (identities.has(identity)) throw new WorkspaceValidationError(`Duplicate repository in Workspace: ${repo.provider}:${repo.repo}`);
2845
+ identities.add(identity);
2846
+ }
2847
+ const checkoutPaths = /* @__PURE__ */ new Set();
2848
+ for (const repo of repos) {
2849
+ const path = tryWorkspaceRepoCheckoutPath(repo.repo);
2850
+ const key = path.toLowerCase();
2851
+ if (checkoutPaths.has(key)) throw new WorkspaceValidationError(`Workspace checkout path collision: ${path}`);
2852
+ checkoutPaths.add(key);
2853
+ }
2854
+ return {
2855
+ name,
2856
+ setupScript,
2857
+ repos
2858
+ };
2859
+ }
2860
+ //#endregion
2861
+ //#region src/chat/workspaces/store.ts
2862
+ function workspaceFromRows(row, repos, snapshot) {
2863
+ return {
2864
+ id: row.id,
2865
+ name: row.name,
2866
+ setupScript: row.setupScript,
2867
+ repos: repos.map((repo) => ({
2868
+ provider: repo.provider,
2869
+ repo: repo.repo
2870
+ })),
2871
+ snapshot
2872
+ };
2873
+ }
2874
+ async function workspaceWithSnapshot(db, row, repos) {
2875
+ const workspace = workspaceFromRows(row, repos, null);
2876
+ const profileHash = hash(SANDBOX_RUNTIME, workspace);
2877
+ if (!profileHash) return workspace;
2878
+ const snapshots = await loadSnapshotsForProfile(db, workspace.id, profileHash);
2879
+ return {
2880
+ ...workspace,
2881
+ snapshot: snapshots.ready
2882
+ };
2883
+ }
2884
+ async function loadWorkspaceRepos(db, workspaceId) {
2885
+ return await db.select().from(juniorWorkspaceRepos).where(eq(juniorWorkspaceRepos.workspaceId, workspaceId)).orderBy(asc(juniorWorkspaceRepos.provider), asc(juniorWorkspaceRepos.repo));
2886
+ }
2887
+ async function replaceWorkspaceRepos(db, workspaceId, repos) {
2888
+ await db.delete(juniorWorkspaceRepos).where(eq(juniorWorkspaceRepos.workspaceId, workspaceId));
2889
+ if (repos.length === 0) return;
2890
+ await db.insert(juniorWorkspaceRepos).values(repos.map((repo) => ({
2891
+ workspaceId,
2892
+ provider: repo.provider,
2893
+ repo: repo.repo
2894
+ })));
2895
+ }
2896
+ function sameWorkspaceRepos(current, next) {
2897
+ if (current.length !== next.length) return false;
2898
+ const identity = (repo) => `${repo.provider}:${repo.repo.toLowerCase()}`;
2899
+ const currentIds = current.map(identity).sort();
2900
+ const nextIds = next.map(identity).sort();
2901
+ return currentIds.every((value, index) => value === nextIds[index]);
2902
+ }
2903
+ function isUniqueViolation(error) {
2904
+ let current = error;
2905
+ for (let depth = 0; current && depth < 6; depth += 1) {
2906
+ if (typeof current === "object" && current !== null && "code" in current && current.code === "23505") return true;
2907
+ current = typeof current === "object" && current !== null && "cause" in current ? current.cause : void 0;
2908
+ }
2909
+ return false;
2910
+ }
2911
+ async function cleanupSnapshotBuilders(workspaceId, names) {
2912
+ if (names.length === 0) return;
2913
+ try {
2914
+ await deleteWorkspaceSnapshotBuilders(names);
2915
+ } catch (error) {
2916
+ logException(error, "sandbox.workspace_snapshot.builder.delete_failed", {
2917
+ "app.workspace.id": workspaceId,
2918
+ "app.sandbox.snapshot.builder_count": names.length
2919
+ });
2920
+ }
2921
+ }
2922
+ /** List Workspace recipes by stable name. */
2923
+ async function listWorkspaces(db) {
2924
+ const [workspaces, repos] = await Promise.all([db.select().from(juniorWorkspaces).orderBy(asc(juniorWorkspaces.name)), db.select().from(juniorWorkspaceRepos).orderBy(asc(juniorWorkspaceRepos.workspaceId), asc(juniorWorkspaceRepos.provider), asc(juniorWorkspaceRepos.repo))]);
2925
+ return workspaces.map((workspace) => workspaceFromRows(workspace, repos.filter((repo) => repo.workspaceId === workspace.id), null));
2926
+ }
2927
+ /** Find Workspace names that include one provider repository. */
2928
+ async function listWorkspaceNamesByRepository(db, input) {
2929
+ const provider = input.provider.trim().toLowerCase();
2930
+ const repo = input.repo.trim();
2931
+ return (await db.select({ name: juniorWorkspaces.name }).from(juniorWorkspaceRepos).innerJoin(juniorWorkspaces, eq(juniorWorkspaces.id, juniorWorkspaceRepos.workspaceId)).where(and(eq(juniorWorkspaceRepos.provider, provider), sql`lower(${juniorWorkspaceRepos.repo}) = lower(${repo})`)).orderBy(asc(juniorWorkspaces.name))).map((row) => row.name);
2932
+ }
2933
+ /** Resolve one Workspace recipe by name. */
2934
+ async function getWorkspaceByName(db, name) {
2935
+ const workspace = (await db.select().from(juniorWorkspaces).where(eq(juniorWorkspaces.name, name)).limit(1))[0];
2936
+ if (!workspace) return void 0;
2937
+ return await workspaceWithSnapshot(db, workspace, await loadWorkspaceRepos(db, workspace.id));
2938
+ }
2939
+ /** Resolve one Workspace recipe by id. */
2940
+ async function getWorkspace(db, id) {
2941
+ const workspace = (await db.select().from(juniorWorkspaces).where(eq(juniorWorkspaces.id, id)).limit(1))[0];
2942
+ if (!workspace) return void 0;
2943
+ return await workspaceWithSnapshot(db, workspace, await loadWorkspaceRepos(db, workspace.id));
2944
+ }
2945
+ /** Create one install-wide Workspace recipe. */
2946
+ async function createWorkspace(input) {
2947
+ const recipe = normalizeWorkspaceRecipe(input);
2948
+ const executor = getSqlExecutor();
2949
+ const now = /* @__PURE__ */ new Date();
2950
+ const id = randomUUID();
2951
+ try {
2952
+ await executor.transaction(async () => {
2953
+ const db = executor.db();
2954
+ await db.insert(juniorWorkspaces).values({
2955
+ id,
2956
+ name: recipe.name,
2957
+ setupScript: recipe.setupScript,
2958
+ createdAt: now,
2959
+ updatedAt: now
2960
+ });
2961
+ await replaceWorkspaceRepos(db, id, recipe.repos);
2962
+ });
2963
+ } catch (error) {
2964
+ if (isUniqueViolation(error)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
2965
+ throw error;
2966
+ }
2967
+ return await getWorkspace(executor.db(), id);
2968
+ }
2969
+ /** Replace one install-wide Workspace recipe. */
2970
+ async function updateWorkspace(id, input) {
2971
+ const recipe = normalizeWorkspaceRecipe(input);
2972
+ const executor = getSqlExecutor();
2973
+ const now = /* @__PURE__ */ new Date();
2974
+ try {
2975
+ const result = await executor.transaction(async () => {
2976
+ const db = executor.db();
2977
+ const existing = (await db.select().from(juniorWorkspaces).where(eq(juniorWorkspaces.id, id)).limit(1))[0];
2978
+ if (!existing) return void 0;
2979
+ const existingRepos = await loadWorkspaceRepos(db, id);
2980
+ const snapshotChanged = existing.setupScript !== recipe.setupScript || !sameWorkspaceRepos(existingRepos, recipe.repos);
2981
+ const rows = await db.update(juniorWorkspaces).set({
2982
+ name: recipe.name,
2983
+ setupScript: recipe.setupScript,
2984
+ updatedAt: now
2985
+ }).where(eq(juniorWorkspaces.id, id)).returning();
2986
+ await replaceWorkspaceRepos(db, id, recipe.repos);
2987
+ return {
2988
+ builderNames: snapshotChanged ? await clearWorkspaceSnapshots(db, id) : [],
2989
+ workspace: rows[0]
2990
+ };
2991
+ });
2992
+ if (!result) return void 0;
2993
+ await cleanupSnapshotBuilders(id, result.builderNames);
2994
+ } catch (error) {
2995
+ if (isUniqueViolation(error)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
2996
+ throw error;
2997
+ }
2998
+ return await getWorkspace(executor.db(), id);
2999
+ }
3000
+ /** Delete one install-wide Workspace recipe. */
3001
+ async function deleteWorkspace(id) {
3002
+ const executor = getSqlExecutor();
3003
+ const result = await executor.transaction(async () => {
3004
+ const db = executor.db();
3005
+ return {
3006
+ builderNames: await clearWorkspaceSnapshots(db, id),
3007
+ deleted: (await db.delete(juniorWorkspaces).where(eq(juniorWorkspaces.id, id)).returning({ id: juniorWorkspaces.id })).length > 0
3008
+ };
3009
+ });
3010
+ await cleanupSnapshotBuilders(id, result.builderNames);
3011
+ return result.deleted;
3012
+ }
3013
+ //#endregion
3014
+ //#region src/chat/code/store.ts
3015
+ /** Record the latest details for one code change created by Junior. */
3016
+ async function recordCodeChange(db, provider, input) {
3017
+ const change = codeChangeInputSchema.parse(input);
3018
+ const repositories = await db.insert(juniorCodeRepositories).values({
3019
+ id: randomUUID(),
3020
+ name: change.repository.name,
3021
+ provider,
3022
+ providerId: change.repository.providerId,
3023
+ url: change.repository.url,
3024
+ updatedAt: change.updatedAt
3025
+ }).onConflictDoUpdate({
3026
+ target: [juniorCodeRepositories.provider, juniorCodeRepositories.providerId],
3027
+ set: {
3028
+ name: change.repository.name,
3029
+ ...change.repository.url ? { url: change.repository.url } : void 0,
3030
+ updatedAt: change.updatedAt
3031
+ },
3032
+ where: lte(juniorCodeRepositories.updatedAt, change.updatedAt)
3033
+ }).returning({ id: juniorCodeRepositories.id });
3034
+ const existingRepositories = repositories[0] ? [] : await db.select({ id: juniorCodeRepositories.id }).from(juniorCodeRepositories).where(and(eq(juniorCodeRepositories.provider, provider), eq(juniorCodeRepositories.providerId, change.repository.providerId))).limit(1);
3035
+ const repositoryId = repositories[0]?.id ?? existingRepositories[0]?.id;
3036
+ if (!repositoryId) throw new Error("Code repository upsert returned no row");
3037
+ const conversationIds = sql.join(change.conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
3038
+ const values = {
3039
+ closedAt: change.closedAt ?? null,
3040
+ conversationIds: change.conversationIds.length > 0 ? sql`ARRAY(
3041
+ SELECT DISTINCT value
3042
+ FROM unnest(
3043
+ ${juniorCodeChanges.conversationIds}
3044
+ || ARRAY[${conversationIds}]::text[]
3045
+ ) AS value
3046
+ ORDER BY value
3047
+ )` : juniorCodeChanges.conversationIds,
3048
+ mergedAt: change.mergedAt ?? null,
3049
+ number: change.number,
3050
+ openedAt: change.openedAt,
3051
+ repositoryId,
3052
+ state: change.state,
3053
+ ...change.title ? { title: change.title } : void 0,
3054
+ updatedAt: change.updatedAt,
3055
+ url: change.url ?? null
3056
+ };
3057
+ await db.insert(juniorCodeChanges).values({
3058
+ ...values,
3059
+ conversationIds: change.conversationIds,
3060
+ id: randomUUID(),
3061
+ provider,
3062
+ providerId: change.providerId
3063
+ }).onConflictDoUpdate({
3064
+ target: [juniorCodeChanges.provider, juniorCodeChanges.providerId],
3065
+ set: values,
3066
+ where: lte(juniorCodeChanges.updatedAt, change.updatedAt)
3067
+ });
3068
+ }
3069
+ /** Add conversation links to an existing code change. */
3070
+ async function associateCodeChangeConversations(db, provider, input) {
3071
+ if (input.conversationIds.length === 0) return;
3072
+ const conversationIds = sql.join(input.conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
3073
+ await db.update(juniorCodeChanges).set({ conversationIds: sql`ARRAY(
3074
+ SELECT DISTINCT value
3075
+ FROM unnest(
3076
+ ${juniorCodeChanges.conversationIds}
3077
+ || ARRAY[${conversationIds}]::text[]
3078
+ ) AS value
3079
+ ORDER BY value
3080
+ )` }).where(and(eq(juniorCodeChanges.provider, provider), eq(juniorCodeChanges.providerId, input.providerId)));
3081
+ }
3082
+ //#endregion
3083
+ //#region src/chat/code/publisher.ts
3084
+ /** Connect a plugin to Junior's code records. */
3085
+ function createCodeChangePublisher(provider) {
3086
+ return {
3087
+ async associateConversations(input) {
3088
+ await associateCodeChangeConversations(getDb(), provider, input);
3089
+ },
3090
+ async record(input) {
3091
+ await recordCodeChange(getDb(), provider, input);
3092
+ }
3093
+ };
3094
+ }
3095
+ //#endregion
3096
+ //#region src/chat/plugins/agent-hooks.ts
3097
+ var agent_hooks_exports = /* @__PURE__ */ __exportAll({
3098
+ PluginHookDeniedError: () => PluginHookDeniedError,
3099
+ applyPluginFormatMarkdown: () => applyPluginFormatMarkdown,
3100
+ createPluginHookRunner: () => createPluginHookRunner,
3101
+ getPluginApiRoutes: () => getPluginApiRoutes,
3102
+ getPluginOperationalReports: () => getPluginOperationalReports,
3103
+ getPluginProfileReports: () => getPluginProfileReports,
3104
+ getPluginRoutes: () => getPluginRoutes,
3105
+ getPluginSlackConversationLink: () => getPluginSlackConversationLink,
3106
+ getPluginSystemPromptContributions: () => getPluginSystemPromptContributions,
3107
+ getPluginTools: () => getPluginTools,
3108
+ getPluginUserPromptContributions: () => getPluginUserPromptContributions,
3109
+ getPlugins: () => getPlugins,
3110
+ setPlugins: () => setPlugins,
3111
+ validatePlugins: () => validatePlugins
3112
+ });
3113
+ /** Signal that a plugin intentionally denied a tool execution. */
3114
+ var PluginHookDeniedError = class extends Error {
3115
+ constructor(message) {
3116
+ super(message);
3117
+ this.name = "PluginHookDeniedError";
3118
+ }
3119
+ };
3120
+ let registeredPlugins = [];
3121
+ const PLUGIN_NAME_RE = /^[a-z][a-z0-9-]*$/;
3122
+ const PLUGIN_TOOL_NAME_RE = /^[a-z][A-Za-z0-9]*$/;
3123
+ const OPERATIONAL_REPORT_MAX_METRICS = 8;
3124
+ const OPERATIONAL_REPORT_MAX_WIDGETS = 12;
3125
+ const OPERATIONAL_REPORT_MAX_CHART_SERIES = 8;
3126
+ const OPERATIONAL_REPORT_MAX_RECORD_SETS = 8;
3127
+ const OPERATIONAL_REPORT_MAX_FIELDS = 8;
3128
+ const OPERATIONAL_REPORT_MAX_RECORDS = 25;
3129
+ const OPERATIONAL_REPORT_MAX_LABEL_LENGTH = 80;
3130
+ const OPERATIONAL_REPORT_MAX_VALUE_LENGTH = 160;
3131
+ const PLUGIN_ROUTE_METHODS = /* @__PURE__ */ new Set([
3132
+ "GET",
3133
+ "POST",
3134
+ "PUT",
3135
+ "PATCH",
3136
+ "DELETE",
3137
+ "HEAD",
3138
+ "OPTIONS",
3139
+ "ALL"
3140
+ ]);
3141
+ const PLUGIN_PROMPT_CONTRIBUTION_TOTAL_MAX_CHARS = 16e3;
3142
+ const PLUGIN_PROMPT_CONTEXT_MAX_BYTES = 8e3;
3143
+ const PLUGIN_PROMPT_CONTEXT_TOTAL_MAX_BYTES = 16e3;
3144
+ const systemPromptMessageArraySchema = z.array(promptMessageSchema);
3145
+ function isRecord(value) {
3146
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
3147
+ }
3148
+ function basePluginContext(plugin) {
3149
+ const name = plugin.manifest.name;
3150
+ return {
3151
+ plugin: { name },
3152
+ log: createPluginLogger(name),
3153
+ db: getDb()
3154
+ };
3155
+ }
3156
+ /** Convert manifest names into model-facing tool namespaces. */
3157
+ function pluginToolNamespace(pluginName) {
3158
+ const [first = "plugin", ...rest] = pluginName.split("-").filter(Boolean);
3159
+ return `${first}${rest.map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join("")}`;
3160
+ }
3161
+ function systemPromptPluginContext(plugin) {
3162
+ return { ...basePluginContext(plugin) };
3163
+ }
3164
+ /** Bind Source, Destination, and Actor for one plugin invocation. */
3165
+ function pluginInvocationContext(context) {
3166
+ const common = {
3167
+ conversationId: context.conversationId,
3168
+ locationId: context.locationId
3169
+ };
3170
+ switch (context.source.kind) {
3171
+ case "slack":
3172
+ if (context.destination.platform !== "slack") throw new TypeError("Slack plugin context requires Slack destination");
3173
+ return {
3174
+ ...common,
3175
+ actor: context.actor?.platform === "slack" ? context.actor : void 0,
3176
+ destination: context.destination,
3177
+ source: context.source
3178
+ };
3179
+ case "local":
3180
+ if (context.destination.platform !== "local") throw new TypeError("Local plugin context requires local destination");
3181
+ return {
3182
+ ...common,
3183
+ actor: context.actor?.platform === "local" ? context.actor : void 0,
3184
+ destination: context.destination,
3185
+ source: context.source
3186
+ };
3187
+ case "web": return {
3188
+ ...common,
3189
+ actor: context.actor?.platform === "web" ? context.actor : void 0,
3190
+ destination: context.destination,
3191
+ source: context.source
3192
+ };
3193
+ case "resource_event":
3194
+ case "scheduled_task":
3195
+ case "event_task":
3196
+ case "plugin_dispatch":
3197
+ case "agent_invocation": return {
3198
+ ...common,
3199
+ actor: context.actor,
3200
+ destination: context.destination,
3201
+ source: context.source
3202
+ };
3203
+ }
3204
+ }
3205
+ function invocationPluginContext(plugin, context, turnId) {
3206
+ return {
3207
+ ...basePluginContext(plugin),
3208
+ conversationId: context.conversationId,
3209
+ locationId: context.locationId,
3210
+ embedder: createPluginEmbedder(plugin.manifest.name),
3211
+ ...context.conversationId && turnId ? { events: createPluginConversationEvents({
3212
+ conversationId: context.conversationId,
3213
+ operationId: `user-prompt:${turnId}`,
3214
+ plugin,
3215
+ turnId
3216
+ }) } : void 0,
3217
+ model: createPluginModel(plugin.manifest.name, plugin.model),
3218
+ source: context.source,
3219
+ text: context.userText ?? "",
3220
+ state: createPluginState(plugin.manifest.name),
3221
+ users: { resolveActor: context.resolveActorIdentity ?? (async () => void 0) },
3222
+ ...pluginInvocationContext(context)
3223
+ };
3224
+ }
3225
+ function pluginMcpContext(plugin, context) {
3226
+ const manager = context.mcpToolManager;
3227
+ const wrappedTools = new Set(plugin.manifest.mcp?.wrappedTools ?? []);
3228
+ if (!manager || wrappedTools.size === 0) return;
3229
+ const provider = plugin.manifest.name;
3230
+ const prepare = async () => {
3231
+ await manager.activateProvider(provider);
3232
+ return manager.getActiveProviders().includes(provider) ? "ready" : "authorization_pending";
3233
+ };
3234
+ return {
3235
+ prepare,
3236
+ async callTool(input) {
3237
+ if (await prepare() === "authorization_pending") return { status: "authorization_pending" };
3238
+ return await manager.callWrappedTool(provider, input.name, input.arguments ?? {}, input.toolCallId ? { toolCallId: input.toolCallId } : void 0);
3239
+ }
3240
+ };
3241
+ }
3242
+ function safeErrorMessage(error) {
3243
+ return error instanceof Error ? error.message : String(error);
3244
+ }
3245
+ function toPromptContributionContext(args) {
3246
+ return {
3247
+ id: `${args.hookName}:${args.index}`,
3248
+ pluginName: args.pluginName,
3249
+ text: args.message.text
3250
+ };
3251
+ }
3252
+ function normalizePromptContext(value) {
3253
+ const serialized = JSON.stringify(value);
3254
+ if (serialized === void 0 || Buffer.byteLength(serialized, "utf8") > PLUGIN_PROMPT_CONTEXT_MAX_BYTES) throw new TypeError("Plugin prompt context exceeded its serialized budget");
3255
+ const parsed = JSON.parse(serialized);
3256
+ if (!isRecord(parsed)) throw new TypeError("Plugin prompt context must be a JSON object");
3257
+ return parsed;
3258
+ }
3259
+ function toUserPromptContributionContext(args) {
3260
+ const message = promptMessageSchema.safeParse(args.value);
3261
+ if (message.success) return toPromptContributionContext({
3262
+ hookName: "userPrompt",
3263
+ index: args.index,
3264
+ message: message.data,
3265
+ pluginName: args.pluginName
3266
+ });
3267
+ if (!isRecord(args.value) || typeof args.value.renderPrompt !== "function") return;
3268
+ const context = promptContextSchema.safeParse(args.value.context);
3269
+ if (!context.success) return;
3270
+ const text = promptMessageSchema.safeParse({ text: args.value.renderPrompt() });
3271
+ if (!text.success) return;
3272
+ return {
3273
+ id: `userPrompt:${args.index}`,
3274
+ pluginName: args.pluginName,
3275
+ text: text.data.text,
3276
+ context: {
3277
+ content: normalizePromptContext(context.data.content),
3278
+ kind: context.data.kind,
3279
+ loadedAtMs: Date.now(),
3280
+ pluginName: args.pluginName,
3281
+ version: context.data.version
3282
+ }
3283
+ };
3284
+ }
3285
+ function logInvalidPromptContributions(args) {
3286
+ logWarn("plugin.prompt.contribution_result.invalid", {
3287
+ "app.plugin.hook": args.hookName,
3288
+ "app.plugin.name": args.pluginName,
3289
+ "app.plugin.validation_reason": "invalid_shape"
3290
+ });
3291
+ }
3292
+ /** Validate plugin identity before it can affect process-wide hooks. */
3293
+ function validatePlugins(plugins) {
3294
+ const seen = /* @__PURE__ */ new Set();
3295
+ for (const plugin of plugins) {
3296
+ const name = plugin.manifest.name;
3297
+ if (!PLUGIN_NAME_RE.test(name)) throw new Error(`Plugin name "${name}" must be a lowercase plugin identifier`);
3298
+ if (seen.has(name)) throw new Error(`Duplicate plugin name "${name}"`);
3299
+ if (plugin.resourceEvents !== void 0 && !pluginResourceEventsSchema.safeParse(plugin.resourceEvents).success) throw new Error(`Plugin "${name}" resourceEvents is invalid`);
3300
+ for (const [taskName, task] of Object.entries(plugin.tasks ?? {})) {
3301
+ if (!PLUGIN_TOOL_NAME_RE.test(taskName)) throw new Error(`Plugin task "${taskName}" from plugin "${name}" must be a camelCase identifier`);
3302
+ if (typeof task.run !== "function") throw new Error(`Plugin task "${taskName}" from plugin "${name}" must define a run function`);
3303
+ }
3304
+ seen.add(name);
3305
+ }
3306
+ }
3307
+ /** Replace runtime hook plugins and return the previous list for rollback. */
3308
+ function setPlugins(nextPlugins) {
3309
+ validatePlugins(nextPlugins);
3310
+ const previous = registeredPlugins;
3311
+ registeredPlugins = [...nextPlugins].sort((left, right) => left.manifest.name.localeCompare(right.manifest.name));
3312
+ return previous;
3313
+ }
3314
+ /** Return the current runtime hook plugins without exposing mutable state. */
3315
+ function getPlugins() {
3316
+ return [...registeredPlugins];
3317
+ }
3318
+ /** Apply plugin Markdown rewrites before destination delivery formatting. */
3319
+ function applyPluginFormatMarkdown(text) {
3320
+ let transformed = text;
3321
+ for (const plugin of getPlugins()) {
3322
+ const hook = plugin.hooks?.formatMarkdown;
3323
+ if (!hook) continue;
3324
+ try {
3325
+ const next = hook({ text: transformed });
3326
+ if (typeof next === "string") transformed = next;
3327
+ } catch (error) {
3328
+ logWarn("plugin.format_markdown.hook.failed", {
3329
+ "app.plugin.name": plugin.manifest.name,
3330
+ "exception.message": safeErrorMessage(error)
3331
+ });
3332
+ }
3333
+ }
3334
+ return transformed;
3335
+ }
3336
+ /** Collect stable plugin prompt contributions for the static system prompt. */
3337
+ async function getPluginSystemPromptContributions(platform) {
3338
+ const contributions = [];
3339
+ let totalChars = 0;
3340
+ for (const plugin of getPlugins()) {
3341
+ const pluginName = plugin.manifest.name;
3342
+ const hook = plugin.hooks?.systemPrompt;
3343
+ if (!hook) continue;
3344
+ try {
3345
+ const pluginContributions = await hook({
3346
+ ...systemPromptPluginContext(plugin),
3347
+ platform
3348
+ });
3349
+ const result = systemPromptMessageArraySchema.safeParse(pluginContributions);
3350
+ if (!result.success) {
3351
+ logInvalidPromptContributions({
3352
+ hookName: "systemPrompt",
3353
+ pluginName
3354
+ });
3355
+ continue;
3356
+ }
3357
+ const acceptedContributions = result.data.map((message, index) => toPromptContributionContext({
3358
+ hookName: "systemPrompt",
3359
+ index,
3360
+ message,
3361
+ pluginName
3362
+ }));
3363
+ const pluginContributionChars = acceptedContributions.reduce((sum, contribution) => sum + contribution.text.length, 0);
3364
+ if (totalChars + pluginContributionChars > PLUGIN_PROMPT_CONTRIBUTION_TOTAL_MAX_CHARS) {
3365
+ logWarn("plugin.system_prompt.contribution_budget_exceeded", { "app.plugin.name": pluginName });
3366
+ continue;
3367
+ }
3368
+ totalChars += pluginContributionChars;
3369
+ contributions.push(...acceptedContributions);
3370
+ } catch (error) {
3371
+ logWarn("plugin.system_prompt.hook.failed", {
3372
+ "app.plugin.name": pluginName,
3373
+ "exception.message": safeErrorMessage(error)
3374
+ });
3375
+ }
3376
+ }
3377
+ return contributions;
3378
+ }
3379
+ /** Collect request-scoped plugin prompt contributions. */
3380
+ async function getPluginUserPromptContributions(args) {
3381
+ const contributions = [];
3382
+ let totalChars = 0;
3383
+ let totalContextBytes = 0;
3384
+ for (const plugin of getPlugins()) {
3385
+ const pluginName = plugin.manifest.name;
3386
+ const hook = plugin.hooks?.userPrompt;
3387
+ if (!hook) continue;
3388
+ try {
3389
+ const rawResult = await hook({ ...invocationPluginContext(plugin, args.context, args.turnId) });
3390
+ if (rawResult === void 0) continue;
3391
+ if (!Array.isArray(rawResult)) {
3392
+ logInvalidPromptContributions({
3393
+ hookName: "userPrompt",
3394
+ pluginName
3395
+ });
3396
+ continue;
3397
+ }
3398
+ const acceptedContributions = rawResult.map((value, index) => toUserPromptContributionContext({
3399
+ index,
3400
+ pluginName,
3401
+ value
3402
+ }));
3403
+ if (acceptedContributions.some((contribution) => !contribution)) {
3404
+ logInvalidPromptContributions({
3405
+ hookName: "userPrompt",
3406
+ pluginName
3407
+ });
3408
+ continue;
3409
+ }
3410
+ const validContributions = acceptedContributions.filter((contribution) => contribution !== void 0);
3411
+ const pluginContributionChars = validContributions.reduce((sum, contribution) => sum + contribution.text.length, 0);
3412
+ const pluginContextBytes = validContributions.reduce((sum, contribution) => sum + (contribution.context ? Buffer.byteLength(JSON.stringify(contribution.context.content), "utf8") : 0), 0);
3413
+ if (totalChars + pluginContributionChars > PLUGIN_PROMPT_CONTRIBUTION_TOTAL_MAX_CHARS || totalContextBytes + pluginContextBytes > PLUGIN_PROMPT_CONTEXT_TOTAL_MAX_BYTES) {
3414
+ logWarn("plugin.user_prompt.contribution_budget_exceeded", { "app.plugin.name": pluginName });
3415
+ continue;
3416
+ }
3417
+ totalChars += pluginContributionChars;
3418
+ totalContextBytes += pluginContextBytes;
3419
+ contributions.push(...validContributions);
3420
+ } catch (error) {
3421
+ logWarn("plugin.user_prompt.hook.failed", {
3422
+ "app.plugin.name": pluginName,
3423
+ "exception.message": safeErrorMessage(error)
3424
+ });
3425
+ }
3426
+ }
3427
+ return contributions;
3428
+ }
3429
+ /** Collect turn-scoped tools exposed by plugins. */
3430
+ function getPluginTools(context, sandbox = createSandboxCapability(context.workspace)) {
3431
+ const tools = {};
3432
+ for (const plugin of getPlugins()) {
3433
+ const pluginName = plugin.manifest.name;
3434
+ const hook = plugin.hooks?.tools;
3435
+ if (!hook) continue;
3436
+ const slackToolContext = getSlackToolContext(context);
3437
+ const credentialSubject = slackToolContext ? createSlackDirectCredentialSubject({
3438
+ channelId: slackToolContext.locationChannelId,
3439
+ teamId: slackToolContext.teamId,
3440
+ userId: slackToolContext.actor?.userId
3441
+ }) : void 0;
3442
+ const dashboardConversationUrl = getDashboardConversationLink(context.conversationId);
3443
+ const slackContext = slackToolContext ? {
3444
+ channelCapabilities: resolveChannelCapabilities(slackToolContext.locationChannelId),
3445
+ ...dashboardConversationUrl ? { conversationLink: { url: dashboardConversationUrl } } : void 0,
3446
+ ...credentialSubject ? { credentialSubject } : void 0
3447
+ } : void 0;
3448
+ const annotations = createPluginAnnotations({
3449
+ conversationId: context.conversationId,
3450
+ db: getDb(),
3451
+ plugin: pluginName
3452
+ });
3453
+ const mcp = pluginMcpContext(plugin, context);
3454
+ const canSubscribe = Boolean(plugin.resourceEvents) && plugin.resourceEvents?.isEnabled?.() !== false;
3455
+ const resourceEvents = {
3456
+ canSubscribe,
3457
+ async subscribe(input) {
3458
+ if (!canSubscribe) throw new Error("Resource subscriptions are not available in this conversation.");
3459
+ const registration = plugin.resourceEvents;
3460
+ const resourceType = registration?.resourceTypes.find((candidate) => candidate.type === input.resource.type);
3461
+ if (input.resource.namespace !== pluginName || !resourceType || input.events.length === 0 || input.events.some((eventType) => !resourceType.supportedEvents.includes(eventType))) throw new Error("Resource subscription contains an event or resource that the plugin does not support.");
3462
+ const subscription = await createResourceEventSubscription({
3463
+ conversationId: context.conversationId,
3464
+ events: input.events,
3465
+ expiresAtMs: Date.now() + RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS,
3466
+ intent: input.intent,
3467
+ label: input.resource.label,
3468
+ namespace: pluginName,
3469
+ identifier: normalizeResourceEventIdentifier(registration, input.resource.identifier),
3470
+ resourceType: input.resource.type
3471
+ });
3472
+ return {
3473
+ events: subscription.events,
3474
+ id: subscription.id
3475
+ };
3476
+ }
3477
+ };
3478
+ const resolveActor = context.resolveActorIdentity ?? (async () => void 0);
3479
+ const common = {
3480
+ ...basePluginContext(plugin),
3481
+ annotations,
3482
+ conversationId: context.conversationId,
3483
+ locationId: context.locationId,
3484
+ ...slackContext ? { slack: slackContext } : void 0,
3485
+ userText: context.userText,
3486
+ embedder: createPluginEmbedder(pluginName),
3487
+ egress: context.egress,
3488
+ ...mcp ? { mcp } : void 0,
3489
+ model: createPluginModel(pluginName, plugin.model),
3490
+ resourceEvents,
3491
+ sandbox,
3492
+ state: createPluginState(pluginName),
3493
+ users: { resolveActor },
3494
+ workspaces: { async findByRepository(input) {
3495
+ return await listWorkspaceNamesByRepository(getDb(), input);
3496
+ } }
3497
+ };
3498
+ let pluginContext;
3499
+ switch (context.source.kind) {
3500
+ case "slack":
3501
+ if (context.destination.platform !== "slack") throw new TypeError("Slack plugin context requires Slack destination");
3502
+ pluginContext = {
3503
+ ...common,
3504
+ actor: context.actor?.platform === "slack" ? context.actor : void 0,
3505
+ destination: context.destination,
3506
+ source: context.source
3507
+ };
3508
+ break;
3509
+ case "local":
3510
+ if (context.destination.platform !== "local") throw new TypeError("Local plugin context requires local destination");
3511
+ pluginContext = {
3512
+ ...common,
3513
+ actor: context.actor?.platform === "local" ? context.actor : void 0,
3514
+ destination: context.destination,
3515
+ source: context.source
3516
+ };
3517
+ break;
3518
+ case "web":
3519
+ pluginContext = {
3520
+ ...common,
3521
+ actor: context.actor?.platform === "web" ? context.actor : void 0,
3522
+ destination: context.destination,
3523
+ source: context.source
3524
+ };
3525
+ break;
3526
+ case "resource_event":
3527
+ case "scheduled_task":
3528
+ case "event_task":
3529
+ case "plugin_dispatch":
3530
+ case "agent_invocation": pluginContext = {
3531
+ ...common,
3532
+ actor: context.actor,
3533
+ destination: context.destination,
3534
+ source: context.source
3535
+ };
3536
+ }
3537
+ const pluginTools = hook(pluginContext);
3538
+ const namespace = pluginToolNamespace(pluginName);
3539
+ for (const [localName, tool] of Object.entries(pluginTools)) {
3540
+ if (!PLUGIN_TOOL_NAME_RE.test(localName)) throw new Error(`Plugin tool "${localName}" from plugin "${pluginName}" must be a camelCase identifier`);
3541
+ const name = `${namespace}_${localName}`;
3542
+ if (tools[name]) throw new Error(`Duplicate plugin tool "${name}" from plugin "${pluginName}"`);
3543
+ const definition = tool;
3544
+ const missingAnnotationKeys = missingToolAnnotationKeys(definition.annotations);
3545
+ if (missingAnnotationKeys.length > 0) logWarn("plugin.tool_annotations.missing", {
3546
+ "app.plugin.name": pluginName,
3547
+ "gen_ai.tool.name": localName,
3548
+ "app.tool.missing_annotations": missingAnnotationKeys.join(",")
3549
+ });
3550
+ definition.approvalMode ??= "auto";
3551
+ definition.identity = {
3552
+ id: `${pluginName}.${localName}`,
3553
+ name: localName,
3554
+ plugin: pluginName
3555
+ };
3556
+ definition.source = {
3557
+ id: pluginName,
3558
+ description: plugin.manifest.description
3559
+ };
3560
+ definition.exposure ??= "deferred";
3561
+ tools[name] = definition;
3562
+ }
3563
+ }
3564
+ return tools;
3565
+ }
3566
+ /** Normalize route methods so JS plugins cannot register invalid verbs. */
3567
+ function routeMethods(route, pluginName) {
3568
+ const methods = Array.isArray(route.method) ? route.method : [route.method ?? "ALL"];
3569
+ if (methods.length === 0) throw new Error(`Plugin route "${route.path}" from plugin "${pluginName}" must declare at least one method`);
3570
+ for (const method of methods) if (!PLUGIN_ROUTE_METHODS.has(method)) throw new Error(`Plugin route "${route.path}" from plugin "${pluginName}" has invalid method "${String(method)}"`);
3571
+ if (methods.includes("ALL") && methods.length > 1) throw new Error(`Plugin route "${route.path}" from plugin "${pluginName}" must not combine ALL with explicit methods`);
3572
+ return methods;
3573
+ }
3574
+ function requirePublishedResourceEvent(plugin, eventType) {
3575
+ const registration = plugin.resourceEvents;
3576
+ if (!registration || registration.isEnabled?.() === false) throw new Error(`Plugin "${plugin.manifest.name}" cannot publish resource events without an active registration`);
3577
+ if (!registration.resourceTypes.some((resourceType) => resourceType.supportedEvents.includes(eventType))) throw new Error(`Plugin "${plugin.manifest.name}" did not register resource event "${eventType}"`);
3578
+ }
3579
+ /** Collect route handlers exposed by plugins for app-level mounting. */
3580
+ function getPluginRoutes(options) {
3581
+ const routes = [];
3582
+ const seen = /* @__PURE__ */ new Set();
3583
+ const methodsByPath = /* @__PURE__ */ new Map();
3584
+ for (const plugin of getPlugins()) {
3585
+ const pluginName = plugin.manifest.name;
3586
+ const hook = plugin.hooks?.routes;
3587
+ if (!hook) continue;
3588
+ const pluginRoutes = hook({
3589
+ ...basePluginContext(plugin),
3590
+ annotations: { forConversation: (conversationId) => createPluginAnnotations({
3591
+ conversationId,
3592
+ db: getDb(),
3593
+ plugin: pluginName
3594
+ }) },
3595
+ codeChanges: createCodeChangePublisher(pluginName),
3596
+ resourceEvents: {
3597
+ async hasMatch(event) {
3598
+ if (!options.resourceEvents.hasMatch) return false;
3599
+ const parsed = resourceEventInputSchema.parse(event);
3600
+ requirePublishedResourceEvent(plugin, parsed.eventType);
3601
+ return await options.resourceEvents.hasMatch({
3602
+ ...parsed,
3603
+ identifier: normalizeResourceEventIdentifier(plugin.resourceEvents, parsed.identifier),
3604
+ namespace: pluginName
3605
+ });
3606
+ },
3607
+ async neededMatchKeys(input) {
3608
+ if (!options.resourceEvents.neededMatchKeys) return [];
3609
+ const identifiers = [...new Set(input.identifiers.map((identifier) => normalizeResourceEventIdentifier(plugin.resourceEvents, identifier)).filter(Boolean))];
3610
+ if (identifiers.length === 0 || input.eventTypes.length === 0) return [];
3611
+ return await options.resourceEvents.neededMatchKeys({
3612
+ eventTypes: input.eventTypes,
3613
+ identifiers,
3614
+ namespace: pluginName
3615
+ });
3616
+ },
3617
+ async publish(event) {
3618
+ const parsed = resourceEventInputSchema.parse(event);
3619
+ requirePublishedResourceEvent(plugin, parsed.eventType);
3620
+ await options.resourceEvents.publish({
3621
+ ...parsed,
3622
+ identifier: normalizeResourceEventIdentifier(plugin.resourceEvents, parsed.identifier),
3623
+ namespace: pluginName
3624
+ });
3625
+ }
3626
+ }
3627
+ });
3628
+ if (!Array.isArray(pluginRoutes)) throw new Error(`Plugin routes hook from plugin "${pluginName}" must return an array`);
3629
+ for (const route of pluginRoutes) {
3630
+ if (!isRecord(route)) throw new Error(`Plugin route from plugin "${pluginName}" must be an object`);
3631
+ if (typeof route.path !== "string" || !route.path.startsWith("/")) throw new Error(`Plugin route "${route.path}" from plugin "${pluginName}" must start with /`);
3632
+ if (typeof route.handler !== "function") throw new Error(`Plugin route "${route.path}" from plugin "${pluginName}" must provide a handler`);
3633
+ const methods = routeMethods(route, pluginName);
3634
+ const pathMethods = methodsByPath.get(route.path) ?? /* @__PURE__ */ new Set();
3635
+ if (pathMethods.has("ALL") || methods.includes("ALL") && pathMethods.size > 0) throw new Error(`Plugin route "${route.path}" conflicts with an ALL route for the same path`);
3636
+ for (const method of methods) {
3637
+ const key = `${method}:${route.path}`;
3638
+ if (seen.has(key)) throw new Error(`Duplicate plugin route "${method} ${route.path}"`);
3639
+ seen.add(key);
3640
+ pathMethods.add(method);
3641
+ }
3642
+ methodsByPath.set(route.path, pathMethods);
3643
+ routes.push({
3644
+ ...route,
3645
+ pluginName
3646
+ });
3647
+ }
3648
+ }
3649
+ return routes;
3650
+ }
3651
+ /** Collect authenticated product API route apps exposed by plugins. */
3652
+ function getPluginApiRoutes() {
3653
+ const routes = [];
3654
+ for (const plugin of getPlugins()) {
3655
+ const pluginName = plugin.manifest.name;
3656
+ const hook = plugin.hooks?.apiRoutes;
3657
+ if (!hook) continue;
3658
+ const app = hook({
3659
+ ...basePluginContext(plugin),
3660
+ eventStats: createPluginConversationEventStats(plugin),
3661
+ users: { resolve: resolveViewerUser }
3662
+ });
3663
+ if (app === void 0) continue;
3664
+ if (!isRecord(app) || typeof app.fetch !== "function") throw new Error(`Plugin apiRoutes hook from plugin "${pluginName}" must return a fetch-compatible app`);
3665
+ routes.push({
3666
+ app,
3667
+ pluginName
3668
+ });
3669
+ }
3670
+ return routes;
3671
+ }
3672
+ /** Return only absolute HTTP(S) URLs that Slack can render as footer links. */
3673
+ function trustedSlackConversationUrl(pluginName, link) {
3674
+ const url = typeof link?.url === "string" ? link.url.trim() : "";
3675
+ if (!url) return;
3676
+ let parsed;
3677
+ try {
3678
+ parsed = new URL(url);
3679
+ } catch (error) {
3680
+ throw new Error(`Plugin "${pluginName}" slackConversationLink must return an absolute http(s) URL`, { cause: error });
3681
+ }
3682
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`Plugin "${pluginName}" slackConversationLink must return an absolute http(s) URL`);
3683
+ return parsed.toString();
3684
+ }
3685
+ /** Resolve the first plugin conversation URL for finalized Slack footers. */
3686
+ function getPluginSlackConversationLink(conversationId) {
3687
+ for (const plugin of getPlugins()) {
3688
+ const pluginName = plugin.manifest.name;
3689
+ const hook = plugin.hooks?.slackConversationLink;
3690
+ if (!hook) continue;
3691
+ const url = trustedSlackConversationUrl(pluginName, hook({
3692
+ ...basePluginContext(plugin),
3693
+ conversationId
3694
+ }));
3695
+ if (url) return { url };
3696
+ }
3697
+ }
3698
+ function pluginReadState(state) {
3699
+ return { get: state.get };
3700
+ }
3701
+ function operationalReportText(value, maxLength) {
3702
+ if (typeof value !== "string") return;
3703
+ const trimmed = value.trim();
3704
+ if (!trimmed) return;
3705
+ return trimmed.length <= maxLength ? trimmed : `${trimmed.slice(0, Math.max(0, maxLength - 3))}...`;
3706
+ }
3707
+ function operationalReportTone(tone) {
3708
+ return tone === "danger" || tone === "good" || tone === "neutral" || tone === "warning" ? tone : void 0;
3709
+ }
3710
+ function sanitizeOperationalReport(args) {
3711
+ const metrics = args.report.metrics?.slice(0, OPERATIONAL_REPORT_MAX_METRICS).map((metric) => {
3712
+ const label = operationalReportText(metric.label, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3713
+ const value = operationalReportText(metric.value, OPERATIONAL_REPORT_MAX_VALUE_LENGTH);
3714
+ if (!label || !value) return;
3715
+ const sanitizedMetric = {
3716
+ label,
3717
+ value
3718
+ };
3719
+ const tone = operationalReportTone(metric.tone);
3720
+ if (tone) sanitizedMetric.tone = tone;
3721
+ return sanitizedMetric;
3722
+ }).filter((metric) => Boolean(metric));
3723
+ const recordSets = args.report.recordSets?.slice(0, OPERATIONAL_REPORT_MAX_RECORD_SETS).map((recordSet, recordSetIndex) => {
3724
+ const title = operationalReportText(recordSet.title, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3725
+ if (!title) return;
3726
+ const fields = recordSet.fields?.slice(0, OPERATIONAL_REPORT_MAX_FIELDS).map((field) => {
3727
+ const key = operationalReportText(field.key, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3728
+ const label = operationalReportText(field.label, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3729
+ return key && label ? {
3730
+ key,
3731
+ label
3732
+ } : void 0;
3733
+ }).filter((field) => Boolean(field));
3734
+ const records = recordSet.records?.slice(0, OPERATIONAL_REPORT_MAX_RECORDS).map((record, recordIndex) => {
3735
+ const sanitizedRecord = {
3736
+ id: operationalReportText(record.id, OPERATIONAL_REPORT_MAX_LABEL_LENGTH) ?? `${recordSetIndex}:${recordIndex}`,
3737
+ values: Object.fromEntries((fields ?? []).map((field) => [field.key, operationalReportText(record.values[field.key], OPERATIONAL_REPORT_MAX_VALUE_LENGTH) ?? ""]))
3738
+ };
3739
+ const tone = operationalReportTone(record.tone);
3740
+ if (tone) sanitizedRecord.tone = tone;
3741
+ return sanitizedRecord;
3742
+ });
3743
+ const sanitizedRecordSet = { title };
3744
+ if (fields?.length) sanitizedRecordSet.fields = fields;
3745
+ const emptyText = operationalReportText(recordSet.emptyText, OPERATIONAL_REPORT_MAX_VALUE_LENGTH);
3746
+ if (emptyText) sanitizedRecordSet.emptyText = emptyText;
3747
+ if (records?.length) sanitizedRecordSet.records = records;
3748
+ return sanitizedRecordSet;
3749
+ }).filter((recordSet) => Boolean(recordSet));
3750
+ const widgets = args.report.widgets?.slice(0, OPERATIONAL_REPORT_MAX_WIDGETS).map((widget, widgetIndex) => {
3751
+ const id = operationalReportText(widget.id, OPERATIONAL_REPORT_MAX_LABEL_LENGTH) ?? String(widgetIndex);
3752
+ const title = operationalReportText(widget.title, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3753
+ if (!title) return;
3754
+ const seriesEntries = widget.series.slice(0, OPERATIONAL_REPORT_MAX_CHART_SERIES).map((item) => {
3755
+ const key = operationalReportText(item.key, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3756
+ const label = operationalReportText(item.label, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3757
+ if (!key || !label) return;
3758
+ const sanitizedSeries = {
3759
+ key,
3760
+ label
3761
+ };
3762
+ if (item.format === "usd") sanitizedSeries.format = "usd";
3763
+ const tone = operationalReportTone(item.tone);
3764
+ if (tone) sanitizedSeries.tone = tone;
3765
+ return {
3766
+ sanitizedSeries,
3767
+ sourceKey: item.key
3768
+ };
3769
+ }).filter((item) => Boolean(item));
3770
+ if (!seriesEntries.length) return;
3771
+ const series = seriesEntries.map((item) => item.sanitizedSeries);
3772
+ const sanitizedWidget = {
3773
+ categories: widget.categories.slice(-100).map((category, categoryIndex) => ({
3774
+ id: operationalReportText(category.id, OPERATIONAL_REPORT_MAX_LABEL_LENGTH) ?? `${widgetIndex}:${categoryIndex}`,
3775
+ label: operationalReportText(category.label, OPERATIONAL_REPORT_MAX_LABEL_LENGTH) ?? String(categoryIndex + 1),
3776
+ values: Object.fromEntries(seriesEntries.map(({ sanitizedSeries, sourceKey }) => [sanitizedSeries.key, Number.isFinite(category.values[sourceKey]) ? category.values[sourceKey] : 0]))
3777
+ })),
3778
+ id,
3779
+ series,
3780
+ title,
3781
+ type: "bar_chart"
3782
+ };
3783
+ const description = operationalReportText(widget.description, OPERATIONAL_REPORT_MAX_VALUE_LENGTH);
3784
+ if (description) sanitizedWidget.description = description;
3785
+ const emptyText = operationalReportText(widget.emptyText, OPERATIONAL_REPORT_MAX_VALUE_LENGTH);
3786
+ if (emptyText) sanitizedWidget.emptyText = emptyText;
3787
+ const timeRangeDays = widget.timeRangeDays?.filter((days) => days === 1 || days === 7 || days === 30 || days === 90);
3788
+ if (timeRangeDays?.length) sanitizedWidget.timeRangeDays = [...new Set(timeRangeDays)];
3789
+ return sanitizedWidget;
3790
+ }).filter((widget) => Boolean(widget));
3791
+ const sanitized = { pluginName: args.pluginName };
3792
+ const generatedAt = operationalReportText(args.report.generatedAt, OPERATIONAL_REPORT_MAX_VALUE_LENGTH);
3793
+ if (generatedAt) sanitized.generatedAt = generatedAt;
3794
+ if (recordSets?.length) sanitized.recordSets = recordSets;
3795
+ if (metrics?.length) sanitized.metrics = metrics;
3796
+ if (widgets?.length) sanitized.widgets = widgets;
3797
+ const title = operationalReportText(args.report.title, OPERATIONAL_REPORT_MAX_LABEL_LENGTH);
3798
+ if (title) sanitized.title = title;
3799
+ return sanitized;
3800
+ }
3801
+ function failedOperationalReport(args) {
3802
+ return {
3803
+ generatedAt: new Date(args.nowMs).toISOString(),
3804
+ pluginName: args.pluginName,
3805
+ metrics: [{
3806
+ label: "report",
3807
+ tone: "danger",
3808
+ value: "failed"
3809
+ }],
3810
+ title: args.pluginName,
3811
+ recordSets: [{
3812
+ emptyText: "This plugin report failed to load.",
3813
+ title: "Error"
3814
+ }]
3815
+ };
3816
+ }
3817
+ /** Collect read-only operational summaries exposed by plugins. */
3818
+ async function getPluginOperationalReports(nowMs) {
3819
+ const reports = [];
3820
+ for (const plugin of getPlugins()) {
3821
+ const pluginName = plugin.manifest.name;
3822
+ const hook = plugin.hooks?.operationalReport;
3823
+ if (!hook) continue;
3824
+ try {
3825
+ const state = createPluginState(pluginName);
3826
+ const report = await hook({
3827
+ ...basePluginContext(plugin),
3828
+ eventStats: createPluginConversationEventStats(plugin, () => nowMs),
3829
+ nowMs,
3830
+ state: pluginReadState(state)
3831
+ });
3832
+ if (!report) continue;
3833
+ reports.push(sanitizeOperationalReport({
3834
+ pluginName,
3835
+ report
3836
+ }));
3837
+ } catch (error) {
3838
+ createPluginLogger(pluginName).error("Plugin operational report failed", { error: error instanceof Error ? error.message : String(error) });
3839
+ reports.push(failedOperationalReport({
3840
+ nowMs,
3841
+ pluginName
3842
+ }));
3843
+ }
3844
+ }
3845
+ return reports;
3846
+ }
3847
+ /** Collect person-scoped plugin reports for one profile subject. */
3848
+ async function getPluginProfileReports(args) {
3849
+ const reports = [];
3850
+ for (const plugin of getPlugins()) {
3851
+ const pluginName = plugin.manifest.name;
3852
+ const hook = plugin.hooks?.profileReport;
3853
+ if (!hook) continue;
3854
+ try {
3855
+ const state = createPluginState(pluginName);
3856
+ const report = await hook({
3857
+ ...basePluginContext(plugin),
3858
+ nowMs: args.nowMs,
3859
+ state: pluginReadState(state),
3860
+ subject: args.subject,
3861
+ viewer: args.viewer
3862
+ });
3863
+ if (!report) continue;
3864
+ reports.push(sanitizeOperationalReport({
3865
+ pluginName,
3866
+ report
3867
+ }));
3868
+ } catch (error) {
3869
+ createPluginLogger(pluginName).error("Plugin profile report failed", { error: error instanceof Error ? error.message : String(error) });
3870
+ }
3871
+ }
3872
+ return reports;
3873
+ }
3874
+ function normalizeEnv(value) {
3875
+ if (!isRecord(value)) return {};
3876
+ const env = {};
3877
+ for (const [key, rawValue] of Object.entries(value)) if (typeof rawValue === "string") env[key] = rawValue;
3878
+ return env;
3879
+ }
3880
+ function preparationSignal(inputSignal, ownerSignal) {
3881
+ if (!inputSignal) return ownerSignal;
3882
+ if (!ownerSignal) return inputSignal;
3883
+ return AbortSignal.any([inputSignal, ownerSignal]);
3884
+ }
3885
+ function createSandboxCapability(workspace, ownerSignal) {
3886
+ return {
3887
+ root: SANDBOX_WORKSPACE_ROOT,
3888
+ juniorRoot: `${SANDBOX_WORKSPACE_ROOT}/.junior`,
3889
+ async readFile(filePath) {
3890
+ return await workspace.readFileToBuffer({ path: filePath }) ?? null;
3891
+ },
3892
+ async run(input) {
3893
+ const signal = preparationSignal(input.signal, ownerSignal);
3894
+ const result = await runNonInteractiveCommand(workspace, {
3895
+ ...input,
3896
+ ...signal ? { signal } : void 0
3897
+ });
3898
+ return {
3899
+ exitCode: result.exitCode,
3900
+ stdout: result.stdout,
3901
+ stderr: result.stderr
3902
+ };
3903
+ },
3904
+ async writeFile(input) {
3905
+ await workspace.writeFiles([{
3906
+ path: input.path,
3907
+ content: input.content,
3908
+ ...input.mode !== void 0 ? { mode: input.mode } : void 0
3909
+ }]);
3910
+ }
3911
+ };
3912
+ }
3913
+ /** Create one runner over runtime hook plugins registered by the app. */
3914
+ function createPluginHookRunner(input = {}) {
3915
+ const loaded = getPlugins();
3916
+ return {
3917
+ async afterMcpTool(tool) {
3918
+ for (const plugin of loaded) {
3919
+ if (plugin.manifest.name !== tool.provider) continue;
3920
+ const hook = plugin.hooks?.afterMcpTool;
3921
+ if (!hook) continue;
3922
+ const annotations = tool.conversationId ? createPluginAnnotations({
3923
+ conversationId: tool.conversationId,
3924
+ db: getDb(),
3925
+ plugin: plugin.manifest.name
3926
+ }) : void 0;
3927
+ try {
3928
+ await hook({
3929
+ ...basePluginContext(plugin),
3930
+ ...tool.conversationId ? { conversationId: tool.conversationId } : void 0,
3931
+ ...annotations ? { annotations } : void 0,
3932
+ result: tool.structuredContent !== void 0 ? { structuredContent: tool.structuredContent } : {},
3933
+ tool: {
3934
+ arguments: tool.arguments,
3935
+ name: tool.toolName
3936
+ }
3937
+ });
3938
+ } catch (error) {
3939
+ logWarn("agent.plugin.after_mcp_tool.failed", {
3940
+ "app.plugin.name": plugin.manifest.name,
3941
+ "gen_ai.tool.name": tool.toolName,
3942
+ "exception.message": error instanceof Error ? error.message : String(error)
3943
+ });
3944
+ }
3945
+ }
3946
+ },
3947
+ async prepareWorkspace(sandbox, repos, signal) {
3948
+ const preparers = new Set(loaded.filter((plugin) => plugin.hooks?.workspacePrepare).map((plugin) => plugin.manifest.name));
3949
+ const unhandledProviders = [...new Set(repos.map((repo) => repo.provider).filter((provider) => !preparers.has(provider)))].sort();
3950
+ if (unhandledProviders.length > 0) throw new Error(`Workspace repository providers have no preparation hook: ${unhandledProviders.join(", ")}`);
3951
+ const selectedRepos = repos.map((repo) => ({
3952
+ provider: repo.provider,
3953
+ repo: repo.repo,
3954
+ path: workspaceRepoCheckoutPath(repo.repo)
3955
+ }));
3956
+ const paths = /* @__PURE__ */ new Set();
3957
+ for (const entry of selectedRepos) {
3958
+ const key = entry.path.toLowerCase();
3959
+ if (paths.has(key)) throw new Error(`Workspace checkout path collision: ${entry.path}`);
3960
+ paths.add(key);
3961
+ }
3962
+ const sandboxCapability = createSandboxCapability(sandbox, signal);
3963
+ for (const plugin of loaded) {
3964
+ const hook = plugin.hooks?.workspacePrepare;
3965
+ if (!hook) continue;
3966
+ const selected = selectedRepos.filter((repo) => repo.provider === plugin.manifest.name).map((repo) => ({
3967
+ path: repo.path,
3968
+ repo: repo.repo
3969
+ }));
3970
+ if (selected.length === 0) continue;
3971
+ await hook({
3972
+ ...basePluginContext(plugin),
3973
+ repos: selected,
3974
+ sandbox: sandboxCapability
3975
+ });
3976
+ }
3977
+ },
3978
+ async prepareSandbox(sandbox) {
3979
+ const sandboxCapability = createSandboxCapability(sandbox);
3980
+ for (const plugin of loaded) {
3981
+ const pluginName = plugin.manifest.name;
3982
+ const hook = plugin.hooks?.sandboxPrepare;
3983
+ if (!hook) continue;
3984
+ logInfo("agent.plugin.sandbox_preparation.started", { "app.plugin.name": pluginName });
3985
+ await hook({
3986
+ ...basePluginContext(plugin),
3987
+ actor: input.actor,
3988
+ sandbox: sandboxCapability
3989
+ });
3990
+ }
3991
+ },
3992
+ async beforeToolExecute(tool) {
3993
+ const env = {};
3994
+ let nextInput = { ...tool.input };
3995
+ const actors = input.actors?.() ?? (input.actor ? [input.actor] : []);
3996
+ for (const plugin of loaded) {
3997
+ const pluginName = plugin.manifest.name;
3998
+ const hook = plugin.hooks?.beforeToolExecute;
3999
+ if (!hook) continue;
4000
+ let replacement;
4001
+ let denied;
4002
+ await hook({
4003
+ ...basePluginContext(plugin),
4004
+ actor: input.actor,
4005
+ actors,
4006
+ tool: {
4007
+ name: tool.name,
4008
+ input: nextInput
4009
+ },
4010
+ users: { resolveActor: async () => input.actor ? await readActorIdentity(input.actor) : void 0 },
4011
+ env: {
4012
+ get(key) {
4013
+ return env[key] ?? normalizeEnv(nextInput.env)[key];
4014
+ },
4015
+ set(key, value) {
4016
+ env[key] = value;
4017
+ }
4018
+ },
4019
+ decision: {
4020
+ deny(message) {
4021
+ denied = message;
4022
+ },
4023
+ replaceInput(input) {
4024
+ replacement = input;
4025
+ }
4026
+ }
4027
+ });
4028
+ if (denied) throw new PluginHookDeniedError(denied);
4029
+ if (replacement !== void 0) {
4030
+ if (!isRecord(replacement)) throw new Error(`Plugin "${pluginName}" replaced tool input with a non-object value`);
4031
+ nextInput = { ...replacement };
4032
+ }
4033
+ }
4034
+ return {
4035
+ input: nextInput,
4036
+ env
4037
+ };
4038
+ }
4039
+ };
4040
+ }
4041
+ //#endregion
4042
+ export { RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as $, bindEventTaskCredentialSubject as A, sanitizePostgresJson as At, getSlackClient as B, parseDestination as Bt, setWorkspaceSnapshotBuild as C, getConversationEventStore as Ct, tryWorkspaceRepoCheckoutPath as D, getSqlExecutor as Dt, getWorkspaceSnapshotBuilder as E, getDb as Et, verifySlackDirectCredentialSubject as F, resolveRootConversationId as Ft, withSlackRetries as G, isDmChannel as H, sameDestination as Ht, SlackActionError as I, deleteProviderIdentityForSlackUser as It, findUserByEmail as J, getWorkspaceTeamId as K, downloadPrivateSlackFile as L, upsertIdentity as Lt, bindSlackDirectCredentialSubject as M, locationFromRow as Mt, verifyEventTaskCredentialSubject as N, bindProviderConversation as Nt, workspaceRepoCheckoutPath as O, createSqlConversationEventStore as Ot, verifyScheduledTaskCredentialSubject as P, parseSessionSource as Pt, getSlackToolContext as Q, getFilePermalink as R, upsertLinkedIdentity as Rt, setWorkspaceSnapshot as S, db_exports as St, deleteWorkspaceSnapshotBuilders as T, getConversationStore as Tt, normalizeSlackConversationId as U, isConversationScopedChannel as V, requireSlackDestination as Vt, runWithSlackInstallationToken as W, resolveViewerUser as X, readActorIdentity as Y, updateViewerDisplayName as Z, listWorkspaces as _, createPluginLogger as _t, getPluginRoutes as a, collectResourceEventMatchKeys as at, invalidateReadySnapshot as b, listConversationAnnotations as bt, getPluginTools as c, findMatchingResourceEventSubscriptions as ct, setPlugins as d, getDashboardConversationLink as dt, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as et, validatePlugins as f, getDashboardTaskLink as ft, getWorkspaceByName as g, createPluginModel as gt, getWorkspace as h, createPluginEmbedder as ht, getPluginApiRoutes as i, cancelSubscriptions as it, bindScheduledTaskCredentialSubject as j, withConversationMutationLock as jt, resolveChannelCapabilities as k, withConversationEventLock as kt, getPluginUserPromptContributions as l, listResourceEventSubscriptions as lt, deleteWorkspace as m, createPluginState as mt, applyPluginFormatMarkdown as n, STOP_WATCHING_TOOL_NAME as nt, getPluginSlackConversationLink as o, createResourceEventSubscription as ot, createWorkspace as p, setDashboardConversationLinkOptions as pt, runWithWorkspaceTeamId as q, createPluginHookRunner as r, cancelResourceEventSubscription as rt, getPluginSystemPromptContributions as s, deliverResourceEventSubscription as st, agent_hooks_exports as t, RESOURCE_WATCH_TOOL_SOURCE as tt, getPlugins as u, JUNIOR_THREAD_STATE_TTL_MS as ut, updateWorkspace as v, createPluginConversationEvents as vt, SANDBOX_RUNTIME as w, getConversationMessageSearchStore as wt, loadSnapshotsForProfile as x, listConversationAnnotationsById as xt, WorkspaceValidationError as y, renderPluginConversationEvent as yt, getHeaderString as z, createSlackDestination as zt };