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,536 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import fs from "node:fs/promises";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import { promisify } from "node:util";
6
- import { Effect } from "effect";
7
- import type { Database } from "./sqlite";
8
- import {
9
- maybeAutoSyncBackupEffect,
10
- type BackupAutoUpdateResult,
11
- } from "./backup";
12
- import { ensureBirdclawDirs, getBirdclawPaths } from "./config";
13
- import { getNativeDb } from "./db";
14
- import { runEffectPromise, tryPromise } from "./effect-runtime";
15
- import {
16
- syncTimelineCollectionEffect,
17
- type TimelineCollectionMode,
18
- } from "./timeline-collections-live";
19
-
20
- const execFileAsync = promisify(execFile);
21
- const DEFAULT_BOOKMARK_SYNC_INTERVAL_SECONDS = 3 * 60 * 60;
22
- const DEFAULT_BOOKMARK_SYNC_LIMIT = 100;
23
- const DEFAULT_BOOKMARK_SYNC_MAX_PAGES = 5;
24
- const DEFAULT_LAUNCHD_LABEL = "com.steipete.birdclaw.bookmarks-sync";
25
- const DEFAULT_LAUNCHD_PATH =
26
- "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
27
- const DEFAULT_LOCK_STALE_MS = 6 * 60 * 60 * 1000;
28
-
29
- export interface BookmarkSyncJobOptions {
30
- account?: string;
31
- mode?: TimelineCollectionMode;
32
- limit?: number;
33
- all?: boolean;
34
- maxPages?: number;
35
- refresh?: boolean;
36
- cacheTtlMs?: number;
37
- logPath?: string;
38
- lockPath?: string;
39
- db?: Database;
40
- }
41
-
42
- export interface BookmarkSyncAuditEntry {
43
- job: "bookmarks-sync";
44
- ok: boolean;
45
- startedAt: string;
46
- finishedAt: string;
47
- durationMs: number;
48
- host: string;
49
- pid: number;
50
- options: {
51
- account?: string;
52
- mode: TimelineCollectionMode;
53
- limit: number;
54
- all: boolean;
55
- maxPages?: number;
56
- refresh: boolean;
57
- cacheTtlMs?: number;
58
- };
59
- before: {
60
- bookmarks: number;
61
- };
62
- after: {
63
- bookmarks: number;
64
- };
65
- added: number;
66
- skipped?: "already-running";
67
- sync?: {
68
- source: string;
69
- count: number;
70
- accountId: string;
71
- };
72
- backup?: BackupAutoUpdateResult;
73
- error?: string;
74
- }
75
-
76
- export interface BookmarkSyncLaunchAgentOptions {
77
- label?: string;
78
- intervalSeconds?: number;
79
- program?: string;
80
- mode?: TimelineCollectionMode;
81
- limit?: number;
82
- all?: boolean;
83
- maxPages?: number;
84
- refresh?: boolean;
85
- cacheTtlSeconds?: number;
86
- logPath?: string;
87
- envFile?: string;
88
- stdoutPath?: string;
89
- stderrPath?: string;
90
- launchAgentsDir?: string;
91
- load?: boolean;
92
- }
93
-
94
- export interface BookmarkSyncLaunchAgentInstallResult {
95
- ok: true;
96
- label: string;
97
- plistPath: string;
98
- loaded: boolean;
99
- programArguments: string[];
100
- logPath: string;
101
- stdoutPath: string;
102
- stderrPath: string;
103
- intervalSeconds: number;
104
- envFile?: string;
105
- }
106
-
107
- function expandHome(input: string) {
108
- return input === "~" || input.startsWith("~/")
109
- ? path.join(os.homedir(), input.slice(2))
110
- : input;
111
- }
112
-
113
- function resolvePath(input: string) {
114
- return path.resolve(expandHome(input));
115
- }
116
-
117
- export function getDefaultBookmarkSyncAuditLogPath() {
118
- return path.join(getBirdclawPaths().rootDir, "audit", "bookmarks-sync.jsonl");
119
- }
120
-
121
- export function getDefaultBookmarkSyncLockPath() {
122
- return path.join(getBirdclawPaths().rootDir, "locks", "bookmarks-sync.lock");
123
- }
124
-
125
- function countBookmarks(db: Database) {
126
- const row = db
127
- .prepare("select count(*) as count from tweet_collections where kind = ?")
128
- .get("bookmarks") as { count: number };
129
- return row.count;
130
- }
131
-
132
- function toError(error: unknown) {
133
- return error instanceof Error ? error : new Error(String(error));
134
- }
135
-
136
- function trySync<T>(try_: () => T) {
137
- return Effect.try({
138
- try: try_,
139
- catch: toError,
140
- });
141
- }
142
-
143
- function appendAuditEntryEffect(
144
- logPath: string,
145
- entry: BookmarkSyncAuditEntry,
146
- ) {
147
- return Effect.gen(function* () {
148
- yield* tryPromise(() =>
149
- fs.mkdir(path.dirname(logPath), { recursive: true }),
150
- );
151
- yield* tryPromise(() =>
152
- fs.appendFile(logPath, `${JSON.stringify(entry)}\n`, "utf8"),
153
- );
154
- });
155
- }
156
-
157
- function messageFromError(error: unknown) {
158
- return error instanceof Error ? error.message : String(error);
159
- }
160
-
161
- function isFileExistsError(error: unknown) {
162
- return (
163
- typeof error === "object" &&
164
- error !== null &&
165
- "code" in error &&
166
- error.code === "EEXIST"
167
- );
168
- }
169
-
170
- function acquireLockEffect(
171
- lockPath: string,
172
- ): Effect.Effect<(() => Effect.Effect<void, never>) | undefined, unknown> {
173
- return Effect.gen(function* () {
174
- yield* tryPromise(() =>
175
- fs.mkdir(path.dirname(lockPath), { recursive: true }),
176
- );
177
- const handleResult = yield* tryPromise(() => fs.open(lockPath, "wx")).pipe(
178
- Effect.map((handle) => ({ handle, ok: true as const })),
179
- Effect.catchAll((error) => {
180
- if (isFileExistsError(error)) {
181
- return Effect.succeed({ error, ok: false as const });
182
- }
183
- return Effect.fail(error);
184
- }),
185
- );
186
-
187
- if (!handleResult.ok) {
188
- const stats = yield* tryPromise(() => fs.stat(lockPath)).pipe(
189
- Effect.catchAll(() => Effect.succeed(undefined)),
190
- );
191
- if (stats && Date.now() - stats.mtimeMs > DEFAULT_LOCK_STALE_MS) {
192
- yield* tryPromise(() => fs.rm(lockPath, { force: true }));
193
- return yield* acquireLockEffect(lockPath);
194
- }
195
- return undefined;
196
- }
197
-
198
- const { handle } = handleResult;
199
- yield* tryPromise(() =>
200
- handle.writeFile(
201
- `${JSON.stringify({
202
- pid: process.pid,
203
- host: os.hostname(),
204
- startedAt: new Date().toISOString(),
205
- })}\n`,
206
- "utf8",
207
- ),
208
- ).pipe(
209
- Effect.ensuring(
210
- tryPromise(() => handle.close()).pipe(
211
- Effect.catchAll(() => Effect.void),
212
- ),
213
- ),
214
- );
215
- return () =>
216
- tryPromise(() => fs.rm(lockPath, { force: true })).pipe(
217
- Effect.asVoid,
218
- Effect.catchAll(() => Effect.void),
219
- );
220
- });
221
- }
222
-
223
- export function runBookmarkSyncJobEffect({
224
- account,
225
- mode = "auto",
226
- limit = DEFAULT_BOOKMARK_SYNC_LIMIT,
227
- all,
228
- maxPages = DEFAULT_BOOKMARK_SYNC_MAX_PAGES,
229
- refresh = true,
230
- cacheTtlMs,
231
- logPath,
232
- lockPath,
233
- db,
234
- }: BookmarkSyncJobOptions = {}): Effect.Effect<
235
- BookmarkSyncAuditEntry,
236
- unknown
237
- > {
238
- return Effect.gen(function* () {
239
- yield* trySync(() => ensureBirdclawDirs());
240
- const database =
241
- db ?? (yield* trySync(() => getNativeDb({ seedDemoData: false })));
242
- const resolvedLogPath = yield* trySync(() =>
243
- resolvePath(logPath ?? getDefaultBookmarkSyncAuditLogPath()),
244
- );
245
- const resolvedLockPath = yield* trySync(() =>
246
- resolvePath(lockPath ?? getDefaultBookmarkSyncLockPath()),
247
- );
248
- const effectiveAll = all ?? maxPages !== undefined;
249
- const started = Date.now();
250
- const startedAt = new Date(started).toISOString();
251
- const before = yield* trySync(() => ({
252
- bookmarks: countBookmarks(database),
253
- }));
254
- const options = {
255
- ...(account ? { account } : {}),
256
- mode,
257
- limit,
258
- all: effectiveAll,
259
- ...(maxPages === undefined ? {} : { maxPages }),
260
- refresh,
261
- ...(cacheTtlMs === undefined ? {} : { cacheTtlMs }),
262
- };
263
-
264
- const releaseLock = yield* acquireLockEffect(resolvedLockPath);
265
- if (!releaseLock) {
266
- const finished = Date.now();
267
- const entry: BookmarkSyncAuditEntry = {
268
- job: "bookmarks-sync",
269
- ok: true,
270
- startedAt,
271
- finishedAt: new Date(finished).toISOString(),
272
- durationMs: finished - started,
273
- host: os.hostname(),
274
- pid: process.pid,
275
- options,
276
- before,
277
- after: before,
278
- added: 0,
279
- skipped: "already-running",
280
- };
281
- yield* appendAuditEntryEffect(resolvedLogPath, entry);
282
- return entry;
283
- }
284
-
285
- return yield* Effect.gen(function* () {
286
- const result = yield* Effect.gen(function* () {
287
- const sync = yield* syncTimelineCollectionEffect({
288
- kind: "bookmarks",
289
- account,
290
- mode,
291
- limit,
292
- all: effectiveAll,
293
- maxPages,
294
- refresh,
295
- cacheTtlMs,
296
- });
297
- const backup = yield* maybeAutoSyncBackupEffect(database);
298
- const finished = Date.now();
299
- const after = yield* trySync(() => ({
300
- bookmarks: countBookmarks(database),
301
- }));
302
- return {
303
- job: "bookmarks-sync",
304
- ok: true,
305
- startedAt,
306
- finishedAt: new Date(finished).toISOString(),
307
- durationMs: finished - started,
308
- host: os.hostname(),
309
- pid: process.pid,
310
- options,
311
- before,
312
- after,
313
- added: Math.max(0, after.bookmarks - before.bookmarks),
314
- sync: {
315
- source: sync.source,
316
- count: sync.count,
317
- accountId: sync.accountId,
318
- },
319
- backup,
320
- } satisfies BookmarkSyncAuditEntry;
321
- }).pipe(
322
- Effect.catchAll((error) =>
323
- Effect.gen(function* () {
324
- const finished = Date.now();
325
- const after = yield* trySync(() => ({
326
- bookmarks: countBookmarks(database),
327
- }));
328
- return {
329
- job: "bookmarks-sync",
330
- ok: false,
331
- startedAt,
332
- finishedAt: new Date(finished).toISOString(),
333
- durationMs: finished - started,
334
- host: os.hostname(),
335
- pid: process.pid,
336
- options,
337
- before,
338
- after,
339
- added: Math.max(0, after.bookmarks - before.bookmarks),
340
- error: messageFromError(error),
341
- } satisfies BookmarkSyncAuditEntry;
342
- }),
343
- ),
344
- );
345
- yield* appendAuditEntryEffect(resolvedLogPath, result);
346
- return result;
347
- }).pipe(Effect.ensuring(releaseLock()));
348
- });
349
- }
350
-
351
- export function runBookmarkSyncJob(
352
- options: BookmarkSyncJobOptions = {},
353
- ): Promise<BookmarkSyncAuditEntry> {
354
- return runEffectPromise(runBookmarkSyncJobEffect(options));
355
- }
356
-
357
- function xmlEscape(value: string) {
358
- return value
359
- .replaceAll("&", "&amp;")
360
- .replaceAll("<", "&lt;")
361
- .replaceAll(">", "&gt;");
362
- }
363
-
364
- function stringEntry(value: string) {
365
- return `<string>${xmlEscape(value)}</string>`;
366
- }
367
-
368
- function shellQuote(value: string) {
369
- return `'${value.replaceAll("'", "'\\''")}'`;
370
- }
371
-
372
- function buildProgramArguments({
373
- program = "birdclaw",
374
- mode = "auto",
375
- limit = DEFAULT_BOOKMARK_SYNC_LIMIT,
376
- all = false,
377
- maxPages = DEFAULT_BOOKMARK_SYNC_MAX_PAGES,
378
- refresh = true,
379
- cacheTtlSeconds,
380
- logPath,
381
- envFile,
382
- }: BookmarkSyncLaunchAgentOptions) {
383
- const args =
384
- path.isAbsolute(program) || program.includes("/")
385
- ? [program]
386
- : ["/usr/bin/env", program];
387
- args.push(
388
- "--json",
389
- "jobs",
390
- "sync-bookmarks",
391
- "--mode",
392
- mode,
393
- "--limit",
394
- String(limit),
395
- "--log",
396
- resolvePath(logPath ?? getDefaultBookmarkSyncAuditLogPath()),
397
- );
398
- if (all || maxPages !== undefined) {
399
- args.push("--all");
400
- }
401
- if (maxPages !== undefined) {
402
- args.push("--max-pages", String(maxPages));
403
- }
404
- if (refresh) {
405
- args.push("--refresh");
406
- }
407
- if (cacheTtlSeconds !== undefined) {
408
- args.push("--cache-ttl", String(cacheTtlSeconds));
409
- }
410
- if (envFile) {
411
- const resolvedEnvFile = resolvePath(envFile);
412
- return [
413
- "/bin/bash",
414
- "-lc",
415
- [
416
- "set -a",
417
- `[ ! -f ${shellQuote(resolvedEnvFile)} ] || . ${shellQuote(resolvedEnvFile)}`,
418
- "set +a",
419
- `exec ${args.map(shellQuote).join(" ")}`,
420
- ].join("; "),
421
- ];
422
- }
423
- return args;
424
- }
425
-
426
- export function buildBookmarkSyncLaunchAgentPlist(
427
- options: BookmarkSyncLaunchAgentOptions = {},
428
- ) {
429
- const label = options.label ?? DEFAULT_LAUNCHD_LABEL;
430
- const intervalSeconds =
431
- options.intervalSeconds ?? DEFAULT_BOOKMARK_SYNC_INTERVAL_SECONDS;
432
- const logPath = resolvePath(
433
- options.logPath ?? getDefaultBookmarkSyncAuditLogPath(),
434
- );
435
- const stdoutPath = resolvePath(
436
- options.stdoutPath ??
437
- path.join(getBirdclawPaths().rootDir, "logs", "bookmarks-sync.out.log"),
438
- );
439
- const stderrPath = resolvePath(
440
- options.stderrPath ??
441
- path.join(getBirdclawPaths().rootDir, "logs", "bookmarks-sync.err.log"),
442
- );
443
- const programArguments = buildProgramArguments({ ...options, logPath });
444
- const plist = `<?xml version="1.0" encoding="UTF-8"?>
445
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
446
- <plist version="1.0">
447
- <dict>
448
- <key>Label</key>
449
- ${stringEntry(label)}
450
- <key>ProgramArguments</key>
451
- <array>
452
- ${programArguments.map(stringEntry).join("\n ")}
453
- </array>
454
- <key>StartInterval</key>
455
- <integer>${String(intervalSeconds)}</integer>
456
- <key>RunAtLoad</key>
457
- <true/>
458
- <key>StandardOutPath</key>
459
- ${stringEntry(stdoutPath)}
460
- <key>StandardErrorPath</key>
461
- ${stringEntry(stderrPath)}
462
- <key>EnvironmentVariables</key>
463
- <dict>
464
- <key>PATH</key>
465
- ${stringEntry(DEFAULT_LAUNCHD_PATH)}
466
- </dict>
467
- </dict>
468
- </plist>
469
- `;
470
- return {
471
- label,
472
- intervalSeconds,
473
- logPath,
474
- ...(options.envFile ? { envFile: resolvePath(options.envFile) } : {}),
475
- stdoutPath,
476
- stderrPath,
477
- programArguments,
478
- plist,
479
- };
480
- }
481
-
482
- export function installBookmarkSyncLaunchAgentEffect(
483
- options: BookmarkSyncLaunchAgentOptions = {},
484
- ): Effect.Effect<BookmarkSyncLaunchAgentInstallResult, unknown> {
485
- return Effect.gen(function* () {
486
- yield* trySync(() => ensureBirdclawDirs());
487
- const agent = yield* trySync(() =>
488
- buildBookmarkSyncLaunchAgentPlist(options),
489
- );
490
- const launchAgentsDir = yield* trySync(() =>
491
- resolvePath(options.launchAgentsDir ?? "~/Library/LaunchAgents"),
492
- );
493
- const plistPath = path.join(launchAgentsDir, `${agent.label}.plist`);
494
- yield* tryPromise(() => fs.mkdir(launchAgentsDir, { recursive: true }));
495
- yield* tryPromise(() =>
496
- fs.mkdir(path.dirname(agent.logPath), { recursive: true }),
497
- );
498
- yield* tryPromise(() =>
499
- fs.mkdir(path.dirname(agent.stdoutPath), { recursive: true }),
500
- );
501
- yield* tryPromise(() =>
502
- fs.mkdir(path.dirname(agent.stderrPath), { recursive: true }),
503
- );
504
- yield* tryPromise(() => fs.writeFile(plistPath, agent.plist, "utf8"));
505
-
506
- let loaded = false;
507
- if (options.load !== false) {
508
- yield* tryPromise(() =>
509
- execFileAsync("launchctl", ["unload", plistPath]),
510
- ).pipe(Effect.catchAll(() => Effect.void));
511
- yield* tryPromise(() =>
512
- execFileAsync("launchctl", ["load", "-w", plistPath]),
513
- );
514
- loaded = true;
515
- }
516
-
517
- return {
518
- ok: true,
519
- label: agent.label,
520
- plistPath,
521
- loaded,
522
- programArguments: agent.programArguments,
523
- logPath: agent.logPath,
524
- stdoutPath: agent.stdoutPath,
525
- stderrPath: agent.stderrPath,
526
- intervalSeconds: agent.intervalSeconds,
527
- ...(agent.envFile ? { envFile: agent.envFile } : {}),
528
- };
529
- });
530
- }
531
-
532
- export function installBookmarkSyncLaunchAgent(
533
- options: BookmarkSyncLaunchAgentOptions = {},
534
- ): Promise<BookmarkSyncLaunchAgentInstallResult> {
535
- return runEffectPromise(installBookmarkSyncLaunchAgentEffect(options));
536
- }
@@ -1,109 +0,0 @@
1
- const DEFAULT_MAX_ENTRIES = 100;
2
-
3
- interface ClientCacheEntry<T> {
4
- value: T;
5
- updatedAt: number;
6
- }
7
-
8
- interface LoadClientCacheOptions {
9
- force?: boolean;
10
- maxAgeMs?: number;
11
- }
12
-
13
- const values = new Map<string, ClientCacheEntry<unknown>>();
14
- const pending = new Map<string, Promise<unknown>>();
15
- const revisions = new Map<string, number>();
16
- let generation = 0;
17
-
18
- function cacheToken(key: string) {
19
- return `${String(generation)}:${String(revisions.get(key) ?? 0)}`;
20
- }
21
-
22
- function invalidateKey(key: string) {
23
- revisions.set(key, (revisions.get(key) ?? 0) + 1);
24
- }
25
-
26
- function pruneCache() {
27
- while (values.size > DEFAULT_MAX_ENTRIES) {
28
- const oldestKey = values.keys().next().value as string | undefined;
29
- if (!oldestKey) return;
30
- values.delete(oldestKey);
31
- }
32
- }
33
-
34
- export function readClientCache<T>(
35
- key: string,
36
- maxAgeMs = Number.POSITIVE_INFINITY,
37
- ) {
38
- const entry = values.get(key) as ClientCacheEntry<T> | undefined;
39
- if (!entry) return undefined;
40
- if (Date.now() - entry.updatedAt > maxAgeMs) {
41
- values.delete(key);
42
- return undefined;
43
- }
44
- return entry.value;
45
- }
46
-
47
- export function writeClientCache<T>(key: string, value: T) {
48
- values.delete(key);
49
- values.set(key, { value, updatedAt: Date.now() });
50
- pruneCache();
51
- return value;
52
- }
53
-
54
- export function loadClientCache<T>(
55
- key: string,
56
- load: () => Promise<T>,
57
- {
58
- force = false,
59
- maxAgeMs = Number.POSITIVE_INFINITY,
60
- }: LoadClientCacheOptions = {},
61
- ) {
62
- if (force) {
63
- invalidateKey(key);
64
- values.delete(key);
65
- pending.delete(key);
66
- } else {
67
- const cached = readClientCache<T>(key, maxAgeMs);
68
- if (cached !== undefined) return Promise.resolve(cached);
69
- }
70
-
71
- const active = pending.get(key) as Promise<T> | undefined;
72
- if (active) return active;
73
-
74
- const token = cacheToken(key);
75
- let request: Promise<T>;
76
- request = load()
77
- .then((value) => {
78
- if (cacheToken(key) === token) writeClientCache(key, value);
79
- return value;
80
- })
81
- .finally(() => {
82
- if (pending.get(key) === request) pending.delete(key);
83
- });
84
- pending.set(key, request);
85
- return request;
86
- }
87
-
88
- export function deleteClientCache(key: string) {
89
- invalidateKey(key);
90
- values.delete(key);
91
- pending.delete(key);
92
- }
93
-
94
- export function deleteClientCacheByPrefix(prefix: string) {
95
- const keys = new Set([...values.keys(), ...pending.keys()]);
96
- for (const key of keys) {
97
- if (!key.startsWith(prefix)) continue;
98
- invalidateKey(key);
99
- values.delete(key);
100
- pending.delete(key);
101
- }
102
- }
103
-
104
- export function clearClientCache() {
105
- generation += 1;
106
- values.clear();
107
- pending.clear();
108
- revisions.clear();
109
- }