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
@@ -1,812 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { Effect } from "effect";
3
- import { z } from "zod";
4
- import {
5
- createAnalysisRequestBody,
6
- type HybridAnalysisResult,
7
- parseHybridAnalysis,
8
- resolveAnalysisModelSettings,
9
- streamHybridAnalysisEffect,
10
- } from "./analysis-runtime";
11
- import { prefetchCachedAvatarsForProfileIdsEffect } from "./avatar-cache";
12
- import { runEffectBackground, runEffectPromise } from "./effect-runtime";
13
- import { getNativeDb } from "./db";
14
- import { listDmConversations } from "./dm-read-model";
15
- import {
16
- type OpenAIStreamState,
17
- processOpenAIResponseSseChunk,
18
- } from "./openai-response-runtime";
19
- import { listTimelineItems } from "./timeline-read-model";
20
- import { readSyncCache, writeSyncCache } from "./sync-cache";
21
- import {
22
- syncTweetSearchEffect,
23
- type SyncTweetSearchResult,
24
- type TweetSearchMode,
25
- } from "./tweet-search-live";
26
- import type { ProfileRecord } from "./types";
27
-
28
- export type SearchDiscussionSource =
29
- | "all"
30
- | "home"
31
- | "mentions"
32
- | "authored"
33
- | "search"
34
- | "likes"
35
- | "bookmarks";
36
-
37
- export interface SearchDiscussionOptions {
38
- query: string;
39
- account?: string;
40
- source?: SearchDiscussionSource;
41
- since?: string;
42
- until?: string;
43
- includeDms?: boolean;
44
- originalsOnly?: boolean;
45
- hideLowQuality?: boolean;
46
- question?: string;
47
- mode?: TweetSearchMode;
48
- limit?: number;
49
- maxPages?: number;
50
- refresh?: boolean;
51
- model?: string;
52
- reasoningEffort?: "minimal" | "low" | "medium" | "high";
53
- serviceTier?: "default" | "flex" | "priority";
54
- signal?: AbortSignal;
55
- prefetchAvatars?: boolean;
56
- }
57
-
58
- export interface SearchDiscussionStreamHandlers {
59
- onDelta?: (delta: string) => void;
60
- onEvent?: (event: SearchDiscussionStreamEvent) => void;
61
- }
62
-
63
- interface CompactSearchTweet {
64
- id: string;
65
- url: string;
66
- source: Exclude<SearchDiscussionSource, "all">;
67
- author: string;
68
- name: string;
69
- authorProfile: ProfileRecord;
70
- createdAt: string;
71
- text: string;
72
- likeCount: number;
73
- liked: boolean;
74
- bookmarked: boolean;
75
- needsReply: boolean;
76
- }
77
-
78
- interface CompactSearchDm {
79
- id: string;
80
- participant: string;
81
- name: string;
82
- lastMessageAt: string;
83
- text: string;
84
- needsReply: boolean;
85
- influenceScore: number;
86
- }
87
-
88
- export interface SearchDiscussionContext {
89
- query: string;
90
- question?: string;
91
- account?: string;
92
- source: SearchDiscussionSource;
93
- since?: string;
94
- until?: string;
95
- includeDms: boolean;
96
- counts: Record<Exclude<SearchDiscussionSource, "all"> | "dms", number>;
97
- tweets: CompactSearchTweet[];
98
- dms: CompactSearchDm[];
99
- liveSearch?: SyncTweetSearchResult;
100
- hash: string;
101
- }
102
-
103
- const SearchDiscussionSchema = z.object({
104
- title: z.string().min(1),
105
- summary: z.string().min(1),
106
- themes: z.array(
107
- z.object({
108
- title: z.string().min(1),
109
- summary: z.string().min(1),
110
- tweetIds: z.array(z.string()).default([]),
111
- dmConversationIds: z.array(z.string()).default([]),
112
- handles: z.array(z.string()).default([]),
113
- }),
114
- ),
115
- tensions: z.array(z.string()).default([]),
116
- followUps: z.array(z.string()).default([]),
117
- sourceTweetIds: z.array(z.string()).default([]),
118
- sourceDmConversationIds: z.array(z.string()).default([]),
119
- });
120
-
121
- export type SearchDiscussion = z.infer<typeof SearchDiscussionSchema>;
122
-
123
- export interface SearchDiscussionRunResult {
124
- context: SearchDiscussionContext;
125
- discussion: SearchDiscussion;
126
- markdown: string;
127
- model: string;
128
- reasoningEffort: string;
129
- serviceTier: string;
130
- cached: boolean;
131
- updatedAt: string;
132
- }
133
-
134
- export type SearchDiscussionStreamEvent =
135
- | { type: "start"; context: SearchDiscussionContext; cached: boolean }
136
- | { type: "delta"; delta: string }
137
- | { type: "done"; result: SearchDiscussionRunResult }
138
- | { type: "error"; error: string };
139
-
140
- const DEFAULT_LIMIT = 20_000;
141
- const DEFAULT_MAX_PAGES = 200;
142
- const MAX_PROMPT_DATA_CHARS = 1_200_000;
143
- const DELIMITER_PATTERN = /\n---\s*\n/;
144
-
145
- function toError(error: unknown) {
146
- return error instanceof Error ? error : new Error(String(error));
147
- }
148
-
149
- function trySearchSync<T>(try_: () => T): Effect.Effect<T, Error> {
150
- return Effect.try({
151
- try: try_,
152
- catch: toError,
153
- });
154
- }
155
-
156
- function tweetUrl(handle: string, id: string) {
157
- return `https://x.com/${handle}/status/${id}`;
158
- }
159
-
160
- function sourceList(source: SearchDiscussionSource) {
161
- if (source !== "all") return [source];
162
- return [
163
- "search",
164
- "home",
165
- "mentions",
166
- "authored",
167
- "likes",
168
- "bookmarks",
169
- ] as const;
170
- }
171
-
172
- function compactTweet(
173
- source: Exclude<SearchDiscussionSource, "all">,
174
- item: ReturnType<typeof listTimelineItems>[number],
175
- ): CompactSearchTweet {
176
- return {
177
- id: item.id,
178
- url: tweetUrl(item.author.handle, item.id),
179
- source,
180
- author: item.author.handle,
181
- name: item.author.displayName,
182
- authorProfile: item.author,
183
- createdAt: item.createdAt,
184
- text: item.text,
185
- likeCount: item.likeCount,
186
- liked: item.liked,
187
- bookmarked: item.bookmarked,
188
- needsReply: !item.isReplied,
189
- };
190
- }
191
-
192
- function collectTweetsForSource(
193
- source: Exclude<SearchDiscussionSource, "all">,
194
- options: SearchDiscussionOptions & { limit: number },
195
- ) {
196
- const timelineResource =
197
- source === "likes" || source === "bookmarks" ? "home" : source;
198
- return listTimelineItems({
199
- resource: timelineResource,
200
- account: options.account,
201
- search: options.query,
202
- since: options.since,
203
- until: options.until,
204
- includeReplies: !options.originalsOnly,
205
- qualityFilter: options.hideLowQuality ? "summary" : "all",
206
- likedOnly: source === "likes",
207
- bookmarkedOnly: source === "bookmarks",
208
- limit: options.limit,
209
- }).map((item) => compactTweet(source, item));
210
- }
211
-
212
- function collectLiveSearchTweets(
213
- options: SearchDiscussionOptions & {
214
- limit: number;
215
- liveSearch?: SyncTweetSearchResult;
216
- },
217
- ) {
218
- if (options.source !== "search" || options.liveSearch?.ok !== true) {
219
- return null;
220
- }
221
- if (options.liveSearch.tweetIds.length === 0) return [];
222
- const ids = [...new Set(options.liveSearch.tweetIds)].slice(0, options.limit);
223
- const positionById = new Map(ids.map((id, index) => [id, index]));
224
- const placeholders = ids.map(() => "?").join(",");
225
- const accountId = options.liveSearch.accountId;
226
- const rows = getNativeDb({ seedDemoData: false })
227
- .prepare(`
228
- select
229
- t.id,
230
- t.text,
231
- t.created_at,
232
- t.is_replied,
233
- t.like_count,
234
- t.media_count,
235
- case
236
- when exists (
237
- select 1 from tweet_collections collection
238
- where collection.account_id = ?
239
- and collection.tweet_id = t.id
240
- and collection.kind = 'bookmarks'
241
- ) then 1
242
- when t.account_id = ? and t.bookmarked = 1 then 1
243
- else 0
244
- end as bookmarked,
245
- case
246
- when exists (
247
- select 1 from tweet_collections collection
248
- where collection.account_id = ?
249
- and collection.tweet_id = t.id
250
- and collection.kind = 'likes'
251
- ) then 1
252
- when t.account_id = ? and t.liked = 1 then 1
253
- else 0
254
- end as liked,
255
- p.id as profile_id,
256
- p.handle,
257
- p.display_name,
258
- p.bio,
259
- p.followers_count,
260
- p.following_count,
261
- p.avatar_hue,
262
- p.avatar_url,
263
- p.created_at as profile_created_at
264
- from tweets t
265
- join profiles p on p.id = t.author_profile_id
266
- where t.id in (${placeholders})
267
- `)
268
- .all(accountId, accountId, accountId, accountId, ...ids) as Array<
269
- Record<string, unknown>
270
- >;
271
-
272
- return rows
273
- .sort(
274
- (left, right) =>
275
- (positionById.get(String(left.id)) ?? Number.MAX_SAFE_INTEGER) -
276
- (positionById.get(String(right.id)) ?? Number.MAX_SAFE_INTEGER),
277
- )
278
- .filter((row) => liveSearchRowPassesFilters(row, options))
279
- .map(
280
- (row): CompactSearchTweet => ({
281
- id: String(row.id),
282
- url: tweetUrl(String(row.handle), String(row.id)),
283
- source: "search",
284
- author: String(row.handle),
285
- name: String(row.display_name),
286
- authorProfile: {
287
- id: String(row.profile_id),
288
- handle: String(row.handle),
289
- displayName: String(row.display_name),
290
- bio: String(row.bio),
291
- followersCount: Number(row.followers_count),
292
- followingCount: Number(row.following_count ?? 0),
293
- avatarHue: Number(row.avatar_hue),
294
- avatarUrl:
295
- typeof row.avatar_url === "string"
296
- ? String(row.avatar_url)
297
- : undefined,
298
- createdAt: String(row.profile_created_at),
299
- },
300
- createdAt: String(row.created_at),
301
- text: String(row.text),
302
- likeCount: Number(row.like_count),
303
- liked: Boolean(row.liked),
304
- bookmarked: Boolean(row.bookmarked),
305
- needsReply: !row.is_replied,
306
- }),
307
- );
308
- }
309
-
310
- function liveSearchRowPassesFilters(
311
- row: Record<string, unknown>,
312
- options: SearchDiscussionOptions,
313
- ) {
314
- const text = String(row.text);
315
- const createdAt = String(row.created_at);
316
- if (options.originalsOnly && text.startsWith("@")) return false;
317
- if (options.since?.trim() && createdAt < options.since.trim()) return false;
318
- if (options.until?.trim() && createdAt >= options.until.trim()) return false;
319
- if (!options.hideLowQuality) return true;
320
-
321
- const trimmed = text.trim();
322
- const strippedShortUrlText = text.replaceAll("https://t.co/", "").trim();
323
- const likeCount = Number(row.like_count);
324
- const mediaCount = Number(row.media_count);
325
- return !(
326
- text.startsWith("RT @") ||
327
- (likeCount < 50 &&
328
- ((strippedShortUrlText.length < 16 && mediaCount === 0) ||
329
- (text.startsWith("@") && trimmed.length < 60) ||
330
- (text.includes("https://t.co/") &&
331
- mediaCount === 0 &&
332
- strippedShortUrlText.length < 45)))
333
- );
334
- }
335
-
336
- function collectDms(options: SearchDiscussionOptions & { limit: number }) {
337
- if (!options.includeDms) return [];
338
- return listDmConversations({
339
- account: options.account,
340
- search: options.query,
341
- since: options.since,
342
- until: options.until,
343
- sort: "recent",
344
- context: 2,
345
- limit: Math.max(1, Math.ceil(options.limit / 2)),
346
- }).map((item): CompactSearchDm => {
347
- const matchText = item.matches
348
- ?.flatMap((match) => [
349
- ...match.before.map((message) => message.text),
350
- match.message.text,
351
- ...match.after.map((message) => message.text),
352
- ])
353
- .join("\n");
354
- return {
355
- id: item.id,
356
- participant: item.participant.handle,
357
- name: item.participant.displayName,
358
- lastMessageAt: item.lastMessageAt,
359
- text: matchText || item.lastMessagePreview,
360
- needsReply: item.needsReply,
361
- influenceScore: item.influenceScore,
362
- };
363
- });
364
- }
365
-
366
- function dedupeTweets(tweets: CompactSearchTweet[]) {
367
- const seen = new Set<string>();
368
- const items: CompactSearchTweet[] = [];
369
- for (const tweet of tweets) {
370
- if (seen.has(tweet.id)) continue;
371
- seen.add(tweet.id);
372
- items.push(tweet);
373
- }
374
- return items.sort((left, right) =>
375
- right.createdAt.localeCompare(left.createdAt),
376
- );
377
- }
378
-
379
- function contextHash(context: Omit<SearchDiscussionContext, "hash">) {
380
- const liveSearch =
381
- context.liveSearch?.ok === true
382
- ? {
383
- ok: true,
384
- accountId: context.liveSearch.accountId,
385
- query: context.liveSearch.query,
386
- count: context.liveSearch.count,
387
- pageCount: context.liveSearch.pageCount,
388
- tweetIds: context.liveSearch.tweetIds,
389
- }
390
- : context.liveSearch;
391
- return createHash("sha1")
392
- .update(
393
- JSON.stringify({
394
- query: context.query,
395
- question: context.question,
396
- account: context.account,
397
- source: context.source,
398
- since: context.since,
399
- until: context.until,
400
- includeDms: context.includeDms,
401
- tweets: context.tweets.map((tweet) => [
402
- tweet.id,
403
- tweet.source,
404
- tweet.author,
405
- tweet.name,
406
- tweet.authorProfile.bio,
407
- tweet.authorProfile.followersCount,
408
- tweet.createdAt,
409
- tweet.text,
410
- tweet.likeCount,
411
- tweet.liked,
412
- tweet.bookmarked,
413
- tweet.needsReply,
414
- ]),
415
- dms: context.dms.map((dm) => [
416
- dm.id,
417
- dm.lastMessageAt,
418
- dm.text,
419
- dm.needsReply,
420
- dm.influenceScore,
421
- ]),
422
- liveSearch,
423
- }),
424
- )
425
- .digest("hex");
426
- }
427
-
428
- export function collectSearchDiscussionContext(
429
- options: SearchDiscussionOptions & { liveSearch?: SyncTweetSearchResult },
430
- ): SearchDiscussionContext {
431
- const query = options.query.trim();
432
- if (!query) {
433
- throw new Error("Search query is required");
434
- }
435
- const limit = Math.max(1, Math.trunc(options.limit ?? DEFAULT_LIMIT));
436
- const source = options.source ?? "all";
437
- const counts = {
438
- home: 0,
439
- mentions: 0,
440
- authored: 0,
441
- search: 0,
442
- likes: 0,
443
- bookmarks: 0,
444
- dms: 0,
445
- };
446
- const liveSearchTweets = collectLiveSearchTweets({
447
- ...options,
448
- query,
449
- source,
450
- limit,
451
- });
452
- const tweets =
453
- liveSearchTweets ??
454
- sourceList(source).flatMap((item) => {
455
- const sourceTweets = collectTweetsForSource(item, {
456
- ...options,
457
- query,
458
- source,
459
- limit,
460
- });
461
- counts[item] = sourceTweets.length;
462
- return sourceTweets;
463
- });
464
- if (liveSearchTweets) {
465
- counts.search = liveSearchTweets.length;
466
- }
467
- const dms = collectDms({ ...options, query, source, limit });
468
- counts.dms = dms.length;
469
- const limitedTweets = dedupeTweets(tweets).slice(0, limit);
470
- const withoutHash = {
471
- query,
472
- ...(options.question?.trim() ? { question: options.question.trim() } : {}),
473
- ...(options.account ? { account: options.account } : {}),
474
- source,
475
- ...(options.since ? { since: options.since } : {}),
476
- ...(options.until ? { until: options.until } : {}),
477
- includeDms: Boolean(options.includeDms),
478
- counts,
479
- tweets: limitedTweets,
480
- dms,
481
- ...(options.liveSearch ? { liveSearch: options.liveSearch } : {}),
482
- } satisfies Omit<SearchDiscussionContext, "hash">;
483
- return {
484
- ...withoutHash,
485
- hash: contextHash(withoutHash),
486
- };
487
- }
488
-
489
- function prefetchDiscussionAvatars(context: SearchDiscussionContext) {
490
- const profileIds = context.tweets
491
- .filter((tweet) => tweet.authorProfile.avatarUrl)
492
- .map((tweet) => tweet.authorProfile.id);
493
- if (profileIds.length === 0) {
494
- return;
495
- }
496
- runEffectBackground(
497
- prefetchCachedAvatarsForProfileIdsEffect(profileIds).pipe(
498
- Effect.catchAll(() =>
499
- Effect.succeed({
500
- requested: 0,
501
- available: 0,
502
- missing: 0,
503
- failed: 0,
504
- }),
505
- ),
506
- ),
507
- {
508
- onSuccess: () => {},
509
- onFailure: () => {},
510
- },
511
- );
512
- }
513
-
514
- function modelFromOptions(options: SearchDiscussionOptions) {
515
- return resolveAnalysisModelSettings(options).model;
516
- }
517
-
518
- function reasoningEffortFromOptions(options: SearchDiscussionOptions) {
519
- return resolveAnalysisModelSettings(options).reasoningEffort;
520
- }
521
-
522
- function serviceTierFromOptions(options: SearchDiscussionOptions) {
523
- return resolveAnalysisModelSettings(options).serviceTier;
524
- }
525
-
526
- function cacheKey(
527
- context: SearchDiscussionContext,
528
- options: SearchDiscussionOptions,
529
- ) {
530
- return [
531
- "search-discussion:v1",
532
- modelFromOptions(options),
533
- reasoningEffortFromOptions(options),
534
- serviceTierFromOptions(options),
535
- context.hash,
536
- ].join(":");
537
- }
538
-
539
- function buildPrompt(context: SearchDiscussionContext) {
540
- const promptTweets = context.tweets.map((tweet) => ({
541
- id: tweet.id,
542
- url: tweet.url,
543
- source: tweet.source,
544
- author: tweet.author,
545
- name: tweet.name,
546
- bio: tweet.authorProfile.bio,
547
- followersCount: tweet.authorProfile.followersCount,
548
- createdAt: tweet.createdAt,
549
- text: tweet.text,
550
- likeCount: tweet.likeCount,
551
- liked: tweet.liked,
552
- bookmarked: tweet.bookmarked,
553
- needsReply: tweet.needsReply,
554
- }));
555
- const fitDataset = () => {
556
- let tweetCount = promptTweets.length;
557
- let dmCount = context.dms.length;
558
- const datasetFor = (tweets: number, dms: number) => ({
559
- tweets: promptTweets.slice(0, tweets),
560
- dms: context.dms.slice(0, dms),
561
- });
562
- const lengthFor = (tweets: number, dms: number) =>
563
- JSON.stringify(datasetFor(tweets, dms)).length;
564
- const fitCount = (max: number, fits: (count: number) => boolean) => {
565
- let low = 0;
566
- let high = max;
567
- let best = 0;
568
- while (low <= high) {
569
- const mid = Math.floor((low + high) / 2);
570
- if (fits(mid)) {
571
- best = mid;
572
- low = mid + 1;
573
- } else {
574
- high = mid - 1;
575
- }
576
- }
577
- return best;
578
- };
579
- if (lengthFor(tweetCount, dmCount) <= MAX_PROMPT_DATA_CHARS) {
580
- return { dataset: datasetFor(tweetCount, dmCount), tweetCount };
581
- }
582
- dmCount = fitCount(
583
- dmCount,
584
- (count) => lengthFor(tweetCount, count) <= MAX_PROMPT_DATA_CHARS,
585
- );
586
- if (lengthFor(tweetCount, dmCount) > MAX_PROMPT_DATA_CHARS) {
587
- tweetCount = fitCount(
588
- tweetCount,
589
- (count) => lengthFor(count, dmCount) <= MAX_PROMPT_DATA_CHARS,
590
- );
591
- }
592
- return { dataset: datasetFor(tweetCount, dmCount), tweetCount };
593
- };
594
- const { dataset, tweetCount } = fitDataset();
595
-
596
- return `Search query: ${context.query}
597
- ${context.question ? `Discussion question: ${context.question}\n` : ""}Account: ${context.account ?? "all"}
598
- Source: ${context.source}
599
- Live search: ${context.liveSearch ? JSON.stringify(context.liveSearch) : "not run"}
600
- Since: ${context.since ?? "(none)"}
601
- Until: ${context.until ?? "(none)"}
602
- Counts: ${JSON.stringify(context.counts)}
603
- Prompt tweets: ${String(tweetCount)} of ${String(context.tweets.length)} selected context tweets
604
-
605
- Write a high-signal Markdown discussion from this local Twitter/X search result set.
606
-
607
- Requirements:
608
- - Start with a concise summary of what the matching posts are really about.
609
- - Then write sections named "Themes", "Discussion", and "Follow-ups".
610
- - Use bullets when grouping multiple points.
611
- - Compare agreement, disagreement, shifts over time, and recurring people or links when visible.
612
- - Cite claims with tweet ids or DM conversation ids at the end of the sentence, e.g. (tweet_123) or (dm_456).
613
- - DMs are private context and only present when explicitly included; do not quote private text at length.
614
- - If there is no data, say that plainly in one short paragraph.
615
- - After the Markdown, output a blank line, then a line containing only three hyphens, then one compact JSON object.
616
- - Put every cited tweet id in sourceTweetIds and every cited DM conversation id in sourceDmConversationIds.
617
- - JSON shape: { "title": string, "summary": string, "themes": [{ "title": string, "summary": string, "tweetIds": string[], "dmConversationIds": string[], "handles": string[] }], "tensions": string[], "followUps": string[], "sourceTweetIds": string[], "sourceDmConversationIds": string[] }
618
-
619
- Dataset:
620
- ${JSON.stringify(dataset)}`;
621
- }
622
-
623
- function fallbackDiscussion(
624
- context: SearchDiscussionContext,
625
- markdown: string,
626
- ): SearchDiscussion {
627
- return {
628
- title: `Search discussion: ${context.query}`,
629
- summary:
630
- markdown.replaceAll(/\s+/g, " ").trim().slice(0, 280) ||
631
- "No model summary was returned.",
632
- themes: [],
633
- tensions: [],
634
- followUps: [],
635
- sourceTweetIds: context.tweets.slice(0, 20).map((tweet) => tweet.id),
636
- sourceDmConversationIds: context.dms.slice(0, 20).map((dm) => dm.id),
637
- };
638
- }
639
-
640
- function parseDiscussionFromHybridText(
641
- context: SearchDiscussionContext,
642
- rawText: string,
643
- ): { discussion: SearchDiscussion; markdown: string } {
644
- const parsed = parseHybridAnalysis({
645
- rawText,
646
- parse: (value) => SearchDiscussionSchema.parse(value),
647
- fallback: (markdown) => fallbackDiscussion(context, markdown),
648
- delimiterPattern: DELIMITER_PATTERN,
649
- });
650
- return { markdown: parsed.markdown, discussion: parsed.value };
651
- }
652
-
653
- function processSseChunk(
654
- state: OpenAIStreamState,
655
- chunk: string,
656
- handlers: SearchDiscussionStreamHandlers,
657
- ) {
658
- processOpenAIResponseSseChunk(state, chunk, {
659
- delimiterPattern: DELIMITER_PATTERN,
660
- onDelta: (delta) => {
661
- handlers.onDelta?.(delta);
662
- handlers.onEvent?.({ type: "delta", delta });
663
- },
664
- });
665
- }
666
-
667
- function createOpenAIRequestBody(
668
- context: SearchDiscussionContext,
669
- options: SearchDiscussionOptions,
670
- ) {
671
- return createAnalysisRequestBody({
672
- settings: resolveAnalysisModelSettings(options),
673
- system:
674
- "You are a precise local Twitter archive analyst. Stream Markdown first, then emit the requested JSON object after the delimiter. Do not invent events not present in the dataset.",
675
- prompt: buildPrompt(context),
676
- stream: true,
677
- });
678
- }
679
-
680
- function completeOpenAIStreamEffect(
681
- stream: HybridAnalysisResult<SearchDiscussion>,
682
- context: SearchDiscussionContext,
683
- options: SearchDiscussionOptions,
684
- handlers: SearchDiscussionStreamHandlers,
685
- ): Effect.Effect<SearchDiscussionRunResult, Error> {
686
- return Effect.gen(function* () {
687
- const updatedAt = yield* trySearchSync(() =>
688
- writeSyncCache(cacheKey(context, options), {
689
- discussion: stream.value,
690
- markdown: stream.markdown,
691
- model: modelFromOptions(options),
692
- reasoningEffort: reasoningEffortFromOptions(options),
693
- serviceTier: serviceTierFromOptions(options),
694
- usage: stream.usage,
695
- responseId: stream.responseId,
696
- }),
697
- );
698
- const result = {
699
- context,
700
- discussion: stream.value,
701
- markdown: stream.markdown,
702
- model: modelFromOptions(options),
703
- reasoningEffort: reasoningEffortFromOptions(options),
704
- serviceTier: serviceTierFromOptions(options),
705
- cached: false,
706
- updatedAt,
707
- };
708
- handlers.onEvent?.({ type: "done", result });
709
- return result;
710
- });
711
- }
712
-
713
- export function streamSearchDiscussionEffect(
714
- options: SearchDiscussionOptions,
715
- handlers: SearchDiscussionStreamHandlers = {},
716
- ): Effect.Effect<SearchDiscussionRunResult, Error> {
717
- return Effect.gen(function* () {
718
- const mode = options.mode ?? "auto";
719
- const liveSearch =
720
- mode === "local"
721
- ? undefined
722
- : yield* syncTweetSearchEffect({
723
- query: options.query,
724
- account: options.account,
725
- mode,
726
- limit: options.limit ?? DEFAULT_LIMIT,
727
- maxPages: options.maxPages ?? DEFAULT_MAX_PAGES,
728
- since: options.since,
729
- until: options.until,
730
- refresh: options.refresh,
731
- timeoutMs: 30_000,
732
- });
733
- if (liveSearch && !liveSearch.ok) {
734
- return yield* Effect.fail(
735
- new Error(
736
- `Live tweet search failed via ${liveSearch.source}: ${liveSearch.error}`,
737
- ),
738
- );
739
- }
740
- const context = yield* trySearchSync(() =>
741
- collectSearchDiscussionContext({
742
- ...options,
743
- source: options.source ?? "search",
744
- liveSearch,
745
- }),
746
- );
747
- if (options.prefetchAvatars) {
748
- prefetchDiscussionAvatars(context);
749
- }
750
- const cached = options.refresh
751
- ? null
752
- : yield* trySearchSync(() =>
753
- readSyncCache<{
754
- discussion: SearchDiscussion;
755
- markdown: string;
756
- model: string;
757
- reasoningEffort: string;
758
- serviceTier: string;
759
- }>(cacheKey(context, options)),
760
- );
761
- if (cached) {
762
- const result: SearchDiscussionRunResult = yield* trySearchSync(() => ({
763
- context,
764
- discussion: SearchDiscussionSchema.parse(cached.value.discussion),
765
- markdown: cached.value.markdown,
766
- model: cached.value.model,
767
- reasoningEffort: cached.value.reasoningEffort,
768
- serviceTier: cached.value.serviceTier,
769
- cached: true,
770
- updatedAt: cached.updatedAt,
771
- }));
772
- handlers.onEvent?.({ type: "start", context, cached: true });
773
- handlers.onDelta?.(result.markdown);
774
- handlers.onEvent?.({ type: "delta", delta: result.markdown });
775
- handlers.onEvent?.({ type: "done", result });
776
- return result;
777
- }
778
-
779
- handlers.onEvent?.({ type: "start", context, cached: false });
780
- const stream = yield* streamHybridAnalysisEffect({
781
- body: createOpenAIRequestBody(context, options),
782
- signal: options.signal,
783
- parse: (value) => SearchDiscussionSchema.parse(value),
784
- fallback: (markdown) => fallbackDiscussion(context, markdown),
785
- delimiterPattern: DELIMITER_PATTERN,
786
- onDelta: (delta) => {
787
- handlers.onDelta?.(delta);
788
- handlers.onEvent?.({ type: "delta", delta });
789
- },
790
- });
791
- return yield* completeOpenAIStreamEffect(
792
- stream,
793
- context,
794
- options,
795
- handlers,
796
- );
797
- });
798
- }
799
-
800
- export function streamSearchDiscussion(
801
- options: SearchDiscussionOptions,
802
- handlers: SearchDiscussionStreamHandlers = {},
803
- ): Promise<SearchDiscussionRunResult> {
804
- return runEffectPromise(streamSearchDiscussionEffect(options, handlers));
805
- }
806
-
807
- export const __test__ = {
808
- SearchDiscussionSchema,
809
- buildPrompt,
810
- parseDiscussionFromHybridText,
811
- processSseChunk,
812
- };