This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

papers / src / worker.ts
20 kB 599 lines
1/** 2 * Papers Appview — watches the Paper Skygest feed, detects linked papers, 3 * generates summaries, and writes org.latha.papers.summary records to PDS. 4 * 5 * Hosted at papers.latha.org 6 */ 7 8import { Hono } from "hono"; 9import { cors } from "hono/cors"; 10import { createWorker } from "@atmo-dev/contrail/worker"; 11import { Contrail } from "@atmo-dev/contrail"; 12import { lexicons } from "../lexicons/generated/index.js"; 13import { config } from "./contrail.config.js"; 14import { pollNewPapers, pollFollowedAccounts, type PaperPost } from "./feed-watcher.js"; 15import { buildSummary, enrichWithLetta, type PaperSummary } from "./paper-summarizer.js"; 16import { writeSummaryToPds } from "./pds-writer.js"; 17import { LANDING_PAGE } from "./landing-page.js"; 18import { SUMMARY_PAGE } from "./summary-page.js"; 19 20interface Env { 21 DB: D1Database; 22 FEED_CURSOR?: string; 23 RESEARCHER_KEY_PEM?: string; 24 LETTA_API_KEY?: string; 25 LETTA_AGENT_ID?: string; 26} 27 28const contrailWorker = createWorker(config, { lexicons }); 29const contrail = new Contrail(config); 30let contrailReady = false; 31 32async function ensureContrailReady(db: D1Database): Promise<void> { 33 if (contrailReady) return; 34 await contrail.init(db); 35 contrailReady = true; 36} 37 38let app: Hono<{ Bindings: Env }> | null = null; 39 40function buildApp(env: Env): Hono<{ Bindings: Env }> { 41 const app = new Hono<{ Bindings: Env }>(); 42 const db = env.DB; 43 44 app.use("*", cors()); 45 46 // Landing page — browse all indexed summaries 47 app.get("/", async (c) => { 48 await ensureContrailReady(db); 49 50 let summaries: any[] = []; 51 try { 52 const rows = await db 53 .prepare( 54 "SELECT uri, record, did, rkey, time_us FROM records_summary ORDER BY time_us DESC LIMIT 100" 55 ) 56 .all(); 57 summaries = (rows.results || []).map((r: any) => { 58 try { 59 const value = JSON.parse(r.record); 60 return { 61 uri: r.uri, 62 rkey: r.rkey, 63 title: value?.title || "Untitled", 64 paperUrl: value?.paperUrl || "", 65 venue: value?.venue || "", 66 year: value?.year || null, 67 authors: value?.authors || [], 68 summary: value?.summary || "", 69 domains: value?.domains || [], 70 posterHandle: value?.posterHandle || "", 71 indexedAt: value?.indexedAt || "", 72 }; 73 } catch { 74 return null; 75 } 76 }).filter(Boolean); 77 } catch { 78 // empty list is fine 79 } 80 81 const page = LANDING_PAGE.replace( 82 "</head>", 83 `<script>window.__SUMMARIES__=${JSON.stringify(summaries).replace(/<\//g, "<\\/")};</script></head>` 84 ); 85 return c.html(page); 86 }); 87 88 // Summary detail page 89 app.get("/paper/:rkey", async (c) => { 90 const rkey = c.req.param("rkey"); 91 await ensureContrailReady(db); 92 93 let summary: any = null; 94 try { 95 const row = await db 96 .prepare("SELECT uri, record, did, rkey FROM records_summary WHERE rkey = ? LIMIT 1") 97 .bind(rkey) 98 .first<{ uri: string; record: string; did: string; rkey: string }>(); 99 if (row) { 100 const value = JSON.parse(row.record); 101 summary = { 102 uri: row.uri, 103 rkey: row.rkey, 104 ...value, 105 }; 106 } 107 } catch { 108 // not found 109 } 110 111 if (!summary) { 112 return c.html("<h1>Not Found</h1>", 404); 113 } 114 115 const page = SUMMARY_PAGE.replace( 116 "</head>", 117 `<script>window.__SUMMARY__=${JSON.stringify(summary)};</script></head>` 118 ); 119 return c.html(page); 120 }); 121 122 // API: list summaries as JSON 123 app.get("/api/summaries", async (c) => { 124 await ensureContrailReady(db); 125 const limit = Math.min(Number(c.req.query("limit") || 50), 200); 126 const cursor = c.req.query("cursor"); 127 128 let rows: D1Result<any>; 129 if (cursor) { 130 rows = await db 131 .prepare("SELECT uri, record, did, rkey, time_us FROM records_summary WHERE time_us < ? ORDER BY time_us DESC LIMIT ?") 132 .bind(cursor, limit) 133 .all(); 134 } else { 135 rows = await db 136 .prepare("SELECT uri, record, did, rkey, time_us FROM records_summary ORDER BY time_us DESC LIMIT ?") 137 .bind(limit) 138 .all(); 139 } 140 141 const summaries = (rows.results || []).map((r: any) => { 142 try { 143 const value = JSON.parse(r.record); 144 return { uri: r.uri, rkey: r.rkey, ...value }; 145 } catch { 146 return null; 147 } 148 }).filter(Boolean); 149 150 const lastRow = rows.results?.[rows.results.length - 1]; 151 const nextCursor = lastRow?.time_us || undefined; 152 153 return c.json({ summaries, cursor: nextCursor }); 154 }); 155 156 // API: trigger feed poll + summary generation 157 app.post("/api/poll", async (c) => { 158 await ensureContrailReady(db); 159 160 // Get last cursor from D1 161 let lastCursor: string | undefined; 162 try { 163 const row = await db 164 .prepare("SELECT value FROM instance_settings WHERE key = 'feed_cursor' LIMIT 1") 165 .first<{ value: string }>(); 166 lastCursor = row?.value || undefined; 167 } catch { 168 // first run 169 } 170 171 const { posts: feedPosts, newCursor } = await pollNewPapers(lastCursor); 172 173 // Also poll followed accounts for paper links 174 let followedPosts: PaperPost[] = []; 175 try { 176 followedPosts = await pollFollowedAccounts(5); 177 } catch (err: any) { 178 console.error(`Followed accounts poll failed: ${err?.message ?? err}`); 179 } 180 181 // Merge and deduplicate 182 const seenPaperUrls = new Set<string>(); 183 const posts: PaperPost[] = []; 184 for (const p of [...feedPosts, ...followedPosts]) { 185 if (!seenPaperUrls.has(p.paperUrl)) { 186 seenPaperUrls.add(p.paperUrl); 187 posts.push(p); 188 } 189 } 190 191 // Deduplicate against existing records 192 const existingUrls = new Set<string>(); 193 if (posts.length > 0) { 194 const placeholders = posts.map(() => "?").join(","); 195 const urls = posts.map(p => p.paperUrl); 196 const rows = await db 197 .prepare( 198 `SELECT DISTINCT json_extract(record, '$.paperUrl') as paperUrl FROM records_summary WHERE paperUrl IN (${placeholders})` 199 ) 200 .bind(...urls) 201 .all<{ paperUrl: string }>(); 202 for (const r of rows.results || []) { 203 if (r.paperUrl) existingUrls.add(r.paperUrl); 204 } 205 } 206 207 const newPosts = posts.filter(p => !existingUrls.has(p.paperUrl)); 208 let written = 0; 209 let errors = 0; 210 const errorDetails: string[] = []; 211 212 const apiKey = process.env.LETTA_API_KEY; 213 const agentId = process.env.LETTA_AGENT_ID; 214 215 // Build heuristic summaries in parallel 216 const heuristicResults = await Promise.all(newPosts.map(async (post) => { 217 try { 218 return { post, summary: await buildSummary(post) }; 219 } catch (err: any) { 220 return { post, error: err?.message ?? err }; 221 } 222 })); 223 224 // Enrich in parallel (batch of 5 to avoid rate limits) 225 const enrichedResults: Array<{ post: PaperPost; summary: PaperSummary; error?: string }> = []; 226 for (let i = 0; i < heuristicResults.length; i += 5) { 227 const batch = heuristicResults.slice(i, i + 5); 228 const batchResults = await Promise.all(batch.map(async ({ post, summary, error }) => { 229 if (error || !summary) return { post, summary: summary!, error }; 230 if (!apiKey || !agentId) return { post, summary }; 231 try { 232 const enrichment = await enrichWithLetta( 233 { title: summary.title, paperUrl: summary.paperUrl, abstract: summary.abstract, domains: summary.domains, venue: summary.venue }, 234 apiKey, 235 agentId, 236 ); 237 if (enrichment.title) summary.title = enrichment.title; 238 summary.summary = enrichment.summary; 239 summary.domains = enrichment.domains; 240 if (enrichment.takeaway) (summary as any).takeaway = enrichment.takeaway; 241 if (enrichment.year) summary.year = enrichment.year; 242 return { post, summary }; 243 } catch (err: any) { 244 console.error(`Enrichment failed for ${post.paperUrl}: ${err?.message ?? err}, using heuristic`); 245 return { post, summary }; 246 } 247 })); 248 enrichedResults.push(...batchResults); 249 } 250 251 // Write all to PDS and D1 252 for (const { post, summary, error } of enrichedResults) { 253 if (error || !summary) { 254 const msg = `${post.paperUrl}: ${error}`; 255 console.error(`Failed to build summary for ${msg}`); 256 if (errors < 3) errorDetails.push(msg.substring(0, 200)); 257 errors++; 258 continue; 259 } 260 try { 261 const result = await writeSummaryToPds(post, summary); 262 263 const rkey = result.uri.split("/").pop() || ""; 264 await db 265 .prepare("INSERT OR REPLACE INTO records_summary (uri, cid, did, rkey, record, time_us, indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?)") 266 .bind(result.uri, result.cid, "did:plc:3kkhul7jznlb6ba7rprzawnj", rkey, JSON.stringify({ 267 $type: "org.latha.papers.summary", 268 ...summary, 269 sourceUri: post.postUri, 270 posterDid: post.posterDid, 271 posterHandle: post.posterHandle, 272 postText: post.postText, 273 indexedAt: new Date().toISOString(), 274 }), Date.now() * 1000, Date.now() * 1000) 275 .run(); 276 written++; 277 } catch (err: any) { 278 const msg = `${post.paperUrl}: ${err?.message ?? err}`; 279 console.error(`Failed to write summary for ${msg}`); 280 if (errors < 3) errorDetails.push(msg.substring(0, 200)); 281 errors++; 282 } 283 } 284 285 // Save cursor 286 if (newCursor) { 287 await db 288 .prepare("INSERT OR REPLACE INTO instance_settings (key, value) VALUES ('feed_cursor', ?)") 289 .bind(newCursor) 290 .run(); 291 } 292 293 return c.json({ 294 polled: posts.length, 295 fromFeed: feedPosts.length, 296 fromFollows: followedPosts.length, 297 new: newPosts.length, 298 written, 299 errors, 300 lastError: errors > 0 ? errorDetails[0] : undefined, 301 }); 302 }); 303 304 // Health check 305 app.get("/api/health", async (c) => { 306 await ensureContrailReady(db); 307 let count = 0; 308 try { 309 const row = await db 310 .prepare("SELECT COUNT(*) as cnt FROM records_summary") 311 .first<{ cnt: number }>(); 312 count = row?.cnt || 0; 313 } catch { 314 // table might not exist yet 315 } 316 const hasKey = !!process.env.RESEARCHER_KEY_PEM; 317 return c.json({ ok: true, summaries: count, hasPdsKey: hasKey }); 318 }); 319 320 // Enrich existing summaries using Letta API 321 app.post("/api/enrich", async (c) => { 322 const apiKey = process.env.LETTA_API_KEY; 323 const agentId = process.env.LETTA_AGENT_ID; 324 if (!apiKey || !agentId) { 325 return c.json({ error: "Missing LETTA_API_KEY or LETTA_AGENT_ID" }, 500); 326 } 327 328 await ensureContrailReady(db); 329 330 // Get records that need enrichment (empty/placeholder summaries, no takeaway, Untitled, or missing year) 331 const rows = await db 332 .prepare( 333 `SELECT rkey, record FROM records_summary 334 WHERE json_extract(record, '$.summary') = '' 335 OR json_extract(record, '$.summary') LIKE 'Published in%' 336 OR json_extract(record, '$.title') = 'Untitled' 337 OR json_extract(record, '$.takeaway') IS NULL 338 OR json_extract(record, '$.takeaway') = '' 339 OR json_extract(record, '$.year') IS NULL 340 OR json_extract(record, '$.year') = 0 341 ORDER BY time_us DESC LIMIT 20` 342 ) 343 .all<{ rkey: string; record: string }>(); 344 345 if (!rows.results?.length) { 346 return c.json({ enriched: 0, message: "No records need enrichment" }); 347 } 348 349 let enriched = 0; 350 let errors = 0; 351 352 // Enrich in parallel batches of 5 353 for (let i = 0; i < rows.results.length; i += 5) { 354 const batch = rows.results.slice(i, i + 5); 355 const results = await Promise.allSettled(batch.map(async (row) => { 356 const record = JSON.parse(row.record) as { 357 title: string; 358 paperUrl: string; 359 abstract: string; 360 domains: string[]; 361 venue: string; 362 summary: string; 363 takeaway?: string; 364 year?: number; 365 }; 366 367 const result = await enrichWithLetta( 368 { 369 title: record.title, 370 paperUrl: record.paperUrl, 371 abstract: record.abstract, 372 domains: record.domains || [], 373 venue: record.venue || "", 374 }, 375 apiKey, 376 agentId, 377 ); 378 379 record.summary = result.summary; 380 record.domains = result.domains; 381 if (result.takeaway) record.takeaway = result.takeaway; 382 if (result.title) record.title = result.title; 383 if (result.year) record.year = result.year; 384 385 await db 386 .prepare("UPDATE records_summary SET record = ? WHERE rkey = ?") 387 .bind(JSON.stringify(record), row.rkey) 388 .run(); 389 390 return record.title; 391 })); 392 393 for (const r of results) { 394 if (r.status === "fulfilled") { 395 enriched++; 396 console.log(`Enriched: ${r.value?.substring(0, 50)}...`); 397 } else { 398 console.error(`Enrichment failed: ${r.reason}`); 399 errors++; 400 } 401 } 402 } 403 404 return c.json({ enriched, errors, total: rows.results.length }); 405 }); 406 407 // Crawl endpoint: register a DID and trigger immediate ingest 408 app.post("/xrpc/com.atproto.sync.requestCrawl", async (c) => { 409 let body: { did?: string; hostname?: string }; 410 try { 411 body = await c.req.json(); 412 } catch { 413 body = {}; 414 } 415 const did = body.did; 416 if (!did) { 417 return c.json({ error: "BadRequest", message: "Provide did" }, 400); 418 } 419 420 await ensureContrailReady(db); 421 try { 422 // Ensure identities table has this DID 423 await db.exec( 424 "CREATE TABLE IF NOT EXISTS identities (did TEXT PRIMARY KEY, handle TEXT, time_us INTEGER)" 425 ); 426 await db 427 .prepare("INSERT OR IGNORE INTO identities (did, handle, time_us) VALUES (?, ?, ?)") 428 .bind(did, "researcher.pds.latha.org", Date.now() * 1000) 429 .run(); 430 431 // Ensure records_summary table exists 432 await db.exec( 433 "CREATE TABLE IF NOT EXISTS records_summary (uri TEXT PRIMARY KEY, cid TEXT, did TEXT, rkey TEXT, record TEXT, time_us INTEGER)" 434 ); 435 436 // Fetch records from PDS and insert directly 437 const pdsUrl = `https://pds.latha.org/xrpc/com.atproto.repo.listRecords?repo=${did}&collection=org.latha.papers.summary&limit=100`; 438 const res = await fetch(pdsUrl); 439 if (res.ok) { 440 const data = await res.json() as { 441 records: Array<{ uri: string; cid: string; value: any }>; 442 }; 443 for (const rec of data.records) { 444 const rkey = rec.uri.split("/").pop() || ""; 445 await db 446 .prepare( 447 "INSERT OR REPLACE INTO records_summary (uri, cid, did, rkey, record, time_us) VALUES (?, ?, ?, ?, ?, ?)" 448 ) 449 .bind(rec.uri, rec.cid, did, rkey, JSON.stringify(rec.value), Date.now() * 1000) 450 .run(); 451 } 452 } 453 } catch (err: any) { 454 console.error(`Crawl error: ${err?.message ?? err}`); 455 } 456 457 return c.json({ ok: true, did }); 458 }); 459 460 // All other routes pass through to contrail 461 app.all("*", async (c) => { 462 const response = await contrailWorker.fetch( 463 c.req.raw, 464 c.env as unknown as Record<string, unknown> 465 ); 466 return response; 467 }); 468 469 return app; 470} 471 472export default { 473 fetch(request: Request, env: Env): Response | Promise<Response> { 474 app ??= buildApp(env); 475 return app.fetch(request, env); 476 }, 477 async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) { 478 // Cron: poll feed and generate summaries 479 const db = env.DB; 480 await ensureContrailReady(db); 481 482 let lastCursor: string | undefined; 483 try { 484 const row = await db 485 .prepare("SELECT value FROM instance_settings WHERE key = 'feed_cursor' LIMIT 1") 486 .first<{ value: string }>(); 487 lastCursor = row?.value || undefined; 488 } catch { 489 // first run 490 } 491 492 const { posts: feedPosts, newCursor } = await pollNewPapers(lastCursor); 493 494 // Also poll followed accounts 495 let followedPosts: PaperPost[] = []; 496 try { 497 followedPosts = await pollFollowedAccounts(5); 498 } catch {} 499 500 // Merge and deduplicate 501 const seenPaperUrls = new Set<string>(); 502 const posts: PaperPost[] = []; 503 for (const p of [...feedPosts, ...followedPosts]) { 504 if (!seenPaperUrls.has(p.paperUrl)) { 505 seenPaperUrls.add(p.paperUrl); 506 posts.push(p); 507 } 508 } 509 510 // Deduplicate against existing records 511 const existingUrls = new Set<string>(); 512 if (posts.length > 0) { 513 const placeholders = posts.map(() => "?").join(","); 514 const urls = posts.map(p => p.paperUrl); 515 const rows = await db 516 .prepare( 517 `SELECT DISTINCT json_extract(record, '$.paperUrl') as paperUrl FROM records_summary WHERE paperUrl IN (${placeholders})` 518 ) 519 .bind(...urls) 520 .all<{ paperUrl: string }>(); 521 for (const r of rows.results || []) { 522 if (r.paperUrl) existingUrls.add(r.paperUrl); 523 } 524 } 525 526 const newPosts = posts.filter(p => !existingUrls.has(p.paperUrl)); 527 const apiKey = process.env.LETTA_API_KEY; 528 const agentId = process.env.LETTA_AGENT_ID; 529 530 // Build heuristic summaries in parallel 531 const heuristicResults = await Promise.all(newPosts.map(async (post) => { 532 try { 533 return { post, summary: await buildSummary(post) }; 534 } catch (err: any) { 535 return { post, error: err?.message ?? err }; 536 } 537 })); 538 539 // Enrich in parallel (batch of 5) 540 const enrichedResults: Array<{ post: PaperPost; summary: PaperSummary; error?: string }> = []; 541 for (let i = 0; i < heuristicResults.length; i += 5) { 542 const batch = heuristicResults.slice(i, i + 5); 543 const batchResults = await Promise.all(batch.map(async ({ post, summary, error }) => { 544 if (error || !summary) return { post, summary: summary!, error }; 545 if (!apiKey || !agentId) return { post, summary }; 546 try { 547 const enrichment = await enrichWithLetta( 548 { title: summary.title, paperUrl: summary.paperUrl, abstract: summary.abstract, domains: summary.domains, venue: summary.venue }, 549 apiKey, 550 agentId, 551 ); 552 if (enrichment.title) summary.title = enrichment.title; 553 summary.summary = enrichment.summary; 554 summary.domains = enrichment.domains; 555 if (enrichment.takeaway) (summary as any).takeaway = enrichment.takeaway; 556 if (enrichment.year) summary.year = enrichment.year; 557 return { post, summary }; 558 } catch { 559 return { post, summary }; 560 } 561 })); 562 enrichedResults.push(...batchResults); 563 } 564 565 // Write all to PDS and D1 566 for (const { post, summary, error } of enrichedResults) { 567 if (error || !summary) { 568 console.error(`Cron: failed to build summary for ${post.paperUrl}: ${error}`); 569 continue; 570 } 571 try { 572 const result = await writeSummaryToPds(post, summary); 573 574 const rkey = result.uri.split("/").pop() || ""; 575 await db 576 .prepare("INSERT OR REPLACE INTO records_summary (uri, cid, did, rkey, record, time_us, indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?)") 577 .bind(result.uri, result.cid, "did:plc:3kkhul7jznlb6ba7rprzawnj", rkey, JSON.stringify({ 578 $type: "org.latha.papers.summary", 579 ...summary, 580 sourceUri: post.postUri, 581 posterDid: post.posterDid, 582 posterHandle: post.posterHandle, 583 postText: post.postText, 584 indexedAt: new Date().toISOString(), 585 }), Date.now() * 1000, Date.now() * 1000) 586 .run(); 587 } catch (err: any) { 588 console.error(`Cron: failed to write summary for ${post.paperUrl}: ${err?.message ?? err}`); 589 } 590 } 591 592 if (newCursor) { 593 await db 594 .prepare("INSERT OR REPLACE INTO instance_settings (key, value) VALUES ('feed_cursor', ?)") 595 .bind(newCursor) 596 .run(); 597 } 598 }, 599};