This repository has no description
0

Configure Feed

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

papers / src / worker.ts
18 kB 544 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 } 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 for (const post of newPosts) { 216 try { 217 let summary = await buildSummary(post); 218 219 // Enrich with LLM if available 220 if (apiKey && agentId) { 221 try { 222 const enrichment = await enrichWithLetta( 223 { title: summary.title, paperUrl: summary.paperUrl, abstract: summary.abstract, domains: summary.domains, venue: summary.venue }, 224 apiKey, 225 agentId, 226 ); 227 if (enrichment.title) summary.title = enrichment.title; 228 summary.summary = enrichment.summary; 229 summary.domains = enrichment.domains; 230 if (enrichment.takeaway) (summary as any).takeaway = enrichment.takeaway; 231 } catch (err: any) { 232 console.error(`Enrichment failed for ${post.paperUrl}: ${err?.message ?? err}, using heuristic`); 233 } 234 } 235 236 const result = await writeSummaryToPds(post, summary); 237 238 // Index the new record into D1 directly 239 const rkey = result.uri.split("/").pop() || ""; 240 await db 241 .prepare("INSERT OR REPLACE INTO records_summary (uri, cid, did, rkey, record, time_us, indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?)") 242 .bind(result.uri, result.cid, "did:plc:3kkhul7jznlb6ba7rprzawnj", rkey, JSON.stringify({ 243 $type: "org.latha.papers.summary", 244 ...summary, 245 sourceUri: post.postUri, 246 posterDid: post.posterDid, 247 posterHandle: post.posterHandle, 248 postText: post.postText, 249 indexedAt: new Date().toISOString(), 250 }), Date.now() * 1000, Date.now() * 1000) 251 .run(); 252 written++; 253 } catch (err: any) { 254 const msg = `${post.paperUrl}: ${err?.message ?? err}`; 255 console.error(`Failed to write summary for ${msg}`); 256 if (errors < 3) errorDetails.push(msg.substring(0, 200)); 257 errors++; 258 } 259 } 260 261 // Save cursor 262 if (newCursor) { 263 await db 264 .prepare("INSERT OR REPLACE INTO instance_settings (key, value) VALUES ('feed_cursor', ?)") 265 .bind(newCursor) 266 .run(); 267 } 268 269 return c.json({ 270 polled: posts.length, 271 fromFeed: feedPosts.length, 272 fromFollows: followedPosts.length, 273 new: newPosts.length, 274 written, 275 errors, 276 lastError: errors > 0 ? errorDetails[0] : undefined, 277 }); 278 }); 279 280 // Health check 281 app.get("/api/health", async (c) => { 282 await ensureContrailReady(db); 283 let count = 0; 284 try { 285 const row = await db 286 .prepare("SELECT COUNT(*) as cnt FROM records_summary") 287 .first<{ cnt: number }>(); 288 count = row?.cnt || 0; 289 } catch { 290 // table might not exist yet 291 } 292 const hasKey = !!process.env.RESEARCHER_KEY_PEM; 293 return c.json({ ok: true, summaries: count, hasPdsKey: hasKey }); 294 }); 295 296 // Enrich existing summaries using Letta API 297 app.post("/api/enrich", async (c) => { 298 const apiKey = process.env.LETTA_API_KEY; 299 const agentId = process.env.LETTA_AGENT_ID; 300 if (!apiKey || !agentId) { 301 return c.json({ error: "Missing LETTA_API_KEY or LETTA_AGENT_ID" }, 500); 302 } 303 304 await ensureContrailReady(db); 305 306 // Get records that need enrichment (empty/placeholder summaries, no takeaway, or Untitled) 307 const rows = await db 308 .prepare( 309 `SELECT rkey, record FROM records_summary 310 WHERE json_extract(record, '$.summary') = '' 311 OR json_extract(record, '$.summary') LIKE 'Published in%' 312 OR json_extract(record, '$.title') = 'Untitled' 313 OR json_extract(record, '$.takeaway') IS NULL 314 OR json_extract(record, '$.takeaway') = '' 315 ORDER BY time_us DESC LIMIT 20` 316 ) 317 .all<{ rkey: string; record: string }>(); 318 319 if (!rows.results?.length) { 320 return c.json({ enriched: 0, message: "No records need enrichment" }); 321 } 322 323 let enriched = 0; 324 let errors = 0; 325 326 for (const row of rows.results) { 327 try { 328 const record = JSON.parse(row.record) as { 329 title: string; 330 paperUrl: string; 331 abstract: string; 332 domains: string[]; 333 venue: string; 334 summary: string; 335 takeaway?: string; 336 }; 337 338 const result = await enrichWithLetta( 339 { 340 title: record.title, 341 paperUrl: record.paperUrl, 342 abstract: record.abstract, 343 domains: record.domains || [], 344 venue: record.venue || "", 345 }, 346 apiKey, 347 agentId, 348 ); 349 350 // Update the record in D1 351 record.summary = result.summary; 352 record.domains = result.domains; 353 if (result.takeaway) record.takeaway = result.takeaway; 354 if (result.title) record.title = result.title; 355 356 await db 357 .prepare("UPDATE records_summary SET record = ? WHERE rkey = ?") 358 .bind(JSON.stringify(record), row.rkey) 359 .run(); 360 361 enriched++; 362 console.log(`Enriched: ${record.title?.substring(0, 50)}...`); 363 } catch (err: any) { 364 console.error(`Enrichment failed for ${row.rkey}: ${err?.message ?? err}`); 365 errors++; 366 } 367 } 368 369 return c.json({ enriched, errors, total: rows.results.length }); 370 }); 371 372 // Crawl endpoint: register a DID and trigger immediate ingest 373 app.post("/xrpc/com.atproto.sync.requestCrawl", async (c) => { 374 let body: { did?: string; hostname?: string }; 375 try { 376 body = await c.req.json(); 377 } catch { 378 body = {}; 379 } 380 const did = body.did; 381 if (!did) { 382 return c.json({ error: "BadRequest", message: "Provide did" }, 400); 383 } 384 385 await ensureContrailReady(db); 386 try { 387 // Ensure identities table has this DID 388 await db.exec( 389 "CREATE TABLE IF NOT EXISTS identities (did TEXT PRIMARY KEY, handle TEXT, time_us INTEGER)" 390 ); 391 await db 392 .prepare("INSERT OR IGNORE INTO identities (did, handle, time_us) VALUES (?, ?, ?)") 393 .bind(did, "researcher.pds.latha.org", Date.now() * 1000) 394 .run(); 395 396 // Ensure records_summary table exists 397 await db.exec( 398 "CREATE TABLE IF NOT EXISTS records_summary (uri TEXT PRIMARY KEY, cid TEXT, did TEXT, rkey TEXT, record TEXT, time_us INTEGER)" 399 ); 400 401 // Fetch records from PDS and insert directly 402 const pdsUrl = `https://pds.latha.org/xrpc/com.atproto.repo.listRecords?repo=${did}&collection=org.latha.papers.summary&limit=100`; 403 const res = await fetch(pdsUrl); 404 if (res.ok) { 405 const data = await res.json() as { 406 records: Array<{ uri: string; cid: string; value: any }>; 407 }; 408 for (const rec of data.records) { 409 const rkey = rec.uri.split("/").pop() || ""; 410 await db 411 .prepare( 412 "INSERT OR REPLACE INTO records_summary (uri, cid, did, rkey, record, time_us) VALUES (?, ?, ?, ?, ?, ?)" 413 ) 414 .bind(rec.uri, rec.cid, did, rkey, JSON.stringify(rec.value), Date.now() * 1000) 415 .run(); 416 } 417 } 418 } catch (err: any) { 419 console.error(`Crawl error: ${err?.message ?? err}`); 420 } 421 422 return c.json({ ok: true, did }); 423 }); 424 425 // All other routes pass through to contrail 426 app.all("*", async (c) => { 427 const response = await contrailWorker.fetch( 428 c.req.raw, 429 c.env as unknown as Record<string, unknown> 430 ); 431 return response; 432 }); 433 434 return app; 435} 436 437export default { 438 fetch(request: Request, env: Env): Response | Promise<Response> { 439 app ??= buildApp(env); 440 return app.fetch(request, env); 441 }, 442 async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) { 443 // Cron: poll feed and generate summaries 444 const db = env.DB; 445 await ensureContrailReady(db); 446 447 let lastCursor: string | undefined; 448 try { 449 const row = await db 450 .prepare("SELECT value FROM instance_settings WHERE key = 'feed_cursor' LIMIT 1") 451 .first<{ value: string }>(); 452 lastCursor = row?.value || undefined; 453 } catch { 454 // first run 455 } 456 457 const { posts: feedPosts, newCursor } = await pollNewPapers(lastCursor); 458 459 // Also poll followed accounts 460 let followedPosts: PaperPost[] = []; 461 try { 462 followedPosts = await pollFollowedAccounts(5); 463 } catch {} 464 465 // Merge and deduplicate 466 const seenPaperUrls = new Set<string>(); 467 const posts: PaperPost[] = []; 468 for (const p of [...feedPosts, ...followedPosts]) { 469 if (!seenPaperUrls.has(p.paperUrl)) { 470 seenPaperUrls.add(p.paperUrl); 471 posts.push(p); 472 } 473 } 474 475 // Deduplicate against existing records 476 const existingUrls = new Set<string>(); 477 if (posts.length > 0) { 478 const placeholders = posts.map(() => "?").join(","); 479 const urls = posts.map(p => p.paperUrl); 480 const rows = await db 481 .prepare( 482 `SELECT DISTINCT json_extract(record, '$.paperUrl') as paperUrl FROM records_summary WHERE paperUrl IN (${placeholders})` 483 ) 484 .bind(...urls) 485 .all<{ paperUrl: string }>(); 486 for (const r of rows.results || []) { 487 if (r.paperUrl) existingUrls.add(r.paperUrl); 488 } 489 } 490 491 const newPosts = posts.filter(p => !existingUrls.has(p.paperUrl)); 492 const apiKey = process.env.LETTA_API_KEY; 493 const agentId = process.env.LETTA_AGENT_ID; 494 495 for (const post of newPosts) { 496 try { 497 let summary = await buildSummary(post); 498 499 // Enrich with LLM if available 500 if (apiKey && agentId) { 501 try { 502 const enrichment = await enrichWithLetta( 503 { title: summary.title, paperUrl: summary.paperUrl, abstract: summary.abstract, domains: summary.domains, venue: summary.venue }, 504 apiKey, 505 agentId, 506 ); 507 if (enrichment.title) summary.title = enrichment.title; 508 summary.summary = enrichment.summary; 509 summary.domains = enrichment.domains; 510 if (enrichment.takeaway) (summary as any).takeaway = enrichment.takeaway; 511 } catch { 512 // Fall back to heuristic summary 513 } 514 } 515 516 const result = await writeSummaryToPds(post, summary); 517 518 // Index into D1 519 const rkey = result.uri.split("/").pop() || ""; 520 await db 521 .prepare("INSERT OR REPLACE INTO records_summary (uri, cid, did, rkey, record, time_us, indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?)") 522 .bind(result.uri, result.cid, "did:plc:3kkhul7jznlb6ba7rprzawnj", rkey, JSON.stringify({ 523 $type: "org.latha.papers.summary", 524 ...summary, 525 sourceUri: post.postUri, 526 posterDid: post.posterDid, 527 posterHandle: post.posterHandle, 528 postText: post.postText, 529 indexedAt: new Date().toISOString(), 530 }), Date.now() * 1000, Date.now() * 1000) 531 .run(); 532 } catch (err: any) { 533 console.error(`Cron: failed to write summary for ${post.paperUrl}: ${err?.message ?? err}`); 534 } 535 } 536 537 if (newCursor) { 538 await db 539 .prepare("INSERT OR REPLACE INTO instance_settings (key, value) VALUES ('feed_cursor', ?)") 540 .bind(newCursor) 541 .run(); 542 } 543 }, 544};