@sentry/junior 0.301.0 → 0.303.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 (101) hide show
  1. package/dist/adapter-context-BdVnSuY5.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-AfeAdS3J.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-BP8_DLUv.js} +4688 -13870
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +13 -12
  7. package/dist/api.js +268 -118
  8. package/dist/{app-HDZglaIu.d.ts → app-Dd9v1mNx.d.ts} +15 -15
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +99 -330
  11. package/dist/{automation-Cva5ZOwW.js → automation-D9MvhOWY.js} +3 -1
  12. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-xaE05jxH.js} +97 -206
  13. package/dist/{briefs-x6Mzwxmg.js → briefs-D8i-dKTp.js} +4 -4
  14. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-d1EM6Z0V.js} +2 -2
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +21 -21
  17. package/dist/cli/check.js +8 -8
  18. package/dist/cli/env.d.ts +1 -0
  19. package/dist/cli/env.js +8 -7
  20. package/dist/cli/init.js +13 -4
  21. package/dist/cli/main.js +4 -4
  22. package/dist/cli/plugins.js +6 -6
  23. package/dist/cli/snapshot-create.js +7 -5
  24. package/dist/cli/upgrade.d.ts +2 -2
  25. package/dist/cli/upgrade.js +5 -5
  26. package/dist/{config-CmjhyqgB.js → config-oGM7KA9M.js} +44 -63
  27. package/dist/{connections-CfIRm0xv.js → connections-BlikzEJv.js} +6 -6
  28. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-BZnYifiG.js} +5 -6
  29. package/dist/{conversation-BNXfq6Lb.js → conversation-CY1jnBiC.js} +1 -1
  30. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-BZJRk6UV.js} +2 -1
  31. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-Cx515ddM.js} +7 -7
  32. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-DAhRdX4m.js} +20 -24
  33. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DfhmWFeo.js} +18 -20
  34. package/dist/{db-Czra10QW.js → db-C-2tFxk3.js} +326 -17
  35. package/dist/{db-BdUHQhrC.d.ts → db-DPqcEM9_.d.ts} +25 -25
  36. package/dist/{executor-D_023K0H.js → executor-NVfS8aQ2.js} +51 -10
  37. package/dist/{history-IjdmO_r6.js → history-UZ3M2M9r.js} +13 -10
  38. package/dist/install-CHLrpRZc.js +228 -0
  39. package/dist/instrumentation.d.ts +4 -4
  40. package/dist/instrumentation.js +10 -10
  41. package/dist/{lineage-DmMIE0VL.js → lineage-HGLhd_-N.js} +2 -2
  42. package/dist/{logging-DcjLDDqi.js → logging-DiyqRLBx.js} +24 -20
  43. package/dist/{message-C0JY9RJP.js → message-CkCOcbFH.js} +9 -9
  44. package/dist/{model-input-CBp-p24N.js → model-input-DmoPPtPE.js} +5 -10
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +7 -6
  47. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-CIf_6YmA.js} +5 -4
  48. package/dist/{oauth-relay-DRzq73b6.js → oauth-relay-DAmfVmJu.js} +3 -6
  49. package/dist/{package-discovery-DJhGdS4c.js → package-discovery-x4AvVhMj.js} +1 -1
  50. package/dist/{plugin-module-Cf5gVPWP.js → plugin-module-Cv2ETe8Y.js} +1 -1
  51. package/dist/{plugins-BBX07Jzt.js → plugins-Bkk0XRo2.js} +3 -3
  52. package/dist/{projection-CQNDOi82.js → projection-DBq8tsA5.js} +489 -223
  53. package/dist/{prompt-DLUB5m72.js → prompt-D2KlJopL.js} +15 -5
  54. package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
  55. package/dist/queue-DFaOscp5.js +115 -0
  56. package/dist/{registry-Dj377ADs.js → registry-Bu0Z9BEO.js} +37 -37
  57. package/dist/{resolve-DJkh9Fky.js → resolve-DXuA3G0g.js} +4 -229
  58. package/dist/{result-C8iIpDl1.js → result-DpiNseDA.js} +11 -16
  59. package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
  60. package/dist/{runner-DZqrOy8C.js → runner-iu1heRFv.js} +10 -10
  61. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-2HFYDcQf.js} +1 -1
  62. package/dist/{schema-CdZFn7Qd.d.ts → schema-DHMOaRzC.d.ts} +959 -41
  63. package/dist/{schema-DyHXiQKI.js → schema-DvfX3Gq_.js} +141 -40
  64. package/dist/{secrets-DebYU866.js → secrets-DHaJ5TTn.js} +4 -4
  65. package/dist/{sentry-BRTJqumy.js → sentry-CPbZjomA.js} +3 -28
  66. package/dist/{sentry-route-name-BhwWnfqj.js → sentry-route-name-C6EIzAGP.js} +1 -1
  67. package/dist/{service-account-suY004dx.js → service-account-BcT5LR7V.js} +271 -20
  68. package/dist/{service-account-D6jGR4a1.js → service-account-xYkaQTrw.js} +3 -3
  69. package/dist/{session-stop-BLmfFI3d.js → session-stop-BLLp1IP_.js} +1098 -1110
  70. package/dist/{skills-CmNG0dHb.js → skills-CNAGH4ju.js} +6 -9
  71. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-DYnqe5ci.js} +10 -14
  72. package/dist/{spawn-CNjkpXpk.js → spawn-cGasWW33.js} +7 -7
  73. package/dist/{state-CEbZuZD6.js → state-CDS6h_Wv.js} +34 -5
  74. package/dist/{stop-Bjy2-K4H.js → stop-DMMA67yT.js} +896 -196
  75. package/dist/{store-DmV4CoNr.js → store-Dgs7Oe44.js} +5 -5
  76. package/dist/{task-queue-AhG1tSXR.js → task-queue-DcF0nhhz.js} +3 -3
  77. package/dist/{task-runner-BMxZI3o7.js → task-runner-BGXF7Fo7.js} +15 -20
  78. package/dist/{thread-context-CXLnbg7g.js → thread-context-BPky1KBe.js} +12 -12
  79. package/dist/{store-Epv6t4vV.js → turn-session-routing-DGvn9MSl.js} +384 -13
  80. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-19CkuUvM.js} +3 -3
  81. package/dist/{validation-DOz8X9BU.js → validation-lu1DgjNQ.js} +2 -2
  82. package/dist/vercel.js +1 -1
  83. package/dist/{version-CGMRmMPK.js → version-Uo3c94Dx.js} +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/{viewer-H3EsMWtJ.js → viewer-BPQHMx3-.js} +3 -3
  86. package/dist/warmup-H8uLvW9e.js +13946 -0
  87. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  88. package/dist/{worker-ClphajjD.js → worker-B-pM_-3K.js} +9 -12
  89. package/migrations/0108_conversation_embeddings.sql +13 -0
  90. package/migrations/0109_user_preferences.sql +1 -0
  91. package/migrations/0110_code_change_repository_state_index.sql +1 -0
  92. package/migrations/meta/0108_snapshot.json +4688 -0
  93. package/migrations/meta/0109_snapshot.json +4925 -0
  94. package/migrations/meta/0110_snapshot.json +4952 -0
  95. package/migrations/meta/_journal.json +22 -1
  96. package/package.json +16 -17
  97. package/dist/adapter-CNjGEJO9.js +0 -303
  98. package/dist/reporting-window-DopzcOHh.js +0 -137
  99. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  100. package/dist/users-BxvYclQg.js +0 -424
  101. package/dist/warmup-CdU5hR49.js +0 -3715
@@ -1,424 +0,0 @@
1
- import { Ko as SlackActionError, Xo as getSlackClient, rs as withSlackRetries, ts as runWithSlackInstallationToken } from "./projection-CQNDOi82.js";
2
- import { a as getConversationStore } from "./db-Czra10QW.js";
3
- import { r as getStateAdapter } from "./adapter-CNjGEJO9.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 };