@sentry/junior 0.297.0 → 0.299.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 (94) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-DFnmLmfn.js → adapter-AgCNqqsG.js} +49 -133
  3. package/dist/{admin-tmGIw4KS.js → admin-1VwEXztm.js} +2 -2
  4. package/dist/{agent-runner-CneTquAE.js → agent-runner-Ciet8_nn.js} +1067 -1353
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +125 -43
  9. package/dist/{app-BJojZ7HL.d.ts → app--ky-Eu33.d.ts} +6 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +126 -299
  12. package/dist/{automation-BrP6ImrC.js → automation-M3RFJUBf.js} +1 -1
  13. package/dist/{background-compaction-queue-CwfJy3Cd.js → background-compaction-queue-CnimvRdk.js} +4 -4
  14. package/dist/{briefs-uFTuhMqA.js → briefs-CwzvgdCa.js} +4 -4
  15. package/dist/{catalog-runtime-0kuQqYL4.js → catalog-runtime-DaBaHY7u.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-Dj9M_nqB.js → config-CAXIpWQb.js} +80 -6
  24. package/dist/{connections-B96JUM5o.js → connections-Dy0hPdUq.js} +6 -6
  25. package/dist/continue-in-slack-DIOjFj76.js +176 -0
  26. package/dist/{conversation-CvcBU1z2.js → conversation-fCWD9Az3.js} +73 -13
  27. package/dist/{conversation-feed-BSMlGZnS.js → conversation-feed-BPK8vkkZ.js} +88 -3
  28. package/dist/{conversation-privacy-DI29jbZV.js → conversation-privacy-DUgtRkf8.js} +1 -1
  29. package/dist/{conversation-turn-CZWBr091.js → conversation-turn-DkJB6yMF.js} +85 -68
  30. package/dist/{credential-sync-Blhx4_xf.js → credential-sync-RX24Y8aY.js} +18 -18
  31. package/dist/{db-CrtyFRz7.d.ts → db-B07FtU9g.d.ts} +1 -1
  32. package/dist/{db-Br0tfAo7.js → db-COYOGzYS.js} +171 -12
  33. package/dist/{executor-BMPipFVA.js → executor-BWmAgSyi.js} +40 -11
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/lineage-D-5jm_oj.js +37 -0
  37. package/dist/{logging-CQjlDQYX.js → logging-DPLEa8Bn.js} +1 -1
  38. package/dist/media-BAHvgkok.js +85 -0
  39. package/dist/{message-BOZEIuxy.js → message-BIHR1yRk.js} +9 -10
  40. package/dist/model-input-BPZYH8Nd.js +82 -0
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +17 -9
  43. package/dist/{oauth-callback-server-V_DuMuNX.js → oauth-callback-server-R7qvSzFG.js} +2 -2
  44. package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
  45. package/dist/{projection-B08mfi0u.js → projection-DEdP1q6f.js} +261 -36
  46. package/dist/{prompt-BlutWLNt.js → prompt-4M98h_tC.js} +4 -4
  47. package/dist/{registry-BDWgCJDf.js → registry-BTKmKM-r.js} +3 -3
  48. package/dist/{resolve-2Z_o_SsI.js → resolve-B8hXNVZ3.js} +3 -3
  49. package/dist/{result-CAujiaci.js → result-g-XAaOj6.js} +158 -69
  50. package/dist/{runner-D2Chc02N.js → runner-BlPSA5A8.js} +9 -9
  51. package/dist/{sandbox-egress-signals-CFoJduFj.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
  52. package/dist/{schema-Bqa5NbcP.js → schema-BNnY_trV.js} +47 -7
  53. package/dist/{schema-Ce2XCS7O.d.ts → schema-DbuWR-DN.d.ts} +663 -346
  54. package/dist/{service-account-C9kRQEb_.js → service-account-9OLNQMyz.js} +4 -4
  55. package/dist/{service-account-CERfXEVU.js → service-account-BYGZ08DQ.js} +3 -3
  56. package/dist/session-stop-2XJrcNCy.js +3356 -0
  57. package/dist/{skills-B0m1nZ_j.js → skills-DpBQoeHV.js} +3 -3
  58. package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
  59. package/dist/spawn-09GssFod.js +73 -0
  60. package/dist/state-Cufq0_rH.js +132 -0
  61. package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
  62. package/dist/{stop-BCH9VNGf.js → stop-U7iUrR1g.js} +6011 -5773
  63. package/dist/{store-B59rOYbS.js → store-BHiaHCQu.js} +24 -4
  64. package/dist/{store-m5bmdmsP.js → store-CSgUTMdv.js} +10 -10
  65. package/dist/{task-queue-N0kuCknH.js → task-queue-bMNq0clp.js} +4 -4
  66. package/dist/{task-runner-COOwR8qm.js → task-runner-B__rxwxU.js} +10 -10
  67. package/dist/{thread-context-Cd44z_W5.js → thread-context-d0ceWbVT.js} +18 -18
  68. package/dist/{turn-session-routing-BlCtVFRN.js → turn-session-routing-BVZHBFCF.js} +5 -5
  69. package/dist/turn-user-message-BEw7acTP.js +355 -0
  70. package/dist/users-BK3dbxZL.js +424 -0
  71. package/dist/{validation-Ba2OcUse.js → validation-BDVJjO2E.js} +1 -1
  72. package/dist/{version-KNDzIAh6.js → version-DQgZoQ3D.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-BPpuN2f9.js → viewer-CAWfFo29.js} +25 -54
  75. package/dist/{warmup-Bskrwmk1.js → warmup-9ySPacF9.js} +1137 -143
  76. package/dist/{worker-B1skZlit.js → worker-D8jJO-WO.js} +8 -7
  77. package/migrations/0104_code_change_draft.sql +1 -0
  78. package/migrations/0105_attachment_uploads.sql +14 -0
  79. package/migrations/0106_conversation_agent_config.sql +1 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +4 -4
  85. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  86. package/dist/locks-D-0h111u.js +0 -48
  87. package/dist/notification-gusCgdQ6.js +0 -1284
  88. package/dist/prompt-input-Dxn8cDC0.js +0 -1424
  89. package/dist/session-stop-B-I1rAS1.js +0 -181
  90. package/dist/spawn-CwMjRRtn.js +0 -80
  91. package/dist/turn-cancel-DDu8TOwt.js +0 -201
  92. package/dist/turn-user-message-ygLG3ylQ.js +0 -641
  93. package/dist/turn-wake-DmQec4AG.js +0 -161
  94. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -0,0 +1,424 @@
1
+ import { Ba as runWithSlackInstallationToken, Fa as getSlackClient, Va as withSlackRetries, ja as SlackActionError } from "./projection-DEdP1q6f.js";
2
+ import { a as getConversationStore } from "./db-COYOGzYS.js";
3
+ import { r as getStateAdapter } from "./adapter-AgCNqqsG.js";
4
+ import * as z from "zod";
5
+ // src/chat/slack/channel.ts
6
+ const replySubtypeSchema = z.object({ subtype: z.string().optional() });
7
+ /** List channel history using Slack-native, pre-validated timestamp bounds. */
8
+ async function listChannelMessages(input) {
9
+ const client = getSlackClient();
10
+ const channelId = input.channelId;
11
+ const targetLimit = Math.max(1, Math.min(input.limit, 1e3));
12
+ const maxPages = Math.max(1, Math.min(input.maxPages ?? 5, 10));
13
+ const messages = [];
14
+ let cursor = input.cursor;
15
+ let pages = 0;
16
+ while (messages.length < targetLimit && pages < maxPages) {
17
+ pages += 1;
18
+ const pageLimit = Math.max(1, Math.min(200, targetLimit - messages.length));
19
+ const response = await withSlackRetries(() => client.conversations.history({
20
+ channel: channelId,
21
+ limit: pageLimit,
22
+ cursor,
23
+ oldest: input.oldest,
24
+ latest: input.latest,
25
+ inclusive: input.inclusive
26
+ }), 3, { action: "conversations.history" });
27
+ const batch = response.messages ?? [];
28
+ messages.push(...batch);
29
+ cursor = response.response_metadata?.next_cursor || void 0;
30
+ if (!cursor) break;
31
+ }
32
+ return {
33
+ messages: messages.slice(0, targetLimit),
34
+ nextCursor: cursor
35
+ };
36
+ }
37
+ /** Read replies from a Slack thread identified by a validated native thread timestamp. */
38
+ async function listThreadReplies(input) {
39
+ const client = getSlackClient();
40
+ const channelId = input.channelId;
41
+ const targetLimit = Math.max(1, Math.min(input.limit ?? 1e3, 1e3));
42
+ const maxPages = Math.max(1, Math.min(input.maxPages ?? 10, 10));
43
+ const pendingTargets = new Set((input.targetMessageTs ?? []).filter((value) => typeof value === "string" && value.length > 0));
44
+ const hasTargetMessages = pendingTargets.size > 0;
45
+ const replies = [];
46
+ let cursor;
47
+ let pages = 0;
48
+ while (replies.length < targetLimit && pages < maxPages) {
49
+ pages += 1;
50
+ const pageLimit = Math.max(1, Math.min(200, targetLimit - replies.length));
51
+ const response = await withSlackRetries(() => client.conversations.replies({
52
+ channel: channelId,
53
+ ts: input.threadTs,
54
+ limit: pageLimit,
55
+ cursor
56
+ }), 3, { action: "conversations.replies" });
57
+ const batch = response.messages ?? [];
58
+ replies.push(...batch.map((reply) => ({
59
+ ...reply,
60
+ ...replySubtypeSchema.parse(reply)
61
+ })));
62
+ for (const reply of batch) if (typeof reply.ts === "string" && pendingTargets.size > 0) pendingTargets.delete(reply.ts);
63
+ cursor = response.response_metadata?.next_cursor || void 0;
64
+ if (!cursor || hasTargetMessages && pendingTargets.size === 0) break;
65
+ }
66
+ return replies.slice(0, targetLimit);
67
+ }
68
+ /** Return whether anyone in the workspace can read the conversation. */
69
+ function isPublicSlackChannel(info) {
70
+ return info.isChannel && !info.isPrivate && !info.isIm && !info.isMpim;
71
+ }
72
+ /** Load conversation metadata used for cross-channel read access checks. */
73
+ async function getConversationInfo(channelId) {
74
+ const client = getSlackClient();
75
+ const channel = (await withSlackRetries(() => client.conversations.info({ channel: channelId }), 3, {
76
+ action: "conversations.info",
77
+ idempotent: true
78
+ })).channel;
79
+ if (!channel || typeof channel !== "object") throw new Error(`Slack conversations.info returned no channel for ${channelId}`);
80
+ return {
81
+ id: channelId,
82
+ ...typeof channel.name === "string" && channel.name ? { name: channel.name } : void 0,
83
+ ...channel.topic?.value ? { topic: channel.topic.value } : void 0,
84
+ ...channel.purpose?.value ? { description: channel.purpose.value } : void 0,
85
+ isChannel: channel.is_channel === true,
86
+ isPrivate: channel.is_private === true,
87
+ isIm: channel.is_im === true,
88
+ isMpim: channel.is_mpim === true,
89
+ ...typeof channel.is_member === "boolean" ? { isMember: channel.is_member } : void 0
90
+ };
91
+ }
92
+ /** Join a public channel so the bot can read history and threads there. */
93
+ async function joinPublicChannel(channelId) {
94
+ const client = getSlackClient();
95
+ await withSlackRetries(() => client.conversations.join({ channel: channelId }), 3, {
96
+ action: "conversations.join",
97
+ idempotent: true
98
+ });
99
+ }
100
+ const MAX_MEMBER_PAGES = 5;
101
+ /** Return whether a Slack user is a member of a channel, DM, or group DM. */
102
+ async function isConversationMember(channelId, userId) {
103
+ const client = getSlackClient();
104
+ let cursor;
105
+ for (let page = 0; page < MAX_MEMBER_PAGES; page += 1) {
106
+ const response = await withSlackRetries(() => client.conversations.members({
107
+ channel: channelId,
108
+ cursor,
109
+ limit: 1e3
110
+ }), 3, {
111
+ action: "conversations.members",
112
+ idempotent: true
113
+ });
114
+ if (response.members?.includes(userId)) return true;
115
+ cursor = response.response_metadata?.next_cursor || void 0;
116
+ if (!cursor) return false;
117
+ }
118
+ return false;
119
+ }
120
+ /** Read one message by its timestamp. A thread reply needs its thread. */
121
+ async function getChannelMessage(input) {
122
+ const client = getSlackClient();
123
+ return (await withSlackRetries(() => client.conversations.replies({
124
+ channel: input.channelId,
125
+ ts: input.threadTs ?? input.messageTs,
126
+ oldest: input.messageTs,
127
+ latest: input.messageTs,
128
+ inclusive: true,
129
+ limit: 2
130
+ }), 3, {
131
+ action: "conversations.replies",
132
+ idempotent: true
133
+ })).messages?.find((message) => message.ts === input.messageTs);
134
+ }
135
+ // src/chat/slack/tool-support/channel-access.ts
136
+ const DENIED_PRIVATE = "Cannot read this Slack conversation because it is private. Only the current conversation or public channels are readable.";
137
+ const DENIED_NOT_FOUND = "Cannot read this Slack conversation because the channel was not found or the bot cannot see it.";
138
+ const DENIED_NOT_IN_CHANNEL = "Cannot read this Slack conversation because the bot is not in the channel.";
139
+ const DENIED_MISSING_SCOPE = "Cannot verify Slack channel access because this installation is missing channel read scopes.";
140
+ function deny(reason, error) {
141
+ return {
142
+ allowed: false,
143
+ reason,
144
+ error
145
+ };
146
+ }
147
+ /**
148
+ * Decide whether the model may read Slack content from a target channel.
149
+ *
150
+ * The current conversation is always readable. Any other channel first checks
151
+ * persisted visibility in the same workspace. Cross-channel reads require live
152
+ * `conversations.info` proof that the destination is public. Stale persisted
153
+ * public rows are not enough, so a channel that later becomes private fails
154
+ * closed. Channel-id prefixes alone cannot prove a channel public.
155
+ */
156
+ async function checkSlackChannelReadAccess(args) {
157
+ if (args.currentChannelIds.filter((channelId) => Boolean(channelId)).includes(args.targetChannelId)) return {
158
+ allowed: true,
159
+ isMember: true
160
+ };
161
+ if (await getConversationStore().getDestinationVisibility({
162
+ provider: "slack",
163
+ providerTenantId: args.teamId,
164
+ providerDestinationId: args.targetChannelId
165
+ }) === "private") return deny("private", DENIED_PRIVATE);
166
+ try {
167
+ const info = await getConversationInfo(args.targetChannelId);
168
+ if (!isPublicSlackChannel(info)) return deny("private", DENIED_PRIVATE);
169
+ return {
170
+ allowed: true,
171
+ isPublic: true,
172
+ ...info.name ? { channelName: info.name } : void 0,
173
+ ...typeof info.isMember === "boolean" ? { isMember: info.isMember } : void 0
174
+ };
175
+ } catch (error) {
176
+ if (error instanceof SlackActionError) {
177
+ if (error.code === "not_found") return deny("not_found", DENIED_NOT_FOUND);
178
+ if (error.code === "not_in_channel") return deny("not_in_channel", DENIED_NOT_IN_CHANNEL);
179
+ if (error.code === "missing_scope") return deny("missing_scope", DENIED_MISSING_SCOPE);
180
+ }
181
+ throw error;
182
+ }
183
+ }
184
+ /**
185
+ * Join one public channel when a read failed because the bot is not a member.
186
+ *
187
+ * Callers should try the read first, then use this helper on `not_in_channel`.
188
+ */
189
+ async function joinPublicChannelForRead(args) {
190
+ try {
191
+ await joinPublicChannel(args.targetChannelId);
192
+ return {
193
+ ok: true,
194
+ ...args.channelName ? { channelName: args.channelName } : void 0
195
+ };
196
+ } catch (error) {
197
+ if (error instanceof SlackActionError) {
198
+ if (error.code === "missing_scope") return {
199
+ ok: false,
200
+ reason: "missing_scope",
201
+ error: "Cannot join this public Slack channel because this installation is missing the `channels:join` scope."
202
+ };
203
+ if (error.code === "not_found") return {
204
+ ok: false,
205
+ reason: "not_found",
206
+ error: DENIED_NOT_FOUND
207
+ };
208
+ if (error.apiError === "method_not_supported_for_channel_type" || error.apiError === "is_archived" || error.apiError === "cant_invite_self") return {
209
+ ok: false,
210
+ reason: "private",
211
+ error: DENIED_PRIVATE
212
+ };
213
+ return {
214
+ ok: false,
215
+ reason: "not_in_channel",
216
+ error: "Could not join this public Slack channel. Ask an admin to add the bot, then retry."
217
+ };
218
+ }
219
+ throw error;
220
+ }
221
+ }
222
+ // src/chat/slack/adapter-context.ts
223
+ const initializedAdapters = /* @__PURE__ */ new WeakSet();
224
+ async function getConnectedState(stateAdapter) {
225
+ const state = stateAdapter ?? getStateAdapter();
226
+ await state.connect();
227
+ return state;
228
+ }
229
+ /** Initialize the Slack adapter against the repository state adapter. */
230
+ async function ensureSlackAdapterInitialized(args) {
231
+ if (initializedAdapters.has(args.adapter)) return;
232
+ const state = await getConnectedState(args.state);
233
+ await args.adapter.initialize({ getState: () => state });
234
+ if (args.adapter.defaultBotTokenProvider && !args.adapter.botUserId) throw new Error("Slack adapter initialized without a resolved bot user id");
235
+ initializedAdapters.add(args.adapter);
236
+ }
237
+ /** Verify a Slack request using the adapter's configured signing secret. */
238
+ function verifySlackSignature(args) {
239
+ const verifySignature = args.adapter.verifySignature;
240
+ if (!verifySignature) throw new Error("Slack adapter does not expose signature verification");
241
+ return verifySignature.call(args.adapter, args.body, args.request.headers.get("x-slack-request-timestamp"), args.request.headers.get("x-slack-signature"));
242
+ }
243
+ /** Run Slack work with the installation token that matches the inbound event. */
244
+ async function runWithSlackInstallation(args) {
245
+ await ensureSlackAdapterInitialized({
246
+ adapter: args.adapter,
247
+ state: args.state
248
+ });
249
+ const internals = args.adapter;
250
+ if (internals.defaultBotTokenProvider) return await args.task();
251
+ const installationId = args.installation.isEnterpriseInstall ? args.installation.enterpriseId : args.installation.teamId;
252
+ if (!installationId) throw new Error("Slack installation context is missing team id");
253
+ if (!internals.resolveTokenForTeam || !internals.requestContext) throw new Error("Slack adapter cannot resolve workspace installations");
254
+ const tokenContext = await internals.resolveTokenForTeam.call(args.adapter, installationId, args.installation.isEnterpriseInstall);
255
+ if (!tokenContext) throw new Error(`Slack installation token was not found for ${installationId}`);
256
+ return await internals.requestContext.run({
257
+ ...tokenContext,
258
+ enterpriseId: args.installation.enterpriseId,
259
+ isEnterpriseInstall: args.installation.isEnterpriseInstall
260
+ }, () => runWithSlackInstallationToken(tokenContext.token, args.task));
261
+ }
262
+ // src/chat/slack/users.ts
263
+ const profileFieldsSchema = z.object({ fields: z.record(z.string(), z.object({
264
+ value: z.string().optional(),
265
+ alt: z.string().optional(),
266
+ label: z.string().optional()
267
+ }).nullable()).nullish() });
268
+ function normalizeUser(raw) {
269
+ const rawFields = profileFieldsSchema.parse(raw.profile ?? {}).fields;
270
+ const profileFields = [];
271
+ if (rawFields) for (const [id, field] of Object.entries(rawFields)) {
272
+ if (!field) continue;
273
+ profileFields.push({
274
+ id,
275
+ label: field.label || void 0,
276
+ value: field.value || void 0,
277
+ alt: field.alt || void 0
278
+ });
279
+ }
280
+ return {
281
+ id: raw.id ?? "",
282
+ team_id: raw.team_id || void 0,
283
+ name: raw.name || void 0,
284
+ real_name: raw.real_name || raw.profile?.real_name || void 0,
285
+ display_name: raw.profile?.display_name || void 0,
286
+ title: raw.profile?.title || void 0,
287
+ email: raw.profile?.email || void 0,
288
+ status_text: raw.profile?.status_text ?? void 0,
289
+ status_emoji: raw.profile?.status_emoji ?? void 0,
290
+ avatar_url: raw.profile?.image_512 || void 0,
291
+ is_bot: raw.is_bot ?? false,
292
+ is_deleted: raw.deleted ?? false,
293
+ timezone: raw.tz || void 0,
294
+ ...profileFields.length > 0 ? { profile_fields: profileFields } : void 0
295
+ };
296
+ }
297
+ function normalizeNameTokens(value) {
298
+ return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
299
+ }
300
+ function nameFields(user) {
301
+ return [
302
+ user.name ?? "",
303
+ user.profile?.display_name ?? "",
304
+ user.real_name ?? user.profile?.real_name ?? ""
305
+ ].map((value) => value.toLowerCase().trim()).filter(Boolean);
306
+ }
307
+ /** Look up a Slack user by ID, returning the full profile including custom fields. */
308
+ async function lookupSlackUserProfile(userId) {
309
+ const client = getSlackClient();
310
+ const user = (await withSlackRetries(() => client.users.info({ user: userId }), 3, { action: "users.info" })).user;
311
+ if (!user) throw new Error(`Slack users.info returned no user for ${userId}`);
312
+ return normalizeUser(user);
313
+ }
314
+ /** Look up a Slack bot by ID. Returns undefined when Slack has no such bot. */
315
+ async function lookupSlackBot(botId) {
316
+ try {
317
+ return (await withSlackRetries(() => getSlackClient().bots.info({ bot: botId }), 3, { action: "bots.info" })).bot;
318
+ } catch (error) {
319
+ if (error instanceof SlackActionError && error.apiError === "bot_not_found") return;
320
+ throw error;
321
+ }
322
+ }
323
+ /** Look up a Slack user by email. Returns null when no user matches. */
324
+ async function lookupSlackUserByEmail(email) {
325
+ const client = getSlackClient();
326
+ let result;
327
+ try {
328
+ result = await withSlackRetries(() => client.users.lookupByEmail({ email }), 3, { action: "users.lookupByEmail" });
329
+ } catch (error) {
330
+ if (error instanceof SlackActionError && error.apiError === "users_not_found") return null;
331
+ throw error;
332
+ }
333
+ const user = result.user;
334
+ if (!user) return null;
335
+ return normalizeUser(user);
336
+ }
337
+ /**
338
+ * Rank Slack name-search quality for one candidate.
339
+ * Exact field and token matches beat field prefixes so a display-name prefix
340
+ * cannot outrank a real-name first-name hit.
341
+ */
342
+ function scoreNameMatch(user, query) {
343
+ const queryLower = query.toLowerCase().trim();
344
+ if (!queryLower) return 0;
345
+ const fields = nameFields(user);
346
+ if (fields.length === 0) return 0;
347
+ let best = 0;
348
+ const queryTokens = normalizeNameTokens(queryLower);
349
+ for (const field of fields) {
350
+ if (field === queryLower) {
351
+ best = Math.max(best, 100);
352
+ continue;
353
+ }
354
+ if (field.startsWith(queryLower)) best = Math.max(best, 70);
355
+ else if (field.includes(queryLower)) best = Math.max(best, 25);
356
+ const tokens = normalizeNameTokens(field);
357
+ for (const token of tokens) if (token === queryLower) best = Math.max(best, 85);
358
+ else if (token.startsWith(queryLower)) best = Math.max(best, 60);
359
+ if (queryTokens.length > 1 && queryTokens.every((queryToken) => tokens.some((token) => token === queryToken || token.startsWith(queryToken)))) best = Math.max(best, 95);
360
+ }
361
+ return best;
362
+ }
363
+ function compareNameMatches(left, right) {
364
+ if (right.score !== left.score) return right.score - left.score;
365
+ return (left.user.name ?? "").localeCompare(right.user.name ?? "");
366
+ }
367
+ async function listWorkspaceUsers(options) {
368
+ const client = getSlackClient();
369
+ const matches = [];
370
+ let cursor;
371
+ let pages = 0;
372
+ let totalScanned = 0;
373
+ while (pages < options.maxPages) {
374
+ pages++;
375
+ const result = await withSlackRetries(() => client.users.list({
376
+ limit: 200,
377
+ ...cursor ? { cursor } : void 0
378
+ }), 3, { action: "users.list" });
379
+ const members = result.members ?? [];
380
+ totalScanned += members.length;
381
+ for (const member of members) {
382
+ if (!options.includeDeleted && member.deleted) continue;
383
+ if (!options.includeBots && member.is_bot) continue;
384
+ if (member.id === "USLACKBOT") continue;
385
+ const score = options.score(member);
386
+ if (score <= 0) continue;
387
+ matches.push({
388
+ user: member,
389
+ score
390
+ });
391
+ }
392
+ const nextCursor = result.response_metadata?.next_cursor;
393
+ if (!nextCursor) {
394
+ cursor = void 0;
395
+ break;
396
+ }
397
+ cursor = nextCursor;
398
+ }
399
+ return {
400
+ matches,
401
+ searched_pages: pages,
402
+ searched_user_count: totalScanned,
403
+ truncated: pages >= options.maxPages && Boolean(cursor)
404
+ };
405
+ }
406
+ /** Search workspace users by name with bounded pagination through `users.list`. */
407
+ async function searchSlackUsers(options) {
408
+ const { query, limit = 10, maxPages = 3, includeDeleted = false, includeBots = false } = options;
409
+ const queryLower = query.toLowerCase().trim();
410
+ const listed = await listWorkspaceUsers({
411
+ maxPages,
412
+ includeDeleted,
413
+ includeBots,
414
+ score: (member) => scoreNameMatch(member, queryLower)
415
+ });
416
+ listed.matches.sort(compareNameMatches);
417
+ return {
418
+ users: listed.matches.slice(0, limit).map((m) => normalizeUser(m.user)),
419
+ searched_pages: listed.searched_pages,
420
+ searched_user_count: listed.searched_user_count,
421
+ truncated: listed.truncated
422
+ };
423
+ }
424
+ export { runWithSlackInstallation as a, joinPublicChannelForRead as c, isConversationMember as d, isPublicSlackChannel as f, listThreadReplies as h, searchSlackUsers as i, getChannelMessage as l, listChannelMessages as m, lookupSlackUserByEmail as n, verifySlackSignature as o, joinPublicChannel as p, lookupSlackUserProfile as r, checkSlackChannelReadAccess as s, lookupSlackBot as t, getConversationInfo as u };
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-0kuQqYL4.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DaBaHY7u.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  // src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.297.0";
2
+ var version = "0.299.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-KNDzIAh6.js";
1
+ export { t as JUNIOR_VERSION } from "./version-DQgZoQ3D.js";
@@ -1,44 +1,10 @@
1
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CQjlDQYX.js";
2
- import { N as findActorIdentityId, o as getDb } from "./db-Br0tfAo7.js";
3
- import { M as juniorUsers, j as juniorIdentities } from "./executor-BMPipFVA.js";
4
- import { r as detectImageMediaType } from "./media-BepyEUNm.js";
5
- import { a as withLock } from "./locks-D-0h111u.js";
1
+ import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-DPLEa8Bn.js";
2
+ import { H as clearCachedUser, M as findActorIdentityId, U as readCachedUserByEmail, W as createCache, o as getDb } from "./db-COYOGzYS.js";
3
+ import { M as juniorIdentities, N as juniorUsers } from "./executor-BWmAgSyi.js";
4
+ import { r as detectImageMediaType } from "./media-BAHvgkok.js";
6
5
  import { createHash, randomUUID } from "node:crypto";
7
6
  import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
8
7
  import { identitySchema, userSchema } from "@sentry/junior-plugin-api";
9
- // src/chat/state/cache.ts
10
- const MAX_CACHE_KEY_LENGTH = 512;
11
- const LOAD_WAIT_MS = 1e4;
12
- /**
13
- * Create a cache in the state adapter under `junior:cache:{namespace}:`.
14
- * Entries are wrapped, so `null` and `false` values are cache hits.
15
- */
16
- function createCache(state, namespace) {
17
- return { async getOrLoad(key, load, options) {
18
- if (!key.trim()) throw new Error("Cache key is required");
19
- if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
20
- const cacheKey = `junior:cache:${namespace}:${key}`;
21
- const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
22
- await state.connect();
23
- const hit = await cached();
24
- if (hit) return hit.value;
25
- const attempt = await withLock(state, `${cacheKey}:load`, async () => {
26
- const loadedMeanwhile = await cached();
27
- if (loadedMeanwhile) return loadedMeanwhile.value;
28
- const entry = await load();
29
- if (entry.ttlMs !== void 0) {
30
- if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
31
- await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
32
- }
33
- return entry.value;
34
- }, {
35
- keepAlive: true,
36
- waitMs: LOAD_WAIT_MS
37
- });
38
- if (attempt.acquired) return attempt.value;
39
- return (await load()).value;
40
- } };
41
- }
42
8
  // src/chat/identities/avatar.ts
43
9
  /**
44
10
  * Profile photos of people, saved on their native Slack and Google
@@ -83,17 +49,23 @@ function avatarPath(identityId, avatarUrl) {
83
49
  */
84
50
  async function readUserAvatarUrls(db, userIds) {
85
51
  if (userIds.length === 0) return /* @__PURE__ */ new Map();
86
- const rows = await db.select({
52
+ return userAvatarUrlsFromIdentities(await db.select({
87
53
  avatarUrl: juniorIdentities.avatarUrl,
88
54
  identityId: juniorIdentities.id,
89
55
  provider: juniorIdentities.provider,
90
56
  updatedAt: juniorIdentities.updatedAt,
91
57
  userId: juniorIdentities.userId
92
- }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), eq(juniorIdentities.kind, "user"), inArray(juniorIdentities.provider, AVATAR_PROVIDERS), isNotNull(juniorIdentities.avatarUrl)));
58
+ }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), eq(juniorIdentities.kind, "user"), inArray(juniorIdentities.provider, AVATAR_PROVIDERS), isNotNull(juniorIdentities.avatarUrl))));
59
+ }
60
+ /**
61
+ * Pick the photo path of each user from their user Identities, for a caller
62
+ * that already read them: the Slack photo, then the Google photo.
63
+ */
64
+ function userAvatarUrlsFromIdentities(rows) {
93
65
  const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
94
- rows.sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
66
+ const ranked = rows.filter((row) => rank(row) >= 0).sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
95
67
  const avatars = /* @__PURE__ */ new Map();
96
- for (const row of rows) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
68
+ for (const row of ranked) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
97
69
  return avatars;
98
70
  }
