birdclaw 0.8.2 → 0.8.4

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 (247) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +10 -8
  3. package/bin/birdclaw.mjs +4 -66
  4. package/dist/cli/birdclaw.js +28165 -0
  5. package/dist/client/assets/AvatarChip-DLoqM5xD.js +1 -0
  6. package/dist/client/assets/ProfilePreview-BejAuYsJ.js +1 -0
  7. package/dist/client/assets/SavedTimelineView-BIS7HKpp.js +1 -0
  8. package/dist/client/assets/SmartTimestamp-BR0-9se2.js +1 -0
  9. package/dist/client/assets/TimelineRouteFrame-CyGPj0eM.js +1 -0
  10. package/dist/client/assets/blocks-7UDKQp8H.js +1 -0
  11. package/dist/client/assets/bookmarks-CbBkMvXk.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-ys3XhWG4.js +5 -0
  15. package/dist/client/assets/createLucideIcon-JV8isFFR.js +1 -0
  16. package/dist/client/assets/data-sources-Cm2bpNvg.js +1 -0
  17. package/dist/client/assets/discuss-DTjaOugw.js +1 -0
  18. package/dist/client/assets/dms-CGd6Eogq.js +1 -0
  19. package/dist/client/assets/inbox-BHlGuOy2.js +1 -0
  20. package/dist/client/assets/index-CEIG7S6s.js +31 -0
  21. package/dist/client/assets/index-bpFrQ5yG.css +1 -0
  22. package/dist/client/assets/likes-cLrcAQem.js +1 -0
  23. package/dist/client/assets/links-CM9QO1LC.js +1 -0
  24. package/dist/client/assets/mapbox-BxTlqXt9.js +2 -0
  25. package/dist/client/assets/mapbox-gl-dgf_hX3a.js +3215 -0
  26. package/dist/client/assets/mentions-CxKCgzIf.js +1 -0
  27. package/dist/client/assets/network-map-B5a3whqj.js +2 -0
  28. package/dist/client/assets/profile-analyze-CRtNEwlb.js +1 -0
  29. package/dist/client/assets/profile-hydration-client-YEtJsNTv.js +1 -0
  30. package/dist/client/assets/profiles._handle-C82_HoKX.js +1 -0
  31. package/dist/client/assets/query-client-fYu2rzRC.js +17 -0
  32. package/dist/client/assets/rate-limits-ScaEwdVK.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-q7ZaW4En.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-CeG1O7Py.js +1 -0
  42. package/dist/client/assets/triangle-alert-CBL7s2pf.js +1 -0
  43. package/dist/client/assets/useTimelineRouteData-1HsqgvUi.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-BFvhVdhn.js +198 -0
  48. package/dist/server/assets/ProfilePreview-C6gAor_j.js +752 -0
  49. package/dist/server/assets/SavedTimelineView-BG1jnBp1.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-CU7ilM7U.js +85 -0
  53. package/dist/server/assets/TweetRichText-DhCVv1-6.js +74 -0
  54. package/dist/server/assets/_tanstack-start-manifest_v-C-ZRnG_n.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-BJN8tykY.js +14 -0
  59. package/dist/server/assets/client-stream-contracts-C2xbWVjm.js +769 -0
  60. package/dist/server/assets/data-sources-BnA1Q94p.js +180 -0
  61. package/dist/server/assets/discuss-CJ1dau1j.js +15 -0
  62. package/dist/server/assets/discuss-QTo08NCN.js +338 -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-DBOAtsJU.js +14 -0
  69. package/dist/server/assets/links-DAhSjynu.js +240 -0
  70. package/dist/server/assets/links-DmH5lxHO.js +468 -0
  71. package/dist/server/assets/mentions-BH2MzKtB.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-BP65PED0.js +90 -0
  75. package/dist/server/assets/profile-analyze-C1NoM0tV.js +9 -0
  76. package/dist/server/assets/profile-hydration-client-GJ4kwJS8.js +133 -0
  77. package/dist/server/assets/profiles._handle-DjwlN_ac.js +184 -0
  78. package/dist/server/assets/profiles._handle-DsLNj2Ca.js +12 -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-DqkwSPiM.js +17026 -0
  83. package/dist/server/assets/routes-A9c9ZhwN.js +26 -0
  84. package/dist/server/assets/start-FaDOTmto.js +4 -0
  85. package/dist/server/assets/today-B5hVM57Z.js +17 -0
  86. package/dist/server/assets/today-fvGiZ7ud.js +303 -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-27cxynxa.js +1101 -0
  90. package/dist/server/server.js +5520 -0
  91. package/package.json +27 -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-moderation.ts +0 -210
  100. package/src/cli.ts +0 -2336
  101. package/src/components/AccountSwitcher.tsx +0 -186
  102. package/src/components/AppNav.tsx +0 -118
  103. package/src/components/AvatarChip.tsx +0 -58
  104. package/src/components/BrandMark.tsx +0 -67
  105. package/src/components/ConversationThread.tsx +0 -131
  106. package/src/components/DmWorkspace.tsx +0 -286
  107. package/src/components/EmbeddedTweetCard.tsx +0 -55
  108. package/src/components/FeedState.tsx +0 -147
  109. package/src/components/FloatingPreview.tsx +0 -382
  110. package/src/components/InboxCard.tsx +0 -152
  111. package/src/components/LinkPreviewCard.tsx +0 -292
  112. package/src/components/MarkdownViewer.tsx +0 -777
  113. package/src/components/ProfileAnalysisStream.tsx +0 -428
  114. package/src/components/ProfilePreview.tsx +0 -129
  115. package/src/components/SavedTimelineView.tsx +0 -155
  116. package/src/components/SmartTimestamp.tsx +0 -72
  117. package/src/components/SyncNowButton.tsx +0 -140
  118. package/src/components/ThemeSlider.tsx +0 -80
  119. package/src/components/TimelineCard.tsx +0 -533
  120. package/src/components/TimelineRouteFrame.tsx +0 -186
  121. package/src/components/TweetArticleCard.tsx +0 -66
  122. package/src/components/TweetMediaGrid.tsx +0 -185
  123. package/src/components/TweetRichText.tsx +0 -159
  124. package/src/components/account-selection.ts +0 -64
  125. package/src/components/useTimelineRouteData.ts +0 -323
  126. package/src/lib/account-sync-job.ts +0 -666
  127. package/src/lib/actions-transport.ts +0 -300
  128. package/src/lib/api-client.ts +0 -419
  129. package/src/lib/archive-finder.ts +0 -185
  130. package/src/lib/archive-import.ts +0 -2764
  131. package/src/lib/authored-live.ts +0 -1072
  132. package/src/lib/avatar-cache.ts +0 -349
  133. package/src/lib/backup.ts +0 -2741
  134. package/src/lib/bird-actions.ts +0 -294
  135. package/src/lib/bird-command.ts +0 -130
  136. package/src/lib/bird.ts +0 -1140
  137. package/src/lib/blocklist.ts +0 -136
  138. package/src/lib/blocks-write.ts +0 -167
  139. package/src/lib/blocks.ts +0 -389
  140. package/src/lib/bookmark-sync-job.ts +0 -536
  141. package/src/lib/client-cache.ts +0 -109
  142. package/src/lib/config.ts +0 -224
  143. package/src/lib/conversation-surface.ts +0 -205
  144. package/src/lib/data-sources.ts +0 -219
  145. package/src/lib/db.ts +0 -1135
  146. package/src/lib/dms-live.ts +0 -933
  147. package/src/lib/effect-runtime.ts +0 -45
  148. package/src/lib/follow-graph.ts +0 -1097
  149. package/src/lib/geocoding.ts +0 -296
  150. package/src/lib/http-effect.ts +0 -222
  151. package/src/lib/identity-search-index.ts +0 -369
  152. package/src/lib/inbox.ts +0 -241
  153. package/src/lib/link-index.ts +0 -641
  154. package/src/lib/link-insights.ts +0 -860
  155. package/src/lib/link-preview-metadata.ts +0 -754
  156. package/src/lib/location.ts +0 -137
  157. package/src/lib/media-fetch.ts +0 -860
  158. package/src/lib/media-includes.ts +0 -165
  159. package/src/lib/mention-threads-live.ts +0 -917
  160. package/src/lib/mentions-export.ts +0 -147
  161. package/src/lib/mentions-live.ts +0 -1238
  162. package/src/lib/moderation-target.ts +0 -216
  163. package/src/lib/moderation-write.ts +0 -131
  164. package/src/lib/mutes-write.ts +0 -167
  165. package/src/lib/mutes.ts +0 -84
  166. package/src/lib/ndjson-stream.ts +0 -106
  167. package/src/lib/network-map.ts +0 -382
  168. package/src/lib/openai.ts +0 -117
  169. package/src/lib/period-digest.ts +0 -1552
  170. package/src/lib/present.ts +0 -118
  171. package/src/lib/profile-affiliation-hydration.ts +0 -228
  172. package/src/lib/profile-affiliations.ts +0 -262
  173. package/src/lib/profile-analysis.ts +0 -1272
  174. package/src/lib/profile-bio-entities.ts +0 -318
  175. package/src/lib/profile-history.ts +0 -164
  176. package/src/lib/profile-hydration.ts +0 -180
  177. package/src/lib/profile-replies.ts +0 -77
  178. package/src/lib/profile-resolver.ts +0 -650
  179. package/src/lib/queries.ts +0 -2381
  180. package/src/lib/research.ts +0 -652
  181. package/src/lib/search-discussion.ts +0 -1016
  182. package/src/lib/seed.ts +0 -613
  183. package/src/lib/sqlite.ts +0 -147
  184. package/src/lib/sync-cache.ts +0 -65
  185. package/src/lib/theme-transition.ts +0 -113
  186. package/src/lib/theme.tsx +0 -165
  187. package/src/lib/timeline-collections-live.ts +0 -581
  188. package/src/lib/timeline-live.ts +0 -452
  189. package/src/lib/tweet-account-edges.ts +0 -48
  190. package/src/lib/tweet-lookup.ts +0 -46
  191. package/src/lib/tweet-render.ts +0 -430
  192. package/src/lib/tweet-search-live.ts +0 -566
  193. package/src/lib/types.ts +0 -723
  194. package/src/lib/ui.ts +0 -529
  195. package/src/lib/url-expansion-store.ts +0 -110
  196. package/src/lib/url-expansion.ts +0 -343
  197. package/src/lib/url-safety.ts +0 -220
  198. package/src/lib/web-sync.ts +0 -516
  199. package/src/lib/whois.ts +0 -1079
  200. package/src/lib/x-profile.ts +0 -365
  201. package/src/lib/x-web.ts +0 -199
  202. package/src/lib/xurl-rate-limits.ts +0 -267
  203. package/src/lib/xurl.ts +0 -1677
  204. package/src/routeTree.gen.ts +0 -723
  205. package/src/router.tsx +0 -20
  206. package/src/routes/__root.tsx +0 -79
  207. package/src/routes/api/action.tsx +0 -147
  208. package/src/routes/api/avatar.tsx +0 -50
  209. package/src/routes/api/blocks.tsx +0 -35
  210. package/src/routes/api/conversation.tsx +0 -45
  211. package/src/routes/api/data-sources.tsx +0 -24
  212. package/src/routes/api/inbox.tsx +0 -43
  213. package/src/routes/api/link-insights.tsx +0 -85
  214. package/src/routes/api/link-preview.tsx +0 -47
  215. package/src/routes/api/network-map.tsx +0 -55
  216. package/src/routes/api/period-digest.tsx +0 -101
  217. package/src/routes/api/profile-analysis.tsx +0 -97
  218. package/src/routes/api/profile-hydrate.tsx +0 -54
  219. package/src/routes/api/query.tsx +0 -115
  220. package/src/routes/api/search-discussion.tsx +0 -113
  221. package/src/routes/api/status.tsx +0 -28
  222. package/src/routes/api/sync.tsx +0 -105
  223. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  224. package/src/routes/blocks.tsx +0 -377
  225. package/src/routes/bookmarks.tsx +0 -18
  226. package/src/routes/data-sources.tsx +0 -257
  227. package/src/routes/discuss.tsx +0 -419
  228. package/src/routes/dms.tsx +0 -432
  229. package/src/routes/inbox.tsx +0 -226
  230. package/src/routes/index.tsx +0 -32
  231. package/src/routes/likes.tsx +0 -18
  232. package/src/routes/links.tsx +0 -994
  233. package/src/routes/mentions.tsx +0 -32
  234. package/src/routes/network-map.tsx +0 -1035
  235. package/src/routes/profile-analyze.tsx +0 -112
  236. package/src/routes/profiles.$handle.tsx +0 -228
  237. package/src/routes/rate-limits.tsx +0 -309
  238. package/src/routes/today.tsx +0 -511
  239. package/src/styles.css +0 -257
  240. package/tsconfig.json +0 -29
  241. package/vite.config.ts +0 -29
  242. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  243. /package/{public → dist/client}/favicon.ico +0 -0
  244. /package/{public → dist/client}/logo192.png +0 -0
  245. /package/{public → dist/client}/logo512.png +0 -0
  246. /package/{public → dist/client}/manifest.json +0 -0
  247. /package/{public → dist/client}/robots.txt +0 -0
