birdclaw 0.8.3 → 0.8.5

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 (284) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +10 -8
  3. package/bin/birdclaw.mjs +4 -66
  4. package/dist/cli/birdclaw.js +28164 -0
  5. package/dist/client/assets/AvatarChip-DLoqM5xD.js +1 -0
  6. package/dist/client/assets/ProfilePreview-DQX6_xc3.js +1 -0
  7. package/dist/client/assets/SavedTimelineView-BhSiVyR1.js +1 -0
  8. package/dist/client/assets/SmartTimestamp-BR0-9se2.js +1 -0
  9. package/dist/client/assets/TimelineRouteFrame-9NDLnXzH.js +1 -0
  10. package/dist/client/assets/blocks-CFp_njvG.js +1 -0
  11. package/dist/client/assets/bookmarks-LbYOsoKf.js +1 -0
  12. package/dist/client/assets/chunk-C0phanGV.js +1 -0
  13. package/dist/client/assets/circle-check-C_Vq3ElD.js +1 -0
  14. package/dist/client/assets/client-stream-contracts-sR4xMQxY.js +5 -0
  15. package/dist/client/assets/createLucideIcon-JV8isFFR.js +1 -0
  16. package/dist/client/assets/data-sources-euTr6T_L.js +1 -0
  17. package/dist/client/assets/discuss-BWKu_p7B.js +1 -0
  18. package/dist/client/assets/dms-SLXMtC4v.js +1 -0
  19. package/dist/client/assets/inbox-BybSI5Vf.js +1 -0
  20. package/dist/client/assets/index-DZVisyna.js +31 -0
  21. package/dist/client/assets/index-bpFrQ5yG.css +1 -0
  22. package/dist/client/assets/likes-dyh9p8y_.js +1 -0
  23. package/dist/client/assets/links-CIwqK_dX.js +1 -0
  24. package/dist/client/assets/mapbox-B4zqX7r0.js +2 -0
  25. package/dist/client/assets/mapbox-gl-DYNcLcll.js +3215 -0
  26. package/dist/client/assets/mentions-BoVVAIT7.js +1 -0
  27. package/dist/client/assets/network-map-zRysIY_b.js +2 -0
  28. package/dist/client/assets/profile-analyze-C_yDeX6-.js +1 -0
  29. package/dist/client/assets/profile-hydration-client-YEtJsNTv.js +1 -0
  30. package/dist/client/assets/profiles._handle-DdIVPqU-.js +1 -0
  31. package/dist/client/assets/query-client-fYu2rzRC.js +17 -0
  32. package/dist/client/assets/rate-limits-BWPmPOSh.js +1 -0
  33. package/dist/client/assets/react-dom-DHl6Ug7F.js +1 -0
  34. package/dist/client/assets/react-nBylq1U5.js +1 -0
  35. package/dist/client/assets/repeat-2-xCwHM9hD.js +1 -0
  36. package/dist/client/assets/routes-CiLuYpZr.js +1 -0
  37. package/dist/client/assets/schemas-I9r6F6ya.js +64 -0
  38. package/dist/client/assets/search-Dq5kYsxA.js +1 -0
  39. package/dist/client/assets/sparkles-CQVlvHsZ.js +1 -0
  40. package/dist/client/assets/styles-B8s3tt3r.css +2 -0
  41. package/dist/client/assets/today-BoO64YoY.js +1 -0
  42. package/dist/client/assets/triangle-alert-CBL7s2pf.js +1 -0
  43. package/dist/client/assets/useTimelineRouteData-BaO3Rna1.js +1 -0
  44. package/dist/client/assets/users-CHbKlqUr.js +1 -0
  45. package/dist/server/assets/AvatarChip-zUDAEmjL.js +105 -0
  46. package/dist/server/assets/FeedState-ntW0Q2GB.js +214 -0
  47. package/dist/server/assets/ProfileAnalysisStream-L7bs6IHH.js +198 -0
  48. package/dist/server/assets/ProfilePreview-Cg-AOHBE.js +751 -0
  49. package/dist/server/assets/SavedTimelineView-BtCq1dHk.js +64 -0
  50. package/dist/server/assets/SmartTimestamp-DfwE1NGf.js +45 -0
  51. package/dist/server/assets/SyncNowButton-BOn_IBXS.js +76 -0
  52. package/dist/server/assets/TimelineRouteFrame-CjMIh63G.js +85 -0
  53. package/dist/server/assets/TweetRichText-DDywESRF.js +74 -0
  54. package/dist/server/assets/_tanstack-start-manifest_v-aLWUdbAc.js +148 -0
  55. package/dist/server/assets/account-selection-CTdFGWRk.js +44 -0
  56. package/dist/server/assets/blocks-C1mgGTB3.js +299 -0
  57. package/dist/server/assets/blocks-DSgQghqP.js +17 -0
  58. package/dist/server/assets/bookmarks-D_YkmCK3.js +14 -0
  59. package/dist/server/assets/client-stream-contracts-Bq6kMmhh.js +769 -0
  60. package/dist/server/assets/data-sources-BnA1Q94p.js +180 -0
  61. package/dist/server/assets/discuss-C1QMBBSk.js +338 -0
  62. package/dist/server/assets/discuss-DAq6ehL9.js +15 -0
  63. package/dist/server/assets/dms-BuLj4bp8.js +368 -0
  64. package/dist/server/assets/dms-DAyQrVM2.js +240 -0
  65. package/dist/server/assets/empty-plugin-adapters-DzrEkdBF.js +5 -0
  66. package/dist/server/assets/inbox-CkGOaW1q.js +214 -0
  67. package/dist/server/assets/inbox-DpWd1EzC.js +146 -0
  68. package/dist/server/assets/likes-BMm2JWYI.js +14 -0
  69. package/dist/server/assets/links-Da4tjWtI.js +468 -0
  70. package/dist/server/assets/links-dqXb35YM.js +240 -0
  71. package/dist/server/assets/mentions-CEyEcOFw.js +26 -0
  72. package/dist/server/assets/network-map-D3CzRcC4.js +224 -0
  73. package/dist/server/assets/network-map-D5DoLOwR.js +582 -0
  74. package/dist/server/assets/profile-analyze-CGCj4VFd.js +90 -0
  75. package/dist/server/assets/profile-analyze-DH1TSBkT.js +9 -0
  76. package/dist/server/assets/profile-hydration-client-GJ4kwJS8.js +133 -0
  77. package/dist/server/assets/profiles._handle-B5V-huoo.js +12 -0
  78. package/dist/server/assets/profiles._handle-CJ6rgzt8.js +184 -0
  79. package/dist/server/assets/query-client-BdauHBgd.js +923 -0
  80. package/dist/server/assets/rate-limits-VAr2qzYD.js +262 -0
  81. package/dist/server/assets/route-search-BUlQ5lGM.js +117 -0
  82. package/dist/server/assets/router-C4cz9ypd.js +17026 -0
  83. package/dist/server/assets/routes-B9aikOdB.js +26 -0
  84. package/dist/server/assets/start-FaDOTmto.js +4 -0
  85. package/dist/server/assets/today-B_TA16QG.js +303 -0
  86. package/dist/server/assets/today-JkxZXdBt.js +17 -0
  87. package/dist/server/assets/ui-qbmcMSSX.js +137 -0
  88. package/{src/components/useDebouncedValue.ts → dist/server/assets/useDebouncedValue-DOnA6Xcy.js} +4 -4
  89. package/dist/server/assets/useTimelineRouteData-BLXvMGb2.js +1101 -0
  90. package/dist/server/server.js +5520 -0
  91. package/package.json +26 -34
  92. package/playwright.config.ts +0 -35
  93. package/scripts/browser-perf.mjs +0 -427
  94. package/scripts/build-docs-site.mjs +0 -967
  95. package/scripts/docs-site-assets.mjs +0 -311
  96. package/scripts/run-vitest.mjs +0 -21
  97. package/scripts/sanitize-node-options.mjs +0 -23
  98. package/scripts/start-test-server.mjs +0 -42
  99. package/src/cli/command-context.ts +0 -17
  100. package/src/cli/register-analysis.ts +0 -500
  101. package/src/cli/register-compose.ts +0 -40
  102. package/src/cli/register-graph.ts +0 -132
  103. package/src/cli/register-inbox.ts +0 -41
  104. package/src/cli/register-storage.ts +0 -106
  105. package/src/cli-moderation.ts +0 -210
  106. package/src/cli.ts +0 -1616
  107. package/src/components/AccountSwitcher.tsx +0 -178
  108. package/src/components/AppNav.tsx +0 -118
  109. package/src/components/AvatarChip.tsx +0 -58
  110. package/src/components/AvatarPreload.ts +0 -149
  111. package/src/components/BrandMark.tsx +0 -67
  112. package/src/components/ConversationThread.tsx +0 -131
  113. package/src/components/DmWorkspace.tsx +0 -286
  114. package/src/components/EmbeddedTweetCard.tsx +0 -55
  115. package/src/components/FeedState.tsx +0 -147
  116. package/src/components/FloatingPreview.tsx +0 -382
  117. package/src/components/InboxCard.tsx +0 -152
  118. package/src/components/LinkPreviewCard.tsx +0 -292
  119. package/src/components/MarkdownCitations.tsx +0 -680
  120. package/src/components/MarkdownViewer.tsx +0 -111
  121. package/src/components/ProfileAnalysisClient.ts +0 -191
  122. package/src/components/ProfileAnalysisStream.tsx +0 -259
  123. package/src/components/ProfilePreview.tsx +0 -131
  124. package/src/components/SavedTimelineView.tsx +0 -155
  125. package/src/components/SmartTimestamp.tsx +0 -72
  126. package/src/components/SyncNowButton.tsx +0 -140
  127. package/src/components/ThemeSlider.tsx +0 -80
  128. package/src/components/TimelineCard.tsx +0 -533
  129. package/src/components/TimelineRouteFrame.tsx +0 -186
  130. package/src/components/TweetArticleCard.tsx +0 -66
  131. package/src/components/TweetMediaGrid.tsx +0 -185
  132. package/src/components/TweetRichText.tsx +0 -159
  133. package/src/components/account-selection.ts +0 -64
  134. package/src/components/links-controller.ts +0 -162
  135. package/src/components/links-model.ts +0 -198
  136. package/src/components/network-map-controller.ts +0 -84
  137. package/src/components/network-map-model.ts +0 -255
  138. package/src/components/useTimelineRouteData.ts +0 -193
  139. package/src/lib/account-sync-job.ts +0 -666
  140. package/src/lib/actions-transport.ts +0 -300
  141. package/src/lib/analysis-runtime.ts +0 -238
  142. package/src/lib/api-client.ts +0 -220
  143. package/src/lib/api-contracts.ts +0 -328
  144. package/src/lib/archive-finder.ts +0 -185
  145. package/src/lib/archive-import-plan.ts +0 -102
  146. package/src/lib/archive-import.ts +0 -2695
  147. package/src/lib/authored-live.ts +0 -1027
  148. package/src/lib/avatar-cache.ts +0 -349
  149. package/src/lib/backup.ts +0 -2652
  150. package/src/lib/bird-actions.ts +0 -294
  151. package/src/lib/bird-command.ts +0 -130
  152. package/src/lib/bird.ts +0 -1140
  153. package/src/lib/blocklist.ts +0 -136
  154. package/src/lib/blocks-write.ts +0 -171
  155. package/src/lib/blocks.ts +0 -387
  156. package/src/lib/bookmark-sync-job.ts +0 -536
  157. package/src/lib/config.ts +0 -224
  158. package/src/lib/conversation-surface.ts +0 -205
  159. package/src/lib/data-sources.ts +0 -219
  160. package/src/lib/database-metrics.ts +0 -88
  161. package/src/lib/database-migrations.ts +0 -34
  162. package/src/lib/database-schema.ts +0 -312
  163. package/src/lib/database-writer.ts +0 -69
  164. package/src/lib/db.ts +0 -889
  165. package/src/lib/dm-read-model.ts +0 -533
  166. package/src/lib/dms-live.ts +0 -870
  167. package/src/lib/effect-runtime.ts +0 -45
  168. package/src/lib/follow-graph.ts +0 -1087
  169. package/src/lib/geocoding.ts +0 -296
  170. package/src/lib/http-effect.ts +0 -222
  171. package/src/lib/identity-search-index.ts +0 -369
  172. package/src/lib/import-repository.ts +0 -138
  173. package/src/lib/inbox.ts +0 -242
  174. package/src/lib/link-index.ts +0 -641
  175. package/src/lib/link-insights.ts +0 -860
  176. package/src/lib/link-preview-metadata.ts +0 -754
  177. package/src/lib/live-sync-engine.ts +0 -209
  178. package/src/lib/live-transport-gateway.ts +0 -128
  179. package/src/lib/location.ts +0 -137
  180. package/src/lib/media-fetch.ts +0 -860
  181. package/src/lib/media-includes.ts +0 -165
  182. package/src/lib/mention-threads-live.ts +0 -830
  183. package/src/lib/mentions-export.ts +0 -147
  184. package/src/lib/mentions-live.ts +0 -1114
  185. package/src/lib/moderation-target.ts +0 -227
  186. package/src/lib/moderation-write.ts +0 -131
  187. package/src/lib/mutes-write.ts +0 -171
  188. package/src/lib/mutes.ts +0 -84
  189. package/src/lib/ndjson-stream.ts +0 -106
  190. package/src/lib/network-map.ts +0 -382
  191. package/src/lib/openai-response-runtime.ts +0 -251
  192. package/src/lib/openai.ts +0 -117
  193. package/src/lib/paginated-sync.ts +0 -93
  194. package/src/lib/period-digest.ts +0 -1364
  195. package/src/lib/present.ts +0 -118
  196. package/src/lib/profile-affiliation-hydration.ts +0 -228
  197. package/src/lib/profile-affiliations.ts +0 -262
  198. package/src/lib/profile-analysis.ts +0 -1198
  199. package/src/lib/profile-bio-entities.ts +0 -318
  200. package/src/lib/profile-history.ts +0 -164
  201. package/src/lib/profile-hydration.ts +0 -180
  202. package/src/lib/profile-replies.ts +0 -77
  203. package/src/lib/profile-resolver.ts +0 -650
  204. package/src/lib/queries.ts +0 -6
  205. package/src/lib/query-actions.ts +0 -437
  206. package/src/lib/query-client.tsx +0 -47
  207. package/src/lib/query-read-model-shared.ts +0 -52
  208. package/src/lib/query-read-models.ts +0 -5
  209. package/src/lib/query-resource.ts +0 -41
  210. package/src/lib/query-status.ts +0 -164
  211. package/src/lib/research.ts +0 -652
  212. package/src/lib/runtime-services.ts +0 -20
  213. package/src/lib/search-discussion.ts +0 -812
  214. package/src/lib/seed.ts +0 -613
  215. package/src/lib/server-runtime-services.ts +0 -30
  216. package/src/lib/sqlite.ts +0 -183
  217. package/src/lib/streaming-ingestion.ts +0 -240
  218. package/src/lib/sync-cache.ts +0 -70
  219. package/src/lib/sync-plan.ts +0 -175
  220. package/src/lib/theme-transition.ts +0 -113
  221. package/src/lib/theme.tsx +0 -165
  222. package/src/lib/timeline-collections-live.ts +0 -407
  223. package/src/lib/timeline-live.ts +0 -302
  224. package/src/lib/timeline-read-model.ts +0 -1191
  225. package/src/lib/tweet-account-edges.ts +0 -48
  226. package/src/lib/tweet-lookup.ts +0 -46
  227. package/src/lib/tweet-render.ts +0 -430
  228. package/src/lib/tweet-repository.ts +0 -156
  229. package/src/lib/tweet-search-live.ts +0 -462
  230. package/src/lib/types.ts +0 -723
  231. package/src/lib/ui.ts +0 -529
  232. package/src/lib/url-expansion-store.ts +0 -110
  233. package/src/lib/url-expansion.ts +0 -343
  234. package/src/lib/url-safety.ts +0 -220
  235. package/src/lib/web-sync.ts +0 -533
  236. package/src/lib/whois.ts +0 -1080
  237. package/src/lib/x-profile.ts +0 -365
  238. package/src/lib/x-web.ts +0 -199
  239. package/src/lib/xurl-rate-limits.ts +0 -267
  240. package/src/lib/xurl.ts +0 -1677
  241. package/src/routeTree.gen.ts +0 -723
  242. package/src/router.tsx +0 -20
  243. package/src/routes/__root.tsx +0 -82
  244. package/src/routes/api/action.tsx +0 -147
  245. package/src/routes/api/avatar.tsx +0 -50
  246. package/src/routes/api/blocks.tsx +0 -35
  247. package/src/routes/api/conversation.tsx +0 -45
  248. package/src/routes/api/data-sources.tsx +0 -24
  249. package/src/routes/api/inbox.tsx +0 -43
  250. package/src/routes/api/link-insights.tsx +0 -85
  251. package/src/routes/api/link-preview.tsx +0 -47
  252. package/src/routes/api/network-map.tsx +0 -55
  253. package/src/routes/api/period-digest.tsx +0 -101
  254. package/src/routes/api/profile-analysis.tsx +0 -97
  255. package/src/routes/api/profile-hydrate.tsx +0 -54
  256. package/src/routes/api/query.tsx +0 -121
  257. package/src/routes/api/search-discussion.tsx +0 -113
  258. package/src/routes/api/status.tsx +0 -30
  259. package/src/routes/api/sync.tsx +0 -108
  260. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  261. package/src/routes/blocks.tsx +0 -343
  262. package/src/routes/bookmarks.tsx +0 -18
  263. package/src/routes/data-sources.tsx +0 -249
  264. package/src/routes/discuss.tsx +0 -419
  265. package/src/routes/dms.tsx +0 -415
  266. package/src/routes/inbox.tsx +0 -232
  267. package/src/routes/index.tsx +0 -32
  268. package/src/routes/likes.tsx +0 -18
  269. package/src/routes/links.tsx +0 -631
  270. package/src/routes/mentions.tsx +0 -32
  271. package/src/routes/network-map.tsx +0 -732
  272. package/src/routes/profile-analyze.tsx +0 -112
  273. package/src/routes/profiles.$handle.tsx +0 -228
  274. package/src/routes/rate-limits.tsx +0 -305
  275. package/src/routes/today.tsx +0 -511
  276. package/src/styles.css +0 -257
  277. package/tsconfig.json +0 -29
  278. package/vite.config.ts +0 -29
  279. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  280. /package/{public → dist/client}/favicon.ico +0 -0
  281. /package/{public → dist/client}/logo192.png +0 -0
  282. /package/{public → dist/client}/logo512.png +0 -0
  283. /package/{public → dist/client}/manifest.json +0 -0
  284. /package/{public → dist/client}/robots.txt +0 -0
