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,293 @@
|
|
|
1
|
+
import { clamp } from '../core/stats.js';
|
|
2
|
+
import { ONCHAIN_WATCH_KINDS, onchainEnabled } from '../core/features.js';
|
|
3
|
+
import { signalId } from '../core/text.js';
|
|
4
|
+
import { lights } from './condor.js';
|
|
5
|
+
import { cricket } from './cricket.js';
|
|
6
|
+
import { track } from './falcon.js';
|
|
7
|
+
import { ferret } from './ferret.js';
|
|
8
|
+
import { rhTokenCheck } from './heron.js';
|
|
9
|
+
import { hound } from './hound.js';
|
|
10
|
+
import { token, wallet } from './magpie.js';
|
|
11
|
+
import { shipsNear } from './ships.js';
|
|
12
|
+
import { air } from './sky.js';
|
|
13
|
+
import { gnews, guardian } from '../sources/press.js';
|
|
14
|
+
import { recentQuakes } from '../sources/usgs.js';
|
|
15
|
+
import { geocode } from '../sources/earth.js';
|
|
16
|
+
import { haversineKm } from '../sources/airports.js';
|
|
17
|
+
import { blackout } from './blackout.js';
|
|
18
|
+
import { vulns } from './vulns.js';
|
|
19
|
+
import { hazards } from './hazards.js';
|
|
20
|
+
import { urlCheck } from './urlcheck.js';
|
|
21
|
+
import { audit } from './audit.js';
|
|
22
|
+
import { travel } from './travel.js';
|
|
23
|
+
const lc = (s) => s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
|
|
24
|
+
/** "Tokyo|5.5" is a place with a minimum magnitude; a bare place uses 5.0. */
|
|
25
|
+
export function splitQuakeTarget(target) {
|
|
26
|
+
const [place, min] = target.split('|');
|
|
27
|
+
const m = Number(min);
|
|
28
|
+
return { place: (place ?? '').trim(), min: Number.isFinite(m) && m > 0 ? m : 5 };
|
|
29
|
+
}
|
|
30
|
+
export const WATCH_KINDS = ['company', 'domain', 'wallet', 'token', 'plane', 'topic', 'lights', 'air', 'port', 'news', 'outage', 'cve', 'quake', 'hazard', 'url', 'package', 'travel'];
|
|
31
|
+
const toItem = (r) => ({ id: r.id, kind: r.kind, target: r.target, label: r.label, createdAt: new Date(r.created_at).toISOString(), lastRun: r.last_run ? new Date(r.last_run).toISOString() : null });
|
|
32
|
+
export function addWatch(ctx, kind, target, label) {
|
|
33
|
+
if (!WATCH_KINDS.includes(kind))
|
|
34
|
+
throw new Error(`kind must be one of: ${WATCH_KINDS.join(', ')}`);
|
|
35
|
+
const t = target.trim();
|
|
36
|
+
if (!t)
|
|
37
|
+
throw new Error('missing target');
|
|
38
|
+
ctx.store.db.prepare('INSERT INTO watchlist (kind, target, label, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(kind, target) DO UPDATE SET label = COALESCE(excluded.label, label)').run(kind, t, label ?? null, ctx.now().getTime());
|
|
39
|
+
return toItem(ctx.store.db.prepare('SELECT * FROM watchlist WHERE kind = ? AND target = ?').get(kind, t));
|
|
40
|
+
}
|
|
41
|
+
export function listWatch(ctx) {
|
|
42
|
+
return ctx.store.db.prepare('SELECT * FROM watchlist ORDER BY id').all().map(toItem);
|
|
43
|
+
}
|
|
44
|
+
export function removeWatch(ctx, id) {
|
|
45
|
+
return ctx.store.db.prepare('DELETE FROM watchlist WHERE id = ?').run(id).changes > 0;
|
|
46
|
+
}
|
|
47
|
+
const pct = (a, b) => (b ? (a - b) / Math.abs(b) : 0);
|
|
48
|
+
const fmtPct = (x) => `${x >= 0 ? '+' : ''}${Math.round(x * 100)}%`;
|
|
49
|
+
const newOnes = (now, before) => {
|
|
50
|
+
const prev = new Set(Array.isArray(before) ? before : []);
|
|
51
|
+
return now.filter((x) => !prev.has(x));
|
|
52
|
+
};
|
|
53
|
+
/** Run the module for one item and return its state plus human-readable changes against the previous state. */
|
|
54
|
+
export async function observe(ctx, item, prev) {
|
|
55
|
+
const changes = [];
|
|
56
|
+
// Wallet and token items wait while on-chain features are paused; their stored state is kept as is.
|
|
57
|
+
if (ONCHAIN_WATCH_KINDS.has(item.kind) && !onchainEnabled())
|
|
58
|
+
return { state: prev ?? {}, changes };
|
|
59
|
+
switch (item.kind) {
|
|
60
|
+
case 'company': {
|
|
61
|
+
const d = (await hound(ctx, item.target)).result;
|
|
62
|
+
const items = d.timeline.slice(0, 40).map((t) => `${t.source}|${t.text}`);
|
|
63
|
+
const cases = (d.court?.cases ?? []).map((c) => c.name);
|
|
64
|
+
const price = d.stock?.quote?.price ?? null;
|
|
65
|
+
const openings = d.hiring ? d.hiring.reduce((a, h) => a + h.openings, 0) : null;
|
|
66
|
+
const sells = (d.stock?.insiders ?? []).filter((t) => t.code === 'S').map((t) => `${t.name}|${t.date}|${t.change}`);
|
|
67
|
+
if (prev) {
|
|
68
|
+
for (const x of newOnes(cases, prev.cases))
|
|
69
|
+
changes.push(`new court case: ${x}`);
|
|
70
|
+
for (const x of newOnes(sells, prev.sells).slice(0, 3))
|
|
71
|
+
changes.push(`insider sale: ${x.split('|')[0]} sold ${Math.abs(Number(x.split('|')[2])).toLocaleString('en-US')} shares (${x.split('|')[1]})`);
|
|
72
|
+
if (price !== null && typeof prev.price === 'number' && Math.abs(pct(price, prev.price)) >= 0.05)
|
|
73
|
+
changes.push(`stock ${fmtPct(pct(price, prev.price))} since last check (${prev.price.toFixed(2)} → ${price.toFixed(2)})`);
|
|
74
|
+
if (openings !== null && typeof prev.openings === 'number' && prev.openings > 0 && Math.abs(pct(openings, prev.openings)) >= 0.15)
|
|
75
|
+
changes.push(`job openings ${fmtPct(pct(openings, prev.openings))} (${prev.openings} → ${openings})`);
|
|
76
|
+
const fresh = newOnes(items, prev.items);
|
|
77
|
+
if (fresh.length)
|
|
78
|
+
changes.push(`${fresh.length} new item(s): ${fresh.slice(0, 3).map((x) => x.split('|')[1].slice(0, 90)).join(' · ')}`);
|
|
79
|
+
}
|
|
80
|
+
return { state: { items, cases, price, openings, sells }, changes };
|
|
81
|
+
}
|
|
82
|
+
case 'domain': {
|
|
83
|
+
const d = (await ferret(ctx, item.target)).result;
|
|
84
|
+
const found = d.findings.map((f) => `${f.kind}:${f.value.split(' — ')[0]}`);
|
|
85
|
+
const flagged = d.flagged.map((f) => f.url);
|
|
86
|
+
if (prev) {
|
|
87
|
+
for (const x of newOnes(found, prev.found).slice(0, 8))
|
|
88
|
+
changes.push(`new ${x.replace(':', ' ')}`);
|
|
89
|
+
for (const x of newOnes(flagged, prev.flagged))
|
|
90
|
+
changes.push(`Safe Browsing now flags ${x}`);
|
|
91
|
+
}
|
|
92
|
+
return { state: { found, flagged }, changes };
|
|
93
|
+
}
|
|
94
|
+
case 'wallet': {
|
|
95
|
+
const w = (await wallet(ctx, item.target)).result;
|
|
96
|
+
const usd = w.portfolio?.totalUsd ?? null;
|
|
97
|
+
const txs = w.recentTxs.map((t) => t.hash);
|
|
98
|
+
if (prev) {
|
|
99
|
+
if (usd !== null && typeof prev.usd === 'number' && prev.usd > 0 && Math.abs(pct(usd, prev.usd)) >= 0.1)
|
|
100
|
+
changes.push(`portfolio ${fmtPct(pct(usd, prev.usd))} ($${Math.round(prev.usd).toLocaleString('en-US')} → $${Math.round(usd).toLocaleString('en-US')})`);
|
|
101
|
+
const fresh = w.recentTxs.filter((t) => newOnes(txs, prev.txs).includes(t.hash));
|
|
102
|
+
if (fresh.length)
|
|
103
|
+
changes.push(`${fresh.length} new transaction(s), e.g. ${fresh[0].method} ${fresh[0].valueEth ? `${fresh[0].valueEth.toFixed(3)} ETH ` : ''}at ${fresh[0].time.slice(0, 16)}Z`);
|
|
104
|
+
for (const x of newOnes(w.labels, prev.labels))
|
|
105
|
+
changes.push(`new risk label: ${x}`);
|
|
106
|
+
}
|
|
107
|
+
return { state: { usd, txs, labels: w.labels }, changes };
|
|
108
|
+
}
|
|
109
|
+
case 'token': {
|
|
110
|
+
const [address, chain = 'eth'] = item.target.split('@');
|
|
111
|
+
let r;
|
|
112
|
+
let liq;
|
|
113
|
+
if (chain === 'robinhood') {
|
|
114
|
+
const rh = (await rhTokenCheck(ctx, address)).result;
|
|
115
|
+
r = rh;
|
|
116
|
+
liq = rh.pools.reduce((a, p) => a + p.pool.liquidityUsd, 0);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
const t = (await token(ctx, address, chain)).result;
|
|
120
|
+
r = t;
|
|
121
|
+
liq = t.pairs.reduce((a, p) => a + (p.liquidityUsd ?? 0), 0);
|
|
122
|
+
}
|
|
123
|
+
if (prev) {
|
|
124
|
+
if (prev.verdict !== r.verdict)
|
|
125
|
+
changes.push(`verdict ${String(prev.verdict)} → ${r.verdict}${r.reasons.length ? ` (${r.reasons.slice(0, 2).join(', ')})` : ''}`);
|
|
126
|
+
if (typeof prev.liq === 'number' && prev.liq > 1000 && Math.abs(pct(liq, prev.liq)) >= 0.3)
|
|
127
|
+
changes.push(`DEX liquidity ${fmtPct(pct(liq, prev.liq))} ($${Math.round(prev.liq).toLocaleString('en-US')} → $${Math.round(liq).toLocaleString('en-US')})`);
|
|
128
|
+
}
|
|
129
|
+
return { state: { verdict: r.verdict, liq }, changes };
|
|
130
|
+
}
|
|
131
|
+
case 'plane': {
|
|
132
|
+
const t = (await track(ctx, item.target)).result;
|
|
133
|
+
if (prev && t.change)
|
|
134
|
+
changes.push(t.change);
|
|
135
|
+
else if (prev && prev.status !== t.status)
|
|
136
|
+
changes.push(`status ${String(prev.status)} → ${t.status}${t.place ? `, ${t.place.relation} ${t.place.airport}` : ''}`);
|
|
137
|
+
return { state: { status: t.status, place: t.place?.ident ?? null }, changes };
|
|
138
|
+
}
|
|
139
|
+
case 'topic': {
|
|
140
|
+
const r = (await cricket(ctx, item.target)).result;
|
|
141
|
+
if (prev && prev.phase !== r.phase)
|
|
142
|
+
changes.push(`hype phase ${String(prev.phase)} → ${r.phase}`);
|
|
143
|
+
return { state: { phase: r.phase }, changes };
|
|
144
|
+
}
|
|
145
|
+
case 'lights': {
|
|
146
|
+
const r = (await lights(ctx, item.target)).result;
|
|
147
|
+
if (prev && prev.verdict !== r.verdict && r.verdict !== 'INSUFFICIENT_DATA')
|
|
148
|
+
changes.push(`night lights ${String(prev.verdict)} → ${r.verdict}${r.ratio ? ` (${fmtPct(r.ratio - 1)} vs baseline)` : ''}`);
|
|
149
|
+
return { state: { verdict: r.verdict }, changes };
|
|
150
|
+
}
|
|
151
|
+
case 'port': {
|
|
152
|
+
const r = (await shipsNear(ctx, item.target, 30)).result;
|
|
153
|
+
// A window with no AIS reports says nothing about the port; keep the previous state.
|
|
154
|
+
if (!r.total)
|
|
155
|
+
return { state: prev ?? {}, changes };
|
|
156
|
+
if (prev && typeof prev.stationary === 'number' && prev.stationary >= 3 && Math.abs(pct(r.stationary, prev.stationary)) >= 0.3)
|
|
157
|
+
changes.push(`vessels waiting ${fmtPct(pct(r.stationary, prev.stationary))} (${prev.stationary} → ${r.stationary} anchored/moored of ${r.total})`);
|
|
158
|
+
if (prev && typeof prev.military === 'number' && (r.byType.military ?? 0) > prev.military)
|
|
159
|
+
changes.push(`military vessels ${prev.military} → ${r.byType.military}`);
|
|
160
|
+
return { state: { stationary: r.stationary, total: r.total, military: r.byType.military ?? 0 }, changes };
|
|
161
|
+
}
|
|
162
|
+
case 'air': {
|
|
163
|
+
const r = (await air(ctx, item.target)).result;
|
|
164
|
+
if (prev && r.category && prev.category !== r.category)
|
|
165
|
+
changes.push(`air quality ${String(prev.category)} → ${r.category} (PM2.5 ${r.median?.toFixed(0)})`);
|
|
166
|
+
return { state: { category: r.category, median: r.median }, changes };
|
|
167
|
+
}
|
|
168
|
+
case 'news': {
|
|
169
|
+
const [g, n] = await Promise.all([guardian(ctx, item.target, 3, 10), gnews(ctx, item.target, 10)]);
|
|
170
|
+
const all = [...(g.data ?? []), ...(n.data ?? [])];
|
|
171
|
+
const seen = all.map((a) => a.url);
|
|
172
|
+
if (prev) {
|
|
173
|
+
const fresh = all.filter((a) => newOnes(seen, prev.seen).includes(a.url));
|
|
174
|
+
for (const a of fresh.slice(0, 4))
|
|
175
|
+
changes.push(`${a.source}: ${a.title.slice(0, 140)} ${a.url}`);
|
|
176
|
+
if (fresh.length > 4)
|
|
177
|
+
changes.push(`${fresh.length - 4} more new stories`);
|
|
178
|
+
}
|
|
179
|
+
return { state: { seen: [...new Set([...seen, ...(Array.isArray(prev?.seen) ? prev.seen : [])])].slice(0, 200) }, changes };
|
|
180
|
+
}
|
|
181
|
+
case 'outage': {
|
|
182
|
+
const r = (await blackout(ctx, 2)).result;
|
|
183
|
+
const q = lc(item.target.trim());
|
|
184
|
+
const hits = r.outages.filter((o) => (o.countryCode && o.countryCode.toLowerCase() === q) || (o.country && lc(o.country).includes(q)));
|
|
185
|
+
const keys = hits.map((o) => `${o.start}|${o.network ?? ''}|${o.end ?? ''}`);
|
|
186
|
+
if (prev)
|
|
187
|
+
for (const o of hits.filter((h) => newOnes(keys, prev.keys).includes(`${h.start}|${h.network ?? ''}|${h.end ?? ''}`)).slice(0, 4))
|
|
188
|
+
changes.push(`${o.end ? 'outage ended' : 'internet outage'} in ${o.country ?? item.target}${o.network ? ` (${o.network})` : ''}: ${o.cause ?? o.type ?? 'cause unknown'}, since ${o.start.slice(0, 16)}Z${o.verified ? ', confirmed' : ''}${o.url ? ` ${o.url}` : ''}`);
|
|
189
|
+
return { state: { keys }, changes };
|
|
190
|
+
}
|
|
191
|
+
case 'cve': {
|
|
192
|
+
const r = (await vulns(ctx, { days: 14, vendor: item.target })).result;
|
|
193
|
+
const ids = [...r.kev.map((k) => k.cveID), ...r.criticalCves.map((c) => c.id), ...r.advisories.map((a) => a.id)];
|
|
194
|
+
if (prev) {
|
|
195
|
+
for (const k of r.kev.filter((x) => newOnes(ids, prev.ids).includes(x.cveID)).slice(0, 3))
|
|
196
|
+
changes.push(`exploited in the wild (CISA KEV): ${k.cveID} ${k.vendorProject} ${k.product}, ${k.vulnerabilityName}`);
|
|
197
|
+
for (const c of r.criticalCves.filter((x) => newOnes(ids, prev.ids).includes(x.id)).slice(0, 3))
|
|
198
|
+
changes.push(`new critical CVE ${c.id}${c.cvss ? ` (CVSS ${c.cvss})` : ''}: ${c.description.slice(0, 140)} ${c.url}`);
|
|
199
|
+
for (const a of r.advisories.filter((x) => newOnes(ids, prev.ids).includes(x.id)).slice(0, 3))
|
|
200
|
+
changes.push(`new critical advisory ${a.cve ?? a.id}: ${a.summary.slice(0, 140)} ${a.url}`);
|
|
201
|
+
}
|
|
202
|
+
return { state: { ids: [...new Set([...ids, ...(Array.isArray(prev?.ids) ? prev.ids : [])])].slice(0, 500) }, changes };
|
|
203
|
+
}
|
|
204
|
+
case 'quake': {
|
|
205
|
+
const { place, min } = splitQuakeTarget(item.target);
|
|
206
|
+
const g = await geocode(ctx, place, 1);
|
|
207
|
+
const p = g.data?.[0];
|
|
208
|
+
if (!p)
|
|
209
|
+
throw new Error(`place not found: ${place}`);
|
|
210
|
+
const qk = await recentQuakes(ctx);
|
|
211
|
+
const near = (qk.data ?? []).filter((q) => q.lat != null && q.lon != null && q.mag >= min).map((q) => ({ ...q, km: Math.round(haversineKm(p.lat, p.lon, q.lat, q.lon)) })).filter((q) => q.km <= 300);
|
|
212
|
+
const ids = near.map((q) => q.id);
|
|
213
|
+
if (prev)
|
|
214
|
+
for (const q of near.filter((x) => newOnes(ids, prev.ids).includes(x.id)).slice(0, 3))
|
|
215
|
+
changes.push(`M${q.mag.toFixed(1)} earthquake ${q.km} km from ${place.split(',')[0]}: ${q.place} at ${new Date(q.time).toISOString().slice(0, 16)}Z${q.tsunami ? ', tsunami flag' : ''} ${q.url}`);
|
|
216
|
+
return { state: { ids: [...new Set([...ids, ...(Array.isArray(prev?.ids) ? prev.ids : [])])].slice(0, 300) }, changes };
|
|
217
|
+
}
|
|
218
|
+
case 'hazard': {
|
|
219
|
+
const r = await hazards(ctx, 7);
|
|
220
|
+
const q = lc(item.target.trim());
|
|
221
|
+
const hits = r.result.filter((h) => h.level !== 'Green' && (lc(h.countries).includes(q) || lc(h.name).includes(q)));
|
|
222
|
+
const keys = hits.map((h) => `${h.id}|${h.level}`);
|
|
223
|
+
if (prev)
|
|
224
|
+
for (const h of hits.filter((x) => newOnes(keys, prev.keys).includes(`${x.id}|${x.level}`)).slice(0, 3))
|
|
225
|
+
changes.push(`${h.level.toLowerCase()} alert: ${h.type} ${h.name} (${h.countries})${h.severity ? `, ${h.severity}` : ''} ${h.url}`);
|
|
226
|
+
return { state: { keys }, changes };
|
|
227
|
+
}
|
|
228
|
+
case 'url': {
|
|
229
|
+
const r = (await urlCheck(ctx, item.target)).result;
|
|
230
|
+
if (prev && prev.verdict !== r.verdict)
|
|
231
|
+
changes.push(`verdict ${String(prev.verdict)} → ${r.verdict}${r.reasons.length ? `: ${r.reasons.slice(0, 2).join('; ')}` : ''}`);
|
|
232
|
+
return { state: { verdict: r.verdict, risk: r.risk }, changes };
|
|
233
|
+
}
|
|
234
|
+
case 'package': {
|
|
235
|
+
const spec = item.target.includes(':') ? item.target : `npm:${item.target}`;
|
|
236
|
+
const p = (await audit(ctx, spec)).result.packages[0];
|
|
237
|
+
if (!p)
|
|
238
|
+
throw new Error(`package not found: ${item.target}`);
|
|
239
|
+
const ids = p.advisories.map((a) => a.id);
|
|
240
|
+
if (prev) {
|
|
241
|
+
for (const a of p.advisories.filter((x) => newOnes(ids, prev.ids).includes(x.id)))
|
|
242
|
+
changes.push(`new advisory for ${p.name}@${p.version}: ${a.aliases[0] ?? a.id} ${a.title}${a.cvss ? ` (CVSS ${a.cvss})` : ''} ${a.url}`);
|
|
243
|
+
if (p.deprecated && !prev.deprecated)
|
|
244
|
+
changes.push(`${p.name} is now deprecated: ${p.deprecated}`);
|
|
245
|
+
if (typeof prev.latest === 'string' && p.latest && p.latest !== prev.latest)
|
|
246
|
+
changes.push(`new release ${p.name}@${p.latest} (was ${prev.latest})`);
|
|
247
|
+
}
|
|
248
|
+
return { state: { ids, deprecated: p.deprecated, latest: p.latest }, changes };
|
|
249
|
+
}
|
|
250
|
+
case 'travel': {
|
|
251
|
+
const r = (await travel(ctx, item.target, { fires: false })).result;
|
|
252
|
+
if (prev && prev.level !== r.level)
|
|
253
|
+
changes.push(`risk ${String(prev.level)} → ${r.level}: ${r.points.slice(0, 2).join('; ')}`);
|
|
254
|
+
else if (prev)
|
|
255
|
+
for (const x of newOnes(r.points, prev.points).filter((x) => !/^UK FCDO has no|moderate earthquake/.test(x)).slice(0, 2))
|
|
256
|
+
changes.push(x);
|
|
257
|
+
return { state: { level: r.level, points: r.points }, changes };
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const KIND_WEIGHT = { company: 55, domain: 60, wallet: 60, token: 65, plane: 65, topic: 50, lights: 65, air: 50, port: 60, news: 50, outage: 70, cve: 65, quake: 70, hazard: 70, url: 70, package: 60, travel: 65 };
|
|
262
|
+
/** Run every watch item (or the given ids) one after another, so free-tier rate limits are respected. */
|
|
263
|
+
export async function runWatch(ctx, ids) {
|
|
264
|
+
const rows = ctx.store.db.prepare('SELECT * FROM watchlist ORDER BY id').all().filter((r) => !ids || ids.includes(r.id));
|
|
265
|
+
const runs = [];
|
|
266
|
+
const signals = [];
|
|
267
|
+
const nowIso = ctx.now().toISOString();
|
|
268
|
+
for (const row of rows) {
|
|
269
|
+
const item = toItem(row);
|
|
270
|
+
const prev = row.last_state ? JSON.parse(row.last_state) : null;
|
|
271
|
+
try {
|
|
272
|
+
const { state, changes } = await observe(ctx, item, prev);
|
|
273
|
+
ctx.store.db.prepare('UPDATE watchlist SET last_run = ?, last_state = ? WHERE id = ?').run(ctx.now().getTime(), JSON.stringify(state), row.id);
|
|
274
|
+
runs.push({ item, baseline: !prev, changes });
|
|
275
|
+
if (changes.length) {
|
|
276
|
+
const name = item.label ?? item.target;
|
|
277
|
+
signals.push({
|
|
278
|
+
id: signalId('meerkat', String(row.id), changes.join('|')),
|
|
279
|
+
module: 'meerkat',
|
|
280
|
+
title: `Watch ${item.kind} ${name}: ${changes[0]}${changes.length > 1 ? ` (+${changes.length - 1} more)` : ''}`,
|
|
281
|
+
score: clamp(KIND_WEIGHT[item.kind] + (changes.length - 1) * 5, 0, 90),
|
|
282
|
+
evidence: changes.map((c) => ({ source: `watch:${item.kind}`, text: c })),
|
|
283
|
+
createdAt: nowIso,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
catch (e) {
|
|
288
|
+
runs.push({ item, baseline: !prev, changes: [], error: e.message });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
signals.forEach((s) => ctx.graph.saveSignal(s));
|
|
292
|
+
return { runs, signals };
|
|
293
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Monitors in plain language: "tell me when there is an internet outage in Iran", "watch new critical CVEs for
|
|
3
|
+
* nginx", "alert me about earthquakes above 6 near Tokyo". A sentence becomes one watchlist rule (kind + target)
|
|
4
|
+
* that Meerkat re-checks on the shared schedule and reports only when something changes, with evidence.
|
|
5
|
+
* An LLM reads the sentence; without one, a small set of patterns covers the common phrasings.
|
|
6
|
+
*/
|
|
7
|
+
import type { Ctx } from '../core/context.js';
|
|
8
|
+
import { type WatchItem, type WatchKind } from './meerkat.js';
|
|
9
|
+
export interface MonitorRule {
|
|
10
|
+
kind: WatchKind;
|
|
11
|
+
target: string;
|
|
12
|
+
/** What the rule does, in one line, for lists and alerts. */
|
|
13
|
+
description: string;
|
|
14
|
+
}
|
|
15
|
+
export declare const availableKinds: () => WatchKind[];
|
|
16
|
+
/** Pattern fallback for the common phrasings (used when no LLM is configured or it gives an unusable answer). */
|
|
17
|
+
export declare function parseMonitorPattern(text: string): MonitorRule | null;
|
|
18
|
+
/** Reads a sentence into a rule: LLM first (it handles any phrasing), patterns as the fallback. */
|
|
19
|
+
export declare function parseMonitor(text: string): Promise<MonitorRule & {
|
|
20
|
+
method: string;
|
|
21
|
+
}>;
|
|
22
|
+
/** Parses the sentence and adds the rule to the watchlist (first check records a baseline). */
|
|
23
|
+
export declare function addMonitor(ctx: Ctx, text: string): Promise<{
|
|
24
|
+
item: WatchItem;
|
|
25
|
+
rule: MonitorRule;
|
|
26
|
+
method: string;
|
|
27
|
+
}>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { complete } from '../core/llm.js';
|
|
2
|
+
import { addWatch, WATCH_KINDS } from './meerkat.js';
|
|
3
|
+
import { onchainEnabled, ONCHAIN_WATCH_KINDS } from '../core/features.js';
|
|
4
|
+
const KIND_HELP = {
|
|
5
|
+
news: 'new news stories about a keyword or name. target: the keyword',
|
|
6
|
+
outage: 'internet outages in a country. target: country name or 2-letter code',
|
|
7
|
+
cve: 'newly exploited (CISA KEV) or new critical vulnerabilities for a vendor or product. target: vendor or product, e.g. "nginx", "Microsoft Exchange"',
|
|
8
|
+
quake: 'earthquakes within 300 km of a place. target: "place|minimum magnitude", e.g. "Tokyo|6"',
|
|
9
|
+
hazard: 'orange or red disaster alerts (cyclones, floods, volcanoes, quakes, wildfires) for a country or named storm. target: country or name',
|
|
10
|
+
url: 'a link turning malicious or suspicious. target: the URL',
|
|
11
|
+
package: 'new vulnerabilities, deprecation or releases of a software package. target: "npm:name" or "pypi:name"',
|
|
12
|
+
travel: 'travel risk level changes for a destination. target: city or country',
|
|
13
|
+
company: 'news, court cases, stock moves, insider sales and hiring for a company. target: company name or ticker',
|
|
14
|
+
domain: 'new subdomains, archived pages and Safe Browsing flags for a domain. target: the domain',
|
|
15
|
+
plane: 'a specific aircraft taking off, landing or changing status. target: tail number, callsign or ICAO hex',
|
|
16
|
+
topic: 'hype phase changes for a topic. target: the topic',
|
|
17
|
+
lights: 'night-time light changes (blackouts, growth) for a place. target: the place',
|
|
18
|
+
air: 'air quality category changes for a place. target: the place',
|
|
19
|
+
port: 'ships queuing or military vessels at a port. target: the port',
|
|
20
|
+
wallet: 'activity of a crypto wallet. target: the address',
|
|
21
|
+
token: 'risk verdict and liquidity of a token. target: the contract address',
|
|
22
|
+
};
|
|
23
|
+
export const availableKinds = () => WATCH_KINDS.filter((k) => onchainEnabled() || !ONCHAIN_WATCH_KINDS.has(k));
|
|
24
|
+
const describe = (kind, target) => {
|
|
25
|
+
switch (kind) {
|
|
26
|
+
case 'news': return `new stories about "${target}"`;
|
|
27
|
+
case 'outage': return `internet outages in ${target}`;
|
|
28
|
+
case 'cve': return `exploited or critical vulnerabilities for ${target}`;
|
|
29
|
+
case 'quake': {
|
|
30
|
+
const [p, m] = target.split('|');
|
|
31
|
+
return `earthquakes M${m ?? '5'}+ within 300 km of ${p}`;
|
|
32
|
+
}
|
|
33
|
+
case 'hazard': return `orange or red disaster alerts for ${target}`;
|
|
34
|
+
case 'url': return `${target} turning malicious or suspicious`;
|
|
35
|
+
case 'package': return `new advisories, deprecation or releases of ${target}`;
|
|
36
|
+
case 'travel': return `travel risk changes for ${target}`;
|
|
37
|
+
case 'company': return `news, filings, cases and stock moves for ${target}`;
|
|
38
|
+
case 'domain': return `new footprints of ${target}`;
|
|
39
|
+
case 'plane': return `status changes of aircraft ${target}`;
|
|
40
|
+
case 'topic': return `hype phase changes for ${target}`;
|
|
41
|
+
case 'lights': return `night-light changes in ${target}`;
|
|
42
|
+
case 'air': return `air quality changes in ${target}`;
|
|
43
|
+
case 'port': return `vessel queues at ${target}`;
|
|
44
|
+
case 'wallet': return `activity of wallet ${target}`;
|
|
45
|
+
case 'token': return `risk changes of token ${target}`;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
// Drops quotes, a leading "the", and trailing verbs such as "changes", "gets worse", "turns red".
|
|
49
|
+
const clean = (s) => s.trim().replace(/^["'“”]+|["'“”.!?]+$/g, '').replace(/^the\s+/i, '').replace(/\s+(changes?|gets?|goes|turns?|becomes?|is|are|has|have|worsens?|improves?)\b.*$/i, '').trim();
|
|
50
|
+
/** Pattern fallback for the common phrasings (used when no LLM is configured or it gives an unusable answer). */
|
|
51
|
+
export function parseMonitorPattern(text) {
|
|
52
|
+
// "the Philippines" → "Philippines", so place patterns can start at the capitalized name.
|
|
53
|
+
const t = text.trim().replace(/\bthe\s+(?=[A-Z])/g, '');
|
|
54
|
+
const after = (re) => { const m = re.exec(t); return m?.[1] ? clean(m[1]) : null; };
|
|
55
|
+
let target;
|
|
56
|
+
if ((target = after(/\b(https?:\/\/\S+)/i)))
|
|
57
|
+
return { kind: 'url', target, description: describe('url', target) };
|
|
58
|
+
if ((target = after(/\b((?:npm|pypi):[@\w./-]+)/i)))
|
|
59
|
+
return { kind: 'package', target: target.toLowerCase(), description: describe('package', target.toLowerCase()) };
|
|
60
|
+
if (/\b(outage|blackout|shutdown|internet (?:is )?down|goes offline|disconnect)/i.test(t) && (target = after(/\b(?:in|for|across)\s+([A-Z][\w .'-]+?)(?:\s*$|[,.!?]|\s+(?:and|or|when|if)\b)/)))
|
|
61
|
+
return { kind: 'outage', target, description: describe('outage', target) };
|
|
62
|
+
if (/\b(cve|vulnerab|exploit|zero[- ]day|security (?:hole|flaw|bug)|patch)/i.test(t) && (target = after(/\b(?:for|in|affecting|on|about)\s+([\w .+-]+?)(?:\s*$|[,.!?])/i)))
|
|
63
|
+
return { kind: 'cve', target, description: describe('cve', target) };
|
|
64
|
+
if (/\b(earthquake|quake|tremor|seismic)/i.test(t) && (target = after(/\b(?:near|around|in|close to)\s+([A-Z][\w .,'-]+?)(?:\s*$|[.!?]|\s+(?:above|over|of)\b)/))) {
|
|
65
|
+
const mag = /\b(?:above|over|magnitude|m)\s*(\d(?:\.\d)?)/i.exec(t)?.[1] ?? /(\d(?:\.\d)?)\s*\+/.exec(t)?.[1];
|
|
66
|
+
const tg = `${target}|${mag ?? '5'}`;
|
|
67
|
+
return { kind: 'quake', target: tg, description: describe('quake', tg) };
|
|
68
|
+
}
|
|
69
|
+
if (/\b(cyclone|hurricane|typhoon|flood|volcano|eruption|disaster|wildfire|tsunami|storm)/i.test(t) && (target = after(/\b(?:in|for|near|hitting|affecting)\s+([A-Z][\w .'-]+?)(?:\s*$|[,.!?])/)))
|
|
70
|
+
return { kind: 'hazard', target, description: describe('hazard', target) };
|
|
71
|
+
if (/\b(travel|trip|safe to (?:go|visit|travel)|visiting|advisory)/i.test(t) && (target = after(/\b(?:to|in|for)\s+([A-Z][\w .'-]+?)(?:\s*$|[,.!?]|\s+(?:next|this|in)\b)/)))
|
|
72
|
+
return { kind: 'travel', target, description: describe('travel', target) };
|
|
73
|
+
if (/\b(air quality|pollution|smog|pm2\.?5)/i.test(t) && (target = after(/\b(?:in|for|near)\s+([A-Z][\w .'-]+?)(?:\s*$|[,.!?])/)))
|
|
74
|
+
return { kind: 'air', target, description: describe('air', target) };
|
|
75
|
+
if ((target = after(/\b(?:news|stories|headlines|articles|coverage|mentions?)\s+(?:about|on|of|for|mentioning)\s+(.+?)(?:\s*$|[.!?])/i)))
|
|
76
|
+
return { kind: 'news', target, description: describe('news', target) };
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
/** Reads a sentence into a rule: LLM first (it handles any phrasing), patterns as the fallback. */
|
|
80
|
+
export async function parseMonitor(text) {
|
|
81
|
+
const kinds = availableKinds();
|
|
82
|
+
try {
|
|
83
|
+
const x = await complete(`You turn a monitoring request into ONE watch rule for an OSINT engine. Kinds:\n${kinds.map((k) => `- ${k}: ${KIND_HELP[k]}`).join('\n')}\nReply as JSON {"kind": "...", "target": "..."} using exactly one kind from the list. If nothing fits, reply {"kind": "none", "target": ""}.`, text, { json: true, maxTokens: 80, temperature: 0 });
|
|
84
|
+
const j = JSON.parse(x.text.replace(/^```(json)?|```$/g, ''));
|
|
85
|
+
const kind = j.kind;
|
|
86
|
+
const target = clean(String(j.target ?? ''));
|
|
87
|
+
if (kinds.includes(kind) && target) {
|
|
88
|
+
const tg = kind === 'quake' && !target.includes('|') ? `${target}|5` : kind === 'package' && !target.includes(':') ? `npm:${target}` : target;
|
|
89
|
+
return { kind, target: tg, description: describe(kind, tg), method: x.provider };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// fall through to patterns
|
|
94
|
+
}
|
|
95
|
+
const p = parseMonitorPattern(text);
|
|
96
|
+
if (p && kinds.includes(p.kind))
|
|
97
|
+
return { ...p, method: 'patterns' };
|
|
98
|
+
throw new Error('could not turn that into a monitor. Try e.g. "internet outages in Iran", "critical CVEs for nginx", "earthquakes above 6 near Tokyo", "news about OpenAI"');
|
|
99
|
+
}
|
|
100
|
+
/** Parses the sentence and adds the rule to the watchlist (first check records a baseline). */
|
|
101
|
+
export async function addMonitor(ctx, text) {
|
|
102
|
+
const r = await parseMonitor(text);
|
|
103
|
+
const item = addWatch(ctx, r.kind, r.target, r.description);
|
|
104
|
+
return { item, rule: { kind: r.kind, target: r.target, description: r.description }, method: r.method };
|
|
105
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narrative Tracker: groups the day's headlines into storylines that persist across days ("Nvidia leadership
|
|
3
|
+
* crisis", "Anthropic IPO"), tracks how many stories each narrative gets per day, and flags narratives that
|
|
4
|
+
* are new and already busy, or growing fast. Assignment is done by an LLM; without one, nothing is grouped.
|
|
5
|
+
*/
|
|
6
|
+
import { type Ctx } from '../core/context.js';
|
|
7
|
+
import { type Phase } from '../core/stats.js';
|
|
8
|
+
import type { ModuleResult } from '../core/types.js';
|
|
9
|
+
export interface Narrative {
|
|
10
|
+
id: number;
|
|
11
|
+
name: string;
|
|
12
|
+
createdAt: string;
|
|
13
|
+
updatedAt: string;
|
|
14
|
+
/** Stories per day for the last 7 days, oldest first. */
|
|
15
|
+
daily: number[];
|
|
16
|
+
total: number;
|
|
17
|
+
phase: Phase;
|
|
18
|
+
latest: {
|
|
19
|
+
title: string;
|
|
20
|
+
url: string;
|
|
21
|
+
source: string;
|
|
22
|
+
day: string;
|
|
23
|
+
}[];
|
|
24
|
+
}
|
|
25
|
+
export declare function listNarratives(ctx: Ctx, activeDays?: number): Narrative[];
|
|
26
|
+
/** Assign new headlines to narratives (existing or new). Returns the narratives touched. */
|
|
27
|
+
export declare function runNarratives(ctx: Ctx, opts?: {
|
|
28
|
+
fetch?: typeof fetch;
|
|
29
|
+
}): Promise<ModuleResult<{
|
|
30
|
+
added: number;
|
|
31
|
+
created: string[];
|
|
32
|
+
narratives: Narrative[];
|
|
33
|
+
}>>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narrative Tracker: groups the day's headlines into storylines that persist across days ("Nvidia leadership
|
|
3
|
+
* crisis", "Anthropic IPO"), tracks how many stories each narrative gets per day, and flags narratives that
|
|
4
|
+
* are new and already busy, or growing fast. Assignment is done by an LLM; without one, nothing is grouped.
|
|
5
|
+
*/
|
|
6
|
+
import { DAY_MS } from '../core/context.js';
|
|
7
|
+
import { availableProviders, chat } from '../core/llm.js';
|
|
8
|
+
import { trend } from '../core/stats.js';
|
|
9
|
+
import { keywords, overlap, signalId } from '../core/text.js';
|
|
10
|
+
import { frontPage, hnItemUrl } from '../sources/hackernews.js';
|
|
11
|
+
import { guardianDay, nytTopStories } from '../sources/press.js';
|
|
12
|
+
const day = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
13
|
+
export function listNarratives(ctx, activeDays = 14) {
|
|
14
|
+
const db = ctx.store.db;
|
|
15
|
+
const nowMs = ctx.now().getTime();
|
|
16
|
+
const since = nowMs - activeDays * DAY_MS;
|
|
17
|
+
const rows = db.prepare('SELECT * FROM narratives WHERE updated_at >= ? ORDER BY updated_at DESC').all(since);
|
|
18
|
+
return rows
|
|
19
|
+
.map((r) => {
|
|
20
|
+
const counts = db.prepare('SELECT day, COUNT(*) AS n FROM narrative_items WHERE narrative_id = ? GROUP BY day').all(r.id);
|
|
21
|
+
const byDay = new Map(counts.map((c) => [c.day, c.n]));
|
|
22
|
+
const daily = Array.from({ length: 7 }, (_, i) => byDay.get(day(nowMs - (6 - i) * DAY_MS)) ?? 0);
|
|
23
|
+
const latest = db.prepare('SELECT title, url, source, day FROM narrative_items WHERE narrative_id = ? ORDER BY added_at DESC LIMIT 6').all(r.id);
|
|
24
|
+
return { id: r.id, name: r.name, createdAt: new Date(r.created_at).toISOString(), updatedAt: new Date(r.updated_at).toISOString(), daily, total: counts.reduce((a, c) => a + c.n, 0), phase: trend(daily).phase, latest };
|
|
25
|
+
})
|
|
26
|
+
.sort((a, b) => b.daily[6] + b.daily[5] - (a.daily[6] + a.daily[5]));
|
|
27
|
+
}
|
|
28
|
+
async function collectHeadlines(ctx) {
|
|
29
|
+
const nowMs = ctx.now().getTime();
|
|
30
|
+
const [g0, g1, nyt, hn] = await Promise.all([guardianDay(ctx, day(nowMs), 40), guardianDay(ctx, day(nowMs - DAY_MS), 40), nytTopStories(ctx), frontPage(ctx)]);
|
|
31
|
+
const items = [
|
|
32
|
+
...[...(g0.data ?? []), ...(g1.data ?? [])].map((n) => ({ title: n.title, url: n.url, source: 'guardian' })),
|
|
33
|
+
...(nyt.data ?? []).map((n) => ({ title: n.title, url: n.url, source: 'nyt' })),
|
|
34
|
+
...(hn.data ?? []).filter((s) => s.points >= 100).map((s) => ({ title: s.title, url: hnItemUrl(s.objectID), source: 'hackernews' })),
|
|
35
|
+
...ctx.graph
|
|
36
|
+
.recentSignals(200)
|
|
37
|
+
.filter((s) => s.module === 'owl' && nowMs - Date.parse(s.createdAt) < DAY_MS)
|
|
38
|
+
.map((s) => ({ title: s.title, url: s.evidence[0]?.url ?? `oculon:${s.id}`, source: 'oculon' })),
|
|
39
|
+
];
|
|
40
|
+
return { items, provenance: [g0.prov, g1.prov, nyt.prov, hn.prov] };
|
|
41
|
+
}
|
|
42
|
+
/** Assign new headlines to narratives (existing or new). Returns the narratives touched. */
|
|
43
|
+
export async function runNarratives(ctx, opts = {}) {
|
|
44
|
+
const nowMs = ctx.now().getTime();
|
|
45
|
+
const nowIso = new Date(nowMs).toISOString();
|
|
46
|
+
const db = ctx.store.db;
|
|
47
|
+
const { items, provenance } = await collectHeadlines(ctx);
|
|
48
|
+
const known = new Set(db.prepare('SELECT url FROM narrative_items').all().map((r) => r.url));
|
|
49
|
+
const fresh = items.filter((i) => !known.has(i.url)).slice(0, 120);
|
|
50
|
+
if (!fresh.length || !availableProviders().length) {
|
|
51
|
+
return { module: 'narratives', input: 'run', generatedAt: nowIso, result: { added: 0, created: [], narratives: listNarratives(ctx) }, signals: [], provenance: [...provenance, ...(availableProviders().length ? [] : [{ source: 'llm', url: '', status: 'UNAVAILABLE', fetchedAt: nowIso, note: 'narratives need an LLM key' }])] };
|
|
52
|
+
}
|
|
53
|
+
const active = listNarratives(ctx).slice(0, 40);
|
|
54
|
+
// Batches of 40 keep each JSON answer short enough to arrive complete.
|
|
55
|
+
let assign = [];
|
|
56
|
+
for (let start = 0; start < fresh.length; start += 40) {
|
|
57
|
+
const batch = fresh.slice(start, start + 40);
|
|
58
|
+
const prompt = `Existing narratives:\n${active.map((n) => `#${n.id} ${n.name} (e.g. ${n.latest.slice(0, 2).map((l) => l.title).join(' / ')})`).join('\n') || '(none yet)'}\n\nNew headlines:\n${batch.map((f, i) => `${i}. ${f.title}`).join('\n')}`;
|
|
59
|
+
try {
|
|
60
|
+
const r = await chat([
|
|
61
|
+
{
|
|
62
|
+
role: 'system',
|
|
63
|
+
content: 'You track news narratives: storylines that continue across days (a company crisis, an election, a conflict, a product launch). For each headline: give the id of the existing narrative it continues, or a short new narrative name (3-6 words) if it starts or belongs to a storyline with other headlines in this batch, or skip it if it is a one-off. Be strict: same storyline, not same broad topic. Reply JSON {"assign":[{"item":n,"narrative":id}|{"item":n,"new":"name"}]}.',
|
|
64
|
+
},
|
|
65
|
+
{ role: 'user', content: prompt },
|
|
66
|
+
], { json: true, temperature: 0, maxTokens: 4000, ...(opts.fetch ? { fetch: opts.fetch } : {}) });
|
|
67
|
+
const part = JSON.parse(r.message.content ?? '{}').assign ?? [];
|
|
68
|
+
assign.push(...part.map((a) => ({ ...a, item: Number(a.item) + start })));
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
// Skip this batch (its headlines are picked up next run), but say so instead of failing silently.
|
|
72
|
+
provenance.push({ source: 'llm', url: '', status: 'ERROR', fetchedAt: nowIso, note: `narrative batch ${start / 40 + 1}: ${e.message.slice(0, 200)}` });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// New narratives need at least two headlines in this batch: a single story is not yet a storyline.
|
|
76
|
+
const newGroups = new Map();
|
|
77
|
+
for (const a of assign)
|
|
78
|
+
if (typeof a.new === 'string' && a.new.trim())
|
|
79
|
+
newGroups.set(a.new.trim().slice(0, 60), [...(newGroups.get(a.new.trim().slice(0, 60)) ?? []), Number(a.item)]);
|
|
80
|
+
const created = [];
|
|
81
|
+
const newIds = new Map();
|
|
82
|
+
// Batches can name the same storyline twice ("APEC summit tensions" / "APEC summit leadership meeting");
|
|
83
|
+
// fold a new name into an existing or just-created narrative when their key words overlap.
|
|
84
|
+
const named = active.map((n) => ({ name: n.name, id: n.id }));
|
|
85
|
+
const sameStory = (a, b) => {
|
|
86
|
+
const ov = overlap(keywords(a), keywords(b));
|
|
87
|
+
return ov.shared.length >= 2 || (ov.shared.length >= 1 && ov.score >= 0.5 && Math.min(keywords(a).size, keywords(b).size) <= 2);
|
|
88
|
+
};
|
|
89
|
+
for (const [name, idxs] of newGroups) {
|
|
90
|
+
const twin = named.find((n) => sameStory(n.name, name));
|
|
91
|
+
if (twin) {
|
|
92
|
+
newIds.set(name, twin.id);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (idxs.filter((i) => fresh[i]).length < 2)
|
|
96
|
+
continue;
|
|
97
|
+
const id = Number(db.prepare('INSERT INTO narratives (name, created_at, updated_at) VALUES (?, ?, ?)').run(name, nowMs, nowMs).lastInsertRowid);
|
|
98
|
+
newIds.set(name, id);
|
|
99
|
+
named.push({ name, id });
|
|
100
|
+
created.push(name);
|
|
101
|
+
}
|
|
102
|
+
const activeIds = new Set(active.map((n) => n.id));
|
|
103
|
+
const ins = db.prepare('INSERT OR IGNORE INTO narrative_items (url, narrative_id, title, source, day, added_at) VALUES (?, ?, ?, ?, ?, ?)');
|
|
104
|
+
const touch = db.prepare('UPDATE narratives SET updated_at = ? WHERE id = ?');
|
|
105
|
+
let added = 0;
|
|
106
|
+
for (const a of assign) {
|
|
107
|
+
const it = fresh[Number(a.item)];
|
|
108
|
+
if (!it)
|
|
109
|
+
continue;
|
|
110
|
+
const nid = typeof a.new === 'string' ? newIds.get(a.new.trim().slice(0, 60)) : activeIds.has(Number(a.narrative)) ? Number(a.narrative) : undefined;
|
|
111
|
+
if (!nid)
|
|
112
|
+
continue;
|
|
113
|
+
added += Number(ins.run(it.url, nid, it.title, it.source, day(nowMs), nowMs).changes);
|
|
114
|
+
touch.run(nowMs, nid);
|
|
115
|
+
}
|
|
116
|
+
const narratives = listNarratives(ctx);
|
|
117
|
+
const signals = [];
|
|
118
|
+
for (const n of narratives) {
|
|
119
|
+
const today = n.daily[6];
|
|
120
|
+
const before = n.daily.slice(0, 6);
|
|
121
|
+
const avg = before.reduce((x, y) => x + y, 0) / 6;
|
|
122
|
+
const isNew = nowMs - Date.parse(n.createdAt) < DAY_MS;
|
|
123
|
+
if ((isNew && today >= 4) || (!isNew && today >= 4 && today >= 2 * Math.max(1, avg))) {
|
|
124
|
+
signals.push({
|
|
125
|
+
id: signalId('narrative', String(n.id), day(nowMs)),
|
|
126
|
+
module: 'narrative',
|
|
127
|
+
title: `${isNew ? 'New narrative' : 'Narrative growing'}: ${n.name} (${today} stories today)`,
|
|
128
|
+
score: Math.min(85, 50 + today * 3),
|
|
129
|
+
evidence: n.latest.slice(0, 4).map((l) => ({ source: l.source, text: l.title, url: l.url.startsWith('http') ? l.url : undefined })).map((e) => (e.url ? e : { source: e.source, text: e.text })),
|
|
130
|
+
createdAt: nowIso,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
signals.forEach((s) => ctx.graph.saveSignal(s));
|
|
135
|
+
return { module: 'narratives', input: 'run', generatedAt: nowIso, result: { added, created, narratives }, signals, provenance };
|
|
136
|
+
}
|