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.
- package/CHANGELOG.md +24 -0
- package/README.md +10 -8
- package/bin/birdclaw.mjs +4 -66
- package/dist/cli/birdclaw.js +28164 -0
- package/dist/client/assets/AvatarChip-DLoqM5xD.js +1 -0
- package/dist/client/assets/ProfilePreview-DQX6_xc3.js +1 -0
- package/dist/client/assets/SavedTimelineView-BhSiVyR1.js +1 -0
- package/dist/client/assets/SmartTimestamp-BR0-9se2.js +1 -0
- package/dist/client/assets/TimelineRouteFrame-9NDLnXzH.js +1 -0
- package/dist/client/assets/blocks-CFp_njvG.js +1 -0
- package/dist/client/assets/bookmarks-LbYOsoKf.js +1 -0
- package/dist/client/assets/chunk-C0phanGV.js +1 -0
- package/dist/client/assets/circle-check-C_Vq3ElD.js +1 -0
- package/dist/client/assets/client-stream-contracts-sR4xMQxY.js +5 -0
- package/dist/client/assets/createLucideIcon-JV8isFFR.js +1 -0
- package/dist/client/assets/data-sources-euTr6T_L.js +1 -0
- package/dist/client/assets/discuss-BWKu_p7B.js +1 -0
- package/dist/client/assets/dms-SLXMtC4v.js +1 -0
- package/dist/client/assets/inbox-BybSI5Vf.js +1 -0
- package/dist/client/assets/index-DZVisyna.js +31 -0
- package/dist/client/assets/index-bpFrQ5yG.css +1 -0
- package/dist/client/assets/likes-dyh9p8y_.js +1 -0
- package/dist/client/assets/links-CIwqK_dX.js +1 -0
- package/dist/client/assets/mapbox-B4zqX7r0.js +2 -0
- package/dist/client/assets/mapbox-gl-DYNcLcll.js +3215 -0
- package/dist/client/assets/mentions-BoVVAIT7.js +1 -0
- package/dist/client/assets/network-map-zRysIY_b.js +2 -0
- package/dist/client/assets/profile-analyze-C_yDeX6-.js +1 -0
- package/dist/client/assets/profile-hydration-client-YEtJsNTv.js +1 -0
- package/dist/client/assets/profiles._handle-DdIVPqU-.js +1 -0
- package/dist/client/assets/query-client-fYu2rzRC.js +17 -0
- package/dist/client/assets/rate-limits-BWPmPOSh.js +1 -0
- package/dist/client/assets/react-dom-DHl6Ug7F.js +1 -0
- package/dist/client/assets/react-nBylq1U5.js +1 -0
- package/dist/client/assets/repeat-2-xCwHM9hD.js +1 -0
- package/dist/client/assets/routes-CiLuYpZr.js +1 -0
- package/dist/client/assets/schemas-I9r6F6ya.js +64 -0
- package/dist/client/assets/search-Dq5kYsxA.js +1 -0
- package/dist/client/assets/sparkles-CQVlvHsZ.js +1 -0
- package/dist/client/assets/styles-B8s3tt3r.css +2 -0
- package/dist/client/assets/today-BoO64YoY.js +1 -0
- package/dist/client/assets/triangle-alert-CBL7s2pf.js +1 -0
- package/dist/client/assets/useTimelineRouteData-BaO3Rna1.js +1 -0
- package/dist/client/assets/users-CHbKlqUr.js +1 -0
- package/dist/server/assets/AvatarChip-zUDAEmjL.js +105 -0
- package/dist/server/assets/FeedState-ntW0Q2GB.js +214 -0
- package/dist/server/assets/ProfileAnalysisStream-L7bs6IHH.js +198 -0
- package/dist/server/assets/ProfilePreview-Cg-AOHBE.js +751 -0
- package/dist/server/assets/SavedTimelineView-BtCq1dHk.js +64 -0
- package/dist/server/assets/SmartTimestamp-DfwE1NGf.js +45 -0
- package/dist/server/assets/SyncNowButton-BOn_IBXS.js +76 -0
- package/dist/server/assets/TimelineRouteFrame-CjMIh63G.js +85 -0
- package/dist/server/assets/TweetRichText-DDywESRF.js +74 -0
- package/dist/server/assets/_tanstack-start-manifest_v-aLWUdbAc.js +148 -0
- package/dist/server/assets/account-selection-CTdFGWRk.js +44 -0
- package/dist/server/assets/blocks-C1mgGTB3.js +299 -0
- package/dist/server/assets/blocks-DSgQghqP.js +17 -0
- package/dist/server/assets/bookmarks-D_YkmCK3.js +14 -0
- package/dist/server/assets/client-stream-contracts-Bq6kMmhh.js +769 -0
- package/dist/server/assets/data-sources-BnA1Q94p.js +180 -0
- package/dist/server/assets/discuss-C1QMBBSk.js +338 -0
- package/dist/server/assets/discuss-DAq6ehL9.js +15 -0
- package/dist/server/assets/dms-BuLj4bp8.js +368 -0
- package/dist/server/assets/dms-DAyQrVM2.js +240 -0
- package/dist/server/assets/empty-plugin-adapters-DzrEkdBF.js +5 -0
- package/dist/server/assets/inbox-CkGOaW1q.js +214 -0
- package/dist/server/assets/inbox-DpWd1EzC.js +146 -0
- package/dist/server/assets/likes-BMm2JWYI.js +14 -0
- package/dist/server/assets/links-Da4tjWtI.js +468 -0
- package/dist/server/assets/links-dqXb35YM.js +240 -0
- package/dist/server/assets/mentions-CEyEcOFw.js +26 -0
- package/dist/server/assets/network-map-D3CzRcC4.js +224 -0
- package/dist/server/assets/network-map-D5DoLOwR.js +582 -0
- package/dist/server/assets/profile-analyze-CGCj4VFd.js +90 -0
- package/dist/server/assets/profile-analyze-DH1TSBkT.js +9 -0
- package/dist/server/assets/profile-hydration-client-GJ4kwJS8.js +133 -0
- package/dist/server/assets/profiles._handle-B5V-huoo.js +12 -0
- package/dist/server/assets/profiles._handle-CJ6rgzt8.js +184 -0
- package/dist/server/assets/query-client-BdauHBgd.js +923 -0
- package/dist/server/assets/rate-limits-VAr2qzYD.js +262 -0
- package/dist/server/assets/route-search-BUlQ5lGM.js +117 -0
- package/dist/server/assets/router-C4cz9ypd.js +17026 -0
- package/dist/server/assets/routes-B9aikOdB.js +26 -0
- package/dist/server/assets/start-FaDOTmto.js +4 -0
- package/dist/server/assets/today-B_TA16QG.js +303 -0
- package/dist/server/assets/today-JkxZXdBt.js +17 -0
- package/dist/server/assets/ui-qbmcMSSX.js +137 -0
- package/{src/components/useDebouncedValue.ts → dist/server/assets/useDebouncedValue-DOnA6Xcy.js} +4 -4
- package/dist/server/assets/useTimelineRouteData-BLXvMGb2.js +1101 -0
- package/dist/server/server.js +5520 -0
- package/package.json +26 -34
- package/playwright.config.ts +0 -35
- package/scripts/browser-perf.mjs +0 -427
- package/scripts/build-docs-site.mjs +0 -967
- package/scripts/docs-site-assets.mjs +0 -311
- package/scripts/run-vitest.mjs +0 -21
- package/scripts/sanitize-node-options.mjs +0 -23
- package/scripts/start-test-server.mjs +0 -42
- package/src/cli/command-context.ts +0 -17
- package/src/cli/register-analysis.ts +0 -500
- package/src/cli/register-compose.ts +0 -40
- package/src/cli/register-graph.ts +0 -132
- package/src/cli/register-inbox.ts +0 -41
- package/src/cli/register-storage.ts +0 -106
- package/src/cli-moderation.ts +0 -210
- package/src/cli.ts +0 -1616
- package/src/components/AccountSwitcher.tsx +0 -178
- package/src/components/AppNav.tsx +0 -118
- package/src/components/AvatarChip.tsx +0 -58
- package/src/components/AvatarPreload.ts +0 -149
- package/src/components/BrandMark.tsx +0 -67
- package/src/components/ConversationThread.tsx +0 -131
- package/src/components/DmWorkspace.tsx +0 -286
- package/src/components/EmbeddedTweetCard.tsx +0 -55
- package/src/components/FeedState.tsx +0 -147
- package/src/components/FloatingPreview.tsx +0 -382
- package/src/components/InboxCard.tsx +0 -152
- package/src/components/LinkPreviewCard.tsx +0 -292
- package/src/components/MarkdownCitations.tsx +0 -680
- package/src/components/MarkdownViewer.tsx +0 -111
- package/src/components/ProfileAnalysisClient.ts +0 -191
- package/src/components/ProfileAnalysisStream.tsx +0 -259
- package/src/components/ProfilePreview.tsx +0 -131
- package/src/components/SavedTimelineView.tsx +0 -155
- package/src/components/SmartTimestamp.tsx +0 -72
- package/src/components/SyncNowButton.tsx +0 -140
- package/src/components/ThemeSlider.tsx +0 -80
- package/src/components/TimelineCard.tsx +0 -533
- package/src/components/TimelineRouteFrame.tsx +0 -186
- package/src/components/TweetArticleCard.tsx +0 -66
- package/src/components/TweetMediaGrid.tsx +0 -185
- package/src/components/TweetRichText.tsx +0 -159
- package/src/components/account-selection.ts +0 -64
- package/src/components/links-controller.ts +0 -162
- package/src/components/links-model.ts +0 -198
- package/src/components/network-map-controller.ts +0 -84
- package/src/components/network-map-model.ts +0 -255
- package/src/components/useTimelineRouteData.ts +0 -193
- package/src/lib/account-sync-job.ts +0 -666
- package/src/lib/actions-transport.ts +0 -300
- package/src/lib/analysis-runtime.ts +0 -238
- package/src/lib/api-client.ts +0 -220
- package/src/lib/api-contracts.ts +0 -328
- package/src/lib/archive-finder.ts +0 -185
- package/src/lib/archive-import-plan.ts +0 -102
- package/src/lib/archive-import.ts +0 -2695
- package/src/lib/authored-live.ts +0 -1027
- package/src/lib/avatar-cache.ts +0 -349
- package/src/lib/backup.ts +0 -2652
- package/src/lib/bird-actions.ts +0 -294
- package/src/lib/bird-command.ts +0 -130
- package/src/lib/bird.ts +0 -1140
- package/src/lib/blocklist.ts +0 -136
- package/src/lib/blocks-write.ts +0 -171
- package/src/lib/blocks.ts +0 -387
- package/src/lib/bookmark-sync-job.ts +0 -536
- package/src/lib/config.ts +0 -224
- package/src/lib/conversation-surface.ts +0 -205
- package/src/lib/data-sources.ts +0 -219
- package/src/lib/database-metrics.ts +0 -88
- package/src/lib/database-migrations.ts +0 -34
- package/src/lib/database-schema.ts +0 -312
- package/src/lib/database-writer.ts +0 -69
- package/src/lib/db.ts +0 -889
- package/src/lib/dm-read-model.ts +0 -533
- package/src/lib/dms-live.ts +0 -870
- package/src/lib/effect-runtime.ts +0 -45
- package/src/lib/follow-graph.ts +0 -1087
- package/src/lib/geocoding.ts +0 -296
- package/src/lib/http-effect.ts +0 -222
- package/src/lib/identity-search-index.ts +0 -369
- package/src/lib/import-repository.ts +0 -138
- package/src/lib/inbox.ts +0 -242
- package/src/lib/link-index.ts +0 -641
- package/src/lib/link-insights.ts +0 -860
- package/src/lib/link-preview-metadata.ts +0 -754
- package/src/lib/live-sync-engine.ts +0 -209
- package/src/lib/live-transport-gateway.ts +0 -128
- package/src/lib/location.ts +0 -137
- package/src/lib/media-fetch.ts +0 -860
- package/src/lib/media-includes.ts +0 -165
- package/src/lib/mention-threads-live.ts +0 -830
- package/src/lib/mentions-export.ts +0 -147
- package/src/lib/mentions-live.ts +0 -1114
- package/src/lib/moderation-target.ts +0 -227
- package/src/lib/moderation-write.ts +0 -131
- package/src/lib/mutes-write.ts +0 -171
- package/src/lib/mutes.ts +0 -84
- package/src/lib/ndjson-stream.ts +0 -106
- package/src/lib/network-map.ts +0 -382
- package/src/lib/openai-response-runtime.ts +0 -251
- package/src/lib/openai.ts +0 -117
- package/src/lib/paginated-sync.ts +0 -93
- package/src/lib/period-digest.ts +0 -1364
- package/src/lib/present.ts +0 -118
- package/src/lib/profile-affiliation-hydration.ts +0 -228
- package/src/lib/profile-affiliations.ts +0 -262
- package/src/lib/profile-analysis.ts +0 -1198
- package/src/lib/profile-bio-entities.ts +0 -318
- package/src/lib/profile-history.ts +0 -164
- package/src/lib/profile-hydration.ts +0 -180
- package/src/lib/profile-replies.ts +0 -77
- package/src/lib/profile-resolver.ts +0 -650
- package/src/lib/queries.ts +0 -6
- package/src/lib/query-actions.ts +0 -437
- package/src/lib/query-client.tsx +0 -47
- package/src/lib/query-read-model-shared.ts +0 -52
- package/src/lib/query-read-models.ts +0 -5
- package/src/lib/query-resource.ts +0 -41
- package/src/lib/query-status.ts +0 -164
- package/src/lib/research.ts +0 -652
- package/src/lib/runtime-services.ts +0 -20
- package/src/lib/search-discussion.ts +0 -812
- package/src/lib/seed.ts +0 -613
- package/src/lib/server-runtime-services.ts +0 -30
- package/src/lib/sqlite.ts +0 -183
- package/src/lib/streaming-ingestion.ts +0 -240
- package/src/lib/sync-cache.ts +0 -70
- package/src/lib/sync-plan.ts +0 -175
- package/src/lib/theme-transition.ts +0 -113
- package/src/lib/theme.tsx +0 -165
- package/src/lib/timeline-collections-live.ts +0 -407
- package/src/lib/timeline-live.ts +0 -302
- package/src/lib/timeline-read-model.ts +0 -1191
- package/src/lib/tweet-account-edges.ts +0 -48
- package/src/lib/tweet-lookup.ts +0 -46
- package/src/lib/tweet-render.ts +0 -430
- package/src/lib/tweet-repository.ts +0 -156
- package/src/lib/tweet-search-live.ts +0 -462
- package/src/lib/types.ts +0 -723
- package/src/lib/ui.ts +0 -529
- package/src/lib/url-expansion-store.ts +0 -110
- package/src/lib/url-expansion.ts +0 -343
- package/src/lib/url-safety.ts +0 -220
- package/src/lib/web-sync.ts +0 -533
- package/src/lib/whois.ts +0 -1080
- package/src/lib/x-profile.ts +0 -365
- package/src/lib/x-web.ts +0 -199
- package/src/lib/xurl-rate-limits.ts +0 -267
- package/src/lib/xurl.ts +0 -1677
- package/src/routeTree.gen.ts +0 -723
- package/src/router.tsx +0 -20
- package/src/routes/__root.tsx +0 -82
- package/src/routes/api/action.tsx +0 -147
- package/src/routes/api/avatar.tsx +0 -50
- package/src/routes/api/blocks.tsx +0 -35
- package/src/routes/api/conversation.tsx +0 -45
- package/src/routes/api/data-sources.tsx +0 -24
- package/src/routes/api/inbox.tsx +0 -43
- package/src/routes/api/link-insights.tsx +0 -85
- package/src/routes/api/link-preview.tsx +0 -47
- package/src/routes/api/network-map.tsx +0 -55
- package/src/routes/api/period-digest.tsx +0 -101
- package/src/routes/api/profile-analysis.tsx +0 -97
- package/src/routes/api/profile-hydrate.tsx +0 -54
- package/src/routes/api/query.tsx +0 -121
- package/src/routes/api/search-discussion.tsx +0 -113
- package/src/routes/api/status.tsx +0 -30
- package/src/routes/api/sync.tsx +0 -108
- package/src/routes/api/xurl-rate-limits.tsx +0 -24
- package/src/routes/blocks.tsx +0 -343
- package/src/routes/bookmarks.tsx +0 -18
- package/src/routes/data-sources.tsx +0 -249
- package/src/routes/discuss.tsx +0 -419
- package/src/routes/dms.tsx +0 -415
- package/src/routes/inbox.tsx +0 -232
- package/src/routes/index.tsx +0 -32
- package/src/routes/likes.tsx +0 -18
- package/src/routes/links.tsx +0 -631
- package/src/routes/mentions.tsx +0 -32
- package/src/routes/network-map.tsx +0 -732
- package/src/routes/profile-analyze.tsx +0 -112
- package/src/routes/profiles.$handle.tsx +0 -228
- package/src/routes/rate-limits.tsx +0 -305
- package/src/routes/today.tsx +0 -511
- package/src/styles.css +0 -257
- package/tsconfig.json +0 -29
- package/vite.config.ts +0 -29
- /package/{public → dist/client}/birdclaw-mark.png +0 -0
- /package/{public → dist/client}/favicon.ico +0 -0
- /package/{public → dist/client}/logo192.png +0 -0
- /package/{public → dist/client}/logo512.png +0 -0
- /package/{public → dist/client}/manifest.json +0 -0
- /package/{public → dist/client}/robots.txt +0 -0
package/src/lib/period-digest.ts
DELETED
|
@@ -1,1364 +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
|
-
readHybridAnalysisStreamEffect,
|
|
9
|
-
resolveAnalysisModelSettings,
|
|
10
|
-
streamHybridAnalysisEffect,
|
|
11
|
-
} from "./analysis-runtime";
|
|
12
|
-
import { maybeAutoSyncBackupEffect } from "./backup";
|
|
13
|
-
import { runEffectPromise } from "./effect-runtime";
|
|
14
|
-
import { getLinkInsights } from "./link-insights";
|
|
15
|
-
import { syncMentionThreadsEffect } from "./mention-threads-live";
|
|
16
|
-
import { syncMentionsEffect } from "./mentions-live";
|
|
17
|
-
import { listDmConversations } from "./dm-read-model";
|
|
18
|
-
import { getTweetsByIds, listTimelineItems } from "./timeline-read-model";
|
|
19
|
-
import {
|
|
20
|
-
type OpenAIStreamState,
|
|
21
|
-
processOpenAIResponseSseChunk,
|
|
22
|
-
} from "./openai-response-runtime";
|
|
23
|
-
import { readSyncCache, writeSyncCache } from "./sync-cache";
|
|
24
|
-
import { syncHomeTimelineEffect, type HomeTimelineMode } from "./timeline-live";
|
|
25
|
-
import type { EmbeddedTweet, ProfileRecord, TweetEntities } from "./types";
|
|
26
|
-
|
|
27
|
-
export type PeriodDigestPreset = "today" | "yesterday" | "24h" | "week";
|
|
28
|
-
export type PeriodDigestSourceKind =
|
|
29
|
-
| "home"
|
|
30
|
-
| "mentions"
|
|
31
|
-
| "authored"
|
|
32
|
-
| "likes"
|
|
33
|
-
| "bookmarks"
|
|
34
|
-
| "dms";
|
|
35
|
-
|
|
36
|
-
export interface PeriodDigestOptions {
|
|
37
|
-
period?: string;
|
|
38
|
-
since?: string;
|
|
39
|
-
until?: string;
|
|
40
|
-
account?: string;
|
|
41
|
-
includeDms?: boolean;
|
|
42
|
-
refresh?: boolean;
|
|
43
|
-
model?: string;
|
|
44
|
-
language?: string;
|
|
45
|
-
reasoningEffort?: "minimal" | "low" | "medium" | "high";
|
|
46
|
-
serviceTier?: "default" | "flex" | "priority";
|
|
47
|
-
signal?: AbortSignal;
|
|
48
|
-
maxTweets?: number;
|
|
49
|
-
maxLinks?: number;
|
|
50
|
-
liveSync?: boolean;
|
|
51
|
-
liveSyncMode?: HomeTimelineMode;
|
|
52
|
-
liveTimelineLimit?: number;
|
|
53
|
-
liveTimelineMaxPages?: number;
|
|
54
|
-
liveMentionsLimit?: number;
|
|
55
|
-
liveMentionsMaxPages?: number;
|
|
56
|
-
liveThreadLimit?: number;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export interface PeriodDigestWindow {
|
|
60
|
-
label: string;
|
|
61
|
-
since: string;
|
|
62
|
-
until: string;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export interface PeriodDigestRunResult {
|
|
66
|
-
context: PeriodDigestContext;
|
|
67
|
-
digest: PeriodDigest;
|
|
68
|
-
markdown: string;
|
|
69
|
-
model: string;
|
|
70
|
-
reasoningEffort: string;
|
|
71
|
-
serviceTier: string;
|
|
72
|
-
cached: boolean;
|
|
73
|
-
updatedAt: string;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export interface PeriodDigestStreamHandlers {
|
|
77
|
-
onDelta?: (delta: string) => void;
|
|
78
|
-
onEvent?: (event: PeriodDigestStreamEvent) => void;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export type PeriodDigestStreamEvent =
|
|
82
|
-
| { type: "status"; label: string; detail?: string }
|
|
83
|
-
| { type: "start"; context: PeriodDigestContext; cached: boolean }
|
|
84
|
-
| { type: "delta"; delta: string }
|
|
85
|
-
| { type: "done"; result: PeriodDigestRunResult }
|
|
86
|
-
| { type: "error"; error: string };
|
|
87
|
-
|
|
88
|
-
const PeriodDigestSchema = z.object({
|
|
89
|
-
title: z.string().min(1),
|
|
90
|
-
summary: z.string().min(1),
|
|
91
|
-
keyTopics: z.array(
|
|
92
|
-
z.object({
|
|
93
|
-
title: z.string().min(1),
|
|
94
|
-
summary: z.string().min(1),
|
|
95
|
-
tweetIds: z.array(z.string()).default([]),
|
|
96
|
-
handles: z.array(z.string()).default([]),
|
|
97
|
-
}),
|
|
98
|
-
),
|
|
99
|
-
notableLinks: z.array(
|
|
100
|
-
z.object({
|
|
101
|
-
title: z.string().min(1),
|
|
102
|
-
url: z.string().min(1),
|
|
103
|
-
why: z.string().min(1),
|
|
104
|
-
sourceTweetIds: z.array(z.string()).default([]),
|
|
105
|
-
}),
|
|
106
|
-
),
|
|
107
|
-
people: z.array(
|
|
108
|
-
z.object({
|
|
109
|
-
handle: z.string().min(1),
|
|
110
|
-
name: z.string().optional(),
|
|
111
|
-
why: z.string().min(1),
|
|
112
|
-
}),
|
|
113
|
-
),
|
|
114
|
-
actionItems: z.array(
|
|
115
|
-
z.object({
|
|
116
|
-
kind: z.enum(["reply", "follow_up", "read", "sync"]),
|
|
117
|
-
label: z.string().min(1),
|
|
118
|
-
tweetId: z.string().optional(),
|
|
119
|
-
dmConversationId: z.string().optional(),
|
|
120
|
-
}),
|
|
121
|
-
),
|
|
122
|
-
sourceTweetIds: z.array(z.string()).default([]),
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
const MAX_DIGEST_LANGUAGE_LENGTH = 64;
|
|
126
|
-
|
|
127
|
-
export function normalizeDigestLanguage(
|
|
128
|
-
value: string | undefined,
|
|
129
|
-
): string | undefined {
|
|
130
|
-
const trimmed = value?.trim();
|
|
131
|
-
if (!trimmed) return undefined;
|
|
132
|
-
if (
|
|
133
|
-
trimmed.length > MAX_DIGEST_LANGUAGE_LENGTH ||
|
|
134
|
-
!/^[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(trimmed)
|
|
135
|
-
) {
|
|
136
|
-
throw new Error(
|
|
137
|
-
"Digest language must be a valid Unicode locale identifier such as en, zh-CN, or pt-BR",
|
|
138
|
-
);
|
|
139
|
-
}
|
|
140
|
-
try {
|
|
141
|
-
const [canonical] = Intl.getCanonicalLocales(trimmed);
|
|
142
|
-
if (!canonical) throw new Error("missing canonical locale");
|
|
143
|
-
return canonical;
|
|
144
|
-
} catch {
|
|
145
|
-
throw new Error(
|
|
146
|
-
"Digest language must be a valid Unicode locale identifier such as en, zh-CN, or pt-BR",
|
|
147
|
-
);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export type PeriodDigest = z.infer<typeof PeriodDigestSchema>;
|
|
152
|
-
|
|
153
|
-
interface CompactTweet {
|
|
154
|
-
id: string;
|
|
155
|
-
url: string;
|
|
156
|
-
source: PeriodDigestSourceKind;
|
|
157
|
-
author: string;
|
|
158
|
-
name: string;
|
|
159
|
-
authorProfile: ProfileRecord;
|
|
160
|
-
createdAt: string;
|
|
161
|
-
text: string;
|
|
162
|
-
entities?: TweetEntities;
|
|
163
|
-
likeCount: number;
|
|
164
|
-
liked: boolean;
|
|
165
|
-
bookmarked: boolean;
|
|
166
|
-
needsReply: boolean;
|
|
167
|
-
replyToId?: string | null;
|
|
168
|
-
replyToTweet?: {
|
|
169
|
-
id: string;
|
|
170
|
-
url: string;
|
|
171
|
-
author: string;
|
|
172
|
-
name: string;
|
|
173
|
-
createdAt: string;
|
|
174
|
-
text: string;
|
|
175
|
-
} | null;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
interface CompactDm {
|
|
179
|
-
id: string;
|
|
180
|
-
participant: string;
|
|
181
|
-
name: string;
|
|
182
|
-
lastMessageAt: string;
|
|
183
|
-
text: string;
|
|
184
|
-
needsReply: boolean;
|
|
185
|
-
influenceScore: number;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
interface CompactLink {
|
|
189
|
-
title: string;
|
|
190
|
-
url: string;
|
|
191
|
-
displayUrl: string;
|
|
192
|
-
description?: string | null;
|
|
193
|
-
shareCount: number;
|
|
194
|
-
commentCount: number;
|
|
195
|
-
lastSeenAt: string;
|
|
196
|
-
mentions: Array<{
|
|
197
|
-
id: string;
|
|
198
|
-
sourceKind: string;
|
|
199
|
-
sourceId: string;
|
|
200
|
-
createdAt: string;
|
|
201
|
-
author?: string;
|
|
202
|
-
text: string;
|
|
203
|
-
tweetId?: string | null;
|
|
204
|
-
}>;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
export interface PeriodDigestContext {
|
|
208
|
-
window: PeriodDigestWindow;
|
|
209
|
-
account?: string;
|
|
210
|
-
includeDms: boolean;
|
|
211
|
-
counts: Record<PeriodDigestSourceKind | "links", number>;
|
|
212
|
-
tweets: CompactTweet[];
|
|
213
|
-
dms: CompactDm[];
|
|
214
|
-
links: CompactLink[];
|
|
215
|
-
hash: string;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
const DEFAULT_MAX_TWEETS = 2_500;
|
|
219
|
-
const DEFAULT_MAX_LINKS = 12;
|
|
220
|
-
const DEFAULT_LIVE_TIMELINE_MAX_PAGES = undefined;
|
|
221
|
-
const DEFAULT_LIVE_MENTIONS_LIMIT = 100;
|
|
222
|
-
const DEFAULT_LIVE_MENTIONS_MAX_PAGES = undefined;
|
|
223
|
-
const DEFAULT_LIVE_THREAD_LIMIT = 12;
|
|
224
|
-
const DEFAULT_LIVE_THREAD_TIMEOUT_MS = 5_000;
|
|
225
|
-
const DEFAULT_DIGEST_FRESHNESS_MS = 5 * 60_000;
|
|
226
|
-
const MAX_PROMPT_DATA_CHARS = 1_200_000;
|
|
227
|
-
const DELIMITER_PATTERN = /\n---\s*\n/;
|
|
228
|
-
|
|
229
|
-
function toError(error: unknown) {
|
|
230
|
-
return error instanceof Error ? error : new Error(String(error));
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
function tryDigestSync<T>(try_: () => T): Effect.Effect<T, Error> {
|
|
234
|
-
return Effect.try({
|
|
235
|
-
try: try_,
|
|
236
|
-
catch: toError,
|
|
237
|
-
});
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function localDateStart(date: Date) {
|
|
241
|
-
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function addDays(date: Date, days: number) {
|
|
245
|
-
const next = new Date(date);
|
|
246
|
-
next.setDate(next.getDate() + days);
|
|
247
|
-
return next;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
function parseDate(value: string | undefined) {
|
|
251
|
-
if (!value?.trim()) return null;
|
|
252
|
-
const parsed = new Date(value);
|
|
253
|
-
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function floorIsoToHour(value: string) {
|
|
257
|
-
const date = new Date(value);
|
|
258
|
-
date.setUTCMinutes(0, 0, 0);
|
|
259
|
-
return date.toISOString();
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
function normalizePeriod(value: string | undefined): PeriodDigestPreset {
|
|
263
|
-
const normalized = value?.trim().toLowerCase();
|
|
264
|
-
if (normalized === "yesterday") return "yesterday";
|
|
265
|
-
if (normalized === "24h" || normalized === "day") return "24h";
|
|
266
|
-
if (normalized === "week" || normalized === "7d") return "week";
|
|
267
|
-
return "today";
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
export function resolvePeriodDigestWindow(
|
|
271
|
-
options: Pick<PeriodDigestOptions, "period" | "since" | "until"> & {
|
|
272
|
-
now?: Date;
|
|
273
|
-
} = {},
|
|
274
|
-
): PeriodDigestWindow {
|
|
275
|
-
const now = options.now ?? new Date();
|
|
276
|
-
const explicitSince = parseDate(options.since);
|
|
277
|
-
const explicitUntil = parseDate(options.until);
|
|
278
|
-
if (explicitSince || explicitUntil) {
|
|
279
|
-
const since = explicitSince ?? addDays(explicitUntil ?? now, -1);
|
|
280
|
-
const until = explicitUntil ?? now;
|
|
281
|
-
return {
|
|
282
|
-
label: `${since.toLocaleString()} - ${until.toLocaleString()}`,
|
|
283
|
-
since: since.toISOString(),
|
|
284
|
-
until: until.toISOString(),
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
const period = normalizePeriod(options.period);
|
|
289
|
-
if (period === "24h") {
|
|
290
|
-
const since = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
291
|
-
return {
|
|
292
|
-
label: "Last 24 hours",
|
|
293
|
-
since: since.toISOString(),
|
|
294
|
-
until: now.toISOString(),
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
if (period === "week") {
|
|
298
|
-
const since = addDays(now, -7);
|
|
299
|
-
return {
|
|
300
|
-
label: "Last 7 days",
|
|
301
|
-
since: since.toISOString(),
|
|
302
|
-
until: now.toISOString(),
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
if (period === "yesterday") {
|
|
306
|
-
const today = localDateStart(now);
|
|
307
|
-
const yesterday = addDays(today, -1);
|
|
308
|
-
return {
|
|
309
|
-
label: "Yesterday",
|
|
310
|
-
since: yesterday.toISOString(),
|
|
311
|
-
until: today.toISOString(),
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
const start = localDateStart(now);
|
|
316
|
-
return {
|
|
317
|
-
label: "Today",
|
|
318
|
-
since: start.toISOString(),
|
|
319
|
-
until: now.toISOString(),
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
function tweetUrl(handle: string, id: string) {
|
|
324
|
-
return `https://x.com/${handle}/status/${id}`;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
function compactTweet(
|
|
328
|
-
source: PeriodDigestSourceKind,
|
|
329
|
-
item: ReturnType<typeof listTimelineItems>[number],
|
|
330
|
-
): CompactTweet {
|
|
331
|
-
const replyToTweet = item.replyToTweet
|
|
332
|
-
? {
|
|
333
|
-
id: item.replyToTweet.id,
|
|
334
|
-
url: tweetUrl(item.replyToTweet.author.handle, item.replyToTweet.id),
|
|
335
|
-
author: item.replyToTweet.author.handle,
|
|
336
|
-
name: item.replyToTweet.author.displayName,
|
|
337
|
-
createdAt: item.replyToTweet.createdAt,
|
|
338
|
-
text: item.replyToTweet.text,
|
|
339
|
-
}
|
|
340
|
-
: null;
|
|
341
|
-
return {
|
|
342
|
-
id: item.id,
|
|
343
|
-
url: tweetUrl(item.author.handle, item.id),
|
|
344
|
-
source,
|
|
345
|
-
author: item.author.handle,
|
|
346
|
-
name: item.author.displayName,
|
|
347
|
-
authorProfile: item.author,
|
|
348
|
-
createdAt: item.createdAt,
|
|
349
|
-
text: item.text,
|
|
350
|
-
entities: item.entities,
|
|
351
|
-
likeCount: item.likeCount,
|
|
352
|
-
liked: item.liked,
|
|
353
|
-
bookmarked: item.bookmarked,
|
|
354
|
-
needsReply: !item.isReplied,
|
|
355
|
-
replyToId: item.replyToId ?? null,
|
|
356
|
-
replyToTweet,
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
function compactEmbeddedTweet(item: EmbeddedTweet): CompactTweet {
|
|
361
|
-
return {
|
|
362
|
-
id: item.id,
|
|
363
|
-
url: tweetUrl(item.author.handle, item.id),
|
|
364
|
-
source: "home",
|
|
365
|
-
author: item.author.handle,
|
|
366
|
-
name: item.author.displayName,
|
|
367
|
-
authorProfile: item.author,
|
|
368
|
-
createdAt: item.createdAt,
|
|
369
|
-
text: item.text,
|
|
370
|
-
entities: item.entities,
|
|
371
|
-
likeCount: item.likeCount ?? 0,
|
|
372
|
-
liked: Boolean(item.liked),
|
|
373
|
-
bookmarked: Boolean(item.bookmarked),
|
|
374
|
-
needsReply: !item.isReplied,
|
|
375
|
-
replyToId: item.replyToId ?? null,
|
|
376
|
-
replyToTweet: null,
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
function dedupeTweets(tweets: CompactTweet[]) {
|
|
381
|
-
const seen = new Set<string>();
|
|
382
|
-
const items: CompactTweet[] = [];
|
|
383
|
-
for (const tweet of tweets) {
|
|
384
|
-
if (seen.has(tweet.id)) continue;
|
|
385
|
-
seen.add(tweet.id);
|
|
386
|
-
items.push(tweet);
|
|
387
|
-
}
|
|
388
|
-
return items.sort((left, right) =>
|
|
389
|
-
right.createdAt.localeCompare(left.createdAt),
|
|
390
|
-
);
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
function collectTweetsForSource(
|
|
394
|
-
source: Exclude<PeriodDigestSourceKind, "dms">,
|
|
395
|
-
options: {
|
|
396
|
-
account?: string;
|
|
397
|
-
window: PeriodDigestWindow;
|
|
398
|
-
limit: number;
|
|
399
|
-
},
|
|
400
|
-
) {
|
|
401
|
-
if (source === "likes" || source === "bookmarks") {
|
|
402
|
-
return listTimelineItems({
|
|
403
|
-
resource: "home",
|
|
404
|
-
account: options.account,
|
|
405
|
-
since: options.window.since,
|
|
406
|
-
until: options.window.until,
|
|
407
|
-
likedOnly: source === "likes",
|
|
408
|
-
bookmarkedOnly: source === "bookmarks",
|
|
409
|
-
limit: Math.ceil(options.limit / 3),
|
|
410
|
-
}).map((item) => compactTweet(source, item));
|
|
411
|
-
}
|
|
412
|
-
return listTimelineItems({
|
|
413
|
-
resource: source,
|
|
414
|
-
account: options.account,
|
|
415
|
-
since: options.window.since,
|
|
416
|
-
until: options.window.until,
|
|
417
|
-
limit: source === "home" ? options.limit : Math.ceil(options.limit / 2),
|
|
418
|
-
}).map((item) => compactTweet(source, item));
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
function collectDms(options: {
|
|
422
|
-
account?: string;
|
|
423
|
-
includeDms: boolean;
|
|
424
|
-
window: PeriodDigestWindow;
|
|
425
|
-
limit: number;
|
|
426
|
-
}) {
|
|
427
|
-
if (!options.includeDms) return [];
|
|
428
|
-
return listDmConversations({
|
|
429
|
-
account: options.account,
|
|
430
|
-
since: options.window.since,
|
|
431
|
-
until: options.window.until,
|
|
432
|
-
sort: "recent",
|
|
433
|
-
limit: options.limit,
|
|
434
|
-
}).map(
|
|
435
|
-
(item): CompactDm => ({
|
|
436
|
-
id: item.id,
|
|
437
|
-
participant: item.participant.handle,
|
|
438
|
-
name: item.participant.displayName,
|
|
439
|
-
lastMessageAt: item.lastMessageAt,
|
|
440
|
-
text: item.lastMessagePreview,
|
|
441
|
-
needsReply: item.needsReply,
|
|
442
|
-
influenceScore: item.influenceScore,
|
|
443
|
-
}),
|
|
444
|
-
);
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
function compactLinks(options: {
|
|
448
|
-
account?: string;
|
|
449
|
-
window: PeriodDigestWindow;
|
|
450
|
-
limit: number;
|
|
451
|
-
}) {
|
|
452
|
-
return getLinkInsights({
|
|
453
|
-
account: options.account,
|
|
454
|
-
range: "today",
|
|
455
|
-
sort: "rank",
|
|
456
|
-
source: "tweet",
|
|
457
|
-
since: options.window.since,
|
|
458
|
-
until: options.window.until,
|
|
459
|
-
limit: options.limit,
|
|
460
|
-
commentsLimit: 5,
|
|
461
|
-
}).items.map(
|
|
462
|
-
(item): CompactLink => ({
|
|
463
|
-
title: item.title ?? item.displayUrl,
|
|
464
|
-
url: item.url,
|
|
465
|
-
displayUrl: item.displayUrl,
|
|
466
|
-
description: item.description,
|
|
467
|
-
shareCount: item.shareCount,
|
|
468
|
-
commentCount: item.commentCount,
|
|
469
|
-
lastSeenAt: item.lastSeenAt,
|
|
470
|
-
mentions: item.mentions.slice(0, 5).map((mention) => ({
|
|
471
|
-
id: mention.id,
|
|
472
|
-
sourceKind: mention.sourceKind,
|
|
473
|
-
sourceId: mention.sourceId,
|
|
474
|
-
createdAt: mention.createdAt,
|
|
475
|
-
author: mention.sharedBy?.handle,
|
|
476
|
-
text:
|
|
477
|
-
mention.commentText || mention.sharedContentText || mention.rawText,
|
|
478
|
-
tweetId: mention.timelineTweetId ?? mention.contentTweetId,
|
|
479
|
-
})),
|
|
480
|
-
}),
|
|
481
|
-
);
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
function contextHash(context: Omit<PeriodDigestContext, "hash">) {
|
|
485
|
-
return createHash("sha1")
|
|
486
|
-
.update(
|
|
487
|
-
JSON.stringify({
|
|
488
|
-
window: {
|
|
489
|
-
label: context.window.label,
|
|
490
|
-
bucket: context.window.until.slice(0, 10),
|
|
491
|
-
},
|
|
492
|
-
account: context.account,
|
|
493
|
-
includeDms: context.includeDms,
|
|
494
|
-
tweets: context.tweets.map((tweet) => [
|
|
495
|
-
tweet.id,
|
|
496
|
-
tweet.url,
|
|
497
|
-
tweet.source,
|
|
498
|
-
tweet.author,
|
|
499
|
-
tweet.name,
|
|
500
|
-
tweet.authorProfile.bio,
|
|
501
|
-
tweet.authorProfile.followersCount,
|
|
502
|
-
tweet.createdAt,
|
|
503
|
-
tweet.text,
|
|
504
|
-
tweet.likeCount,
|
|
505
|
-
tweet.liked,
|
|
506
|
-
tweet.bookmarked,
|
|
507
|
-
tweet.needsReply,
|
|
508
|
-
tweet.replyToId,
|
|
509
|
-
tweet.replyToTweet?.id,
|
|
510
|
-
tweet.replyToTweet?.text,
|
|
511
|
-
]),
|
|
512
|
-
dms: context.dms.map((dm) => [
|
|
513
|
-
dm.id,
|
|
514
|
-
dm.lastMessageAt,
|
|
515
|
-
dm.text,
|
|
516
|
-
dm.needsReply,
|
|
517
|
-
]),
|
|
518
|
-
links: context.links.map((link) => [
|
|
519
|
-
link.url,
|
|
520
|
-
link.shareCount,
|
|
521
|
-
link.commentCount,
|
|
522
|
-
link.lastSeenAt,
|
|
523
|
-
]),
|
|
524
|
-
}),
|
|
525
|
-
)
|
|
526
|
-
.digest("hex");
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
export function collectPeriodDigestContext(
|
|
530
|
-
options: PeriodDigestOptions = {},
|
|
531
|
-
): PeriodDigestContext {
|
|
532
|
-
const window = resolvePeriodDigestWindow(options);
|
|
533
|
-
const maxTweets = Math.max(
|
|
534
|
-
20,
|
|
535
|
-
Math.trunc(options.maxTweets ?? DEFAULT_MAX_TWEETS),
|
|
536
|
-
);
|
|
537
|
-
const maxLinks = Math.max(
|
|
538
|
-
3,
|
|
539
|
-
Math.trunc(options.maxLinks ?? DEFAULT_MAX_LINKS),
|
|
540
|
-
);
|
|
541
|
-
const home = collectTweetsForSource("home", {
|
|
542
|
-
account: options.account,
|
|
543
|
-
window,
|
|
544
|
-
limit: maxTweets,
|
|
545
|
-
});
|
|
546
|
-
const mentions = collectTweetsForSource("mentions", {
|
|
547
|
-
account: options.account,
|
|
548
|
-
window,
|
|
549
|
-
limit: maxTweets,
|
|
550
|
-
});
|
|
551
|
-
const authored = collectTweetsForSource("authored", {
|
|
552
|
-
account: options.account,
|
|
553
|
-
window,
|
|
554
|
-
limit: maxTweets,
|
|
555
|
-
});
|
|
556
|
-
const likes = collectTweetsForSource("likes", {
|
|
557
|
-
account: options.account,
|
|
558
|
-
window,
|
|
559
|
-
limit: maxTweets,
|
|
560
|
-
});
|
|
561
|
-
const bookmarks = collectTweetsForSource("bookmarks", {
|
|
562
|
-
account: options.account,
|
|
563
|
-
window,
|
|
564
|
-
limit: maxTweets,
|
|
565
|
-
});
|
|
566
|
-
const dms = collectDms({
|
|
567
|
-
account: options.account,
|
|
568
|
-
includeDms: Boolean(options.includeDms),
|
|
569
|
-
window,
|
|
570
|
-
limit: Math.ceil(maxTweets / 3),
|
|
571
|
-
});
|
|
572
|
-
const links = compactLinks({
|
|
573
|
-
account: options.account,
|
|
574
|
-
window,
|
|
575
|
-
limit: maxLinks,
|
|
576
|
-
});
|
|
577
|
-
const tweets = dedupeTweets([
|
|
578
|
-
...home,
|
|
579
|
-
...mentions,
|
|
580
|
-
...authored,
|
|
581
|
-
...likes,
|
|
582
|
-
...bookmarks,
|
|
583
|
-
]).slice(0, maxTweets);
|
|
584
|
-
const withoutHash = {
|
|
585
|
-
window,
|
|
586
|
-
...(options.account ? { account: options.account } : {}),
|
|
587
|
-
includeDms: Boolean(options.includeDms),
|
|
588
|
-
counts: {
|
|
589
|
-
home: home.length,
|
|
590
|
-
mentions: mentions.length,
|
|
591
|
-
authored: authored.length,
|
|
592
|
-
likes: likes.length,
|
|
593
|
-
bookmarks: bookmarks.length,
|
|
594
|
-
dms: dms.length,
|
|
595
|
-
links: links.length,
|
|
596
|
-
},
|
|
597
|
-
tweets,
|
|
598
|
-
dms,
|
|
599
|
-
links,
|
|
600
|
-
} satisfies Omit<PeriodDigestContext, "hash">;
|
|
601
|
-
return {
|
|
602
|
-
...withoutHash,
|
|
603
|
-
hash: contextHash(withoutHash),
|
|
604
|
-
};
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
function languageFromOptions(options: PeriodDigestOptions) {
|
|
608
|
-
return normalizeDigestLanguage(
|
|
609
|
-
options.language ?? process.env.BIRDCLAW_DIGEST_LANGUAGE,
|
|
610
|
-
);
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
function modelFromOptions(options: PeriodDigestOptions) {
|
|
614
|
-
return resolveAnalysisModelSettings(options).model;
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
function reasoningEffortFromOptions(options: PeriodDigestOptions) {
|
|
618
|
-
return resolveAnalysisModelSettings(options).reasoningEffort;
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
function serviceTierFromOptions(options: PeriodDigestOptions) {
|
|
622
|
-
return resolveAnalysisModelSettings(options).serviceTier;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
function boundedPositiveInteger(
|
|
626
|
-
value: number | undefined,
|
|
627
|
-
fallback: number,
|
|
628
|
-
max: number,
|
|
629
|
-
) {
|
|
630
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value < 1) {
|
|
631
|
-
return fallback;
|
|
632
|
-
}
|
|
633
|
-
return Math.min(max, Math.floor(value));
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
function emitDigestStatus(
|
|
637
|
-
handlers: PeriodDigestStreamHandlers,
|
|
638
|
-
label: string,
|
|
639
|
-
detail?: string,
|
|
640
|
-
) {
|
|
641
|
-
handlers.onEvent?.({
|
|
642
|
-
type: "status",
|
|
643
|
-
label,
|
|
644
|
-
...(detail ? { detail } : {}),
|
|
645
|
-
});
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
function formatFetchedStatus({
|
|
649
|
-
fetched,
|
|
650
|
-
total,
|
|
651
|
-
noun,
|
|
652
|
-
}: {
|
|
653
|
-
fetched: number;
|
|
654
|
-
total: number;
|
|
655
|
-
noun: string;
|
|
656
|
-
}) {
|
|
657
|
-
const count = `${String(Math.min(fetched, total))}/${String(total)}`;
|
|
658
|
-
return `Fetched ${count} ${noun}`;
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
function formatPageDetail({
|
|
662
|
-
source,
|
|
663
|
-
page,
|
|
664
|
-
maxPages,
|
|
665
|
-
done,
|
|
666
|
-
}: {
|
|
667
|
-
source: string;
|
|
668
|
-
page?: number;
|
|
669
|
-
maxPages?: number;
|
|
670
|
-
done: boolean;
|
|
671
|
-
}) {
|
|
672
|
-
const pageText =
|
|
673
|
-
page === undefined
|
|
674
|
-
? undefined
|
|
675
|
-
: `page ${String(page)}${maxPages === undefined ? "" : `/${String(maxPages)}`}`;
|
|
676
|
-
return [source, pageText, done ? "done" : undefined]
|
|
677
|
-
.filter(Boolean)
|
|
678
|
-
.join(" · ");
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
function refreshPeriodDigestInputsEffect(
|
|
682
|
-
options: PeriodDigestOptions,
|
|
683
|
-
phase: {
|
|
684
|
-
timeline?: boolean;
|
|
685
|
-
mentions?: boolean;
|
|
686
|
-
threads?: boolean;
|
|
687
|
-
threadTweetIds?: string[];
|
|
688
|
-
} = {},
|
|
689
|
-
handlers: PeriodDigestStreamHandlers = {},
|
|
690
|
-
): Effect.Effect<void, unknown> {
|
|
691
|
-
if (!options.liveSync) {
|
|
692
|
-
return Effect.void;
|
|
693
|
-
}
|
|
694
|
-
const includeTimeline = phase.timeline ?? true;
|
|
695
|
-
const includeMentions = phase.mentions ?? true;
|
|
696
|
-
const includeThreads = phase.threads ?? true;
|
|
697
|
-
const window = resolvePeriodDigestWindow(options);
|
|
698
|
-
const liveStartTime = floorIsoToHour(window.since);
|
|
699
|
-
const mode = options.liveSyncMode ?? "xurl";
|
|
700
|
-
const contextTweetBudget = Math.max(
|
|
701
|
-
20,
|
|
702
|
-
Math.trunc(options.maxTweets ?? DEFAULT_MAX_TWEETS),
|
|
703
|
-
);
|
|
704
|
-
const timelineLimit =
|
|
705
|
-
options.liveTimelineLimit === undefined
|
|
706
|
-
? undefined
|
|
707
|
-
: boundedPositiveInteger(options.liveTimelineLimit, 300, 100_000);
|
|
708
|
-
const mentionsLimit = boundedPositiveInteger(
|
|
709
|
-
options.liveMentionsLimit,
|
|
710
|
-
DEFAULT_LIVE_MENTIONS_LIMIT,
|
|
711
|
-
100,
|
|
712
|
-
);
|
|
713
|
-
const threadLimit = boundedPositiveInteger(
|
|
714
|
-
options.liveThreadLimit,
|
|
715
|
-
DEFAULT_LIVE_THREAD_LIMIT,
|
|
716
|
-
100,
|
|
717
|
-
);
|
|
718
|
-
const timelineMaxPages =
|
|
719
|
-
options.liveTimelineMaxPages === undefined
|
|
720
|
-
? DEFAULT_LIVE_TIMELINE_MAX_PAGES
|
|
721
|
-
: boundedPositiveInteger(options.liveTimelineMaxPages, 3, 1_000);
|
|
722
|
-
const mentionsMaxPages =
|
|
723
|
-
options.liveMentionsMaxPages === undefined
|
|
724
|
-
? DEFAULT_LIVE_MENTIONS_MAX_PAGES
|
|
725
|
-
: boundedPositiveInteger(options.liveMentionsMaxPages, 3, 1_000);
|
|
726
|
-
|
|
727
|
-
return Effect.gen(function* () {
|
|
728
|
-
if (includeTimeline) {
|
|
729
|
-
yield* Effect.sync(() =>
|
|
730
|
-
emitDigestStatus(
|
|
731
|
-
handlers,
|
|
732
|
-
"Fetching home timeline from X",
|
|
733
|
-
"Walking the selected time window with xurl.",
|
|
734
|
-
),
|
|
735
|
-
);
|
|
736
|
-
const result = yield* syncHomeTimelineEffect({
|
|
737
|
-
account: options.account,
|
|
738
|
-
mode,
|
|
739
|
-
limit: timelineLimit,
|
|
740
|
-
maxPages: timelineMaxPages,
|
|
741
|
-
startTime: liveStartTime,
|
|
742
|
-
following: true,
|
|
743
|
-
refresh: Boolean(options.refresh),
|
|
744
|
-
cacheTtlMs: 2 * 60_000,
|
|
745
|
-
timeoutMs: 30_000,
|
|
746
|
-
onProgress: (progress) =>
|
|
747
|
-
emitDigestStatus(
|
|
748
|
-
handlers,
|
|
749
|
-
formatFetchedStatus({
|
|
750
|
-
fetched: progress.fetched,
|
|
751
|
-
total: progress.total ?? contextTweetBudget,
|
|
752
|
-
noun: "home tweets",
|
|
753
|
-
}),
|
|
754
|
-
formatPageDetail({
|
|
755
|
-
source: progress.source,
|
|
756
|
-
page: progress.page,
|
|
757
|
-
maxPages: progress.maxPages,
|
|
758
|
-
done: progress.done,
|
|
759
|
-
}),
|
|
760
|
-
),
|
|
761
|
-
}).pipe(
|
|
762
|
-
Effect.match({
|
|
763
|
-
onFailure: () => null,
|
|
764
|
-
onSuccess: (value) => value,
|
|
765
|
-
}),
|
|
766
|
-
);
|
|
767
|
-
yield* Effect.sync(() =>
|
|
768
|
-
emitDigestStatus(
|
|
769
|
-
handlers,
|
|
770
|
-
result
|
|
771
|
-
? `Fetched ${String(result.count)} home tweets from ${result.source}`
|
|
772
|
-
: "Home timeline fetch failed; using local data",
|
|
773
|
-
),
|
|
774
|
-
);
|
|
775
|
-
}
|
|
776
|
-
if (includeMentions) {
|
|
777
|
-
yield* Effect.sync(() =>
|
|
778
|
-
emitDigestStatus(
|
|
779
|
-
handlers,
|
|
780
|
-
"Fetching mentions from X",
|
|
781
|
-
"Reading replies and mentions for the selected window.",
|
|
782
|
-
),
|
|
783
|
-
);
|
|
784
|
-
const result = yield* syncMentionsEffect({
|
|
785
|
-
account: options.account,
|
|
786
|
-
mode: "xurl",
|
|
787
|
-
limit: mentionsLimit,
|
|
788
|
-
maxPages: mentionsMaxPages,
|
|
789
|
-
startTime: liveStartTime,
|
|
790
|
-
refresh: Boolean(options.refresh),
|
|
791
|
-
cacheTtlMs: 2 * 60_000,
|
|
792
|
-
onProgress: (progress) =>
|
|
793
|
-
emitDigestStatus(
|
|
794
|
-
handlers,
|
|
795
|
-
formatFetchedStatus({
|
|
796
|
-
fetched: progress.fetched,
|
|
797
|
-
total: progress.total ?? contextTweetBudget,
|
|
798
|
-
noun: "mentions",
|
|
799
|
-
}),
|
|
800
|
-
formatPageDetail({
|
|
801
|
-
source: progress.source,
|
|
802
|
-
page: progress.page,
|
|
803
|
-
maxPages: progress.maxPages,
|
|
804
|
-
done: progress.done,
|
|
805
|
-
}),
|
|
806
|
-
),
|
|
807
|
-
}).pipe(
|
|
808
|
-
Effect.match({
|
|
809
|
-
onFailure: () => null,
|
|
810
|
-
onSuccess: (value) => value,
|
|
811
|
-
}),
|
|
812
|
-
);
|
|
813
|
-
yield* Effect.sync(() =>
|
|
814
|
-
emitDigestStatus(
|
|
815
|
-
handlers,
|
|
816
|
-
result
|
|
817
|
-
? `Fetched ${String(result.count)} mentions from ${result.source}`
|
|
818
|
-
: "Mention fetch failed; using local data",
|
|
819
|
-
),
|
|
820
|
-
);
|
|
821
|
-
}
|
|
822
|
-
if (includeThreads) {
|
|
823
|
-
yield* Effect.sync(() =>
|
|
824
|
-
emitDigestStatus(
|
|
825
|
-
handlers,
|
|
826
|
-
"Fetching mention conversations",
|
|
827
|
-
"Pulling parent tweets so the AI sees what replies refer to.",
|
|
828
|
-
),
|
|
829
|
-
);
|
|
830
|
-
const result = yield* syncMentionThreadsEffect({
|
|
831
|
-
account: options.account,
|
|
832
|
-
mode: "xurl",
|
|
833
|
-
limit: threadLimit,
|
|
834
|
-
tweetIds: phase.threadTweetIds,
|
|
835
|
-
delayMs: 100,
|
|
836
|
-
timeoutMs: DEFAULT_LIVE_THREAD_TIMEOUT_MS,
|
|
837
|
-
maxPages: 2,
|
|
838
|
-
onProgress: (progress) =>
|
|
839
|
-
emitDigestStatus(
|
|
840
|
-
handlers,
|
|
841
|
-
`Fetched conversations for ${String(progress.processed)}/${String(progress.total)} mentions`,
|
|
842
|
-
`${String(progress.fetched)} tweets · ${progress.source}${
|
|
843
|
-
progress.done ? " · done" : ""
|
|
844
|
-
}`,
|
|
845
|
-
),
|
|
846
|
-
}).pipe(
|
|
847
|
-
Effect.match({
|
|
848
|
-
onFailure: () => null,
|
|
849
|
-
onSuccess: (value) => value,
|
|
850
|
-
}),
|
|
851
|
-
);
|
|
852
|
-
yield* Effect.sync(() =>
|
|
853
|
-
emitDigestStatus(
|
|
854
|
-
handlers,
|
|
855
|
-
result
|
|
856
|
-
? `Fetched ${String(result.uniqueTweets)} conversation tweets`
|
|
857
|
-
: "Conversation fetch failed; using available context",
|
|
858
|
-
),
|
|
859
|
-
);
|
|
860
|
-
}
|
|
861
|
-
yield* Effect.sync(() =>
|
|
862
|
-
emitDigestStatus(handlers, "Preparing local AI context"),
|
|
863
|
-
);
|
|
864
|
-
yield* maybeAutoSyncBackupEffect().pipe(Effect.catchAll(() => Effect.void));
|
|
865
|
-
}).pipe(Effect.asVoid);
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
function digestCacheKey(
|
|
869
|
-
context: PeriodDigestContext,
|
|
870
|
-
options: PeriodDigestOptions,
|
|
871
|
-
) {
|
|
872
|
-
const parts = [
|
|
873
|
-
"period-digest:v2",
|
|
874
|
-
modelFromOptions(options),
|
|
875
|
-
reasoningEffortFromOptions(options),
|
|
876
|
-
serviceTierFromOptions(options),
|
|
877
|
-
context.hash,
|
|
878
|
-
];
|
|
879
|
-
const lang = languageFromOptions(options);
|
|
880
|
-
if (lang) parts.push(`lang:${lang}`);
|
|
881
|
-
return parts.join(":");
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
function latestDigestCacheKey(options: PeriodDigestOptions) {
|
|
885
|
-
const period = normalizePeriod(options.period);
|
|
886
|
-
const window = resolvePeriodDigestWindow(options);
|
|
887
|
-
const identity = {
|
|
888
|
-
period,
|
|
889
|
-
day:
|
|
890
|
-
period === "today" || period === "yesterday"
|
|
891
|
-
? window.since
|
|
892
|
-
: localDateStart(new Date()).toISOString(),
|
|
893
|
-
since: options.since?.trim() || null,
|
|
894
|
-
until: options.until?.trim() || null,
|
|
895
|
-
account: options.account?.trim() || null,
|
|
896
|
-
includeDms: Boolean(options.includeDms),
|
|
897
|
-
maxTweets: Math.max(
|
|
898
|
-
20,
|
|
899
|
-
Math.trunc(options.maxTweets ?? DEFAULT_MAX_TWEETS),
|
|
900
|
-
),
|
|
901
|
-
maxLinks: Math.max(3, Math.trunc(options.maxLinks ?? DEFAULT_MAX_LINKS)),
|
|
902
|
-
model: modelFromOptions(options),
|
|
903
|
-
language: languageFromOptions(options) ?? null,
|
|
904
|
-
reasoningEffort: reasoningEffortFromOptions(options),
|
|
905
|
-
serviceTier: serviceTierFromOptions(options),
|
|
906
|
-
};
|
|
907
|
-
return `period-digest-latest:v1:${createHash("sha1")
|
|
908
|
-
.update(JSON.stringify(identity))
|
|
909
|
-
.digest("hex")}`;
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
function collectDigestTweetIds(digest: PeriodDigest) {
|
|
913
|
-
const tweetIds = new Set(digest.sourceTweetIds);
|
|
914
|
-
for (const topic of digest.keyTopics) {
|
|
915
|
-
for (const tweetId of topic.tweetIds) tweetIds.add(tweetId);
|
|
916
|
-
}
|
|
917
|
-
for (const link of digest.notableLinks) {
|
|
918
|
-
for (const tweetId of link.sourceTweetIds) tweetIds.add(tweetId);
|
|
919
|
-
}
|
|
920
|
-
for (const action of digest.actionItems) {
|
|
921
|
-
if (action.tweetId) tweetIds.add(action.tweetId);
|
|
922
|
-
}
|
|
923
|
-
return [...tweetIds];
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
function enrichContextWithCitedTweets(
|
|
927
|
-
context: PeriodDigestContext,
|
|
928
|
-
digest: PeriodDigest,
|
|
929
|
-
) {
|
|
930
|
-
const existingIds = new Set(context.tweets.map((tweet) => tweet.id));
|
|
931
|
-
const missingIds = collectDigestTweetIds(digest).filter(
|
|
932
|
-
(tweetId) => !existingIds.has(tweetId.replace(/^tweet_/, "")),
|
|
933
|
-
);
|
|
934
|
-
if (missingIds.length === 0) return context;
|
|
935
|
-
const citedTweets = getTweetsByIds(missingIds, context.account).map(
|
|
936
|
-
compactEmbeddedTweet,
|
|
937
|
-
);
|
|
938
|
-
return citedTweets.length > 0
|
|
939
|
-
? { ...context, tweets: [...context.tweets, ...citedTweets] }
|
|
940
|
-
: context;
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
interface CachedPeriodDigestValue {
|
|
944
|
-
context?: PeriodDigestContext;
|
|
945
|
-
digest: PeriodDigest;
|
|
946
|
-
markdown: string;
|
|
947
|
-
model: string;
|
|
948
|
-
reasoningEffort: string;
|
|
949
|
-
serviceTier: string;
|
|
950
|
-
updatedAt?: string;
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
function cachedDigestResult(
|
|
954
|
-
cached: { value: CachedPeriodDigestValue; updatedAt: string },
|
|
955
|
-
context: PeriodDigestContext,
|
|
956
|
-
): PeriodDigestRunResult {
|
|
957
|
-
const digest = PeriodDigestSchema.parse(cached.value.digest);
|
|
958
|
-
return {
|
|
959
|
-
context: enrichContextWithCitedTweets(context, digest),
|
|
960
|
-
digest,
|
|
961
|
-
markdown: cached.value.markdown,
|
|
962
|
-
model: cached.value.model,
|
|
963
|
-
reasoningEffort: cached.value.reasoningEffort,
|
|
964
|
-
serviceTier: cached.value.serviceTier,
|
|
965
|
-
cached: true,
|
|
966
|
-
updatedAt: cached.value.updatedAt ?? cached.updatedAt,
|
|
967
|
-
};
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
function isFreshDigestCache(updatedAt: string) {
|
|
971
|
-
const timestamp = Date.parse(updatedAt);
|
|
972
|
-
return (
|
|
973
|
-
Number.isFinite(timestamp) &&
|
|
974
|
-
Date.now() - timestamp <= DEFAULT_DIGEST_FRESHNESS_MS
|
|
975
|
-
);
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
function emitCachedDigest(
|
|
979
|
-
result: PeriodDigestRunResult,
|
|
980
|
-
handlers: PeriodDigestStreamHandlers,
|
|
981
|
-
) {
|
|
982
|
-
handlers.onEvent?.({ type: "start", context: result.context, cached: true });
|
|
983
|
-
handlers.onDelta?.(result.markdown);
|
|
984
|
-
handlers.onEvent?.({ type: "delta", delta: result.markdown });
|
|
985
|
-
handlers.onEvent?.({ type: "done", result });
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
function buildPrompt(
|
|
989
|
-
context: PeriodDigestContext,
|
|
990
|
-
options?: { language?: string },
|
|
991
|
-
) {
|
|
992
|
-
const language = normalizeDigestLanguage(options?.language);
|
|
993
|
-
const promptTweets = context.tweets.map((tweet) => ({
|
|
994
|
-
id: tweet.id,
|
|
995
|
-
url: tweet.url,
|
|
996
|
-
source: tweet.source,
|
|
997
|
-
author: tweet.author,
|
|
998
|
-
name: tweet.name,
|
|
999
|
-
bio: tweet.authorProfile.bio,
|
|
1000
|
-
followersCount: tweet.authorProfile.followersCount,
|
|
1001
|
-
createdAt: tweet.createdAt,
|
|
1002
|
-
text: tweet.text,
|
|
1003
|
-
likeCount: tweet.likeCount,
|
|
1004
|
-
liked: tweet.liked,
|
|
1005
|
-
bookmarked: tweet.bookmarked,
|
|
1006
|
-
needsReply: tweet.needsReply,
|
|
1007
|
-
replyToId: tweet.replyToId,
|
|
1008
|
-
replyToTweet: tweet.replyToTweet,
|
|
1009
|
-
}));
|
|
1010
|
-
const fitDataset = () => {
|
|
1011
|
-
let tweetCount = promptTweets.length;
|
|
1012
|
-
let dmCount = context.dms.length;
|
|
1013
|
-
let linkCount = context.links.length;
|
|
1014
|
-
const datasetFor = (tweets: number, dms: number, links: number) => ({
|
|
1015
|
-
tweets: promptTweets.slice(0, tweets),
|
|
1016
|
-
dms: context.dms.slice(0, dms),
|
|
1017
|
-
links: context.links.slice(0, links),
|
|
1018
|
-
});
|
|
1019
|
-
const lengthFor = (tweets: number, dms: number, links: number) =>
|
|
1020
|
-
JSON.stringify(datasetFor(tweets, dms, links)).length;
|
|
1021
|
-
const fitCount = (max: number, fits: (count: number) => boolean) => {
|
|
1022
|
-
let low = 0;
|
|
1023
|
-
let high = max;
|
|
1024
|
-
let best = 0;
|
|
1025
|
-
while (low <= high) {
|
|
1026
|
-
const mid = Math.floor((low + high) / 2);
|
|
1027
|
-
if (fits(mid)) {
|
|
1028
|
-
best = mid;
|
|
1029
|
-
low = mid + 1;
|
|
1030
|
-
} else {
|
|
1031
|
-
high = mid - 1;
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
return best;
|
|
1035
|
-
};
|
|
1036
|
-
if (lengthFor(tweetCount, dmCount, linkCount) <= MAX_PROMPT_DATA_CHARS) {
|
|
1037
|
-
return {
|
|
1038
|
-
dataset: datasetFor(tweetCount, dmCount, linkCount),
|
|
1039
|
-
tweetCount,
|
|
1040
|
-
};
|
|
1041
|
-
}
|
|
1042
|
-
dmCount = fitCount(
|
|
1043
|
-
dmCount,
|
|
1044
|
-
(count) =>
|
|
1045
|
-
lengthFor(tweetCount, count, linkCount) <= MAX_PROMPT_DATA_CHARS,
|
|
1046
|
-
);
|
|
1047
|
-
if (lengthFor(tweetCount, dmCount, linkCount) > MAX_PROMPT_DATA_CHARS) {
|
|
1048
|
-
linkCount = fitCount(
|
|
1049
|
-
linkCount,
|
|
1050
|
-
(count) =>
|
|
1051
|
-
lengthFor(tweetCount, dmCount, count) <= MAX_PROMPT_DATA_CHARS,
|
|
1052
|
-
);
|
|
1053
|
-
}
|
|
1054
|
-
if (lengthFor(tweetCount, dmCount, linkCount) > MAX_PROMPT_DATA_CHARS) {
|
|
1055
|
-
tweetCount = fitCount(
|
|
1056
|
-
tweetCount,
|
|
1057
|
-
(count) =>
|
|
1058
|
-
lengthFor(count, dmCount, linkCount) <= MAX_PROMPT_DATA_CHARS,
|
|
1059
|
-
);
|
|
1060
|
-
}
|
|
1061
|
-
return { dataset: datasetFor(tweetCount, dmCount, linkCount), tweetCount };
|
|
1062
|
-
};
|
|
1063
|
-
const { dataset, tweetCount } = fitDataset();
|
|
1064
|
-
|
|
1065
|
-
return `Window: ${context.window.label}
|
|
1066
|
-
Since: ${context.window.since}
|
|
1067
|
-
Until: ${context.window.until}
|
|
1068
|
-
Sources: ${JSON.stringify(context.counts)}
|
|
1069
|
-
Prompt tweets: ${String(tweetCount)} of ${String(context.tweets.length)} selected context tweets
|
|
1070
|
-
|
|
1071
|
-
Write a high-signal "what happened" report from this local Twitter/X dataset.
|
|
1072
|
-
|
|
1073
|
-
Requirements:
|
|
1074
|
-
- Stream one readable Markdown report first. The UI will show this text directly; do not rely on separate cards or structured summaries.
|
|
1075
|
-
- Target 700-1100 words when there is enough data.
|
|
1076
|
-
- Start with a 2-3 sentence lead that immediately says what people are talking about.
|
|
1077
|
-
- Use sections named "What people are talking about", "Important links shared", and "Worth opening". Add "Worth replying to" only if there are clearly high-signal replies. Translate these section titles when a report language is requested.
|
|
1078
|
-
- When a tweet has replyToTweet, use that parent context to understand what the author was replying to and whether Peter already joined the conversation.
|
|
1079
|
-
- Use bullets under each section. Each bullet should be specific and explain why it matters.
|
|
1080
|
-
- For tweets: cite every claim with inline tweet ids at the end of the relevant sentence or bullet, e.g. (tweet_123, tweet_456). These citations become hoverable source links.
|
|
1081
|
-
- For links: emit normal Markdown links with no space between the label and URL, e.g. [title](https://example.com), then cite the sharing tweet ids in the same bullet.
|
|
1082
|
-
- Prefer synthesis over chronology. Group repeated chatter into one bullet.
|
|
1083
|
-
- Mention handles when useful, but do not make the report a list of handles.
|
|
1084
|
-
- Do not include a generic "Action items" section.
|
|
1085
|
-
- If there is no data, say that plainly in one short paragraph.
|
|
1086
|
-
- DMs are private context and only present when explicitly included.
|
|
1087
|
-
- After the Markdown, output a blank line, then a line containing only three hyphens, then one compact JSON object.
|
|
1088
|
-
- Keep actionItems empty unless you wrote a "Worth replying to" section.
|
|
1089
|
-
- Put every tweet id cited in the Markdown into sourceTweetIds.
|
|
1090
|
-
- JSON shape: { "title": string, "summary": string, "keyTopics": [{ "title": string, "summary": string, "tweetIds": string[], "handles": string[] }], "notableLinks": [{ "title": string, "url": string, "why": string, "sourceTweetIds": string[] }], "people": [{ "handle": string, "name"?: string, "why": string }], "actionItems": [{ "kind": "reply"|"follow_up"|"read"|"sync", "label": string, "tweetId"?: string, "dmConversationId"?: string }], "sourceTweetIds": string[] }
|
|
1091
|
-
${language ? `- Write all human-readable prose, including section titles and JSON prose fields, in ${language}.\n- Preserve handles, URLs, tweet ids, and JSON property names exactly.` : ""}
|
|
1092
|
-
|
|
1093
|
-
Dataset:
|
|
1094
|
-
${JSON.stringify(dataset)}`;
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
function fallbackDigest(
|
|
1098
|
-
context: PeriodDigestContext,
|
|
1099
|
-
markdown: string,
|
|
1100
|
-
language?: string,
|
|
1101
|
-
): PeriodDigest {
|
|
1102
|
-
const normalized = markdown.replaceAll(/\s+/g, " ").trim();
|
|
1103
|
-
const heading = markdown
|
|
1104
|
-
.split("\n")
|
|
1105
|
-
.map((line) => line.match(/^#{1,6}\s+(.+)$/)?.[1]?.trim())
|
|
1106
|
-
.find(Boolean);
|
|
1107
|
-
const neutralFallback = language ? `[${language}]` : undefined;
|
|
1108
|
-
return {
|
|
1109
|
-
title:
|
|
1110
|
-
heading?.slice(0, 160) ??
|
|
1111
|
-
neutralFallback ??
|
|
1112
|
-
`${context.window.label} digest`,
|
|
1113
|
-
summary:
|
|
1114
|
-
normalized.slice(0, 280) ||
|
|
1115
|
-
neutralFallback ||
|
|
1116
|
-
"No model summary was returned.",
|
|
1117
|
-
keyTopics: [],
|
|
1118
|
-
notableLinks: [],
|
|
1119
|
-
people: [],
|
|
1120
|
-
actionItems: [],
|
|
1121
|
-
sourceTweetIds: context.tweets.slice(0, 20).map((tweet) => tweet.id),
|
|
1122
|
-
};
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
function parseDigestFromHybridText(
|
|
1126
|
-
context: PeriodDigestContext,
|
|
1127
|
-
rawText: string,
|
|
1128
|
-
language?: string,
|
|
1129
|
-
): { digest: PeriodDigest; markdown: string } {
|
|
1130
|
-
const parsed = parseHybridAnalysis({
|
|
1131
|
-
rawText,
|
|
1132
|
-
parse: (value) => PeriodDigestSchema.parse(value),
|
|
1133
|
-
fallback: (markdown) => fallbackDigest(context, markdown, language),
|
|
1134
|
-
delimiterPattern: DELIMITER_PATTERN,
|
|
1135
|
-
});
|
|
1136
|
-
return { markdown: parsed.markdown, digest: parsed.value };
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
function processSseChunk(
|
|
1140
|
-
state: OpenAIStreamState,
|
|
1141
|
-
chunk: string,
|
|
1142
|
-
handlers: PeriodDigestStreamHandlers,
|
|
1143
|
-
) {
|
|
1144
|
-
processOpenAIResponseSseChunk(state, chunk, {
|
|
1145
|
-
delimiterPattern: DELIMITER_PATTERN,
|
|
1146
|
-
onDelta: (delta) => {
|
|
1147
|
-
handlers.onDelta?.(delta);
|
|
1148
|
-
handlers.onEvent?.({ type: "delta", delta });
|
|
1149
|
-
},
|
|
1150
|
-
});
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
function createOpenAIRequestBody(
|
|
1154
|
-
context: PeriodDigestContext,
|
|
1155
|
-
options: PeriodDigestOptions,
|
|
1156
|
-
) {
|
|
1157
|
-
return createAnalysisRequestBody({
|
|
1158
|
-
settings: resolveAnalysisModelSettings(options),
|
|
1159
|
-
system:
|
|
1160
|
-
"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.",
|
|
1161
|
-
prompt: buildPrompt(context, {
|
|
1162
|
-
language: languageFromOptions(options),
|
|
1163
|
-
}),
|
|
1164
|
-
stream: true,
|
|
1165
|
-
});
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
function completeOpenAIStreamEffect(
|
|
1169
|
-
stream: HybridAnalysisResult<PeriodDigest>,
|
|
1170
|
-
context: PeriodDigestContext,
|
|
1171
|
-
options: PeriodDigestOptions,
|
|
1172
|
-
handlers: PeriodDigestStreamHandlers,
|
|
1173
|
-
): Effect.Effect<PeriodDigestRunResult, Error> {
|
|
1174
|
-
return Effect.gen(function* () {
|
|
1175
|
-
const enrichedContext = yield* tryDigestSync(() =>
|
|
1176
|
-
enrichContextWithCitedTweets(context, stream.value),
|
|
1177
|
-
);
|
|
1178
|
-
const cacheKey = digestCacheKey(context, options);
|
|
1179
|
-
const updatedAt = yield* tryDigestSync(() =>
|
|
1180
|
-
writeSyncCache(cacheKey, {
|
|
1181
|
-
digest: stream.value,
|
|
1182
|
-
markdown: stream.markdown,
|
|
1183
|
-
model: modelFromOptions(options),
|
|
1184
|
-
reasoningEffort: reasoningEffortFromOptions(options),
|
|
1185
|
-
serviceTier: serviceTierFromOptions(options),
|
|
1186
|
-
usage: stream.usage,
|
|
1187
|
-
responseId: stream.responseId,
|
|
1188
|
-
}),
|
|
1189
|
-
);
|
|
1190
|
-
const result: PeriodDigestRunResult = {
|
|
1191
|
-
context: enrichedContext,
|
|
1192
|
-
digest: stream.value,
|
|
1193
|
-
markdown: stream.markdown,
|
|
1194
|
-
model: modelFromOptions(options),
|
|
1195
|
-
reasoningEffort: reasoningEffortFromOptions(options),
|
|
1196
|
-
serviceTier: serviceTierFromOptions(options),
|
|
1197
|
-
cached: false,
|
|
1198
|
-
updatedAt,
|
|
1199
|
-
};
|
|
1200
|
-
yield* tryDigestSync(() =>
|
|
1201
|
-
writeSyncCache(latestDigestCacheKey(options), {
|
|
1202
|
-
context: result.context,
|
|
1203
|
-
digest: result.digest,
|
|
1204
|
-
markdown: result.markdown,
|
|
1205
|
-
model: result.model,
|
|
1206
|
-
reasoningEffort: result.reasoningEffort,
|
|
1207
|
-
serviceTier: result.serviceTier,
|
|
1208
|
-
updatedAt: result.updatedAt,
|
|
1209
|
-
}),
|
|
1210
|
-
);
|
|
1211
|
-
handlers.onEvent?.({ type: "done", result });
|
|
1212
|
-
return result;
|
|
1213
|
-
});
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
function readOpenAIStreamEffect(
|
|
1217
|
-
response: Response,
|
|
1218
|
-
context: PeriodDigestContext,
|
|
1219
|
-
options: PeriodDigestOptions,
|
|
1220
|
-
handlers: PeriodDigestStreamHandlers,
|
|
1221
|
-
): Effect.Effect<PeriodDigestRunResult, Error> {
|
|
1222
|
-
return Effect.gen(function* () {
|
|
1223
|
-
const stream = yield* readHybridAnalysisStreamEffect(response, {
|
|
1224
|
-
parse: (value) => PeriodDigestSchema.parse(value),
|
|
1225
|
-
fallback: (markdown) =>
|
|
1226
|
-
fallbackDigest(context, markdown, languageFromOptions(options)),
|
|
1227
|
-
delimiterPattern: DELIMITER_PATTERN,
|
|
1228
|
-
onDelta: (delta) => {
|
|
1229
|
-
handlers.onDelta?.(delta);
|
|
1230
|
-
handlers.onEvent?.({ type: "delta", delta });
|
|
1231
|
-
},
|
|
1232
|
-
});
|
|
1233
|
-
return yield* completeOpenAIStreamEffect(
|
|
1234
|
-
stream,
|
|
1235
|
-
context,
|
|
1236
|
-
options,
|
|
1237
|
-
handlers,
|
|
1238
|
-
);
|
|
1239
|
-
});
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
export function streamPeriodDigestEffect(
|
|
1243
|
-
options: PeriodDigestOptions = {},
|
|
1244
|
-
handlers: PeriodDigestStreamHandlers = {},
|
|
1245
|
-
): Effect.Effect<PeriodDigestRunResult, Error> {
|
|
1246
|
-
return Effect.gen(function* () {
|
|
1247
|
-
const resolvedOptions = {
|
|
1248
|
-
...options,
|
|
1249
|
-
language: yield* tryDigestSync(() => languageFromOptions(options)),
|
|
1250
|
-
};
|
|
1251
|
-
const latestCached = resolvedOptions.refresh
|
|
1252
|
-
? null
|
|
1253
|
-
: !resolvedOptions.liveSync
|
|
1254
|
-
? yield* tryDigestSync(() =>
|
|
1255
|
-
readSyncCache<CachedPeriodDigestValue>(
|
|
1256
|
-
latestDigestCacheKey(resolvedOptions),
|
|
1257
|
-
),
|
|
1258
|
-
)
|
|
1259
|
-
: null;
|
|
1260
|
-
const latestContext = latestCached?.value.context;
|
|
1261
|
-
if (
|
|
1262
|
-
latestCached &&
|
|
1263
|
-
latestContext &&
|
|
1264
|
-
isFreshDigestCache(latestCached.value.updatedAt ?? latestCached.updatedAt)
|
|
1265
|
-
) {
|
|
1266
|
-
const result = yield* tryDigestSync(() =>
|
|
1267
|
-
cachedDigestResult(latestCached, latestContext),
|
|
1268
|
-
);
|
|
1269
|
-
emitCachedDigest(result, handlers);
|
|
1270
|
-
return result;
|
|
1271
|
-
}
|
|
1272
|
-
|
|
1273
|
-
yield* refreshPeriodDigestInputsEffect(
|
|
1274
|
-
resolvedOptions,
|
|
1275
|
-
{ threads: false },
|
|
1276
|
-
handlers,
|
|
1277
|
-
).pipe(Effect.catchAll(() => Effect.void));
|
|
1278
|
-
let context = yield* tryDigestSync(() =>
|
|
1279
|
-
collectPeriodDigestContext(resolvedOptions),
|
|
1280
|
-
);
|
|
1281
|
-
let cacheKey = digestCacheKey(context, resolvedOptions);
|
|
1282
|
-
const cached = resolvedOptions.refresh
|
|
1283
|
-
? null
|
|
1284
|
-
: yield* tryDigestSync(() =>
|
|
1285
|
-
readSyncCache<CachedPeriodDigestValue>(cacheKey),
|
|
1286
|
-
);
|
|
1287
|
-
|
|
1288
|
-
if (cached) {
|
|
1289
|
-
const result = yield* tryDigestSync(() =>
|
|
1290
|
-
cachedDigestResult(cached, context),
|
|
1291
|
-
);
|
|
1292
|
-
yield* tryDigestSync(() =>
|
|
1293
|
-
writeSyncCache(latestDigestCacheKey(resolvedOptions), {
|
|
1294
|
-
context: result.context,
|
|
1295
|
-
digest: result.digest,
|
|
1296
|
-
markdown: result.markdown,
|
|
1297
|
-
model: result.model,
|
|
1298
|
-
reasoningEffort: result.reasoningEffort,
|
|
1299
|
-
serviceTier: result.serviceTier,
|
|
1300
|
-
updatedAt: result.updatedAt,
|
|
1301
|
-
}),
|
|
1302
|
-
);
|
|
1303
|
-
emitCachedDigest(result, handlers);
|
|
1304
|
-
return result;
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
yield* refreshPeriodDigestInputsEffect(
|
|
1308
|
-
resolvedOptions,
|
|
1309
|
-
{
|
|
1310
|
-
timeline: false,
|
|
1311
|
-
mentions: false,
|
|
1312
|
-
threads: true,
|
|
1313
|
-
threadTweetIds: context.tweets
|
|
1314
|
-
.filter((tweet) => tweet.source === "mentions")
|
|
1315
|
-
.map((tweet) => tweet.id),
|
|
1316
|
-
},
|
|
1317
|
-
handlers,
|
|
1318
|
-
).pipe(Effect.catchAll(() => Effect.void));
|
|
1319
|
-
context = yield* tryDigestSync(() =>
|
|
1320
|
-
collectPeriodDigestContext(resolvedOptions),
|
|
1321
|
-
);
|
|
1322
|
-
cacheKey = digestCacheKey(context, resolvedOptions);
|
|
1323
|
-
|
|
1324
|
-
handlers.onEvent?.({ type: "start", context, cached: false });
|
|
1325
|
-
emitDigestStatus(handlers, "Streaming AI summary");
|
|
1326
|
-
const stream = yield* streamHybridAnalysisEffect({
|
|
1327
|
-
body: createOpenAIRequestBody(context, resolvedOptions),
|
|
1328
|
-
signal: resolvedOptions.signal,
|
|
1329
|
-
parse: (value) => PeriodDigestSchema.parse(value),
|
|
1330
|
-
fallback: (markdown) =>
|
|
1331
|
-
fallbackDigest(context, markdown, languageFromOptions(resolvedOptions)),
|
|
1332
|
-
delimiterPattern: DELIMITER_PATTERN,
|
|
1333
|
-
onDelta: (delta) => {
|
|
1334
|
-
handlers.onDelta?.(delta);
|
|
1335
|
-
handlers.onEvent?.({ type: "delta", delta });
|
|
1336
|
-
},
|
|
1337
|
-
});
|
|
1338
|
-
return yield* completeOpenAIStreamEffect(
|
|
1339
|
-
stream,
|
|
1340
|
-
context,
|
|
1341
|
-
resolvedOptions,
|
|
1342
|
-
handlers,
|
|
1343
|
-
);
|
|
1344
|
-
});
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
export function streamPeriodDigest(
|
|
1348
|
-
options: PeriodDigestOptions = {},
|
|
1349
|
-
handlers: PeriodDigestStreamHandlers = {},
|
|
1350
|
-
): Promise<PeriodDigestRunResult> {
|
|
1351
|
-
return runEffectPromise(streamPeriodDigestEffect(options, handlers));
|
|
1352
|
-
}
|
|
1353
|
-
|
|
1354
|
-
export const __test__ = {
|
|
1355
|
-
PeriodDigestSchema,
|
|
1356
|
-
buildPrompt,
|
|
1357
|
-
digestCacheKey,
|
|
1358
|
-
languageFromOptions,
|
|
1359
|
-
normalizeDigestLanguage,
|
|
1360
|
-
readOpenAIStreamEffect,
|
|
1361
|
-
parseDigestFromHybridText,
|
|
1362
|
-
processSseChunk,
|
|
1363
|
-
resolvePeriodDigestWindow,
|
|
1364
|
-
};
|