package/src/lib/whois.ts DELETED
@@ -1,1080 +0,0 @@
1
- import { Effect } from "effect";
2
- import { getNativeDb } from "./db";
3
- import { runEffectPromise } from "./effect-runtime";
4
- import {
5
- ensureIdentitySearchIndexForDmProfiles,
6
- syncIdentitySearchIndexForProfileIds,
7
- } from "./identity-search-index";
8
- import { fetchProfileBioEntities } from "./profile-bio-entities";
9
- import { fetchProfileSnapshots } from "./profile-history";
10
- import { resolveProfilesForIdsEffect } from "./profile-resolver";
11
- import type { ProfileResolveResult } from "./profile-resolver";
12
- import { listDmConversations } from "./dm-read-model";
13
- import { listTimelineItems } from "./timeline-read-model";
14
- import { expandUrlsFromTextsEffect } from "./url-expansion";
15
- import type {
16
- DmConversationItem,
17
- ProfileAffiliation,
18
- ProfileBioEntity,
19
- ProfileRecord,
20
- ProfileSnapshot,
21
- TimelineItem,
22
- UrlExpansionItem,
23
- } from "./types";
24
-
25
- export interface WhoisOptions {
26
- account?: string;
27
- dms?: boolean;
28
- tweets?: boolean;
29
- resolveProfiles?: boolean;
30
- expandUrls?: boolean;
31
- refreshProfileCache?: boolean;
32
- refreshUrlCache?: boolean;
33
- xurlFallback?: boolean;
34
- context?: number;
35
- limit?: number;
36
- affiliation?: string;
37
- currentAffiliation?: string;
38
- excludeDomainOnly?: boolean;
39
- }
40
-
41
- export interface WhoisCandidate {
42
- conversation: DmConversationItem;
43
- confidence: number;
44
- category: WhoisCandidateCategory;
45
- reasons: string[];
46
- profileEvidence: WhoisEvidenceSignal[];
47
- evidence: Array<{
48
- messageId: string;
49
- createdAt: string;
50
- direction: string;
51
- text: string;
52
- urlExpansions?: UrlExpansionItem[];
53
- }>;
54
- }
55
-
56
- export type WhoisCandidateCategory =
57
- | "likely_affiliated"
58
- | "ecosystem"
59
- | "profile_or_link"
60
- | "dm_context"
61
- | "other";
62
-
63
- export interface WhoisResult {
64
- query: string;
65
- candidates: WhoisCandidate[];
66
- relatedTweets: TimelineItem[];
67
- urlExpansions: UrlExpansionItem[];
68
- profileResolution?: ProfileResolveResult[];
69
- }
70
-
71
- export interface WhoisEvidenceSignal {
72
- kind:
73
- | "profile_handle"
74
- | "profile_name"
75
- | "profile_bio"
76
- | "profile_location"
77
- | "profile_url"
78
- | "profile_bio_url"
79
- | "profile_verified_type"
80
- | "affiliation"
81
- | "bio_handle"
82
- | "bio_domain"
83
- | "bio_company"
84
- | "profile_history"
85
- | "dm_context"
86
- | "expanded_url";
87
- value: string;
88
- source: "profile" | "affiliation" | "bio_entity" | "history" | "dm" | "url";
89
- }
90
-
91
- function trySync<T>(try_: () => T) {
92
- return Effect.try({
93
- try: try_,
94
- catch: (cause) => cause,
95
- });
96
- }
97
-
98
- interface WhoisQueryIntent {
99
- raw: string;
100
- normalized: string;
101
- terms: string[];
102
- handles: string[];
103
- domains: string[];
104
- wantsPerson: boolean;
105
- wantsAffiliation: boolean;
106
- wantsDomain: boolean;
107
- }
108
-
109
- function normalizeQuery(query: string) {
110
- return query.trim().toLowerCase();
111
- }
112
-
113
- function getSignificantQueryTerms(query: string) {
114
- const stopwords = new Set([
115
- "a",
116
- "an",
117
- "and",
118
- "at",
119
- "for",
120
- "from",
121
- "guy",
122
- "is",
123
- "of",
124
- "person",
125
- "the",
126
- "who",
127
- "with",
128
- ]);
129
- return Array.from(
130
- new Set(
131
- normalizeQuery(query)
132
- .split(/[^a-z0-9_@.-]+/)
133
- .map((term) => term.replace(/^@/, ""))
134
- .filter((term) => term.length >= 3 && !stopwords.has(term)),
135
- ),
136
- );
137
- }
138
-
139
- function getQueryDomains(query: string) {
140
- return Array.from(
141
- new Set(
142
- query
143
- .toLowerCase()
144
- .match(/\b(?:[a-z0-9-]+\.)+[a-z]{2,}\b/g)
145
- ?.map((domain) => domain.replace(/^www\./, "")) ?? [],
146
- ),
147
- );
148
- }
149
-
150
- function getQueryHandles(query: string) {
151
- return Array.from(
152
- new Set(
153
- query
154
- .match(/@[A-Za-z0-9_]{1,15}\b/g)
155
- ?.map((handle) => handle.toLowerCase()) ?? [],
156
- ),
157
- );
158
- }
159
-
160
- function getQueryIntent(query: string): WhoisQueryIntent {
161
- const normalized = normalizeQuery(query);
162
- const domains = getQueryDomains(query);
163
- const handles = getQueryHandles(query);
164
- const terms = getSignificantQueryTerms(query);
165
- const wantsPerson =
166
- /\b(guy|person|people|who|someone|staff|employee|devrel|founder|founders)\b/i.test(
167
- query,
168
- );
169
- const wantsDomain =
170
- domains.length > 0 ||
171
- (/\b(link|url|domain|repo|repository|github\.com)\b/i.test(query) &&
172
- !wantsPerson);
173
- const wantsAffiliation =
174
- handles.length > 0 ||
175
- wantsPerson ||
176
- /\b(at|from|works?|employee|staff|affiliation|company|org|devrel)\b/i.test(
177
- query,
178
- );
179
- return {
180
- raw: query,
181
- normalized,
182
- terms,
183
- handles,
184
- domains,
185
- wantsPerson,
186
- wantsAffiliation,
187
- wantsDomain,
188
- };
189
- }
190
-
191
- function matchesQueryText(query: string, value: string | undefined | null) {
192
- if (!value) {
193
- return false;
194
- }
195
- const normalizedValue = value.toLowerCase();
196
- if (normalizedValue.includes(query)) {
197
- return true;
198
- }
199
- return getSignificantQueryTerms(query).some((term) =>
200
- normalizedValue.includes(term),
201
- );
202
- }
203
-
204
- function getDmSearchQueries(query: string) {
205
- const trimmed = query.trim();
206
- const values = [trimmed, ...getSignificantQueryTerms(trimmed)];
207
- return Array.from(new Set(values.filter((value) => value.length > 0)));
208
- }
209
-
210
- function getMessageTexts(conversation: DmConversationItem) {
211
- return (conversation.matches ?? []).flatMap((match) => [
212
- ...match.before.map((message) => message.text),
213
- match.message.text,
214
- ...match.after.map((message) => message.text),
215
- ]);
216
- }
217
-
218
- function getUrlEntityExpandedUrl(entity: unknown) {
219
- if (!entity || typeof entity !== "object") {
220
- return undefined;
221
- }
222
- const record = entity as Record<string, unknown>;
223
- const expanded = record.expandedUrl ?? record.expanded_url ?? record.url;
224
- return typeof expanded === "string" && expanded.length > 0
225
- ? expanded
226
- : undefined;
227
- }
228
-
229
- function getProfileBioUrls(profile: ProfileRecord) {
230
- const description = profile.entities?.description;
231
- if (!description || typeof description !== "object") {
232
- return [];
233
- }
234
- const urls = (description as { urls?: unknown }).urls;
235
- if (!Array.isArray(urls)) {
236
- return [];
237
- }
238
- return urls
239
- .map(getUrlEntityExpandedUrl)
240
- .filter((url): url is string => Boolean(url));
241
- }
242
-
243
- function getAffiliationTexts(affiliation: ProfileAffiliation) {
244
- return [
245
- affiliation.organizationName,
246
- affiliation.organizationHandle,
247
- affiliation.label,
248
- affiliation.url,
249
- affiliation.organizationProfileId,
250
- ].filter((item): item is string => Boolean(item));
251
- }
252
-
253
- function pushMatchEvidence(
254
- signals: WhoisEvidenceSignal[],
255
- query: string,
256
- kind: WhoisEvidenceSignal["kind"],
257
- value: string | undefined | null,
258
- source: WhoisEvidenceSignal["source"],
259
- ) {
260
- if (!matchesQueryText(query, value)) {
261
- return;
262
- }
263
- signals.push({ kind, value: String(value), source });
264
- }
265
-
266
- function getSnapshotAffiliationTexts(snapshot: ProfileSnapshot) {
267
- return snapshot.affiliations.flatMap((affiliation) => {
268
- if (!affiliation || typeof affiliation !== "object") {
269
- return [];
270
- }
271
- const record = affiliation as Record<string, unknown>;
272
- return [
273
- record.organizationName,
274
- record.organizationHandle,
275
- record.label,
276
- record.url,
277
- ].filter(
278
- (item): item is string => typeof item === "string" && item.length > 0,
279
- );
280
- });
281
- }
282
-
283
- function getHistoricalSnapshotTexts(
284
- snapshot: ProfileSnapshot,
285
- profile: ProfileRecord,
286
- ) {
287
- const texts: string[] = [];
288
- if (snapshot.handle !== profile.handle) {
289
- texts.push(`previous handle: @${snapshot.handle}`);
290
- }
291
- if (snapshot.displayName !== profile.displayName) {
292
- texts.push(`previous name: ${snapshot.displayName}`);
293
- }
294
- if (snapshot.bio !== profile.bio) {
295
- texts.push(`previous bio: ${snapshot.bio}`);
296
- }
297
- if (snapshot.location && snapshot.location !== (profile.location ?? null)) {
298
- texts.push(`previous location: ${snapshot.location}`);
299
- }
300
- if (snapshot.url && snapshot.url !== (profile.url ?? null)) {
301
- texts.push(`previous url: ${snapshot.url}`);
302
- }
303
- if (
304
- snapshot.verifiedType &&
305
- snapshot.verifiedType !== (profile.verifiedType ?? null)
306
- ) {
307
- texts.push(`previous verified: ${snapshot.verifiedType}`);
308
- }
309
- const currentAffiliationTexts = new Set(
310
- (profile.affiliations ?? [])
311
- .flatMap((affiliation) => [
312
- affiliation.organizationName,
313
- affiliation.organizationHandle,
314
- affiliation.label,
315
- affiliation.url,
316
- ])
317
- .filter((item): item is string => Boolean(item))
318
- .map((item) => item.toLowerCase()),
319
- );
320
- const previousAffiliationTexts = getSnapshotAffiliationTexts(snapshot);
321
- if (
322
- previousAffiliationTexts.some(
323
- (text) => !currentAffiliationTexts.has(text.toLowerCase()),
324
- )
325
- ) {
326
- texts.push(
327
- `previous affiliations: ${JSON.stringify(snapshot.affiliations)}`,
328
- );
329
- }
330
- return texts;
331
- }
332
-
333
- function collectProfileEvidence(
334
- query: string,
335
- profile: ProfileRecord,
336
- bioEntities: ProfileBioEntity[] = [],
337
- snapshots: ProfileSnapshot[] = [],
338
- ) {
339
- const signals: WhoisEvidenceSignal[] = [];
340
- pushMatchEvidence(
341
- signals,
342
- query,
343
- "profile_handle",
344
- profile.handle,
345
- "profile",
346
- );
347
- pushMatchEvidence(
348
- signals,
349
- query,
350
- "profile_name",
351
- profile.displayName,
352
- "profile",
353
- );
354
- pushMatchEvidence(signals, query, "profile_bio", profile.bio, "profile");
355
- pushMatchEvidence(
356
- signals,
357
- query,
358
- "profile_location",
359
- profile.location,
360
- "profile",
361
- );
362
- pushMatchEvidence(signals, query, "profile_url", profile.url, "profile");
363
- pushMatchEvidence(
364
- signals,
365
- query,
366
- "profile_verified_type",
367
- profile.verifiedType,
368
- "profile",
369
- );
370
- for (const url of getProfileBioUrls(profile)) {
371
- pushMatchEvidence(signals, query, "profile_bio_url", url, "profile");
372
- }
373
- for (const affiliation of profile.affiliations ?? []) {
374
- for (const text of getAffiliationTexts(affiliation)) {
375
- pushMatchEvidence(signals, query, "affiliation", text, "affiliation");
376
- }
377
- }
378
- for (const entity of bioEntities) {
379
- const kind =
380
- entity.kind === "handle"
381
- ? "bio_handle"
382
- : entity.kind === "domain"
383
- ? "bio_domain"
384
- : "bio_company";
385
- pushMatchEvidence(signals, query, kind, entity.value, "bio_entity");
386
- }
387
- for (const snapshot of snapshots) {
388
- for (const text of getHistoricalSnapshotTexts(snapshot, profile)) {
389
- pushMatchEvidence(
390
- signals,
391
- query,
392
- "profile_history",
393
- `${snapshot.lastSeenAt}: ${text}`,
394
- "history",
395
- );
396
- }
397
- }
398
- return signals;
399
- }
400
-
401
- const DOMAIN_ONLY_EVIDENCE = new Set<WhoisEvidenceSignal["kind"]>([
402
- "profile_url",
403
- "profile_bio_url",
404
- "bio_domain",
405
- "expanded_url",
406
- ]);
407
-
408
- function getEvidenceWeight(
409
- signal: WhoisEvidenceSignal,
410
- intent: WhoisQueryIntent,
411
- profile: ProfileRecord,
412
- ) {
413
- const bio = profile.bio.toLowerCase();
414
- const ecosystemPenalty =
415
- signal.kind === "bio_handle" || signal.kind === "bio_company"
416
- ? isEcosystemMention(bio, intent)
417
- : false;
418
- switch (signal.kind) {
419
- case "affiliation":
420
- return 72;
421
- case "bio_handle":
422
- return ecosystemPenalty ? 20 : 56;
423
- case "bio_company":
424
- return ecosystemPenalty ? 16 : 46;
425
- case "profile_history":
426
- return 36;
427
- case "profile_handle":
428
- return intent.handles.length > 0 ? 44 : 24;
429
- case "profile_name":
430
- case "profile_bio":
431
- return 24;
432
- case "dm_context":
433
- return intent.wantsAffiliation ? 12 : 22;
434
- case "expanded_url":
435
- return intent.wantsDomain ? 26 : 8;
436
- case "profile_url":
437
- case "profile_bio_url":
438
- case "bio_domain":
439
- return intent.wantsDomain ? 30 : 8;
440
- case "profile_location":
441
- case "profile_verified_type":
442
- return 8;
443
- }
444
- }
445
-
446
- function isEcosystemMention(bio: string, intent: WhoisQueryIntent) {
447
- const terms = new Set([
448
- ...intent.terms,
449
- ...intent.handles.map((handle) => handle.replace(/^@/, "")),
450
- ]);
451
- for (const term of terms) {
452
- const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
453
- if (
454
- new RegExp(
455
- `\\b${escaped}\\s+(star|stars|sponsor|sponsors|campus expert|expert|partner|alumni)\\b`,
456
- "i",
457
- ).test(bio)
458
- ) {
459
- return true;
460
- }
461
- }
462
- return false;
463
- }
464
-
465
- function hasCurrentAffiliationMatch(
466
- profile: ProfileRecord,
467
- affiliationQuery: string | undefined,
468
- ) {
469
- if (!affiliationQuery?.trim()) {
470
- return true;
471
- }
472
- const normalized = normalizeQuery(affiliationQuery);
473
- return (profile.affiliations ?? []).some((affiliation) =>
474
- getAffiliationTexts(affiliation).some((text) =>
475
- matchesQueryText(normalized, text),
476
- ),
477
- );
478
- }
479
-
480
- function hasAffiliationEvidenceMatch(
481
- profile: ProfileRecord,
482
- profileEvidence: WhoisEvidenceSignal[],
483
- affiliationQuery: string | undefined,
484
- ) {
485
- if (!affiliationQuery?.trim()) {
486
- return true;
487
- }
488
- const normalized = normalizeQuery(affiliationQuery);
489
- if (hasCurrentAffiliationMatch(profile, affiliationQuery)) {
490
- return true;
491
- }
492
- return profileEvidence.some(
493
- (signal) =>
494
- (signal.kind === "affiliation" ||
495
- signal.kind === "bio_handle" ||
496
- signal.kind === "bio_company" ||
497
- signal.kind === "profile_history") &&
498
- matchesQueryText(normalized, signal.value),
499
- );
500
- }
501
-
502
- function hasNonDomainEvidence(profileEvidence: WhoisEvidenceSignal[]) {
503
- return profileEvidence.some(
504
- (signal) => !DOMAIN_ONLY_EVIDENCE.has(signal.kind),
505
- );
506
- }
507
-
508
- function getCandidateCategory(
509
- profile: ProfileRecord,
510
- profileEvidence: WhoisEvidenceSignal[],
511
- intent: WhoisQueryIntent,
512
- messageMatched: boolean,
513
- ): WhoisCandidateCategory {
514
- if (profileEvidence.some((signal) => signal.kind === "affiliation")) {
515
- return "likely_affiliated";
516
- }
517
- if (
518
- profileEvidence.some(
519
- (signal) =>
520
- signal.kind === "bio_handle" ||
521
- signal.kind === "bio_company" ||
522
- signal.kind === "profile_history",
523
- )
524
- ) {
525
- return isEcosystemMention(profile.bio.toLowerCase(), intent)
526
- ? "ecosystem"
527
- : "likely_affiliated";
528
- }
529
- if (profileEvidence.some((signal) => DOMAIN_ONLY_EVIDENCE.has(signal.kind))) {
530
- return "profile_or_link";
531
- }
532
- return messageMatched ? "dm_context" : "other";
533
- }
534
-
535
- function scoreCandidate(
536
- query: string,
537
- conversation: DmConversationItem,
538
- expansions: UrlExpansionItem[],
539
- bioEntities: ProfileBioEntity[] = [],
540
- snapshots: ProfileSnapshot[] = [],
541
- ) {
542
- const normalized = normalizeQuery(query);
543
- const intent = getQueryIntent(query);
544
- const profile = conversation.participant;
545
- const profileEvidence = collectProfileEvidence(
546
- normalized,
547
- profile,
548
- bioEntities,
549
- snapshots,
550
- );
551
- const affiliationTexts = (profile.affiliations ?? []).flatMap(
552
- getAffiliationTexts,
553
- );
554
- const profileBioUrls = getProfileBioUrls(profile);
555
- const bioEntityTexts = bioEntities.map((entity) => entity.value);
556
- const profileHistoryTexts = snapshots.flatMap((snapshot) =>
557
- getHistoricalSnapshotTexts(snapshot, profile),
558
- );
559
- const messageTexts = getMessageTexts(conversation);
560
- const haystack = [
561
- conversation.title,
562
- profile.handle,
563
- profile.displayName,
564
- profile.bio,
565
- profile.location,
566
- profile.url,
567
- profile.verifiedType,
568
- ...profileBioUrls,
569
- ...affiliationTexts,
570
- ...bioEntityTexts,
571
- ...profileHistoryTexts,
572
- ...messageTexts,
573
- ]
574
- .filter(Boolean)
575
- .join("\n")
576
- .toLowerCase();
577
- const reasons: string[] = [];
578
- let confidence = 0;
579
-
580
- if (!/^id\d+$/.test(conversation.participant.handle)) {
581
- confidence += 18;
582
- reasons.push("resolved profile");
583
- }
584
- if (
585
- matchesQueryText(normalized, profile.handle) ||
586
- matchesQueryText(normalized, profile.displayName) ||
587
- matchesQueryText(normalized, profile.bio)
588
- ) {
589
- confidence += 18;
590
- reasons.push("profile matches query");
591
- }
592
- if (
593
- matchesQueryText(normalized, profile.url) ||
594
- profileBioUrls.some((url) => matchesQueryText(normalized, url))
595
- ) {
596
- confidence += intent.wantsDomain ? 28 : 8;
597
- reasons.push("profile URL matches query");
598
- }
599
- if (profileEvidence.some((signal) => signal.kind === "affiliation")) {
600
- confidence += 40;
601
- reasons.push("affiliation matches query");
602
- }
603
- if (profileEvidence.some((signal) => signal.source === "bio_entity")) {
604
- confidence += 24;
605
- reasons.push("bio entity matches query");
606
- }
607
- if (profileEvidence.some((signal) => signal.source === "history")) {
608
- confidence += 20;
609
- reasons.push("profile history matches query");
610
- }
611
- if (haystack.includes("co-founder") || haystack.includes("cofounder")) {
612
- confidence += 25;
613
- reasons.push("cofounder language");
614
- }
615
- const messageMatched = messageTexts.some((text) =>
616
- matchesQueryText(normalized, text),
617
- );
618
- if (messageMatched) {
619
- confidence += intent.wantsAffiliation ? 10 : 18;
620
- reasons.push("message text matches query");
621
- profileEvidence.push({
622
- kind: "dm_context",
623
- value: query,
624
- source: "dm",
625
- });
626
- }
627
- if (expansions.some((item) => matchesQueryText(normalized, item.finalUrl))) {
628
- confidence += intent.wantsDomain ? 20 : 8;
629
- reasons.push("expanded URL matches query");
630
- for (const item of expansions) {
631
- pushMatchEvidence(
632
- profileEvidence,
633
- normalized,
634
- "expanded_url",
635
- item.finalUrl,
636
- "url",
637
- );
638
- }
639
- }
640
-
641
- for (const signal of profileEvidence) {
642
- confidence += getEvidenceWeight(signal, intent, profile);
643
- }
644
- const category = getCandidateCategory(
645
- profile,
646
- profileEvidence,
647
- intent,
648
- messageMatched,
649
- );
650
- if (category === "ecosystem") {
651
- confidence -= 24;
652
- reasons.push("ecosystem mention, not direct affiliation");
653
- }
654
- if (category === "profile_or_link" && intent.wantsAffiliation) {
655
- confidence -= 18;
656
- }
657
-
658
- return {
659
- confidence: Math.max(0, Math.min(100, confidence)),
660
- category,
661
- reasons: reasons.length > 0 ? reasons : ["local DM match"],
662
- profileEvidence,
663
- };
664
- }
665
-
666
- function attachExpansionsToMatches(
667
- conversation: DmConversationItem,
668
- expansions: UrlExpansionItem[],
669
- ) {
670
- for (const match of conversation.matches ?? []) {
671
- const matchUrls = new Set(
672
- [...match.before, match.message, ...match.after].flatMap((message) =>
673
- expansions
674
- .filter((item) => message.text.includes(item.url))
675
- .map((item) => item.url),
676
- ),
677
- );
678
- if (matchUrls.size > 0) {
679
- match.urlExpansions = expansions.filter((item) =>
680
- matchUrls.has(item.url),
681
- );
682
- }
683
- }
684
- }
685
-
686
- function mergeConversations(
687
- target: Map<string, DmConversationItem>,
688
- conversations: DmConversationItem[],
689
- ) {
690
- for (const conversation of conversations) {
691
- if (!target.has(conversation.id)) {
692
- target.set(conversation.id, conversation);
693
- }
694
- }
695
- }
696
-
697
- function findProfileEvidenceConversationIds(
698
- query: string,
699
- account: string | undefined,
700
- limit: number,
701
- ) {
702
- const terms = [normalizeQuery(query), ...getSignificantQueryTerms(query)]
703
- .filter((term) => term.length > 0)
704
- .filter((term, index, array) => array.indexOf(term) === index);
705
- if (terms.length === 0) {
706
- return [];
707
- }
708
- const db = getNativeDb();
709
- ensureIdentitySearchIndexForDmProfiles(db, account);
710
- const clauses: string[] = [];
711
- const params: Array<string | number> = [];
712
- for (const term of terms) {
713
- const pattern = `%${term}%`;
714
- clauses.push("isi.normalized_value like ?");
715
- params.push(pattern);
716
- }
717
-
718
- let accountClause = "";
719
- if (account && account !== "all") {
720
- accountClause = "and c.account_id = ?";
721
- params.push(account);
722
- }
723
- params.push(limit);
724
-
725
- const rows = db
726
- .prepare(
727
- `
728
- select c.id, max(isi.weight) as max_weight
729
- from dm_conversations c
730
- join identity_search_index isi on isi.profile_id = c.participant_profile_id
731
- where (${clauses.map((clause) => `(${clause})`).join(" or ")})
732
- ${accountClause}
733
- group by c.id
734
- order by max_weight desc, c.last_message_at desc
735
- limit ?
736
- `,
737
- )
738
- .all(...params) as Array<{ id: string }>;
739
- return rows.map((row) => row.id);
740
- }
741
-
742
- function loadWhoisConversations(
743
- query: string,
744
- options: WhoisOptions,
745
- includeDms: boolean,
746
- context: number,
747
- limit: number,
748
- ) {
749
- if (!includeDms) {
750
- return [];
751
- }
752
- const merged = new Map<string, DmConversationItem>();
753
- const batchLimit = Math.max(limit * 3, 20);
754
- for (const search of getDmSearchQueries(query)) {
755
- mergeConversations(
756
- merged,
757
- listDmConversations({
758
- account: options.account,
759
- search,
760
- context,
761
- limit: batchLimit,
762
- }),
763
- );
764
- }
765
-
766
- const profileEvidenceIds = findProfileEvidenceConversationIds(
767
- query,
768
- options.account,
769
- Math.max(limit * 5, 50),
770
- );
771
- if (profileEvidenceIds.length > 0) {
772
- mergeConversations(
773
- merged,
774
- listDmConversations({
775
- account: options.account,
776
- conversationIds: profileEvidenceIds,
777
- limit: profileEvidenceIds.length,
778
- }),
779
- );
780
- }
781
-
782
- return [...merged.values()];
783
- }
784
-
785
- export function runWhoisEffect(
786
- query: string,
787
- options: WhoisOptions = {},
788
- ): Effect.Effect<WhoisResult, unknown> {
789
- return Effect.gen(function* () {
790
- const includeDms = options.dms ?? true;
791
- const includeTweets = options.tweets ?? false;
792
- const limit = options.limit ?? 10;
793
- const context = options.context ?? 4;
794
- let conversations = yield* trySync(() =>
795
- loadWhoisConversations(query, options, includeDms, context, limit),
796
- );
797
- let profileResolution: WhoisResult["profileResolution"];
798
-
799
- if (options.resolveProfiles ?? true) {
800
- profileResolution = yield* resolveProfilesForIdsEffect(
801
- conversations.map((item) => item.participant.id),
802
- {
803
- refresh: options.refreshProfileCache,
804
- xurlFallback: options.xurlFallback ?? true,
805
- },
806
- );
807
- conversations = yield* trySync(() =>
808
- loadWhoisConversations(query, options, includeDms, context, limit),
809
- );
810
- }
811
- yield* trySync(() =>
812
- syncIdentitySearchIndexForProfileIds(
813
- getNativeDb(),
814
- conversations.map((item) => item.participant.id),
815
- ),
816
- );
817
-
818
- const relatedTweets = includeTweets
819
- ? yield* trySync(() => [
820
- ...listTimelineItems({
821
- resource: "home",
822
- account: options.account,
823
- search: query,
824
- limit,
825
- }),
826
- ...listTimelineItems({
827
- resource: "mentions",
828
- account: options.account,
829
- search: query,
830
- limit,
831
- }),
832
- ])
833
- : [];
834
-
835
- const texts = yield* trySync(() => [
836
- ...conversations.flatMap(getMessageTexts),
837
- ...conversations.flatMap((conversation) =>
838
- [
839
- conversation.participant.bio,
840
- conversation.participant.url ?? "",
841
- ...getProfileBioUrls(conversation.participant),
842
- ].filter((text) => text.includes("https://t.co/")),
843
- ),
844
- ...relatedTweets.map((tweet) => tweet.text),
845
- ]);
846
- const urlExpansions =
847
- (options.expandUrls ?? true)
848
- ? yield* expandUrlsFromTextsEffect(texts, {
849
- refresh: options.refreshUrlCache,
850
- })
851
- : [];
852
- yield* trySync(() => {
853
- for (const conversation of conversations) {
854
- attachExpansionsToMatches(conversation, urlExpansions);
855
- }
856
- });
857
-
858
- const candidates = yield* trySync(() => {
859
- const profileIds = conversations.map(
860
- (conversation) => conversation.participant.id,
861
- );
862
- const db = getNativeDb();
863
- const bioEntitiesByProfile = fetchProfileBioEntities(db, profileIds);
864
- const snapshotsByProfile = fetchProfileSnapshots(db, profileIds);
865
- return conversations
866
- .map((conversation): WhoisCandidate | null => {
867
- const conversationExpansions = urlExpansions.filter((item) =>
868
- getMessageTexts(conversation).some((text) =>
869
- text.includes(item.url),
870
- ),
871
- );
872
- const profileId = conversation.participant.id;
873
- const score = scoreCandidate(
874
- query,
875
- conversation,
876
- conversationExpansions,
877
- bioEntitiesByProfile.get(profileId) ?? [],
878
- snapshotsByProfile.get(profileId) ?? [],
879
- );
880
- if (
881
- !hasCurrentAffiliationMatch(
882
- conversation.participant,
883
- options.currentAffiliation,
884
- )
885
- ) {
886
- return null;
887
- }
888
- if (
889
- !hasAffiliationEvidenceMatch(
890
- conversation.participant,
891
- score.profileEvidence,
892
- options.affiliation,
893
- )
894
- ) {
895
- return null;
896
- }
897
- if (
898
- options.excludeDomainOnly &&
899
- !hasNonDomainEvidence(score.profileEvidence)
900
- ) {
901
- return null;
902
- }
903
- return {
904
- conversation,
905
- confidence: score.confidence,
906
- category: score.category,
907
- reasons: score.reasons,
908
- profileEvidence: score.profileEvidence,
909
- evidence: (conversation.matches ?? []).map((match) => ({
910
- messageId: match.message.id,
911
- createdAt: match.message.createdAt,
912
- direction: match.message.direction,
913
- text: match.message.text,
914
- ...(match.urlExpansions
915
- ? { urlExpansions: match.urlExpansions }
916
- : {}),
917
- })),
918
- };
919
- })
920
- .filter((candidate): candidate is WhoisCandidate => candidate !== null)
921
- .sort((left, right) => {
922
- if (right.confidence !== left.confidence) {
923
- return right.confidence - left.confidence;
924
- }
925
- return (
926
- new Date(right.conversation.lastMessageAt).getTime() -
927
- new Date(left.conversation.lastMessageAt).getTime()
928
- );
929
- })
930
- .slice(0, limit);
931
- });
932
-
933
- return {
934
- query,
935
- candidates,
936
- relatedTweets,
937
- urlExpansions,
938
- ...(profileResolution ? { profileResolution } : {}),
939
- };
940
- });
941
- }
942
-
943
- export function runWhois(
944
- query: string,
945
- options: WhoisOptions = {},
946
- ): Promise<WhoisResult> {
947
- return runEffectPromise(runWhoisEffect(query, options));
948
- }
949
-
950
- const CATEGORY_LABELS: Record<WhoisCandidateCategory, string> = {
951
- likely_affiliated: "Likely affiliated",
952
- ecosystem: "Ecosystem / role mentions",
953
- profile_or_link: "Profile or link matches",
954
- dm_context: "DM context matches",
955
- other: "Other local matches",
956
- };
957
-
958
- function summarizeSignal(signal: WhoisEvidenceSignal) {
959
- switch (signal.kind) {
960
- case "affiliation":
961
- return `current affiliation ${signal.value}`;
962
- case "bio_handle":
963
- return `bio handle ${signal.value}`;
964
- case "bio_company":
965
- return `bio company ${signal.value}`;
966
- case "profile_history":
967
- return `profile history ${signal.value}`;
968
- case "profile_url":
969
- case "profile_bio_url":
970
- case "bio_domain":
971
- return `domain/link ${signal.value}`;
972
- case "dm_context":
973
- return `DM context`;
974
- case "expanded_url":
975
- return `expanded URL ${signal.value}`;
976
- default:
977
- return `${signal.kind.replace(/^profile_/, "profile ")} ${signal.value}`;
978
- }
979
- }
980
-
981
- function signalSummaryRank(signal: WhoisEvidenceSignal) {
982
- switch (signal.kind) {
983
- case "affiliation":
984
- return 0;
985
- case "bio_handle":
986
- return 1;
987
- case "bio_company":
988
- return 2;
989
- case "profile_history":
990
- return 3;
991
- case "dm_context":
992
- return 4;
993
- case "expanded_url":
994
- return 5;
995
- case "profile_url":
996
- case "profile_bio_url":
997
- case "bio_domain":
998
- return 6;
999
- default:
1000
- return 7;
1001
- }
1002
- }
1003
-
1004
- function explainCandidate(candidate: WhoisCandidate) {
1005
- const evidence = candidate.profileEvidence
1006
- .slice()
1007
- .sort((left, right) => signalSummaryRank(left) - signalSummaryRank(right))
1008
- .slice(0, 4)
1009
- .map(summarizeSignal);
1010
- return evidence.length > 0
1011
- ? evidence.join(" + ")
1012
- : candidate.reasons.join(", ");
1013
- }
1014
-
1015
- export function formatWhois(result: WhoisResult) {
1016
- const lines = [`Whois: ${result.query}`];
1017
- if (result.candidates.length === 0) {
1018
- lines.push("No matching DM candidates.");
1019
- } else {
1020
- let activeCategory: WhoisCandidateCategory | undefined;
1021
- for (const candidate of result.candidates) {
1022
- const profile = candidate.conversation.participant;
1023
- if (activeCategory !== candidate.category) {
1024
- activeCategory = candidate.category;
1025
- lines.push("");
1026
- lines.push(CATEGORY_LABELS[candidate.category]);
1027
- }
1028
- lines.push("");
1029
- lines.push(
1030
- `${candidate.confidence}% @${profile.handle} (${profile.displayName})`,
1031
- );
1032
- lines.push(`Why: ${explainCandidate(candidate)}`);
1033
- lines.push(`Reasons: ${candidate.reasons.join(", ")}`);
1034
- lines.push(`Conversation: ${candidate.conversation.id}`);
1035
- for (const signal of candidate.profileEvidence.slice(0, 5)) {
1036
- lines.push(`Evidence: ${signal.kind}: ${signal.value}`);
1037
- }
1038
- for (const evidence of candidate.evidence.slice(0, 3)) {
1039
- lines.push(
1040
- `- ${evidence.createdAt} ${evidence.direction}: ${evidence.text}`,
1041
- );
1042
- for (const expansion of evidence.urlExpansions ?? []) {
1043
- lines.push(` ${expansion.url} -> ${expansion.finalUrl}`);
1044
- }
1045
- }
1046
- }
1047
- }
1048
-
1049
- if (result.relatedTweets.length > 0) {
1050
- lines.push("");
1051
- lines.push(`Related tweets: ${result.relatedTweets.length}`);
1052
- for (const tweet of result.relatedTweets.slice(0, 5)) {
1053
- lines.push(`- ${tweet.createdAt} @${tweet.author.handle}: ${tweet.text}`);
1054
- }
1055
- }
1056
-
1057
- return lines.join("\n");
1058
- }
1059
-
1060
- export const __test__ = {
1061
- getSignificantQueryTerms,
1062
- getQueryDomains,
1063
- getQueryHandles,
1064
- getQueryIntent,
1065
- matchesQueryText,
1066
- getDmSearchQueries,
1067
- getUrlEntityExpandedUrl,
1068
- getProfileBioUrls,
1069
- getAffiliationTexts,
1070
- getSnapshotAffiliationTexts,
1071
- getHistoricalSnapshotTexts,
1072
- collectProfileEvidence,
1073
- hasCurrentAffiliationMatch,
1074
- hasAffiliationEvidenceMatch,
1075
- hasNonDomainEvidence,
1076
- scoreCandidate,
1077
- explainCandidate,
1078
- attachExpansionsToMatches,
1079
- mergeConversations,
1080
- };