@@ -1,1272 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { Effect } from "effect";
3
- import { z } from "zod";
4
- import { getNativeDb } from "./db";
5
- import { runEffectPromise, tryPromise } from "./effect-runtime";
6
- import { buildMediaJsonFromIncludes, countTweetMedia } from "./media-includes";
7
- import type { Database } from "./sqlite";
8
- import { readSyncCache, writeSyncCache } from "./sync-cache";
9
- import { tweetEntitiesFromXurl } from "./tweet-render";
10
- import type {
11
- ProfileRecord,
12
- TweetEntities,
13
- XurlMediaItem,
14
- XurlMentionUser,
15
- XurlTweetData,
16
- XurlTweetsResponse,
17
- XurlUserTweet,
18
- XurlUserTweetsResponse,
19
- } from "./types";
20
- import {
21
- type TweetAccountEdgeKind,
22
- upsertTweetAccountEdge,
23
- } from "./tweet-account-edges";
24
- import { buildExternalProfileId, upsertProfileFromXUser } from "./x-profile";
25
- import { recordXurlRateLimitEventSafe } from "./xurl-rate-limits";
26
- import type { XurlJsonCommandAttempt } from "./xurl";
27
- import {
28
- listUserTweetsEffect,
29
- lookupUsersByHandlesEffect,
30
- searchRecentByConversationIdEffect,
31
- } from "./xurl";
32
-
33
- export interface ProfileAnalysisOptions {
34
- handle: string;
35
- account?: string;
36
- refresh?: boolean;
37
- maxTweets?: number;
38
- maxPages?: number;
39
- maxConversations?: number;
40
- maxConversationPages?: number;
41
- conversationDelayMs?: number;
42
- rateLimitRetryMs?: number;
43
- rateLimitMaxRetries?: number;
44
- cacheTtlMs?: number;
45
- model?: string;
46
- reasoningEffort?: "minimal" | "low" | "medium" | "high";
47
- serviceTier?: "default" | "flex" | "priority";
48
- signal?: AbortSignal;
49
- }
50
-
51
- export interface ProfileAnalysisStreamHandlers {
52
- onDelta?: (delta: string) => void;
53
- onEvent?: (event: ProfileAnalysisStreamEvent) => void;
54
- }
55
-
56
- export interface CompactProfileTweet {
57
- id: string;
58
- url: string;
59
- author: string;
60
- createdAt: string;
61
- text: string;
62
- entities?: TweetEntities;
63
- conversationId?: string;
64
- replyToId?: string;
65
- likeCount: number;
66
- replyCount: number;
67
- retweetCount: number;
68
- quoteCount: number;
69
- bookmarkedCount: number;
70
- }
71
-
72
- export interface CompactConversationTweet extends CompactProfileTweet {
73
- conversationRootId: string;
74
- profileId: string;
75
- name: string;
76
- bio: string;
77
- followersCount: number;
78
- avatarUrl?: string;
79
- }
80
-
81
- export interface ProfileAnalysisContext {
82
- handle: string;
83
- accountId: string;
84
- accountHandle: string;
85
- profile: ProfileRecord;
86
- profiles?: ProfileRecord[];
87
- externalUserId: string;
88
- tweets: CompactProfileTweet[];
89
- conversations: CompactConversationTweet[];
90
- counts: {
91
- tweets: number;
92
- tweetPages: number;
93
- conversationsScanned: number;
94
- conversationTweets: number;
95
- conversationPages: number;
96
- };
97
- fetchCached: boolean;
98
- hash: string;
99
- }
100
-
101
- const ProfileAnalysisSchema = z.object({
102
- title: z.string().min(1),
103
- summary: z.string().min(1),
104
- voice: z.string().min(1),
105
- themes: z.array(
106
- z.object({
107
- title: z.string().min(1),
108
- summary: z.string().min(1),
109
- tweetIds: z.array(z.string()).default([]),
110
- handles: z.array(z.string()).default([]),
111
- }),
112
- ),
113
- conversationStyle: z.string().min(1),
114
- notableSignals: z.array(z.string()).default([]),
115
- risks: z.array(z.string()).default([]),
116
- followUps: z.array(z.string()).default([]),
117
- sourceTweetIds: z.array(z.string()).default([]),
118
- sourceHandles: z.array(z.string()).default([]),
119
- });
120
-
121
- export type ProfileAnalysis = z.infer<typeof ProfileAnalysisSchema>;
122
-
123
- export interface ProfileAnalysisRunResult {
124
- context: ProfileAnalysisContext;
125
- analysis: ProfileAnalysis;
126
- markdown: string;
127
- model: string;
128
- reasoningEffort: string;
129
- serviceTier: string;
130
- cached: boolean;
131
- updatedAt: string;
132
- }
133
-
134
- export type ProfileAnalysisStreamEvent =
135
- | { type: "status"; label: string; detail?: string }
136
- | { type: "start"; context: ProfileAnalysisContext; cached: boolean }
137
- | { type: "delta"; delta: string }
138
- | { type: "done"; result: ProfileAnalysisRunResult }
139
- | { type: "error"; error: string };
140
-
141
- const DEFAULT_MODEL = "gpt-5.5";
142
- const DEFAULT_REASONING_EFFORT = "medium";
143
- const DEFAULT_SERVICE_TIER = "priority";
144
- const DEFAULT_MAX_TWEETS = 10_000;
145
- const DEFAULT_MAX_PAGES = 100;
146
- const DEFAULT_MAX_CONVERSATIONS = 80;
147
- const DEFAULT_MAX_CONVERSATION_PAGES = 3;
148
- const DEFAULT_CACHE_TTL_MS = 6 * 60 * 60_000;
149
- const DEFAULT_CONVERSATION_DELAY_MS = 3_100;
150
- const DEFAULT_RATE_LIMIT_RETRY_MS = 60_000;
151
- const DEFAULT_RATE_LIMIT_MAX_RETRIES = 1;
152
- const XURL_PAGE_SIZE = 100;
153
- const MAX_PROMPT_DATA_CHARS = 1_200_000;
154
- const DELIMITER_PATTERN = /\n---\s*\n/;
155
-
156
- function toError(error: unknown) {
157
- return error instanceof Error ? error : new Error(String(error));
158
- }
159
-
160
- function isXurlRateLimitError(error: Error) {
161
- return (
162
- error.message.includes("Too Many Requests") ||
163
- error.message.includes('"status":429') ||
164
- /\b429\b/.test(error.message)
165
- );
166
- }
167
-
168
- function tryProfileSync<T>(try_: () => T): Effect.Effect<T, Error> {
169
- return Effect.try({ try: try_, catch: toError });
170
- }
171
-
172
- function tryProfilePromise<T>(
173
- try_: () => PromiseLike<T>,
174
- ): Effect.Effect<T, Error> {
175
- return tryPromise(try_).pipe(Effect.mapError(toError));
176
- }
177
-
178
- function normalizeHandle(value: string) {
179
- const handle = value
180
- .trim()
181
- .replace(/^https?:\/\/(x|twitter)\.com\//i, "")
182
- .replace(/^@/, "")
183
- .split(/[/?#]/)[0]
184
- ?.trim();
185
- if (!handle) {
186
- throw new Error("Profile handle is required");
187
- }
188
- return handle;
189
- }
190
-
191
- function normalizePositiveInteger(
192
- value: number | undefined,
193
- defaultValue: number,
194
- optionName: string,
195
- ) {
196
- if (value === undefined) return defaultValue;
197
- if (!Number.isFinite(value) || value < 1) {
198
- throw new Error(`${optionName} must be at least 1`);
199
- }
200
- return Math.floor(value);
201
- }
202
-
203
- function normalizeCacheTtlMs(value: number | undefined) {
204
- if (value === undefined) return DEFAULT_CACHE_TTL_MS;
205
- if (!Number.isFinite(value) || value < 0) {
206
- return DEFAULT_CACHE_TTL_MS;
207
- }
208
- return Math.floor(value);
209
- }
210
-
211
- function normalizeNonNegativeInteger(
212
- value: number | undefined,
213
- defaultValue: number,
214
- ) {
215
- if (value === undefined) return defaultValue;
216
- if (!Number.isFinite(value) || value < 0) return defaultValue;
217
- return Math.floor(value);
218
- }
219
-
220
- function envNonNegativeInteger(name: string) {
221
- const value = process.env[name];
222
- if (value === undefined || value.trim() === "") return undefined;
223
- const numeric = Number(value);
224
- if (!Number.isFinite(numeric) || numeric < 0) return undefined;
225
- return Math.floor(numeric);
226
- }
227
-
228
- function conversationDelayMsFromOptions(options: ProfileAnalysisOptions) {
229
- return normalizeNonNegativeInteger(
230
- options.conversationDelayMs ??
231
- envNonNegativeInteger("BIRDCLAW_PROFILE_ANALYSIS_CONVERSATION_DELAY_MS"),
232
- DEFAULT_CONVERSATION_DELAY_MS,
233
- );
234
- }
235
-
236
- function rateLimitRetryMsFromOptions(options: ProfileAnalysisOptions) {
237
- return normalizeNonNegativeInteger(
238
- options.rateLimitRetryMs ??
239
- envNonNegativeInteger("BIRDCLAW_PROFILE_ANALYSIS_RATE_LIMIT_RETRY_MS"),
240
- DEFAULT_RATE_LIMIT_RETRY_MS,
241
- );
242
- }
243
-
244
- function rateLimitMaxRetriesFromOptions(options: ProfileAnalysisOptions) {
245
- return normalizeNonNegativeInteger(
246
- options.rateLimitMaxRetries ??
247
- envNonNegativeInteger("BIRDCLAW_PROFILE_ANALYSIS_RATE_LIMIT_MAX_RETRIES"),
248
- DEFAULT_RATE_LIMIT_MAX_RETRIES,
249
- );
250
- }
251
-
252
- function normalizeAccountSelector(value: string | undefined) {
253
- const selector = value?.trim();
254
- if (!selector) return undefined;
255
- return selector;
256
- }
257
-
258
- function resolveAccount(db: Database, accountId?: string) {
259
- const selector = normalizeAccountSelector(
260
- accountId ?? process.env.BIRDCLAW_PROFILE_ANALYSIS_ACCOUNT,
261
- );
262
- const row = selector
263
- ? (db
264
- .prepare(
265
- `
266
- select id, handle
267
- from accounts
268
- where id = ? or lower(trim(handle, '@')) = lower(trim(?, '@'))
269
- limit 1
270
- `,
271
- )
272
- .get(selector, selector) as { id: string; handle: string } | undefined)
273
- : (db
274
- .prepare(
275
- `
276
- select id, handle
277
- from accounts
278
- order by is_default desc, created_at asc
279
- limit 1
280
- `,
281
- )
282
- .get() as { id: string; handle: string } | undefined);
283
- if (!row) {
284
- throw new Error(`Unknown account: ${selector ?? "default"}`);
285
- }
286
- return row;
287
- }
288
-
289
- function modelFromOptions(options: ProfileAnalysisOptions) {
290
- return options.model ?? process.env.BIRDCLAW_AI_MODEL ?? DEFAULT_MODEL;
291
- }
292
-
293
- function reasoningEffortFromOptions(options: ProfileAnalysisOptions) {
294
- return (
295
- options.reasoningEffort ??
296
- (process.env.BIRDCLAW_OPENAI_REASONING_EFFORT as
297
- | ProfileAnalysisOptions["reasoningEffort"]
298
- | undefined) ??
299
- DEFAULT_REASONING_EFFORT
300
- );
301
- }
302
-
303
- function serviceTierFromOptions(options: ProfileAnalysisOptions) {
304
- return (
305
- options.serviceTier ??
306
- (process.env.BIRDCLAW_OPENAI_SERVICE_TIER as
307
- | ProfileAnalysisOptions["serviceTier"]
308
- | undefined) ??
309
- DEFAULT_SERVICE_TIER
310
- );
311
- }
312
-
313
- function tweetUrl(handle: string, id: string) {
314
- return `https://x.com/${handle}/status/${id}`;
315
- }
316
-
317
- function replaceTweetFts(db: Database, tweetId: string, text: string) {
318
- db.prepare("delete from tweets_fts where tweet_id = ?").run(tweetId);
319
- db.prepare("insert into tweets_fts (tweet_id, text) values (?, ?)").run(
320
- tweetId,
321
- text,
322
- );
323
- }
324
-
325
- function refreshTweetFts(
326
- db: Database,
327
- tweetId: string,
328
- text: string,
329
- previousText: string | null,
330
- ) {
331
- if (previousText === text) return;
332
- if (previousText !== null) {
333
- replaceTweetFts(db, tweetId, text);
334
- return;
335
- }
336
- db.prepare("insert into tweets_fts (tweet_id, text) values (?, ?)").run(
337
- tweetId,
338
- text,
339
- );
340
- }
341
-
342
- function mergeXurlTweetsIntoLocalStore(
343
- db: Database,
344
- accountId: string,
345
- payload: XurlTweetsResponse,
346
- tweetKind: "profile" | "thread_context",
347
- edgeKind: TweetAccountEdgeKind,
348
- source: "xurl" | "cache",
349
- ) {
350
- const usersById = new Map(
351
- (payload.includes?.users ?? []).map((user) => [user.id, user]),
352
- );
353
- const upsertTweet = db.prepare(
354
- `
355
- insert into tweets (
356
- id, account_id, author_profile_id, kind, text, created_at,
357
- is_replied, reply_to_id, like_count, media_count, bookmarked, liked,
358
- entities_json, media_json, quoted_tweet_id
359
- ) values (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, 0, 0, ?, ?, ?)
360
- on conflict(id) do update set
361
- author_profile_id = excluded.author_profile_id,
362
- kind = tweets.kind,
363
- text = excluded.text,
364
- created_at = excluded.created_at,
365
- reply_to_id = coalesce(tweets.reply_to_id, excluded.reply_to_id),
366
- like_count = excluded.like_count,
367
- media_count = max(tweets.media_count, excluded.media_count),
368
- entities_json = excluded.entities_json,
369
- media_json = case
370
- when excluded.media_json not in ('', '[]', 'null') then excluded.media_json
371
- else tweets.media_json
372
- end,
373
- quoted_tweet_id = coalesce(tweets.quoted_tweet_id, excluded.quoted_tweet_id),
374
- bookmarked = tweets.bookmarked,
375
- liked = tweets.liked
376
- `,
377
- );
378
- const existingTweet = db.prepare("select text from tweets where id = ?");
379
- const seenAt = new Date().toISOString();
380
- db.transaction(() => {
381
- for (const tweet of payload.data) {
382
- const authorId = tweet.author_id;
383
- if (!authorId) continue;
384
- const author = usersById.get(authorId);
385
- if (!author) continue;
386
- const profile = upsertProfileFromXUser(db, author);
387
- const replyToId =
388
- tweet.referenced_tweets?.find((item) => item.type === "replied_to")
389
- ?.id ?? null;
390
- const quotedTweetId =
391
- tweet.referenced_tweets?.find((item) => item.type === "quoted")?.id ??
392
- null;
393
- const previousTweet = existingTweet.get(tweet.id) as
394
- | { text: string | null }
395
- | undefined;
396
- const previousText =
397
- previousTweet && typeof previousTweet.text === "string"
398
- ? previousTweet.text
399
- : null;
400
- upsertTweet.run(
401
- tweet.id,
402
- accountId,
403
- profile.profile.id,
404
- tweetKind,
405
- tweet.text,
406
- tweet.created_at,
407
- replyToId,
408
- Number(tweet.public_metrics?.like_count ?? 0),
409
- countTweetMedia(tweet),
410
- JSON.stringify(tweetEntitiesFromXurl(tweet.entities)),
411
- buildMediaJsonFromIncludes(tweet, payload.includes?.media),
412
- quotedTweetId,
413
- );
414
- upsertTweetAccountEdge(db, {
415
- accountId,
416
- tweetId: tweet.id,
417
- kind: edgeKind,
418
- source,
419
- seenAt,
420
- rawJson: JSON.stringify(tweet),
421
- });
422
- refreshTweetFts(db, tweet.id, tweet.text, previousText);
423
- }
424
- })();
425
- }
426
-
427
- function toTweetData(
428
- tweet: XurlUserTweet,
429
- fallbackAuthorId: string,
430
- ): XurlTweetData {
431
- return {
432
- ...tweet,
433
- author_id: tweet.author_id ?? fallbackAuthorId,
434
- };
435
- }
436
-
437
- function userTimelineToTweetsResponse(
438
- response: XurlUserTweetsResponse,
439
- fallbackAuthorId: string,
440
- ): XurlTweetsResponse {
441
- return {
442
- data: response.items.map((tweet) => toTweetData(tweet, fallbackAuthorId)),
443
- includes: response.includes,
444
- meta: {
445
- result_count: response.items.length,
446
- ...(response.nextToken ? { next_token: response.nextToken } : {}),
447
- },
448
- };
449
- }
450
-
451
- function mergeResponses(responses: XurlTweetsResponse[]): XurlTweetsResponse {
452
- const seenTweetIds = new Set<string>();
453
- const usersById = new Map<string, XurlMentionUser>();
454
- const mediaByKey = new Map<string, XurlMediaItem>();
455
- const data: XurlTweetData[] = [];
456
- for (const response of responses) {
457
- for (const user of response.includes?.users ?? []) {
458
- usersById.set(user.id, user);
459
- }
460
- for (const media of response.includes?.media ?? []) {
461
- mediaByKey.set(media.media_key, media);
462
- }
463
- for (const tweet of response.data) {
464
- if (seenTweetIds.has(tweet.id)) continue;
465
- seenTweetIds.add(tweet.id);
466
- data.push(tweet);
467
- }
468
- }
469
- return {
470
- data,
471
- includes: {
472
- users: [...usersById.values()],
473
- media: [...mediaByKey.values()],
474
- },
475
- meta: { result_count: data.length },
476
- };
477
- }
478
-
479
- function compactProfileTweet(
480
- tweet: XurlTweetData,
481
- profileHandle: string,
482
- ): CompactProfileTweet {
483
- return {
484
- id: tweet.id,
485
- url: tweetUrl(profileHandle, tweet.id),
486
- author: profileHandle,
487
- createdAt: tweet.created_at,
488
- text: tweet.text,
489
- entities: tweetEntitiesFromXurl(tweet.entities),
490
- ...(tweet.conversation_id ? { conversationId: tweet.conversation_id } : {}),
491
- ...(tweet.referenced_tweets?.find((item) => item.type === "replied_to")?.id
492
- ? {
493
- replyToId: tweet.referenced_tweets.find(
494
- (item) => item.type === "replied_to",
495
- )?.id,
496
- }
497
- : {}),
498
- likeCount: Number(tweet.public_metrics?.like_count ?? 0),
499
- replyCount: Number(tweet.public_metrics?.reply_count ?? 0),
500
- retweetCount: Number(tweet.public_metrics?.retweet_count ?? 0),
501
- quoteCount: Number(tweet.public_metrics?.quote_count ?? 0),
502
- bookmarkedCount: Number(tweet.public_metrics?.bookmark_count ?? 0),
503
- };
504
- }
505
-
506
- function compactConversationTweet(
507
- tweet: XurlTweetData,
508
- usersById: Map<string, XurlMentionUser>,
509
- conversationRootId: string,
510
- ): CompactConversationTweet | null {
511
- const user = usersById.get(tweet.author_id);
512
- if (!user) return null;
513
- return {
514
- ...compactProfileTweet(tweet, user.username),
515
- conversationRootId,
516
- profileId: buildExternalProfileId(user.id),
517
- name: user.name,
518
- bio: user.description ?? "",
519
- followersCount: Number(user.public_metrics?.followers_count ?? 0),
520
- ...(user.profile_image_url ? { avatarUrl: user.profile_image_url } : {}),
521
- };
522
- }
523
-
524
- function contextCacheKey(options: {
525
- accountId: string;
526
- handle: string;
527
- maxTweets: number;
528
- maxPages: number;
529
- maxConversations: number;
530
- maxConversationPages: number;
531
- }) {
532
- return [
533
- "profile-analysis:context",
534
- options.accountId,
535
- options.handle.toLowerCase(),
536
- String(options.maxTweets),
537
- String(options.maxPages),
538
- String(options.maxConversations),
539
- String(options.maxConversationPages),
540
- ].join(":");
541
- }
542
-
543
- function promptTweetContext(tweet: CompactProfileTweet) {
544
- const { entities: _entities, ...promptTweet } = tweet;
545
- return promptTweet;
546
- }
547
-
548
- function contextHash(context: Omit<ProfileAnalysisContext, "hash">) {
549
- return createHash("sha1")
550
- .update(
551
- JSON.stringify({
552
- handle: context.handle,
553
- accountId: context.accountId,
554
- accountHandle: context.accountHandle,
555
- externalUserId: context.externalUserId,
556
- profile: context.profile,
557
- counts: context.counts,
558
- tweets: context.tweets.map(promptTweetContext),
559
- conversations: context.conversations.map(promptTweetContext),
560
- }),
561
- )
562
- .digest("hex");
563
- }
564
-
565
- function resultCacheKey(
566
- context: ProfileAnalysisContext,
567
- options: ProfileAnalysisOptions,
568
- ) {
569
- return [
570
- "profile-analysis:result",
571
- modelFromOptions(options),
572
- reasoningEffortFromOptions(options),
573
- serviceTierFromOptions(options),
574
- context.hash,
575
- ].join(":");
576
- }
577
-
578
- function topConversationIds(tweets: XurlTweetData[], maxConversations: number) {
579
- const candidates = new Map<
580
- string,
581
- { id: string; score: number; createdAt: string }
582
- >();
583
- for (const tweet of tweets) {
584
- const id = tweet.conversation_id;
585
- if (!id) continue;
586
- const score =
587
- Number(tweet.public_metrics?.reply_count ?? 0) * 8 +
588
- Number(tweet.public_metrics?.quote_count ?? 0) * 4 +
589
- Number(tweet.public_metrics?.like_count ?? 0);
590
- const existing = candidates.get(id);
591
- if (!existing || score > existing.score) {
592
- candidates.set(id, { id, score, createdAt: tweet.created_at });
593
- }
594
- }
595
- return [...candidates.values()]
596
- .sort(
597
- (left, right) =>
598
- right.score - left.score ||
599
- right.createdAt.localeCompare(left.createdAt),
600
- )
601
- .slice(0, maxConversations)
602
- .map((item) => item.id);
603
- }
604
-
605
- function buildContextFromPayloads({
606
- account,
607
- handle,
608
- profile,
609
- externalUserId,
610
- tweetResponses,
611
- conversationResponses,
612
- conversationRoots,
613
- tweetPages,
614
- conversationPages,
615
- fetchCached,
616
- }: {
617
- account: { id: string; handle: string };
618
- handle: string;
619
- profile: ProfileRecord;
620
- externalUserId: string;
621
- tweetResponses: XurlTweetsResponse[];
622
- conversationResponses: XurlTweetsResponse[];
623
- conversationRoots: string[];
624
- tweetPages: number;
625
- conversationPages: number;
626
- fetchCached: boolean;
627
- }): ProfileAnalysisContext {
628
- const tweetPayload = mergeResponses(tweetResponses);
629
- const conversationPayload = mergeResponses(conversationResponses);
630
- const profileTweets = tweetPayload.data
631
- .map((tweet) => compactProfileTweet(tweet, handle))
632
- .sort((left, right) => right.createdAt.localeCompare(left.createdAt));
633
- const usersById = new Map(
634
- (conversationPayload.includes?.users ?? []).map((user) => [user.id, user]),
635
- );
636
- const conversationSet = new Set(conversationRoots);
637
- const conversations = conversationPayload.data
638
- .filter(
639
- (tweet) =>
640
- tweet.conversation_id && conversationSet.has(tweet.conversation_id),
641
- )
642
- .map((tweet) =>
643
- compactConversationTweet(tweet, usersById, tweet.conversation_id ?? ""),
644
- )
645
- .filter((tweet): tweet is CompactConversationTweet => tweet !== null)
646
- .sort((left, right) => right.createdAt.localeCompare(left.createdAt));
647
- const withoutHash = {
648
- handle,
649
- accountId: account.id,
650
- accountHandle: account.handle,
651
- profile,
652
- externalUserId,
653
- tweets: profileTweets,
654
- conversations,
655
- counts: {
656
- tweets: profileTweets.length,
657
- tweetPages,
658
- conversationsScanned: conversationRoots.length,
659
- conversationTweets: conversations.length,
660
- conversationPages,
661
- },
662
- fetchCached,
663
- } satisfies Omit<ProfileAnalysisContext, "hash">;
664
- return {
665
- ...withoutHash,
666
- hash: contextHash(withoutHash),
667
- };
668
- }
669
-
670
- function emitStatus(
671
- handlers: ProfileAnalysisStreamHandlers,
672
- label: string,
673
- detail?: string,
674
- ) {
675
- handlers.onEvent?.({
676
- type: "status",
677
- label,
678
- ...(detail ? { detail } : {}),
679
- });
680
- }
681
-
682
- function abortIfRequestedEffect(signal: AbortSignal | undefined) {
683
- return tryProfileSync(() => {
684
- if (signal?.aborted) {
685
- throw new Error("Profile analysis aborted");
686
- }
687
- });
688
- }
689
-
690
- function sleepWithAbortEffect(ms: number, signal: AbortSignal | undefined) {
691
- if (ms <= 0) return abortIfRequestedEffect(signal);
692
- return tryProfilePromise(
693
- () =>
694
- new Promise<void>((resolve, reject) => {
695
- if (signal?.aborted) {
696
- reject(new Error("Profile analysis aborted"));
697
- return;
698
- }
699
- const timer = setTimeout(() => {
700
- signal?.removeEventListener("abort", onAbort);
701
- resolve();
702
- }, ms);
703
- const onAbort = () => {
704
- clearTimeout(timer);
705
- reject(new Error("Profile analysis aborted"));
706
- };
707
- signal?.addEventListener("abort", onAbort, { once: true });
708
- }),
709
- );
710
- }
711
-
712
- export function collectProfileAnalysisContextEffect(
713
- options: ProfileAnalysisOptions,
714
- handlers: ProfileAnalysisStreamHandlers = {},
715
- ): Effect.Effect<ProfileAnalysisContext, Error> {
716
- return Effect.gen(function* () {
717
- const db = getNativeDb();
718
- const handle = yield* tryProfileSync(() => normalizeHandle(options.handle));
719
- const account = yield* tryProfileSync(() =>
720
- resolveAccount(db, options.account),
721
- );
722
- const maxTweets = yield* tryProfileSync(() =>
723
- normalizePositiveInteger(
724
- options.maxTweets,
725
- DEFAULT_MAX_TWEETS,
726
- "--max-tweets",
727
- ),
728
- );
729
- const maxPages = yield* tryProfileSync(() =>
730
- normalizePositiveInteger(
731
- options.maxPages,
732
- DEFAULT_MAX_PAGES,
733
- "--max-pages",
734
- ),
735
- );
736
- const maxConversations = yield* tryProfileSync(() =>
737
- normalizePositiveInteger(
738
- options.maxConversations,
739
- DEFAULT_MAX_CONVERSATIONS,
740
- "--max-conversations",
741
- ),
742
- );
743
- const maxConversationPages = yield* tryProfileSync(() =>
744
- normalizePositiveInteger(
745
- options.maxConversationPages,
746
- DEFAULT_MAX_CONVERSATION_PAGES,
747
- "--max-conversation-pages",
748
- ),
749
- );
750
- const conversationDelayMs = conversationDelayMsFromOptions(options);
751
- const rateLimitRetryMs = rateLimitRetryMsFromOptions(options);
752
- const rateLimitMaxRetries = rateLimitMaxRetriesFromOptions(options);
753
- const cacheTtlMs = normalizeCacheTtlMs(options.cacheTtlMs);
754
- const contextKey = contextCacheKey({
755
- accountId: account.id,
756
- handle,
757
- maxTweets,
758
- maxPages,
759
- maxConversations,
760
- maxConversationPages,
761
- });
762
- const cached = yield* tryProfileSync(() =>
763
- readSyncCache<ProfileAnalysisContext>(contextKey, db),
764
- );
765
- const ageMs = cached
766
- ? Date.now() - new Date(cached.updatedAt).getTime()
767
- : Number.POSITIVE_INFINITY;
768
- if (!options.refresh && cached && ageMs <= cacheTtlMs) {
769
- emitStatus(handlers, "Using cached profile backfill", `@${handle}`);
770
- return { ...cached.value, fetchCached: true };
771
- }
772
-
773
- const recordTimelineAttempt = (attempt: XurlJsonCommandAttempt) =>
774
- recordXurlRateLimitEventSafe({
775
- endpoint: "users_id_tweets",
776
- status: attempt.status,
777
- source: "profile-analysis:timeline",
778
- handle,
779
- ...(attempt.error ? { detail: attempt.error.message } : {}),
780
- });
781
- const recordConversationAttempt = (attempt: XurlJsonCommandAttempt) =>
782
- recordXurlRateLimitEventSafe({
783
- endpoint: "tweets_search_recent",
784
- status: attempt.status,
785
- source: "profile-analysis:conversation",
786
- handle,
787
- ...(attempt.error ? { detail: attempt.error.message } : {}),
788
- });
789
-
790
- emitStatus(handlers, "Resolving profile", `@${handle}`);
791
- yield* abortIfRequestedEffect(options.signal);
792
- const [user] = yield* lookupUsersByHandlesEffect([handle], {
793
- auth: "oauth2",
794
- signal: options.signal,
795
- useConfiguredCandidate: false,
796
- });
797
- yield* abortIfRequestedEffect(options.signal);
798
- if (!user) {
799
- return yield* Effect.fail(new Error(`Could not resolve @${handle}`));
800
- }
801
- const resolved = yield* tryProfileSync(() =>
802
- upsertProfileFromXUser(db, user),
803
- );
804
-
805
- const tweetResponses: XurlTweetsResponse[] = [];
806
- let nextToken: string | undefined;
807
- let tweetPages = 0;
808
- let fetchedTweets = 0;
809
- for (
810
- let page = 0;
811
- page < maxPages && fetchedTweets < maxTweets;
812
- page += 1
813
- ) {
814
- yield* abortIfRequestedEffect(options.signal);
815
- const remaining = maxTweets - fetchedTweets;
816
- emitStatus(
817
- handlers,
818
- "Fetching profile tweets",
819
- `page ${String(page + 1)} · ${String(fetchedTweets)} tweets`,
820
- );
821
- const response = yield* listUserTweetsEffect(resolved.externalUserId, {
822
- maxResults: Math.max(5, Math.min(XURL_PAGE_SIZE, remaining)),
823
- paginationToken: nextToken,
824
- excludeRetweets: false,
825
- auth: "oauth2",
826
- tweetFields: [
827
- "created_at",
828
- "conversation_id",
829
- "entities",
830
- "public_metrics",
831
- "referenced_tweets",
832
- "in_reply_to_user_id",
833
- "attachments",
834
- ],
835
- expansions: ["author_id", "attachments.media_keys"],
836
- userFields: [
837
- "description",
838
- "entities",
839
- "location",
840
- "public_metrics",
841
- "profile_image_url",
842
- "url",
843
- "created_at",
844
- "verified",
845
- "verified_type",
846
- ],
847
- signal: options.signal,
848
- onAttempt: recordTimelineAttempt,
849
- useConfiguredCandidate: false,
850
- });
851
- yield* abortIfRequestedEffect(options.signal);
852
- const limitedResponse =
853
- response.items.length > remaining
854
- ? { ...response, items: response.items.slice(0, remaining) }
855
- : response;
856
- tweetPages += 1;
857
- fetchedTweets += limitedResponse.items.length;
858
- tweetResponses.push(
859
- userTimelineToTweetsResponse(limitedResponse, resolved.externalUserId),
860
- );
861
- nextToken =
862
- fetchedTweets < maxTweets
863
- ? (response.nextToken ?? undefined)
864
- : undefined;
865
- if (!nextToken || limitedResponse.items.length === 0) break;
866
- }
867
- const profilePayload = mergeResponses(tweetResponses);
868
- yield* tryProfileSync(() =>
869
- mergeXurlTweetsIntoLocalStore(
870
- db,
871
- account.id,
872
- profilePayload,
873
- "profile",
874
- "profile",
875
- "xurl",
876
- ),
877
- );
878
-
879
- const conversationRoots = topConversationIds(
880
- profilePayload.data,
881
- maxConversations,
882
- );
883
- const conversationResponses: XurlTweetsResponse[] = [];
884
- let conversationPages = 0;
885
- let conversationRateLimited = false;
886
- let conversationRequestCount = 0;
887
- for (const [index, conversationId] of conversationRoots.entries()) {
888
- if (conversationRateLimited) break;
889
- let conversationNextToken: string | undefined;
890
- for (let page = 0; page < maxConversationPages; page += 1) {
891
- yield* abortIfRequestedEffect(options.signal);
892
- if (conversationRequestCount > 0 && conversationDelayMs > 0) {
893
- emitStatus(
894
- handlers,
895
- "Throttling conversation fetch",
896
- `${String(conversationDelayMs)}ms`,
897
- );
898
- yield* sleepWithAbortEffect(conversationDelayMs, options.signal);
899
- }
900
- emitStatus(
901
- handlers,
902
- "Fetching conversations",
903
- `${String(index + 1)}/${String(conversationRoots.length)} · page ${String(page + 1)}`,
904
- );
905
- let response: XurlTweetsResponse | null = null;
906
- for (let attempt = 0; attempt <= rateLimitMaxRetries; attempt += 1) {
907
- conversationRequestCount += 1;
908
- response = yield* searchRecentByConversationIdEffect(conversationId, {
909
- maxResults: XURL_PAGE_SIZE,
910
- paginationToken: conversationNextToken,
911
- timeoutMs: 30_000,
912
- auth: "oauth2",
913
- signal: options.signal,
914
- onAttempt: recordConversationAttempt,
915
- }).pipe(
916
- Effect.catchAll((error) => {
917
- if (!isXurlRateLimitError(error)) {
918
- return Effect.fail(error);
919
- }
920
- if (attempt < rateLimitMaxRetries) {
921
- emitStatus(
922
- handlers,
923
- "Conversation fetch rate limited",
924
- `retrying in ${String(rateLimitRetryMs)}ms`,
925
- );
926
- return sleepWithAbortEffect(
927
- rateLimitRetryMs,
928
- options.signal,
929
- ).pipe(Effect.as(null));
930
- }
931
- conversationRateLimited = true;
932
- emitStatus(
933
- handlers,
934
- "Conversation fetch rate limited",
935
- "using partial profile context",
936
- );
937
- return Effect.succeed(null);
938
- }),
939
- );
940
- if (response || conversationRateLimited) {
941
- break;
942
- }
943
- if (conversationDelayMs > 0) {
944
- emitStatus(
945
- handlers,
946
- "Throttling conversation retry",
947
- `${String(conversationDelayMs)}ms`,
948
- );
949
- yield* sleepWithAbortEffect(conversationDelayMs, options.signal);
950
- }
951
- }
952
- if (!response) break;
953
- yield* abortIfRequestedEffect(options.signal);
954
- conversationPages += 1;
955
- conversationResponses.push(response);
956
- conversationNextToken =
957
- typeof response.meta?.next_token === "string"
958
- ? String(response.meta.next_token)
959
- : undefined;
960
- if (!conversationNextToken || response.data.length === 0) break;
961
- }
962
- }
963
- const conversationPayload = mergeResponses(conversationResponses);
964
- yield* tryProfileSync(() =>
965
- mergeXurlTweetsIntoLocalStore(
966
- db,
967
- account.id,
968
- conversationPayload,
969
- "thread_context",
970
- "thread_context",
971
- "xurl",
972
- ),
973
- );
974
-
975
- const context = buildContextFromPayloads({
976
- account,
977
- handle: resolved.profile.handle,
978
- profile: resolved.profile,
979
- externalUserId: resolved.externalUserId,
980
- tweetResponses,
981
- conversationResponses,
982
- conversationRoots,
983
- tweetPages,
984
- conversationPages,
985
- fetchCached: false,
986
- });
987
- if (!conversationRateLimited) {
988
- yield* tryProfileSync(() => writeSyncCache(contextKey, context, db));
989
- }
990
- return context;
991
- });
992
- }
993
-
994
- function fitPromptDataset(context: ProfileAnalysisContext) {
995
- let tweetCount = context.tweets.length;
996
- let conversationCount = context.conversations.length;
997
- const datasetFor = (tweets: number, conversations: number) => ({
998
- profile: context.profile,
999
- counts: context.counts,
1000
- tweets: context.tweets.slice(0, tweets).map(promptTweetContext),
1001
- conversations: context.conversations
1002
- .slice(0, conversations)
1003
- .map(promptTweetContext),
1004
- });
1005
- const lengthFor = (tweets: number, conversations: number) =>
1006
- JSON.stringify(datasetFor(tweets, conversations)).length;
1007
- const fitCount = (max: number, fits: (count: number) => boolean) => {
1008
- let low = 0;
1009
- let high = max;
1010
- let best = 0;
1011
- while (low <= high) {
1012
- const mid = Math.floor((low + high) / 2);
1013
- if (fits(mid)) {
1014
- best = mid;
1015
- low = mid + 1;
1016
- } else {
1017
- high = mid - 1;
1018
- }
1019
- }
1020
- return best;
1021
- };
1022
- if (lengthFor(tweetCount, conversationCount) <= MAX_PROMPT_DATA_CHARS) {
1023
- return {
1024
- dataset: datasetFor(tweetCount, conversationCount),
1025
- tweetCount,
1026
- conversationCount,
1027
- };
1028
- }
1029
- conversationCount = fitCount(
1030
- conversationCount,
1031
- (count) => lengthFor(tweetCount, count) <= MAX_PROMPT_DATA_CHARS,
1032
- );
1033
- if (lengthFor(tweetCount, conversationCount) > MAX_PROMPT_DATA_CHARS) {
1034
- tweetCount = fitCount(
1035
- tweetCount,
1036
- (count) => lengthFor(count, conversationCount) <= MAX_PROMPT_DATA_CHARS,
1037
- );
1038
- }
1039
- return {
1040
- dataset: datasetFor(tweetCount, conversationCount),
1041
- tweetCount,
1042
- conversationCount,
1043
- };
1044
- }
1045
-
1046
- function buildPrompt(context: ProfileAnalysisContext) {
1047
- const { dataset, tweetCount, conversationCount } = fitPromptDataset(context);
1048
- return `Profile: @${context.handle}
1049
- Account cache: ${context.accountId} (${context.accountHandle})
1050
- Fetched profile tweets: ${String(context.counts.tweets)} across ${String(context.counts.tweetPages)} pages
1051
- Fetched conversation tweets: ${String(context.counts.conversationTweets)} across ${String(context.counts.conversationPages)} pages
1052
- Prompt tweets: ${String(tweetCount)} of ${String(context.tweets.length)}
1053
- Prompt conversation tweets: ${String(conversationCount)} of ${String(context.conversations.length)}
1054
-
1055
- Write a high-signal Markdown profile analysis from X/Twitter API data.
1056
-
1057
- Requirements:
1058
- - Summarize who this person appears to be, what they care about, and what kind of attention they attract.
1059
- - Separate authored profile evidence from conversation/reply evidence.
1060
- - Cover recurring topics, tone, technical interests, social graph hints, interaction style, and likely follow-up angles.
1061
- - Cite claims with tweet ids at sentence ends, e.g. (1234567890). Cite handles only when they are in the dataset.
1062
- - Do not overstate beyond the supplied data.
1063
- - If conversation context is sparse, say so.
1064
- - After Markdown, output a blank line, a line containing only three hyphens, then one compact JSON object.
1065
- - JSON shape: { "title": string, "summary": string, "voice": string, "themes": [{ "title": string, "summary": string, "tweetIds": string[], "handles": string[] }], "conversationStyle": string, "notableSignals": string[], "risks": string[], "followUps": string[], "sourceTweetIds": string[], "sourceHandles": string[] }
1066
-
1067
- Dataset:
1068
- ${JSON.stringify(dataset)}`;
1069
- }
1070
-
1071
- function fallbackAnalysis(
1072
- context: ProfileAnalysisContext,
1073
- markdown: string,
1074
- ): ProfileAnalysis {
1075
- return {
1076
- title: `Profile analysis: @${context.handle}`,
1077
- summary:
1078
- markdown.replaceAll(/\s+/g, " ").trim().slice(0, 320) ||
1079
- "No model summary was returned.",
1080
- voice: "Not enough structured output was returned to classify voice.",
1081
- themes: [],
1082
- conversationStyle: "Not enough structured output was returned.",
1083
- notableSignals: [],
1084
- risks: [],
1085
- followUps: [],
1086
- sourceTweetIds: context.tweets.slice(0, 20).map((tweet) => tweet.id),
1087
- sourceHandles: [context.handle],
1088
- };
1089
- }
1090
-
1091
- function parseAnalysisFromHybridText(
1092
- context: ProfileAnalysisContext,
1093
- rawText: string,
1094
- ): { analysis: ProfileAnalysis; markdown: string } {
1095
- const [markdownPart, jsonPart] = rawText.split(DELIMITER_PATTERN);
1096
- const markdown = (markdownPart ?? rawText).trim();
1097
- const candidate = jsonPart?.slice(
1098
- jsonPart.indexOf("{"),
1099
- jsonPart.lastIndexOf("}") + 1,
1100
- );
1101
- if (candidate?.startsWith("{")) {
1102
- try {
1103
- return {
1104
- markdown,
1105
- analysis: ProfileAnalysisSchema.parse(JSON.parse(candidate)),
1106
- };
1107
- } catch {
1108
- return { markdown, analysis: fallbackAnalysis(context, markdown) };
1109
- }
1110
- }
1111
- return { markdown, analysis: fallbackAnalysis(context, markdown) };
1112
- }
1113
-
1114
- function extractResponseText(payload: Record<string, unknown>) {
1115
- if (typeof payload.output_text === "string") {
1116
- return payload.output_text;
1117
- }
1118
- const output = Array.isArray(payload.output) ? payload.output : [];
1119
- const parts: string[] = [];
1120
- for (const item of output) {
1121
- if (!item || typeof item !== "object") continue;
1122
- const content = (item as { content?: unknown }).content;
1123
- if (!Array.isArray(content)) continue;
1124
- for (const block of content) {
1125
- if (!block || typeof block !== "object") continue;
1126
- const record = block as Record<string, unknown>;
1127
- if (typeof record.text === "string") parts.push(record.text);
1128
- }
1129
- }
1130
- return parts.join("");
1131
- }
1132
-
1133
- function createOpenAIRequestBody(
1134
- context: ProfileAnalysisContext,
1135
- options: ProfileAnalysisOptions,
1136
- ) {
1137
- return {
1138
- model: modelFromOptions(options),
1139
- reasoning: { effort: reasoningEffortFromOptions(options) },
1140
- service_tier: serviceTierFromOptions(options),
1141
- store: false,
1142
- max_output_tokens: 7000,
1143
- input: [
1144
- {
1145
- role: "system",
1146
- content:
1147
- "You are a precise X/Twitter profile analyst. Use only supplied data. Return Markdown plus the requested JSON after the delimiter.",
1148
- },
1149
- {
1150
- role: "user",
1151
- content: buildPrompt(context),
1152
- },
1153
- ],
1154
- };
1155
- }
1156
-
1157
- export function streamProfileAnalysisEffect(
1158
- options: ProfileAnalysisOptions,
1159
- handlers: ProfileAnalysisStreamHandlers = {},
1160
- ): Effect.Effect<ProfileAnalysisRunResult, Error> {
1161
- return Effect.gen(function* () {
1162
- const context = yield* collectProfileAnalysisContextEffect(
1163
- options,
1164
- handlers,
1165
- );
1166
- const cached = options.refresh
1167
- ? null
1168
- : yield* tryProfileSync(() =>
1169
- readSyncCache<{
1170
- analysis: ProfileAnalysis;
1171
- markdown: string;
1172
- model: string;
1173
- reasoningEffort: string;
1174
- serviceTier: string;
1175
- }>(resultCacheKey(context, options)),
1176
- );
1177
- if (cached) {
1178
- const result: ProfileAnalysisRunResult = yield* tryProfileSync(() => ({
1179
- context,
1180
- analysis: ProfileAnalysisSchema.parse(cached.value.analysis),
1181
- markdown: cached.value.markdown,
1182
- model: cached.value.model,
1183
- reasoningEffort: cached.value.reasoningEffort,
1184
- serviceTier: cached.value.serviceTier,
1185
- cached: true,
1186
- updatedAt: cached.updatedAt,
1187
- }));
1188
- handlers.onEvent?.({ type: "start", context, cached: true });
1189
- handlers.onDelta?.(result.markdown);
1190
- handlers.onEvent?.({ type: "delta", delta: result.markdown });
1191
- handlers.onEvent?.({ type: "done", result });
1192
- return result;
1193
- }
1194
-
1195
- const apiKey = process.env.OPENAI_API_KEY;
1196
- if (!apiKey) {
1197
- return yield* Effect.fail(new Error("OPENAI_API_KEY is not set"));
1198
- }
1199
- handlers.onEvent?.({ type: "start", context, cached: false });
1200
- emitStatus(handlers, "Summarizing with AI", modelFromOptions(options));
1201
- const response = yield* tryProfilePromise(() =>
1202
- fetch("https://api.openai.com/v1/responses", {
1203
- method: "POST",
1204
- signal: options.signal,
1205
- headers: {
1206
- authorization: `Bearer ${apiKey}`,
1207
- "content-type": "application/json",
1208
- },
1209
- body: JSON.stringify(createOpenAIRequestBody(context, options)),
1210
- }),
1211
- );
1212
- if (!response.ok) {
1213
- const text = yield* tryProfilePromise(() => response.text());
1214
- return yield* Effect.fail(
1215
- new Error(
1216
- `OpenAI request failed: ${String(response.status)} ${text.slice(
1217
- 0,
1218
- 400,
1219
- )}`,
1220
- ),
1221
- );
1222
- }
1223
- const payload = (yield* tryProfilePromise(() => response.json())) as Record<
1224
- string,
1225
- unknown
1226
- >;
1227
- const rawText = extractResponseText(payload);
1228
- if (!rawText) {
1229
- return yield* Effect.fail(new Error("OpenAI returned no output text"));
1230
- }
1231
- const parsed = yield* tryProfileSync(() =>
1232
- parseAnalysisFromHybridText(context, rawText),
1233
- );
1234
- const updatedAt = yield* tryProfileSync(() =>
1235
- writeSyncCache(resultCacheKey(context, options), {
1236
- analysis: parsed.analysis,
1237
- markdown: parsed.markdown,
1238
- model: modelFromOptions(options),
1239
- reasoningEffort: reasoningEffortFromOptions(options),
1240
- serviceTier: serviceTierFromOptions(options),
1241
- }),
1242
- );
1243
- const result: ProfileAnalysisRunResult = {
1244
- context,
1245
- analysis: parsed.analysis,
1246
- markdown: parsed.markdown,
1247
- model: modelFromOptions(options),
1248
- reasoningEffort: reasoningEffortFromOptions(options),
1249
- serviceTier: serviceTierFromOptions(options),
1250
- cached: false,
1251
- updatedAt,
1252
- };
1253
- handlers.onDelta?.(result.markdown);
1254
- handlers.onEvent?.({ type: "delta", delta: result.markdown });
1255
- handlers.onEvent?.({ type: "done", result });
1256
- return result;
1257
- });
1258
- }
1259
-
1260
- export function streamProfileAnalysis(
1261
- options: ProfileAnalysisOptions,
1262
- handlers: ProfileAnalysisStreamHandlers = {},
1263
- ) {
1264
- return runEffectPromise(streamProfileAnalysisEffect(options, handlers));
1265
- }
1266
-
1267
- export const __test__ = {
1268
- ProfileAnalysisSchema,
1269
- buildPrompt,
1270
- extractResponseText,
1271
- parseAnalysisFromHybridText,
1272
- };