oculon 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +344 -2
- package/dist/agent.d.ts +47 -0
- package/dist/agent.js +104 -0
- package/dist/cases.d.ts +68 -0
- package/dist/cases.js +158 -0
- package/dist/cli/main.d.ts +12 -0
- package/dist/cli/main.js +1999 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +15 -0
- package/dist/core/context.d.ts +19 -0
- package/dist/core/context.js +19 -0
- package/dist/core/features.d.ts +22 -0
- package/dist/core/features.js +28 -0
- package/dist/core/graph.d.ts +38 -0
- package/dist/core/graph.js +81 -0
- package/dist/core/http.d.ts +42 -0
- package/dist/core/http.js +266 -0
- package/dist/core/keys.d.ts +8 -0
- package/dist/core/keys.js +22 -0
- package/dist/core/llm.d.ts +93 -0
- package/dist/core/llm.js +180 -0
- package/dist/core/merkle.d.ts +15 -0
- package/dist/core/merkle.js +46 -0
- package/dist/core/paths.d.ts +2 -0
- package/dist/core/paths.js +6 -0
- package/dist/core/png.d.ts +17 -0
- package/dist/core/png.js +101 -0
- package/dist/core/quota.d.ts +15 -0
- package/dist/core/quota.js +90 -0
- package/dist/core/stats.d.ts +24 -0
- package/dist/core/stats.js +67 -0
- package/dist/core/store.d.ts +20 -0
- package/dist/core/store.js +213 -0
- package/dist/core/text.d.ts +9 -0
- package/dist/core/text.js +30 -0
- package/dist/core/types.d.ts +38 -0
- package/dist/core/types.js +1 -0
- package/dist/index.d.ts +342 -0
- package/dist/index.js +495 -0
- package/dist/live.d.ts +53 -0
- package/dist/live.js +236 -0
- package/dist/mcp.d.ts +43 -0
- package/dist/mcp.js +651 -0
- package/dist/modules/airport.d.ts +60 -0
- package/dist/modules/airport.js +111 -0
- package/dist/modules/audit.d.ts +73 -0
- package/dist/modules/audit.js +211 -0
- package/dist/modules/bgp.d.ts +147 -0
- package/dist/modules/bgp.js +206 -0
- package/dist/modules/blackout.d.ts +41 -0
- package/dist/modules/blackout.js +98 -0
- package/dist/modules/brief.d.ts +26 -0
- package/dist/modules/brief.js +99 -0
- package/dist/modules/calendar.d.ts +27 -0
- package/dist/modules/calendar.js +145 -0
- package/dist/modules/calibrate.d.ts +46 -0
- package/dist/modules/calibrate.js +92 -0
- package/dist/modules/cloud.d.ts +32 -0
- package/dist/modules/cloud.js +94 -0
- package/dist/modules/condor.d.ts +66 -0
- package/dist/modules/condor.js +214 -0
- package/dist/modules/connect.d.ts +47 -0
- package/dist/modules/connect.js +114 -0
- package/dist/modules/contradictions.d.ts +27 -0
- package/dist/modules/contradictions.js +76 -0
- package/dist/modules/country.d.ts +82 -0
- package/dist/modules/country.js +136 -0
- package/dist/modules/cricket.d.ts +34 -0
- package/dist/modules/cricket.js +166 -0
- package/dist/modules/darkships.d.ts +219 -0
- package/dist/modules/darkships.js +400 -0
- package/dist/modules/defi.d.ts +237 -0
- package/dist/modules/defi.js +512 -0
- package/dist/modules/emailsec.d.ts +47 -0
- package/dist/modules/emailsec.js +146 -0
- package/dist/modules/exposure.d.ts +43 -0
- package/dist/modules/exposure.js +89 -0
- package/dist/modules/factcheck.d.ts +39 -0
- package/dist/modules/factcheck.js +127 -0
- package/dist/modules/falcon.d.ts +58 -0
- package/dist/modules/falcon.js +219 -0
- package/dist/modules/feedback.d.ts +24 -0
- package/dist/modules/feedback.js +37 -0
- package/dist/modules/fence.d.ts +52 -0
- package/dist/modules/fence.js +128 -0
- package/dist/modules/ferret.d.ts +47 -0
- package/dist/modules/ferret.js +220 -0
- package/dist/modules/filings.d.ts +86 -0
- package/dist/modules/filings.js +166 -0
- package/dist/modules/fires.d.ts +56 -0
- package/dist/modules/fires.js +150 -0
- package/dist/modules/hazards.d.ts +37 -0
- package/dist/modules/hazards.js +83 -0
- package/dist/modules/health.d.ts +24 -0
- package/dist/modules/health.js +82 -0
- package/dist/modules/heron.d.ts +68 -0
- package/dist/modules/heron.js +184 -0
- package/dist/modules/hound.d.ts +100 -0
- package/dist/modules/hound.js +301 -0
- package/dist/modules/impact.d.ts +39 -0
- package/dist/modules/impact.js +63 -0
- package/dist/modules/launches.d.ts +24 -0
- package/dist/modules/launches.js +61 -0
- package/dist/modules/listen.d.ts +48 -0
- package/dist/modules/listen.js +125 -0
- package/dist/modules/lynx.d.ts +43 -0
- package/dist/modules/lynx.js +127 -0
- package/dist/modules/magpie.d.ts +70 -0
- package/dist/modules/magpie.js +174 -0
- package/dist/modules/meerkat.d.ts +42 -0
- package/dist/modules/meerkat.js +293 -0
- package/dist/modules/monitor.d.ts +27 -0
- package/dist/modules/monitor.js +105 -0
- package/dist/modules/narratives.d.ts +33 -0
- package/dist/modules/narratives.js +136 -0
- package/dist/modules/owl.d.ts +71 -0
- package/dist/modules/owl.js +290 -0
- package/dist/modules/papers.d.ts +46 -0
- package/dist/modules/papers.js +135 -0
- package/dist/modules/personal.d.ts +54 -0
- package/dist/modules/personal.js +153 -0
- package/dist/modules/pulse.d.ts +19 -0
- package/dist/modules/pulse.js +59 -0
- package/dist/modules/raven.d.ts +80 -0
- package/dist/modules/raven.js +147 -0
- package/dist/modules/recall.d.ts +44 -0
- package/dist/modules/recall.js +123 -0
- package/dist/modules/regs.d.ts +88 -0
- package/dist/modules/regs.js +142 -0
- package/dist/modules/rewind.d.ts +22 -0
- package/dist/modules/rewind.js +68 -0
- package/dist/modules/sanctions.d.ts +62 -0
- package/dist/modules/sanctions.js +173 -0
- package/dist/modules/scam.d.ts +43 -0
- package/dist/modules/scam.js +111 -0
- package/dist/modules/scoop.d.ts +31 -0
- package/dist/modules/scoop.js +74 -0
- package/dist/modules/ships.d.ts +33 -0
- package/dist/modules/ships.js +113 -0
- package/dist/modules/sky.d.ts +47 -0
- package/dist/modules/sky.js +183 -0
- package/dist/modules/squawk.d.ts +46 -0
- package/dist/modules/squawk.js +106 -0
- package/dist/modules/tortoise.d.ts +40 -0
- package/dist/modules/tortoise.js +104 -0
- package/dist/modules/travel.d.ts +94 -0
- package/dist/modules/travel.js +241 -0
- package/dist/modules/urlcheck.d.ts +63 -0
- package/dist/modules/urlcheck.js +223 -0
- package/dist/modules/vulns.d.ts +142 -0
- package/dist/modules/vulns.js +276 -0
- package/dist/plugins.d.ts +41 -0
- package/dist/plugins.js +70 -0
- package/dist/report.d.ts +12 -0
- package/dist/report.js +90 -0
- package/dist/scheduler.d.ts +22 -0
- package/dist/scheduler.js +139 -0
- package/dist/sources/aircraft.d.ts +76 -0
- package/dist/sources/aircraft.js +107 -0
- package/dist/sources/airports.d.ts +28 -0
- package/dist/sources/airports.js +100 -0
- package/dist/sources/ais.d.ts +32 -0
- package/dist/sources/ais.js +111 -0
- package/dist/sources/apify.d.ts +28 -0
- package/dist/sources/apify.js +80 -0
- package/dist/sources/arxiv.d.ts +13 -0
- package/dist/sources/arxiv.js +27 -0
- package/dist/sources/certs.d.ts +12 -0
- package/dist/sources/certs.js +23 -0
- package/dist/sources/corp.d.ts +46 -0
- package/dist/sources/corp.js +60 -0
- package/dist/sources/earth.d.ts +39 -0
- package/dist/sources/earth.js +76 -0
- package/dist/sources/fda.d.ts +77 -0
- package/dist/sources/fda.js +121 -0
- package/dist/sources/finance.d.ts +181 -0
- package/dist/sources/finance.js +270 -0
- package/dist/sources/gdelt.d.ts +19 -0
- package/dist/sources/gdelt.js +33 -0
- package/dist/sources/github.d.ts +17 -0
- package/dist/sources/github.js +33 -0
- package/dist/sources/hackernews.d.ts +20 -0
- package/dist/sources/hackernews.js +37 -0
- package/dist/sources/labels.d.ts +21 -0
- package/dist/sources/labels.js +87 -0
- package/dist/sources/launch.d.ts +16 -0
- package/dist/sources/launch.js +41 -0
- package/dist/sources/ofac.d.ts +29 -0
- package/dist/sources/ofac.js +86 -0
- package/dist/sources/onchain.d.ts +77 -0
- package/dist/sources/onchain.js +189 -0
- package/dist/sources/opentimestamps.d.ts +44 -0
- package/dist/sources/opentimestamps.js +131 -0
- package/dist/sources/polymarket.d.ts +36 -0
- package/dist/sources/polymarket.js +70 -0
- package/dist/sources/predict.d.ts +18 -0
- package/dist/sources/predict.js +59 -0
- package/dist/sources/press.d.ts +30 -0
- package/dist/sources/press.js +111 -0
- package/dist/sources/resend.d.ts +14 -0
- package/dist/sources/resend.js +29 -0
- package/dist/sources/robinhood.d.ts +109 -0
- package/dist/sources/robinhood.js +129 -0
- package/dist/sources/sec.d.ts +67 -0
- package/dist/sources/sec.js +129 -0
- package/dist/sources/sentinel.d.ts +13 -0
- package/dist/sources/sentinel.js +63 -0
- package/dist/sources/signatures.d.ts +14 -0
- package/dist/sources/signatures.js +103 -0
- package/dist/sources/social.d.ts +22 -0
- package/dist/sources/social.js +56 -0
- package/dist/sources/space.d.ts +160 -0
- package/dist/sources/space.js +230 -0
- package/dist/sources/usgs.d.ts +17 -0
- package/dist/sources/usgs.js +24 -0
- package/dist/sources/wayback.d.ts +10 -0
- package/dist/sources/wayback.js +28 -0
- package/dist/sources/websec.d.ts +19 -0
- package/dist/sources/websec.js +40 -0
- package/dist/sources/wikidata.d.ts +11 -0
- package/dist/sources/wikidata.js +30 -0
- package/dist/sources/wikimedia.d.ts +28 -0
- package/dist/sources/wikimedia.js +52 -0
- package/dist/telegram.d.ts +104 -0
- package/dist/telegram.js +927 -0
- package/dist/web/assets/favicon-32.png +0 -0
- package/dist/web/assets/fx.js +178 -0
- package/dist/web/assets/icon-192.png +0 -0
- package/dist/web/assets/icon-512.png +0 -0
- package/dist/web/assets/icon-maskable-512.png +0 -0
- package/dist/web/assets/night-americas.jpg +0 -0
- package/dist/web/assets/night-emea.jpg +0 -0
- package/dist/web/assets/og.png +0 -0
- package/dist/web/assets/redsea-bm.jpg +0 -0
- package/dist/web/docs.html +263 -0
- package/dist/web/index.html +1828 -0
- package/dist/web/insights.d.ts +100 -0
- package/dist/web/insights.js +134 -0
- package/dist/web/landing.html +1143 -0
- package/dist/web/legal.html +176 -0
- package/dist/web/manifest.webmanifest +20 -0
- package/dist/web/mcp.html +104 -0
- package/dist/web/mcphttp.d.ts +10 -0
- package/dist/web/mcphttp.js +67 -0
- package/dist/web/openapi.d.ts +1 -0
- package/dist/web/openapi.js +51 -0
- package/dist/web/public.d.ts +45 -0
- package/dist/web/public.js +135 -0
- package/dist/web/server.d.ts +69 -0
- package/dist/web/server.js +750 -0
- package/dist/web/share.d.ts +35 -0
- package/dist/web/share.js +132 -0
- package/dist/web/sw.js +28 -0
- package/package.json +60 -4
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owl: global anomaly radar. Looks at what the world is suddenly paying attention to
|
|
3
|
+
* (Wikipedia spikes, Hacker News front page, prediction-market swings, strong earthquakes)
|
|
4
|
+
* and fuses items that point at the same subject into one corroborated signal.
|
|
5
|
+
*/
|
|
6
|
+
import type { Ctx } from '../core/context.js';
|
|
7
|
+
import type { ModuleResult } from '../core/types.js';
|
|
8
|
+
import { type Market } from '../sources/polymarket.js';
|
|
9
|
+
export interface Blip {
|
|
10
|
+
source: 'wikipedia' | 'hackernews' | 'polymarket' | 'usgs' | 'eonet' | 'nyt' | 'guardian' | 'coingecko' | 'noaa-swpc';
|
|
11
|
+
title: string;
|
|
12
|
+
url: string;
|
|
13
|
+
/** 0-100 strength of this single observation. */
|
|
14
|
+
strength: number;
|
|
15
|
+
detail: string;
|
|
16
|
+
value: number;
|
|
17
|
+
keys: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface OwlResult {
|
|
20
|
+
blips: Blip[];
|
|
21
|
+
fused: {
|
|
22
|
+
title: string;
|
|
23
|
+
score: number;
|
|
24
|
+
sources: string[];
|
|
25
|
+
shared: string[];
|
|
26
|
+
blips: Blip[];
|
|
27
|
+
linkedBy?: string;
|
|
28
|
+
}[];
|
|
29
|
+
/** Groups an LLM linked as the same event, with its reasons. Empty when no LLM key is set. */
|
|
30
|
+
aiLinks: {
|
|
31
|
+
subject: string;
|
|
32
|
+
why: string;
|
|
33
|
+
titles: string[];
|
|
34
|
+
}[];
|
|
35
|
+
}
|
|
36
|
+
export interface OwlOptions {
|
|
37
|
+
/** How many of the day's top Wikipedia articles to check for spikes. */
|
|
38
|
+
wikiDepth?: number;
|
|
39
|
+
/** Link same-event items with an LLM (default on when an LLM key is configured). */
|
|
40
|
+
aiLink?: boolean;
|
|
41
|
+
llmFetch?: typeof fetch;
|
|
42
|
+
}
|
|
43
|
+
export declare function isSportsLine(m: Market): boolean;
|
|
44
|
+
/** Markets about to resolve drift to 0/100 mechanically; that is not news. */
|
|
45
|
+
export declare function isResolving(m: Market, nowMs: number): boolean;
|
|
46
|
+
/** Strongest a single uncorroborated observation can score; corroboration adds the rest. */
|
|
47
|
+
export declare const SINGLE_SOURCE_CAP = 70;
|
|
48
|
+
export declare const CORROBORATION_BONUS = 25;
|
|
49
|
+
export declare function fuse(blips: Blip[], minOverlap?: number): OwlResult['fused'];
|
|
50
|
+
/** Score one group: its strongest blip, plus a bonus per extra independent source. */
|
|
51
|
+
export declare function scoreGroup(g: Blip[], linkedBy?: string): Fused;
|
|
52
|
+
type Fused = OwlResult['fused'][number];
|
|
53
|
+
/**
|
|
54
|
+
* Second pass with an LLM: link groups that are about the same real-world event even when they share
|
|
55
|
+
* no words (a celebrity and their partner's engagement, a company and its CEO's scandal). Strict: same
|
|
56
|
+
* event or same entity only, never "same theme". Each merge keeps the model's stated reason.
|
|
57
|
+
*/
|
|
58
|
+
export declare function aiLink(fused: Fused[], opts?: {
|
|
59
|
+
fetch?: typeof fetch;
|
|
60
|
+
max?: number;
|
|
61
|
+
}): Promise<{
|
|
62
|
+
fused: Fused[];
|
|
63
|
+
links: {
|
|
64
|
+
subject: string;
|
|
65
|
+
why: string;
|
|
66
|
+
titles: string[];
|
|
67
|
+
}[];
|
|
68
|
+
model: string | null;
|
|
69
|
+
}>;
|
|
70
|
+
export declare function owl(ctx: Ctx, opts?: OwlOptions): Promise<ModuleResult<OwlResult>>;
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { entityId } from '../core/graph.js';
|
|
2
|
+
import { clamp, robustZ, spikeRatio } from '../core/stats.js';
|
|
3
|
+
import { articleTitle, keywords, overlap, signalId } from '../core/text.js';
|
|
4
|
+
import { frontPage, hnItemUrl } from '../sources/hackernews.js';
|
|
5
|
+
import { topMarkets } from '../sources/polymarket.js';
|
|
6
|
+
import { eonetEvents } from '../sources/earth.js';
|
|
7
|
+
import { trendingCoins } from '../sources/finance.js';
|
|
8
|
+
import { nytTopStories } from '../sources/press.js';
|
|
9
|
+
import { flareFlux, kpIndex, xrayFlares } from '../sources/space.js';
|
|
10
|
+
import { recentQuakes } from '../sources/usgs.js';
|
|
11
|
+
import { eventSeverity } from './condor.js';
|
|
12
|
+
import { signalThreshold, sourceWeights } from './calibrate.js';
|
|
13
|
+
import { dailyViews, isNoiseArticle, topArticles } from '../sources/wikimedia.js';
|
|
14
|
+
const SPORTS = /\b(spread|o\/u|over\/under|moneyline|vs\.?|map \d|game \d|set \d|total (points|goals|kills)|both teams to score|handicap)\b|:\s*\w+\s*\(([+-]?\d+(\.\d+)?)\)/i;
|
|
15
|
+
const SPORTS_WIN_ON_DATE = /\bwin on \d{4}-\d{2}-\d{2}\b|\b(fc|united|city)\b.*\b(win|draw)\b/i;
|
|
16
|
+
export function isSportsLine(m) {
|
|
17
|
+
return SPORTS.test(m.question) || SPORTS_WIN_ON_DATE.test(m.question);
|
|
18
|
+
}
|
|
19
|
+
/** Markets about to resolve drift to 0/100 mechanically; that is not news. */
|
|
20
|
+
export function isResolving(m, nowMs) {
|
|
21
|
+
const end = m.endDate ? Date.parse(m.endDate) : NaN;
|
|
22
|
+
return Number.isFinite(end) && end - nowMs < 2 * 86_400_000;
|
|
23
|
+
}
|
|
24
|
+
/** Strongest a single uncorroborated observation can score; corroboration adds the rest. */
|
|
25
|
+
export const SINGLE_SOURCE_CAP = 70;
|
|
26
|
+
export const CORROBORATION_BONUS = 25;
|
|
27
|
+
const mkBlip = (b) => ({ ...b, keys: [...keywords(b.title)] });
|
|
28
|
+
export function fuse(blips, minOverlap = 0.5) {
|
|
29
|
+
const groups = [];
|
|
30
|
+
for (const b of [...blips].sort((x, y) => y.strength - x.strength)) {
|
|
31
|
+
const kb = new Set(b.keys);
|
|
32
|
+
const g = groups.find((grp) => grp.some((o) => {
|
|
33
|
+
const ov = overlap(new Set(o.keys), kb);
|
|
34
|
+
if (!ov.shared.length)
|
|
35
|
+
return false;
|
|
36
|
+
// Across sources a partial match is enough; within one source only near-identical subjects merge
|
|
37
|
+
// ("Robert Pattinson" + "Robert Pattinson filmography").
|
|
38
|
+
return o.source !== b.source ? ov.score >= minOverlap : ov.score >= 1 && ov.shared.length >= 2;
|
|
39
|
+
}));
|
|
40
|
+
if (g)
|
|
41
|
+
g.push(b);
|
|
42
|
+
else
|
|
43
|
+
groups.push([b]);
|
|
44
|
+
}
|
|
45
|
+
return groups.map((g) => scoreGroup(g)).sort((a, b) => b.score - a.score);
|
|
46
|
+
}
|
|
47
|
+
/** Score one group: its strongest blip, plus a bonus per extra independent source. */
|
|
48
|
+
export function scoreGroup(g, linkedBy) {
|
|
49
|
+
const sources = [...new Set(g.map((b) => b.source))];
|
|
50
|
+
const lead = [...g].sort((a, b) => b.strength - a.strength)[0];
|
|
51
|
+
const shared = g.length > 1 ? [...g.slice(1).reduce((acc, b) => new Set(overlap(acc, new Set(b.keys)).shared), new Set(lead.keys))] : lead.keys;
|
|
52
|
+
// Corroboration from independent sources is what turns a blip into a signal.
|
|
53
|
+
const best = Math.round((Math.max(...g.map((b) => b.strength)) / 100) * SINGLE_SOURCE_CAP);
|
|
54
|
+
const score = clamp(best + (sources.length - 1) * CORROBORATION_BONUS, 0, 100);
|
|
55
|
+
return { title: lead.title, score, sources, shared, blips: g, ...(linkedBy ? { linkedBy } : {}) };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Second pass with an LLM: link groups that are about the same real-world event even when they share
|
|
59
|
+
* no words (a celebrity and their partner's engagement, a company and its CEO's scandal). Strict: same
|
|
60
|
+
* event or same entity only, never "same theme". Each merge keeps the model's stated reason.
|
|
61
|
+
*/
|
|
62
|
+
export async function aiLink(fused, opts = {}) {
|
|
63
|
+
const { availableProviders, chat } = await import('../core/llm.js');
|
|
64
|
+
if (!availableProviders().length || fused.length < 2)
|
|
65
|
+
return { fused, links: [], model: null };
|
|
66
|
+
const top = fused.slice(0, opts.max ?? 30);
|
|
67
|
+
const list = top.map((f, i) => `${i}. [${f.sources.join('+')}] ${f.title}${f.blips[0]?.detail ? ` — ${f.blips[0].detail.slice(0, 80)}` : ''}`).join('\n');
|
|
68
|
+
let raw;
|
|
69
|
+
let model;
|
|
70
|
+
try {
|
|
71
|
+
const r = await chat([
|
|
72
|
+
{
|
|
73
|
+
role: 'system',
|
|
74
|
+
content: 'You group news items. Link items ONLY if they are about the same specific real-world event or the same person/organization in the same story. Never link items that merely share a theme (e.g. two different AI stories). Most items should stay unlinked. Respond with JSON: {"links":[{"items":[indexes],"subject":"short subject","why":"one sentence"}]}',
|
|
75
|
+
},
|
|
76
|
+
{ role: 'user', content: list },
|
|
77
|
+
], { json: true, temperature: 0, maxTokens: 800, ...(opts.fetch ? { fetch: opts.fetch } : {}) });
|
|
78
|
+
raw = r.message.content ?? '{}';
|
|
79
|
+
model = `${r.provider}:${r.model}`;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return { fused, links: [], model: null };
|
|
83
|
+
}
|
|
84
|
+
let parsed;
|
|
85
|
+
try {
|
|
86
|
+
parsed = JSON.parse(raw.replace(/^```(?:json)?|```$/g, '').trim());
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return { fused, links: [], model };
|
|
90
|
+
}
|
|
91
|
+
const used = new Set();
|
|
92
|
+
const merged = [];
|
|
93
|
+
const links = [];
|
|
94
|
+
for (const l of parsed.links ?? []) {
|
|
95
|
+
const idx = [...new Set((l.items ?? []).map(Number))].filter((i) => Number.isInteger(i) && i >= 0 && i < top.length && !used.has(i));
|
|
96
|
+
if (idx.length < 2)
|
|
97
|
+
continue;
|
|
98
|
+
idx.forEach((i) => used.add(i));
|
|
99
|
+
const why = String(l.why ?? '').slice(0, 200);
|
|
100
|
+
const subject = String(l.subject ?? '').slice(0, 80);
|
|
101
|
+
const group = scoreGroup(idx.flatMap((i) => top[i].blips), `${model}: ${why}`);
|
|
102
|
+
if (subject)
|
|
103
|
+
group.title = subject;
|
|
104
|
+
merged.push(group);
|
|
105
|
+
links.push({ subject, why, titles: idx.map((i) => top[i].title) });
|
|
106
|
+
}
|
|
107
|
+
const rest = fused.filter((_, i) => !(i < top.length && used.has(i)));
|
|
108
|
+
return { fused: [...merged, ...rest].sort((a, b) => b.score - a.score), links, model };
|
|
109
|
+
}
|
|
110
|
+
function blipKind(source) {
|
|
111
|
+
if (source === 'polymarket' || source === 'coingecko')
|
|
112
|
+
return 'market';
|
|
113
|
+
if (source === 'usgs' || source === 'eonet' || source === 'noaa-swpc')
|
|
114
|
+
return 'event';
|
|
115
|
+
if (source === 'hackernews' || source === 'nyt' || source === 'guardian')
|
|
116
|
+
return 'story';
|
|
117
|
+
return 'article';
|
|
118
|
+
}
|
|
119
|
+
export async function owl(ctx, opts = {}) {
|
|
120
|
+
const provenance = [];
|
|
121
|
+
const blips = [];
|
|
122
|
+
const nowMs = ctx.now().getTime();
|
|
123
|
+
const [top, hn, markets, quakes, natural, nyt, coins, kp, flares] = await Promise.all([
|
|
124
|
+
topArticles(ctx),
|
|
125
|
+
frontPage(ctx),
|
|
126
|
+
topMarkets(ctx, 200),
|
|
127
|
+
recentQuakes(ctx),
|
|
128
|
+
eonetEvents(ctx, 3),
|
|
129
|
+
nytTopStories(ctx),
|
|
130
|
+
trendingCoins(ctx),
|
|
131
|
+
kpIndex(ctx),
|
|
132
|
+
xrayFlares(ctx),
|
|
133
|
+
]);
|
|
134
|
+
provenance.push(top.prov, hn.prov, markets.prov, quakes.prov, natural.prov, nyt.prov, coins.prov, kp.prov, flares.prov);
|
|
135
|
+
// Wikipedia: which of today's most-read articles are far above their own normal?
|
|
136
|
+
if (top.data) {
|
|
137
|
+
const candidates = top.data.articles.filter((a) => !isNoiseArticle(a.article)).slice(0, opts.wikiDepth ?? 25);
|
|
138
|
+
const series = await Promise.all(candidates.map((a) => dailyViews(ctx, a.article, 30)));
|
|
139
|
+
series.forEach((s, i) => {
|
|
140
|
+
provenance.push(s.prov);
|
|
141
|
+
const a = candidates[i];
|
|
142
|
+
const vals = s.data?.map((d) => d.views);
|
|
143
|
+
if (!vals || vals.length < 10)
|
|
144
|
+
return;
|
|
145
|
+
const last = vals[vals.length - 1];
|
|
146
|
+
const base = vals.slice(0, -3);
|
|
147
|
+
const ratio = spikeRatio(last, base);
|
|
148
|
+
const z = robustZ(last, base);
|
|
149
|
+
if (ratio < 3 || z < 4)
|
|
150
|
+
return;
|
|
151
|
+
blips.push(mkBlip({
|
|
152
|
+
source: 'wikipedia',
|
|
153
|
+
title: articleTitle(a.article),
|
|
154
|
+
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(a.article)}`,
|
|
155
|
+
// Ratio is capped so a spike from a near-zero baseline is not overrated; absolute reach counts too.
|
|
156
|
+
strength: clamp(Math.round(10 + 6 * Math.log2(Math.min(ratio, 256)) + 5 * Math.log10(Math.max(10, last))), 0, 90),
|
|
157
|
+
detail: `${last.toLocaleString('en-US')} views on ${top.data.date}, ${Number.isFinite(ratio) ? `${ratio.toFixed(1)}x` : 'up from ~0'} its usual`,
|
|
158
|
+
value: ratio,
|
|
159
|
+
}));
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
// Hacker News: front-page stories with unusual traction for their age.
|
|
163
|
+
if (hn.data) {
|
|
164
|
+
for (const s of hn.data) {
|
|
165
|
+
const ageH = Math.max(1, (nowMs / 1000 - s.created_at_i) / 3600);
|
|
166
|
+
const velocity = s.points / ageH;
|
|
167
|
+
if (s.points < 150 && velocity < 40)
|
|
168
|
+
continue;
|
|
169
|
+
blips.push(mkBlip({
|
|
170
|
+
source: 'hackernews',
|
|
171
|
+
title: s.title,
|
|
172
|
+
url: hnItemUrl(s.objectID),
|
|
173
|
+
strength: clamp(Math.round(25 + 10 * Math.log2(Math.max(1, velocity))), 0, 85),
|
|
174
|
+
detail: `${s.points} points, ${s.num_comments} comments in ${ageH.toFixed(0)}h`,
|
|
175
|
+
value: velocity,
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Polymarket: big 24h swings in non-sports markets with real volume.
|
|
180
|
+
if (markets.data) {
|
|
181
|
+
for (const m of markets.data) {
|
|
182
|
+
if (m.change1d === null || isSportsLine(m) || isResolving(m, nowMs) || m.volume24h < 25_000)
|
|
183
|
+
continue;
|
|
184
|
+
const pp = Math.abs(m.change1d) * 100;
|
|
185
|
+
if (pp < 8)
|
|
186
|
+
continue;
|
|
187
|
+
const lead = m.outcomes[0] ?? 'Yes';
|
|
188
|
+
blips.push(mkBlip({
|
|
189
|
+
source: 'polymarket',
|
|
190
|
+
title: m.question,
|
|
191
|
+
url: m.url,
|
|
192
|
+
strength: clamp(Math.round(30 + pp * 1.5), 0, 90),
|
|
193
|
+
detail: `"${lead}" ${m.change1d > 0 ? '+' : '-'}${pp.toFixed(0)}pp in 24h to ${((m.prices[0] ?? 0) * 100).toFixed(0)}%, $${Math.round(m.volume24h).toLocaleString('en-US')} volume`,
|
|
194
|
+
value: m.change1d,
|
|
195
|
+
}));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
// USGS: strong or alert-level earthquakes.
|
|
199
|
+
if (quakes.data) {
|
|
200
|
+
for (const q of quakes.data) {
|
|
201
|
+
if (q.mag < 6 && !q.alert && !q.tsunami)
|
|
202
|
+
continue;
|
|
203
|
+
blips.push(mkBlip({
|
|
204
|
+
source: 'usgs',
|
|
205
|
+
title: `M${q.mag.toFixed(1)} earthquake ${q.place}`,
|
|
206
|
+
url: q.url,
|
|
207
|
+
strength: clamp(Math.round(20 + (q.mag - 5) * 20 + (q.alert ? 15 : 0) + (q.tsunami ? 10 : 0)), 0, 95),
|
|
208
|
+
detail: `${new Date(q.time).toISOString().slice(0, 16)}Z${q.alert ? `, PAGER alert ${q.alert}` : ''}${q.tsunami ? ', tsunami flag' : ''}`,
|
|
209
|
+
value: q.mag,
|
|
210
|
+
}));
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
// NYT top stories: weak on their own (always "top"), but they corroborate other blips about the same subject.
|
|
214
|
+
for (const n of (nyt.data ?? []).slice(0, 15)) {
|
|
215
|
+
blips.push(mkBlip({ source: 'nyt', title: n.title, url: n.url, strength: 30, detail: `${n.source} top story`, value: 0 }));
|
|
216
|
+
}
|
|
217
|
+
// CoinGecko trending coins with a sharp 24h move.
|
|
218
|
+
for (const c of coins.data ?? []) {
|
|
219
|
+
if (c.change24h === null || Math.abs(c.change24h) < 15)
|
|
220
|
+
continue;
|
|
221
|
+
blips.push(mkBlip({
|
|
222
|
+
source: 'coingecko',
|
|
223
|
+
title: `${c.name} (${c.symbol.toUpperCase()}) trending`,
|
|
224
|
+
url: `https://www.coingecko.com/en/coins/${c.id}`,
|
|
225
|
+
strength: clamp(Math.round(30 + Math.abs(c.change24h)), 0, 80),
|
|
226
|
+
detail: `${c.change24h > 0 ? '+' : ''}${c.change24h.toFixed(0)}% in 24h, trending on CoinGecko${c.rank ? `, rank #${c.rank}` : ''}`,
|
|
227
|
+
value: c.change24h,
|
|
228
|
+
}));
|
|
229
|
+
}
|
|
230
|
+
// Space weather: a geomagnetic storm now (Kp >= 5) and M/X-class flares in the last day.
|
|
231
|
+
const kpLast = kp.data?.length ? kp.data[kp.data.length - 1] : null;
|
|
232
|
+
if (kpLast && kpLast.kp >= 5) {
|
|
233
|
+
blips.push(mkBlip({
|
|
234
|
+
source: 'noaa-swpc',
|
|
235
|
+
title: `Geomagnetic storm Kp ${kpLast.kp.toFixed(1)}`,
|
|
236
|
+
url: 'https://www.swpc.noaa.gov/products/planetary-k-index',
|
|
237
|
+
strength: clamp(Math.round(40 + (kpLast.kp - 5) * 12), 0, 90),
|
|
238
|
+
detail: `planetary K index ${kpLast.kp} at ${kpLast.time}Z`,
|
|
239
|
+
value: kpLast.kp,
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
for (const f of (flares.data ?? []).filter((x) => flareFlux(x.maxClass) >= 1e-5 && Date.parse(x.maxTime) > nowMs - 86_400_000)) {
|
|
243
|
+
blips.push(mkBlip({
|
|
244
|
+
source: 'noaa-swpc',
|
|
245
|
+
title: `Solar flare ${f.maxClass}`,
|
|
246
|
+
url: 'https://www.swpc.noaa.gov/products/goes-x-ray-flux',
|
|
247
|
+
strength: flareFlux(f.maxClass) >= 1e-4 ? 75 : 45,
|
|
248
|
+
detail: `peaked ${f.maxTime.slice(0, 16)}Z`,
|
|
249
|
+
value: flareFlux(f.maxClass),
|
|
250
|
+
}));
|
|
251
|
+
}
|
|
252
|
+
// NASA EONET: severe natural events (major storms, big wildfires, volcanoes, floods).
|
|
253
|
+
if (natural.data) {
|
|
254
|
+
for (const e of natural.data) {
|
|
255
|
+
const sev = eventSeverity(e);
|
|
256
|
+
if (!sev)
|
|
257
|
+
continue;
|
|
258
|
+
blips.push(mkBlip({ source: 'eonet', title: e.title, url: e.url, strength: sev.score, detail: `${sev.why}, updated ${e.date.slice(0, 16)}Z`, value: e.magnitude ?? 0 }));
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// Calibrated per-source weights (from `oculon calibrate`), bounded so no source dominates.
|
|
262
|
+
const weights = sourceWeights(ctx);
|
|
263
|
+
for (const b of blips)
|
|
264
|
+
if (weights[b.source])
|
|
265
|
+
b.strength = clamp(Math.round(b.strength * weights[b.source]), 0, 95);
|
|
266
|
+
const linked = opts.aiLink === false ? { fused: fuse(blips), links: [], model: null } : await aiLink(fuse(blips), opts.llmFetch ? { fetch: opts.llmFetch } : {});
|
|
267
|
+
const fused = linked.fused;
|
|
268
|
+
const threshold = signalThreshold(ctx);
|
|
269
|
+
const createdAt = new Date(nowMs).toISOString();
|
|
270
|
+
const signals = fused
|
|
271
|
+
// Threshold measured by `oculon calibrate` when available; 55 until then.
|
|
272
|
+
.filter((f) => f.score >= threshold)
|
|
273
|
+
.slice(0, 15)
|
|
274
|
+
.map((f) => {
|
|
275
|
+
const evidence = f.blips.map((b) => ({ source: b.source, text: `${b.title}: ${b.detail}`, url: b.url, value: b.value }));
|
|
276
|
+
if (f.linkedBy)
|
|
277
|
+
evidence.push({ source: 'ai-link', text: `linked as one event by ${f.linkedBy}` });
|
|
278
|
+
const kind = blipKind(f.blips[0].source);
|
|
279
|
+
const id = ctx.graph.upsert(kind, f.title);
|
|
280
|
+
for (const b of f.blips.slice(f.linkedBy ? 0 : 1)) {
|
|
281
|
+
const other = ctx.graph.upsert(blipKind(b.source), b.title);
|
|
282
|
+
if (other !== id)
|
|
283
|
+
ctx.graph.link(id, other, f.linkedBy ? 'same_event_as' : 'corroborated_by', f.linkedBy ? 'ai-link' : b.source);
|
|
284
|
+
}
|
|
285
|
+
ctx.graph.observe(id, 'owl', 'signal_score', f.score, f.sources.join('+'));
|
|
286
|
+
return { id: signalId('owl', f.title, createdAt.slice(0, 10)), module: 'owl', title: f.title, score: f.score, entity: entityId(kind, f.title), evidence, createdAt };
|
|
287
|
+
});
|
|
288
|
+
signals.forEach((s) => ctx.graph.saveSignal(s));
|
|
289
|
+
return { module: 'owl', input: 'global', generatedAt: createdAt, result: { blips, fused, aiLinks: linked.links }, signals, provenance };
|
|
290
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Research brief: what the literature says about a topic.
|
|
3
|
+
* OpenAlex (no key; OPENALEX_API_KEY raises the budget): the most cited recent papers, the newest relevant
|
|
4
|
+
* ones, and papers per year to show whether the field is growing.
|
|
5
|
+
* PubMed (no key): recent biomedical papers when the topic is medical.
|
|
6
|
+
* Semantic Scholar (SEMANTIC_SCHOLAR_API_KEY, optional): one-line TLDRs for the top papers.
|
|
7
|
+
* An LLM writes a short overview that cites the numbered papers; without one, the list stands alone.
|
|
8
|
+
*/
|
|
9
|
+
import type { Ctx } from '../core/context.js';
|
|
10
|
+
import type { ModuleResult } from '../core/types.js';
|
|
11
|
+
export interface Paper {
|
|
12
|
+
n: number;
|
|
13
|
+
title: string;
|
|
14
|
+
year: number | null;
|
|
15
|
+
date: string | null;
|
|
16
|
+
authors: string[];
|
|
17
|
+
venue: string | null;
|
|
18
|
+
citations: number;
|
|
19
|
+
url: string;
|
|
20
|
+
openAccessUrl: string | null;
|
|
21
|
+
abstract: string;
|
|
22
|
+
tldr: string | null;
|
|
23
|
+
source: 'openalex' | 'pubmed';
|
|
24
|
+
}
|
|
25
|
+
export interface PapersResult {
|
|
26
|
+
topic: string;
|
|
27
|
+
totalWorks: number | null;
|
|
28
|
+
perYear: {
|
|
29
|
+
year: number;
|
|
30
|
+
count: number;
|
|
31
|
+
}[];
|
|
32
|
+
trend: 'growing' | 'steady' | 'shrinking' | null;
|
|
33
|
+
mostCited: Paper[];
|
|
34
|
+
newest: Paper[];
|
|
35
|
+
pubmed: {
|
|
36
|
+
count: number;
|
|
37
|
+
papers: Paper[];
|
|
38
|
+
} | null;
|
|
39
|
+
overview: string | null;
|
|
40
|
+
method: string;
|
|
41
|
+
}
|
|
42
|
+
/** OpenAlex stores abstracts as word → positions; this puts the words back in order. */
|
|
43
|
+
export declare function invertAbstract(idx: Record<string, number[]> | null | undefined, max?: number): string;
|
|
44
|
+
export declare function papers(ctx: Ctx, topicInput: string, opts?: {
|
|
45
|
+
years?: number;
|
|
46
|
+
}): Promise<ModuleResult<PapersResult>>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { key } from '../core/keys.js';
|
|
2
|
+
import { complete } from '../core/llm.js';
|
|
3
|
+
/** OpenAlex stores abstracts as word → positions; this puts the words back in order. */
|
|
4
|
+
export function invertAbstract(idx, max = 600) {
|
|
5
|
+
if (!idx)
|
|
6
|
+
return '';
|
|
7
|
+
const words = [];
|
|
8
|
+
for (const [w, ps] of Object.entries(idx))
|
|
9
|
+
for (const p of ps)
|
|
10
|
+
words[p] = w;
|
|
11
|
+
return words.filter(Boolean).join(' ').slice(0, max);
|
|
12
|
+
}
|
|
13
|
+
const OA = 'https://api.openalex.org/works';
|
|
14
|
+
const SELECT = 'id,title,display_name,publication_year,publication_date,cited_by_count,doi,open_access,primary_location,authorships,abstract_inverted_index';
|
|
15
|
+
const oaKey = () => { const k = key('OPENALEX_API_KEY'); return k ? `&api_key=${encodeURIComponent(k)}` : ''; };
|
|
16
|
+
const toPaper = (w) => ({
|
|
17
|
+
title: (w.title ?? w.display_name ?? '').replace(/<[^>]+>/g, '').trim(),
|
|
18
|
+
year: w.publication_year ?? null,
|
|
19
|
+
date: w.publication_date ?? null,
|
|
20
|
+
authors: (w.authorships ?? []).slice(0, 4).map((a) => a.author?.display_name ?? '').filter(Boolean),
|
|
21
|
+
venue: w.primary_location?.source?.display_name ?? null,
|
|
22
|
+
citations: w.cited_by_count ?? 0,
|
|
23
|
+
url: w.doi ?? w.id ?? '',
|
|
24
|
+
openAccessUrl: w.open_access?.oa_url ?? null,
|
|
25
|
+
abstract: invertAbstract(w.abstract_inverted_index),
|
|
26
|
+
tldr: null,
|
|
27
|
+
source: 'openalex',
|
|
28
|
+
});
|
|
29
|
+
async function oaSearch(ctx, topic, extra) {
|
|
30
|
+
const r = await ctx.http.get(`${OA}?search=${encodeURIComponent(topic)}&${extra}&select=${SELECT}${oaKey()}`, {
|
|
31
|
+
source: 'openalex',
|
|
32
|
+
ttlSec: 12 * 3600,
|
|
33
|
+
keep: (d) => ({ count: d.meta?.count ?? 0, works: d.results ?? [] }),
|
|
34
|
+
});
|
|
35
|
+
return { data: r.data, prov: { ...r.prov, url: r.prov.url.replace(/&api_key=[^&]+/, '') } };
|
|
36
|
+
}
|
|
37
|
+
async function perYear(ctx, topic, fromYear) {
|
|
38
|
+
const r = await ctx.http.get(`${OA}?search=${encodeURIComponent(topic)}&filter=from_publication_date:${fromYear}-01-01&group_by=publication_year${oaKey()}`, {
|
|
39
|
+
source: 'openalex',
|
|
40
|
+
ttlSec: 24 * 3600,
|
|
41
|
+
keep: (d) => (d.group_by ?? []).map((g) => ({ year: Number(g.key), count: g.count })).sort((a, b) => a.year - b.year),
|
|
42
|
+
});
|
|
43
|
+
return { data: r.data, prov: { ...r.prov, url: r.prov.url.replace(/&api_key=[^&]+/, '') } };
|
|
44
|
+
}
|
|
45
|
+
const MEDICAL = /\b(disease|cancer|drug|therapy|treatment|vaccine|clinical|patient|virus|viral|infection|diabetes|obesity|glp-?1|alzheimer|covid|syndrome|tumou?r|gene|protein|antibod|medic|health|surgery|cardio|heart|brain|mental|depress|antibiotic|microbiome|trial)\b/i;
|
|
46
|
+
async function pubmed(ctx, topic) {
|
|
47
|
+
const E = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils';
|
|
48
|
+
const s = await ctx.http.get(`${E}/esearch.fcgi?db=pubmed&term=${encodeURIComponent(topic)}&retmode=json&retmax=6&sort=relevance&datetype=pdat&reldate=730`, { source: 'pubmed', ttlSec: 12 * 3600, keep: (d) => ({ count: Number(d.esearchresult?.count ?? 0), ids: d.esearchresult?.idlist ?? [] }) });
|
|
49
|
+
if (!s.data?.ids.length)
|
|
50
|
+
return { data: s.data ? { count: s.data.count, papers: [] } : null, prov: [s.prov] };
|
|
51
|
+
const m = await ctx.http.get(`${E}/esummary.fcgi?db=pubmed&id=${s.data.ids.join(',')}&retmode=json`, { source: 'pubmed', ttlSec: 24 * 3600, keep: (d) => (d.result?.uids ?? []).map((u) => d.result[u]) });
|
|
52
|
+
const papers = (m.data ?? []).map((x) => ({ n: 0, title: (x.title ?? '').replace(/<[^>]+>/g, ''), year: Number(/\d{4}/.exec(x.pubdate ?? '')?.[0]) || null, date: x.pubdate ?? null, authors: (x.authors ?? []).slice(0, 4).map((a) => a.name), venue: x.fulljournalname ?? null, citations: 0, url: `https://pubmed.ncbi.nlm.nih.gov/${x.uid}/`, openAccessUrl: null, abstract: '', tldr: null, source: 'pubmed' }));
|
|
53
|
+
return { data: { count: s.data.count, papers }, prov: [s.prov, m.prov] };
|
|
54
|
+
}
|
|
55
|
+
async function tldrs(ctx, papers) {
|
|
56
|
+
const k = key('SEMANTIC_SCHOLAR_API_KEY');
|
|
57
|
+
const dois = papers.filter((p) => /doi\.org\//.test(p.url)).slice(0, 20);
|
|
58
|
+
if (!k || !dois.length)
|
|
59
|
+
return null;
|
|
60
|
+
const ids = dois.map((p) => `DOI:${p.url.replace(/^https?:\/\/doi\.org\//, '')}`);
|
|
61
|
+
const cacheKey = `post:s2-batch:${ids.join(',')}`;
|
|
62
|
+
const cached = ctx.store.cacheGet(cacheKey);
|
|
63
|
+
let rows = null;
|
|
64
|
+
if (cached && Date.now() - cached.fetchedAt < 7 * 86_400_000)
|
|
65
|
+
rows = JSON.parse(cached.body);
|
|
66
|
+
else {
|
|
67
|
+
const r = await ctx.http.postBytes('https://api.semanticscholar.org/graph/v1/paper/batch?fields=tldr', new TextEncoder().encode(JSON.stringify({ ids })), { source: 'semantic-scholar', headers: { 'content-type': 'application/json', 'x-api-key': k }, timeoutMs: 20_000 });
|
|
68
|
+
if (!r.data)
|
|
69
|
+
return r.prov;
|
|
70
|
+
try {
|
|
71
|
+
rows = JSON.parse(r.data.toString('utf8'));
|
|
72
|
+
ctx.store.cachePut(cacheKey, r.data.toString('utf8'));
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return { ...r.prov, status: 'ERROR', note: 'invalid JSON' };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
rows?.forEach((row, i) => { if (row?.tldr?.text)
|
|
79
|
+
dois[i].tldr = row.tldr.text; });
|
|
80
|
+
return { source: 'semantic-scholar', url: 'https://api.semanticscholar.org/graph/v1/paper/batch', status: cached ? 'CACHED' : 'LIVE', fetchedAt: new Date().toISOString() };
|
|
81
|
+
}
|
|
82
|
+
export async function papers(ctx, topicInput, opts = {}) {
|
|
83
|
+
const topic = topicInput.trim();
|
|
84
|
+
if (topic.length < 2)
|
|
85
|
+
throw new Error('missing topic');
|
|
86
|
+
const years = Math.max(1, Math.min(opts.years ?? 3, 15));
|
|
87
|
+
const nowYear = ctx.now().getUTCFullYear();
|
|
88
|
+
const from = `${nowYear - years}-01-01`;
|
|
89
|
+
const provenance = [];
|
|
90
|
+
const [cited, fresh, py, pm] = await Promise.all([
|
|
91
|
+
// Most relevant 25 first, then the most cited of those: sorting the whole match set by citations pulls in
|
|
92
|
+
// famous papers that only mention the words.
|
|
93
|
+
oaSearch(ctx, topic, `filter=from_publication_date:${from},type:article|review|preprint&sort=relevance_score:desc&per-page=25`),
|
|
94
|
+
oaSearch(ctx, topic, `filter=from_publication_date:${new Date(ctx.now().getTime() - 180 * 86_400_000).toISOString().slice(0, 10)},type:article|review|preprint&sort=relevance_score:desc&per-page=6`),
|
|
95
|
+
perYear(ctx, topic, nowYear - 6),
|
|
96
|
+
MEDICAL.test(topic) ? pubmed(ctx, topic) : Promise.resolve(null),
|
|
97
|
+
]);
|
|
98
|
+
provenance.push(cited.prov, fresh.prov, py.prov, ...(pm?.prov ?? []));
|
|
99
|
+
let n = 0;
|
|
100
|
+
const mostCited = [...(cited.data?.works ?? [])].sort((a, b) => (b.cited_by_count ?? 0) - (a.cited_by_count ?? 0)).slice(0, 8).map((w) => ({ ...toPaper(w), n: ++n })).filter((p) => p.title);
|
|
101
|
+
const seen = new Set(mostCited.map((p) => p.title.toLowerCase()));
|
|
102
|
+
const newest = (fresh.data?.works ?? []).map(toPaper).filter((p) => p.title && !seen.has(p.title.toLowerCase())).map((p) => ({ ...p, n: ++n }));
|
|
103
|
+
const pubmedPapers = pm?.data ? { count: pm.data.count, papers: pm.data.papers.map((p) => ({ ...p, n: ++n })) } : null;
|
|
104
|
+
const s2 = await tldrs(ctx, [...mostCited, ...newest]);
|
|
105
|
+
if (s2)
|
|
106
|
+
provenance.push(s2);
|
|
107
|
+
// Growth: the last full year against the average of the three before it.
|
|
108
|
+
const years6 = (py.data ?? []).filter((x) => x.year < nowYear);
|
|
109
|
+
const last = years6.at(-1)?.count ?? 0;
|
|
110
|
+
const prior = years6.slice(-4, -1).map((x) => x.count);
|
|
111
|
+
const avg = prior.length ? prior.reduce((a, b) => a + b, 0) / prior.length : 0;
|
|
112
|
+
const trend = !avg || !last ? null : last > avg * 1.2 ? 'growing' : last < avg * 0.8 ? 'shrinking' : 'steady';
|
|
113
|
+
let overview = null;
|
|
114
|
+
let method = 'OpenAlex ranking';
|
|
115
|
+
const all = [...mostCited, ...newest, ...(pubmedPapers?.papers ?? [])];
|
|
116
|
+
if (all.length) {
|
|
117
|
+
try {
|
|
118
|
+
const list = all.slice(0, 16).map((p) => `[${p.n}] ${p.title} (${p.year ?? '?'}, ${p.venue ?? 'unknown venue'}, ${p.citations} citations)${p.tldr ? ` TLDR: ${p.tldr}` : p.abstract ? ` Abstract: ${p.abstract.slice(0, 350)}` : ''}`).join('\n');
|
|
119
|
+
const x = await complete('You summarize research for a busy reader. Using ONLY the numbered papers, write 3-5 sentences on what the recent literature on the topic finds and where it is heading. Cite papers like [3]. No claims beyond the papers. Plain English.', `Topic: ${topic}\n\n${list}`, { maxTokens: 350, temperature: 0.2 });
|
|
120
|
+
overview = x.text.slice(0, 1500) || null;
|
|
121
|
+
method = `${x.provider} over ${Math.min(all.length, 16)} papers`;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// no LLM: the ranked lists stand alone
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
module: 'papers',
|
|
129
|
+
input: topic,
|
|
130
|
+
generatedAt: ctx.now().toISOString(),
|
|
131
|
+
result: { topic, totalWorks: cited.data?.count ?? null, perYear: py.data ?? [], trend, mostCited, newest, pubmed: pubmedPapers, overview, method },
|
|
132
|
+
signals: [],
|
|
133
|
+
provenance,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Ctx } from '../core/context.js';
|
|
2
|
+
import { type WatchKind } from './meerkat.js';
|
|
3
|
+
import { type MonitorRule } from './monitor.js';
|
|
4
|
+
export declare const MAX_PER_OWNER = 10;
|
|
5
|
+
export interface PersonalMonitor {
|
|
6
|
+
id: number;
|
|
7
|
+
kind: WatchKind;
|
|
8
|
+
target: string;
|
|
9
|
+
description: string;
|
|
10
|
+
createdAt: string;
|
|
11
|
+
lastRun: string | null;
|
|
12
|
+
lastChange: string | null;
|
|
13
|
+
}
|
|
14
|
+
export interface PersonalAlert {
|
|
15
|
+
id: number;
|
|
16
|
+
monitorId: number;
|
|
17
|
+
text: string;
|
|
18
|
+
createdAt: string;
|
|
19
|
+
}
|
|
20
|
+
export interface Delivery {
|
|
21
|
+
owner: string;
|
|
22
|
+
monitor: PersonalMonitor;
|
|
23
|
+
changes: string[];
|
|
24
|
+
}
|
|
25
|
+
export declare const isOwner: (o: string) => boolean;
|
|
26
|
+
export declare function listPersonal(ctx: Ctx, owner: string): PersonalMonitor[];
|
|
27
|
+
/** Reads the request into a rule and saves it for this owner (at most MAX_PER_OWNER). */
|
|
28
|
+
export declare function addPersonal(ctx: Ctx, owner: string, text: string): Promise<{
|
|
29
|
+
monitor: PersonalMonitor;
|
|
30
|
+
rule: MonitorRule;
|
|
31
|
+
method: string;
|
|
32
|
+
}>;
|
|
33
|
+
export declare function removePersonal(ctx: Ctx, owner: string, id: number): boolean;
|
|
34
|
+
export declare function personalAlerts(ctx: Ctx, owner: string, limit?: number): PersonalAlert[];
|
|
35
|
+
/** Checks monitors not run in the last ~hour (oldest first, at most `max` per call) and records what changed. */
|
|
36
|
+
export declare function runPersonal(ctx: Ctx, opts?: {
|
|
37
|
+
max?: number;
|
|
38
|
+
everyMs?: number;
|
|
39
|
+
}): Promise<Delivery[]>;
|
|
40
|
+
export interface EmailStatus {
|
|
41
|
+
email: string | null;
|
|
42
|
+
confirmed: boolean;
|
|
43
|
+
}
|
|
44
|
+
export declare function emailStatus(ctx: Ctx, owner: string): EmailStatus;
|
|
45
|
+
/** Saves the address and sends a confirmation link. Limited to one email per owner every 10 minutes. */
|
|
46
|
+
export declare function requestEmail(ctx: Ctx, owner: string, email: string, baseUrl: string): Promise<{
|
|
47
|
+
sent: boolean;
|
|
48
|
+
error?: string;
|
|
49
|
+
}>;
|
|
50
|
+
export declare function confirmEmail(ctx: Ctx, token: string): boolean;
|
|
51
|
+
export declare function unsubscribeEmail(ctx: Ctx, token: string): boolean;
|
|
52
|
+
export declare function removeEmail(ctx: Ctx, owner: string): boolean;
|
|
53
|
+
/** Emails each web owner with a confirmed address one message listing every change from this run. */
|
|
54
|
+
export declare function emailDeliveries(ctx: Ctx, deliveries: Delivery[], baseUrl: string, appUrl: string): Promise<number>;
|