99
71
  /**
@@ -234,13 +206,8 @@ function userFromRows(userRow, identityRows) {
234
206
  });
235
207
  }
236
208
  async function readUserByNormalizedEmail(db, normalizedEmail) {
237
- const rows = await db.select({
238
- user: juniorUsers,
239
- identity: juniorIdentities
240
- }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
241
- const userRow = rows[0]?.user;
242
- if (!userRow) return void 0;
243
- return userFromRows(userRow, rows.flatMap((row) => row.identity ? [row.identity] : []));
209
+ const cached = await readCachedUserByEmail(db, normalizedEmail);
210
+ return cached ? userFromRows(cached.user, cached.identities) : void 0;
244
211
  }
245
212
  /** Resolve or create the canonical user for one verified viewer email. */
246
213
  async function resolveViewerUserFromSql(db, email) {
@@ -275,10 +242,12 @@ async function findUserByEmail(email) {
275
242
  }
276
243
  /** Update one canonical user's display name in SQL. */
277
244
  async function updateViewerDisplayNameFromSql(db, userId, displayName) {
278
- const userRow = (await db.update(juniorUsers).set({
245
+ const rows = await db.update(juniorUsers).set({
279
246
  displayName,
280
247
  updatedAt: /* @__PURE__ */ new Date()
281
- }).where(eq(juniorUsers.id, userId)).returning())[0];
248
+ }).where(eq(juniorUsers.id, userId)).returning();
249
+ await clearCachedUser(userId);
250
+ const userRow = rows[0];
282
251
  return userRow ? await readUserById(db, userRow) : void 0;
283
252
  }
284
253
  /** Read the photo path of one canonical user: Slack, then Google. */
@@ -298,10 +267,12 @@ async function updateViewerDisplayName(userId, displayName) {
298
267
  async function setUserAdminFromSql(db, email, isAdmin) {
299
268
  const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
300
269
  if (!user) return void 0;
301
- const userRow = (await db.update(juniorUsers).set({
270
+ const rows = await db.update(juniorUsers).set({
302
271
  isAdmin,
303
272
  updatedAt: /* @__PURE__ */ new Date()
304
- }).where(eq(juniorUsers.id, user.id)).returning())[0];
273
+ }).where(eq(juniorUsers.id, user.id)).returning();
274
+ await clearCachedUser(user.id);
275
+ const userRow = rows[0];
305
276
  return userRow ? await readUserById(db, userRow) : void 0;
306
277
  }
307
278
  /** List every Junior admin by primary email. */
@@ -334,4 +305,4 @@ async function readIdentityByIdFromSql(db, identityId) {
334
305
  async function readIdentityById(identityId) {
335
306
  return await readIdentityByIdFromSql(getDb(), identityId);
336
307
  }
337
- export { readActorIdentityFromSql as a, readViewerAvatarUrl as c, updateViewerDisplayName as d, identityAvatarUrl as f, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, resolveViewerUser as l, readAvatarImage as m, findUserByEmailFromSql as n, readIdentityById as o, parseAvatarUrl as p, listAdminUsersFromSql as r, readIdentityByIdFromSql as s, findUserByEmail as t, setUserAdminFromSql as u };
308
+ export { readActorIdentityFromSql as a, readViewerAvatarUrl as c, updateViewerDisplayName as d, identityAvatarUrl as f, userAvatarUrlsFromIdentities as g, readUserAvatarUrls as h, readActorIdentity as i, resolveViewerUser as l, readAvatarImage as m, findUserByEmailFromSql as n, readIdentityById as o, parseAvatarUrl as p, listAdminUsersFromSql as r, readIdentityByIdFromSql as s, findUserByEmail as t, setUserAdminFromSql as u };