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.
Files changed (255) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +344 -2
  3. package/dist/agent.d.ts +47 -0
  4. package/dist/agent.js +104 -0
  5. package/dist/cases.d.ts +68 -0
  6. package/dist/cases.js +158 -0
  7. package/dist/cli/main.d.ts +12 -0
  8. package/dist/cli/main.js +1999 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +15 -0
  11. package/dist/core/context.d.ts +19 -0
  12. package/dist/core/context.js +19 -0
  13. package/dist/core/features.d.ts +22 -0
  14. package/dist/core/features.js +28 -0
  15. package/dist/core/graph.d.ts +38 -0
  16. package/dist/core/graph.js +81 -0
  17. package/dist/core/http.d.ts +42 -0
  18. package/dist/core/http.js +266 -0
  19. package/dist/core/keys.d.ts +8 -0
  20. package/dist/core/keys.js +22 -0
  21. package/dist/core/llm.d.ts +93 -0
  22. package/dist/core/llm.js +180 -0
  23. package/dist/core/merkle.d.ts +15 -0
  24. package/dist/core/merkle.js +46 -0
  25. package/dist/core/paths.d.ts +2 -0
  26. package/dist/core/paths.js +6 -0
  27. package/dist/core/png.d.ts +17 -0
  28. package/dist/core/png.js +101 -0
  29. package/dist/core/quota.d.ts +15 -0
  30. package/dist/core/quota.js +90 -0
  31. package/dist/core/stats.d.ts +24 -0
  32. package/dist/core/stats.js +67 -0
  33. package/dist/core/store.d.ts +20 -0
  34. package/dist/core/store.js +213 -0
  35. package/dist/core/text.d.ts +9 -0
  36. package/dist/core/text.js +30 -0
  37. package/dist/core/types.d.ts +38 -0
  38. package/dist/core/types.js +1 -0
  39. package/dist/index.d.ts +342 -0
  40. package/dist/index.js +495 -0
  41. package/dist/live.d.ts +53 -0
  42. package/dist/live.js +236 -0
  43. package/dist/mcp.d.ts +43 -0
  44. package/dist/mcp.js +651 -0
  45. package/dist/modules/airport.d.ts +60 -0
  46. package/dist/modules/airport.js +111 -0
  47. package/dist/modules/audit.d.ts +73 -0
  48. package/dist/modules/audit.js +211 -0
  49. package/dist/modules/bgp.d.ts +147 -0
  50. package/dist/modules/bgp.js +206 -0
  51. package/dist/modules/blackout.d.ts +41 -0
  52. package/dist/modules/blackout.js +98 -0
  53. package/dist/modules/brief.d.ts +26 -0
  54. package/dist/modules/brief.js +99 -0
  55. package/dist/modules/calendar.d.ts +27 -0
  56. package/dist/modules/calendar.js +145 -0
  57. package/dist/modules/calibrate.d.ts +46 -0
  58. package/dist/modules/calibrate.js +92 -0
  59. package/dist/modules/cloud.d.ts +32 -0
  60. package/dist/modules/cloud.js +94 -0
  61. package/dist/modules/condor.d.ts +66 -0
  62. package/dist/modules/condor.js +214 -0
  63. package/dist/modules/connect.d.ts +47 -0
  64. package/dist/modules/connect.js +114 -0
  65. package/dist/modules/contradictions.d.ts +27 -0
  66. package/dist/modules/contradictions.js +76 -0
  67. package/dist/modules/country.d.ts +82 -0
  68. package/dist/modules/country.js +136 -0
  69. package/dist/modules/cricket.d.ts +34 -0
  70. package/dist/modules/cricket.js +166 -0
  71. package/dist/modules/darkships.d.ts +219 -0
  72. package/dist/modules/darkships.js +400 -0
  73. package/dist/modules/defi.d.ts +237 -0
  74. package/dist/modules/defi.js +512 -0
  75. package/dist/modules/emailsec.d.ts +47 -0
  76. package/dist/modules/emailsec.js +146 -0
  77. package/dist/modules/exposure.d.ts +43 -0
  78. package/dist/modules/exposure.js +89 -0
  79. package/dist/modules/factcheck.d.ts +39 -0
  80. package/dist/modules/factcheck.js +127 -0
  81. package/dist/modules/falcon.d.ts +58 -0
  82. package/dist/modules/falcon.js +219 -0
  83. package/dist/modules/feedback.d.ts +24 -0
  84. package/dist/modules/feedback.js +37 -0
  85. package/dist/modules/fence.d.ts +52 -0
  86. package/dist/modules/fence.js +128 -0
  87. package/dist/modules/ferret.d.ts +47 -0
  88. package/dist/modules/ferret.js +220 -0
  89. package/dist/modules/filings.d.ts +86 -0
  90. package/dist/modules/filings.js +166 -0
  91. package/dist/modules/fires.d.ts +56 -0
  92. package/dist/modules/fires.js +150 -0
  93. package/dist/modules/hazards.d.ts +37 -0
  94. package/dist/modules/hazards.js +83 -0
  95. package/dist/modules/health.d.ts +24 -0
  96. package/dist/modules/health.js +82 -0
  97. package/dist/modules/heron.d.ts +68 -0
  98. package/dist/modules/heron.js +184 -0
  99. package/dist/modules/hound.d.ts +100 -0
  100. package/dist/modules/hound.js +301 -0
  101. package/dist/modules/impact.d.ts +39 -0
  102. package/dist/modules/impact.js +63 -0
  103. package/dist/modules/launches.d.ts +24 -0
  104. package/dist/modules/launches.js +61 -0
  105. package/dist/modules/listen.d.ts +48 -0
  106. package/dist/modules/listen.js +125 -0
  107. package/dist/modules/lynx.d.ts +43 -0
  108. package/dist/modules/lynx.js +127 -0
  109. package/dist/modules/magpie.d.ts +70 -0
  110. package/dist/modules/magpie.js +174 -0
  111. package/dist/modules/meerkat.d.ts +42 -0
  112. package/dist/modules/meerkat.js +293 -0
  113. package/dist/modules/monitor.d.ts +27 -0
  114. package/dist/modules/monitor.js +105 -0
  115. package/dist/modules/narratives.d.ts +33 -0
  116. package/dist/modules/narratives.js +136 -0
  117. package/dist/modules/owl.d.ts +71 -0
  118. package/dist/modules/owl.js +290 -0
  119. package/dist/modules/papers.d.ts +46 -0
  120. package/dist/modules/papers.js +135 -0
  121. package/dist/modules/personal.d.ts +54 -0
  122. package/dist/modules/personal.js +153 -0
  123. package/dist/modules/pulse.d.ts +19 -0
  124. package/dist/modules/pulse.js +59 -0
  125. package/dist/modules/raven.d.ts +80 -0
  126. package/dist/modules/raven.js +147 -0
  127. package/dist/modules/recall.d.ts +44 -0
  128. package/dist/modules/recall.js +123 -0
  129. package/dist/modules/regs.d.ts +88 -0
  130. package/dist/modules/regs.js +142 -0
  131. package/dist/modules/rewind.d.ts +22 -0
  132. package/dist/modules/rewind.js +68 -0
  133. package/dist/modules/sanctions.d.ts +62 -0
  134. package/dist/modules/sanctions.js +173 -0
  135. package/dist/modules/scam.d.ts +43 -0
  136. package/dist/modules/scam.js +111 -0
  137. package/dist/modules/scoop.d.ts +31 -0
  138. package/dist/modules/scoop.js +74 -0
  139. package/dist/modules/ships.d.ts +33 -0
  140. package/dist/modules/ships.js +113 -0
  141. package/dist/modules/sky.d.ts +47 -0
  142. package/dist/modules/sky.js +183 -0
  143. package/dist/modules/squawk.d.ts +46 -0
  144. package/dist/modules/squawk.js +106 -0
  145. package/dist/modules/tortoise.d.ts +40 -0
  146. package/dist/modules/tortoise.js +104 -0
  147. package/dist/modules/travel.d.ts +94 -0
  148. package/dist/modules/travel.js +241 -0
  149. package/dist/modules/urlcheck.d.ts +63 -0
  150. package/dist/modules/urlcheck.js +223 -0
  151. package/dist/modules/vulns.d.ts +142 -0
  152. package/dist/modules/vulns.js +276 -0
  153. package/dist/plugins.d.ts +41 -0
  154. package/dist/plugins.js +70 -0
  155. package/dist/report.d.ts +12 -0
  156. package/dist/report.js +90 -0
  157. package/dist/scheduler.d.ts +22 -0
  158. package/dist/scheduler.js +139 -0
  159. package/dist/sources/aircraft.d.ts +76 -0
  160. package/dist/sources/aircraft.js +107 -0
  161. package/dist/sources/airports.d.ts +28 -0
  162. package/dist/sources/airports.js +100 -0
  163. package/dist/sources/ais.d.ts +32 -0
  164. package/dist/sources/ais.js +111 -0
  165. package/dist/sources/apify.d.ts +28 -0
  166. package/dist/sources/apify.js +80 -0
  167. package/dist/sources/arxiv.d.ts +13 -0
  168. package/dist/sources/arxiv.js +27 -0
  169. package/dist/sources/certs.d.ts +12 -0
  170. package/dist/sources/certs.js +23 -0
  171. package/dist/sources/corp.d.ts +46 -0
  172. package/dist/sources/corp.js +60 -0
  173. package/dist/sources/earth.d.ts +39 -0
  174. package/dist/sources/earth.js +76 -0
  175. package/dist/sources/fda.d.ts +77 -0
  176. package/dist/sources/fda.js +121 -0
  177. package/dist/sources/finance.d.ts +181 -0
  178. package/dist/sources/finance.js +270 -0
  179. package/dist/sources/gdelt.d.ts +19 -0
  180. package/dist/sources/gdelt.js +33 -0
  181. package/dist/sources/github.d.ts +17 -0
  182. package/dist/sources/github.js +33 -0
  183. package/dist/sources/hackernews.d.ts +20 -0
  184. package/dist/sources/hackernews.js +37 -0
  185. package/dist/sources/labels.d.ts +21 -0
  186. package/dist/sources/labels.js +87 -0
  187. package/dist/sources/launch.d.ts +16 -0
  188. package/dist/sources/launch.js +41 -0
  189. package/dist/sources/ofac.d.ts +29 -0
  190. package/dist/sources/ofac.js +86 -0
  191. package/dist/sources/onchain.d.ts +77 -0
  192. package/dist/sources/onchain.js +189 -0
  193. package/dist/sources/opentimestamps.d.ts +44 -0
  194. package/dist/sources/opentimestamps.js +131 -0
  195. package/dist/sources/polymarket.d.ts +36 -0
  196. package/dist/sources/polymarket.js +70 -0
  197. package/dist/sources/predict.d.ts +18 -0
  198. package/dist/sources/predict.js +59 -0
  199. package/dist/sources/press.d.ts +30 -0
  200. package/dist/sources/press.js +111 -0
  201. package/dist/sources/resend.d.ts +14 -0
  202. package/dist/sources/resend.js +29 -0
  203. package/dist/sources/robinhood.d.ts +109 -0
  204. package/dist/sources/robinhood.js +129 -0
  205. package/dist/sources/sec.d.ts +67 -0
  206. package/dist/sources/sec.js +129 -0
  207. package/dist/sources/sentinel.d.ts +13 -0
  208. package/dist/sources/sentinel.js +63 -0
  209. package/dist/sources/signatures.d.ts +14 -0
  210. package/dist/sources/signatures.js +103 -0
  211. package/dist/sources/social.d.ts +22 -0
  212. package/dist/sources/social.js +56 -0
  213. package/dist/sources/space.d.ts +160 -0
  214. package/dist/sources/space.js +230 -0
  215. package/dist/sources/usgs.d.ts +17 -0
  216. package/dist/sources/usgs.js +24 -0
  217. package/dist/sources/wayback.d.ts +10 -0
  218. package/dist/sources/wayback.js +28 -0
  219. package/dist/sources/websec.d.ts +19 -0
  220. package/dist/sources/websec.js +40 -0
  221. package/dist/sources/wikidata.d.ts +11 -0
  222. package/dist/sources/wikidata.js +30 -0
  223. package/dist/sources/wikimedia.d.ts +28 -0
  224. package/dist/sources/wikimedia.js +52 -0
  225. package/dist/telegram.d.ts +104 -0
  226. package/dist/telegram.js +927 -0
  227. package/dist/web/assets/favicon-32.png +0 -0
  228. package/dist/web/assets/fx.js +178 -0
  229. package/dist/web/assets/icon-192.png +0 -0
  230. package/dist/web/assets/icon-512.png +0 -0
  231. package/dist/web/assets/icon-maskable-512.png +0 -0
  232. package/dist/web/assets/night-americas.jpg +0 -0
  233. package/dist/web/assets/night-emea.jpg +0 -0
  234. package/dist/web/assets/og.png +0 -0
  235. package/dist/web/assets/redsea-bm.jpg +0 -0
  236. package/dist/web/docs.html +263 -0
  237. package/dist/web/index.html +1828 -0
  238. package/dist/web/insights.d.ts +100 -0
  239. package/dist/web/insights.js +134 -0
  240. package/dist/web/landing.html +1143 -0
  241. package/dist/web/legal.html +176 -0
  242. package/dist/web/manifest.webmanifest +20 -0
  243. package/dist/web/mcp.html +104 -0
  244. package/dist/web/mcphttp.d.ts +10 -0
  245. package/dist/web/mcphttp.js +67 -0
  246. package/dist/web/openapi.d.ts +1 -0
  247. package/dist/web/openapi.js +51 -0
  248. package/dist/web/public.d.ts +45 -0
  249. package/dist/web/public.js +135 -0
  250. package/dist/web/server.d.ts +69 -0
  251. package/dist/web/server.js +750 -0
  252. package/dist/web/share.d.ts +35 -0
  253. package/dist/web/share.js +132 -0
  254. package/dist/web/sw.js +28 -0
  255. package/package.json +60 -4
@@ -0,0 +1,927 @@
1
+ /**
2
+ * Oculon Telegram bot: long polling against the Bot API, no dependencies.
3
+ * Only chats listed in the allowlist can use it (anyone else gets their chat id and setup instructions).
4
+ * With alerts on, a background loop pushes new high-scoring signals to subscribed chats.
5
+ */
6
+ import { ONCHAIN_PAUSED_MESSAGE, onchainEnabled } from './core/features.js';
7
+ import { readFileSync } from 'node:fs';
8
+ import { Oculon } from './index.js';
9
+ import { alertBar, feedbackStats, recordFeedback } from './modules/feedback.js';
10
+ import { describePath } from './modules/connect.js';
11
+ import { fmtTime } from './modules/listen.js';
12
+ import { startScheduler } from './scheduler.js';
13
+ import { addPersonal, listPersonal, removePersonal } from './modules/personal.js';
14
+ export const esc = (s) => String(s ?? '').replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
15
+ const pct = (x) => (x == null ? 'n/a' : `${Math.round(x * 100)}%`);
16
+ export function formatSignal(s) {
17
+ const ev = s.evidence
18
+ .slice(0, 3)
19
+ .map((e) => ` • <i>${esc(e.source)}</i>: ${e.url ? `<a href="${esc(e.url)}">${esc(e.text.slice(0, 140))}</a>` : esc(e.text.slice(0, 140))}`)
20
+ .join('\n');
21
+ return `<b>[${Math.round(s.score)}] ${esc(s.title)}</b> <code>${esc(s.module)}</code>${ev ? `\n${ev}` : ''}`;
22
+ }
23
+ /** Commands anyone may use when the bot is public. Everything else stays with the allowlisted chats. */
24
+ export const PUBLIC_COMMANDS = new Set(['/start', '/help', '/scam', '/url', '/factcheck', '/recall', '/email', '/travel', '/airport', '/country', '/papers', '/audit', '/monitor', '/monitors', '/unmonitor', '/cve', '/vulns', '/hazards', '/blackout', '/cloud', '/space', '/air', '/radar', '/signals', '/alerts', '/ask']);
25
+ /** Commands that start many upstream calls or an LLM get a tighter budget. */
26
+ const HEAVY = new Set(['/factcheck', '/papers', '/travel', '/country', '/ask', '/scam', '/audit', '/radar']);
27
+ export const PUBLIC_HELP = [
28
+ '<b>Oculon</b>: check anything, every answer sourced.',
29
+ '',
30
+ 'Forward or paste any suspicious message and I will check it for scams.',
31
+ '',
32
+ '/scam &lt;message&gt; — is this message a scam?',
33
+ '/url &lt;link&gt; — is this link dangerous?',
34
+ '/factcheck &lt;claim or link&gt; — fact check a claim',
35
+ '/recall &lt;VIN, "2018 Honda Accord" or product&gt; — recalls',
36
+ '/email &lt;domain&gt; — can someone spoof email from this domain?',
37
+ '/travel &lt;place&gt; — travel risk for the coming week',
38
+ '/airport &lt;JFK|EGLL&gt; — airport weather, delays and ground stops',
39
+ '/country &lt;name&gt; — country brief',
40
+ '/papers &lt;topic&gt; — research brief',
41
+ '/audit &lt;npm:name@ver ...&gt; — dependency vulnerabilities',
42
+ '/cve &lt;id&gt; · /vulns · /hazards · /blackout · /cloud · /space · /air &lt;place&gt; · /radar',
43
+ '',
44
+ '/monitor &lt;request&gt; — watch anything, e.g. /monitor internet outages in Iran',
45
+ '/monitors — your monitors · /unmonitor &lt;id&gt; — remove one',
46
+ '/alerts on|off — the strongest worldwide signals',
47
+ '',
48
+ 'Web app: https://app.oculon.live · MCP: https://mcp.oculon.live',
49
+ ].join('\n');
50
+ /** Help text without the paused on-chain commands (they return with OCULON_ONCHAIN=1). */
51
+ export function helpHtml() {
52
+ return onchainEnabled() ? HELP : HELP.split('\n').filter((l) => !/^\/(wallet|token|rh|deployer|defi|protocol)\b/.test(l)).join('\n');
53
+ }
54
+ export const HELP = [
55
+ '<b>Oculon</b> — OSINT radar',
56
+ '/ask &lt;question&gt; — AI agent answers using every tool',
57
+ '/radar — what the world is suddenly watching',
58
+ '/url &lt;link&gt; — is this link dangerous?',
59
+ '/factcheck &lt;claim or link&gt; — fact check a claim',
60
+ '/travel &lt;place&gt; — travel risk brief for the coming week',
61
+ '/audit &lt;npm:name@ver ...&gt; — dependency vulnerabilities and health',
62
+ '/monitor &lt;request&gt; — watch anything in plain words, e.g. /monitor internet outages in Iran',
63
+ '/recall &lt;VIN, "2018 Honda Accord" or product&gt; — vehicle and product recalls',
64
+ '/email &lt;domain&gt; — can someone spoof email from this domain?',
65
+ '/airport &lt;JFK|EGLL&gt; — airport weather, delays and ground stops',
66
+ '/country &lt;name&gt; — economy, leaders, currency, travel advice, headlines',
67
+ '/papers &lt;topic&gt; — research brief: most cited and newest papers',
68
+ '/signals — latest signals',
69
+ '/dossier &lt;name&gt; — e.g. /dossier Nvidia',
70
+ '/hype &lt;topic&gt; — hype phase of a topic',
71
+ '/footprint &lt;domain&gt; — pre-release footprints',
72
+ '/plane &lt;reg or hex&gt; — track an aircraft',
73
+ '/mil — military air traffic',
74
+ '/events — natural events (NASA)',
75
+ '/lights &lt;place&gt; — night lights vs baseline',
76
+ '/image &lt;place&gt; — satellite image',
77
+ '/wallet &lt;address&gt; — wallet portfolio and risk',
78
+ '/token &lt;address&gt; — token contract check',
79
+ '/space — geomagnetic storms and solar flares',
80
+ '/ships &lt;place&gt; — live vessels near a port (AIS)',
81
+ '/air &lt;place&gt; — PM2.5 air quality',
82
+ '/rh — Robinhood Chain trending and new pools',
83
+ '/case &lt;question&gt; — deep investigation; /case lists, /case 3 opens one',
84
+ '/fence — geofences; /fence add &lt;name&gt; &lt;place&gt;; /fence rm &lt;id&gt;',
85
+ '/markets — Polymarket vs Kalshi and Manifold',
86
+ '/launches &lt;company&gt; — new models, apps, packages',
87
+ '/rewind &lt;YYYY-MM-DD&gt; — what Oculon would have seen that day',
88
+ '/deployer &lt;address&gt; — Robinhood Chain deployer reputation',
89
+ '/scoops — how often Oculon beat the media',
90
+ '/sanctions &lt;wallet|IMO|name&gt; — OFAC screening',
91
+ '/narratives — storylines across days',
92
+ '/health &lt;company&gt; — early-warning score',
93
+ '/impact [place] — people exposed to quakes and storms',
94
+ '/contradict &lt;topic&gt; — conflicting facts across sources',
95
+ '/report — weekly HTML report',
96
+ '/brief — today\'s brief',
97
+ '/watch — list; /watch add &lt;kind&gt; &lt;target&gt;; /watch rm &lt;id&gt;',
98
+ '/score — forecast track record',
99
+ '/sentinel &lt;place&gt; — sharp 10 m satellite image (Sentinel-2); /radar_image &lt;place&gt; sees through clouds',
100
+ '/fires &lt;place&gt; — active fires and hotspots nearby (NASA FIRMS)',
101
+ '/blackout — internet outages and shutdowns right now',
102
+ '/cloud — outages on AWS, Azure, Google Cloud, GitHub, Cloudflare, OpenAI...',
103
+ '/bgp [cc|ASN|IP] — BGP hijacks and route leaks worldwide, or routing of a country, network or IP',
104
+ '/vulns — vulnerabilities newly exploited in the wild (CISA KEV)',
105
+ '/cve &lt;id&gt; — one CVE: severity, exploitation odds, fixes',
106
+ '/regs [query] — US executive orders and rules (Federal Register)',
107
+ '/defi — TVL crashes, stablecoin depegs, hacks',
108
+ '/squawk — aircraft squawking emergency codes now',
109
+ '/filings &lt;phrase&gt; — SEC full-text search, last 30 days',
110
+ '/darkships &lt;place&gt; — vessels that switched off AIS there',
111
+ '/vessel &lt;name|MMSI|IMO&gt; — flag, owners, earlier names, sanctions',
112
+ '/hazards — official orange and red disaster alerts (GDACS)',
113
+ '/podcast &lt;subject&gt; — newest podcast episode about it, transcribed, with quotes',
114
+ '/exposure &lt;domain&gt; — open ports and known CVEs on its servers',
115
+ '/social &lt;subject&gt; — posts on X, Reddit, TikTok, Bluesky right now',
116
+ '/calendar [days] — earnings, macro releases and markets closing soon',
117
+ '/connect &lt;A&gt; to &lt;B&gt; — how two things are linked in the graph',
118
+ '/live — what the live Wikipedia and Bluesky streams flagged',
119
+ '/feedback — how your Useful/Noise votes move each module',
120
+ '/alerts on|off — push new strong signals and the daily brief here',
121
+ ].join('\n');
122
+ export class TelegramBot {
123
+ opts;
124
+ offset = 0;
125
+ running = false;
126
+ scheduler = null;
127
+ oculon;
128
+ doFetch;
129
+ log;
130
+ constructor(opts) {
131
+ this.opts = opts;
132
+ if (!opts.token)
133
+ throw new Error('TELEGRAM_BOT_TOKEN is not set');
134
+ this.oculon = opts.oculon ?? new Oculon();
135
+ this.doFetch = opts.fetch ?? fetch;
136
+ this.log = opts.log ?? (() => { });
137
+ const db = this.oculon.ctx.store.db;
138
+ db.exec('CREATE TABLE IF NOT EXISTS telegram_subs (chat_id TEXT PRIMARY KEY, created_at INTEGER NOT NULL)');
139
+ db.exec('CREATE TABLE IF NOT EXISTS telegram_sent (chat_id TEXT NOT NULL, signal_id TEXT NOT NULL, PRIMARY KEY (chat_id, signal_id))');
140
+ }
141
+ /** Bot API call. Never logs the URL, because it contains the token. */
142
+ async call(method, body) {
143
+ const isForm = body instanceof FormData;
144
+ const res = await this.doFetch(`https://api.telegram.org/bot${this.opts.token}/${method}`, {
145
+ method: 'POST',
146
+ ...(isForm ? { body } : { body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }),
147
+ signal: AbortSignal.timeout(method === 'getUpdates' ? 45_000 : 30_000),
148
+ });
149
+ const j = (await res.json().catch(() => ({ ok: false, description: `HTTP ${res.status}` })));
150
+ if (!j.ok)
151
+ throw new Error(`telegram ${method}: ${j.description ?? res.status}`);
152
+ return j.result;
153
+ }
154
+ /** Send HTML text, split under Telegram's 4096-character limit at line breaks. */
155
+ async send(chatId, html) {
156
+ const parts = [];
157
+ let cur = '';
158
+ for (const line of html.split('\n')) {
159
+ if (cur.length + line.length + 1 > 3900) {
160
+ parts.push(cur);
161
+ cur = '';
162
+ }
163
+ cur += (cur ? '\n' : '') + line;
164
+ }
165
+ if (cur)
166
+ parts.push(cur);
167
+ for (const p of parts)
168
+ await this.call('sendMessage', { chat_id: chatId, text: p, parse_mode: 'HTML', disable_web_page_preview: true });
169
+ }
170
+ async sendDocument(chatId, file, caption) {
171
+ const form = new FormData();
172
+ form.set('chat_id', String(chatId));
173
+ form.set('caption', caption.slice(0, 1000));
174
+ form.set('document', new Blob([readFileSync(file)], { type: 'text/html' }), file.split(/[\\/]/).pop() ?? 'report.html');
175
+ await this.call('sendDocument', form);
176
+ }
177
+ /** Send a report file to every subscribed chat. */
178
+ async pushReport(file, caption) {
179
+ const subs = this.oculon.ctx.store.db.prepare('SELECT chat_id FROM telegram_subs').all().map((r) => r.chat_id).filter((c) => this.allowed(c));
180
+ for (const chat of subs)
181
+ await this.sendDocument(chat, file, caption);
182
+ return subs.length;
183
+ }
184
+ async sendPhoto(chatId, file, caption) {
185
+ const form = new FormData();
186
+ form.set('chat_id', String(chatId));
187
+ form.set('caption', caption.slice(0, 1000));
188
+ form.set('photo', new Blob([readFileSync(file)], { type: 'image/png' }), 'image.png');
189
+ await this.call('sendPhoto', form);
190
+ }
191
+ allowed(chatId) {
192
+ return this.opts.allowedChats.includes(chatId);
193
+ }
194
+ get isPublic() {
195
+ return this.opts.publicMode ?? process.env.OCULON_TELEGRAM_PUBLIC === '1';
196
+ }
197
+ usage = new Map();
198
+ /** Per chat: 30 commands an hour, 8 of them heavy. */
199
+ rateOk(chatId, heavy) {
200
+ const now = Date.now();
201
+ const key = heavy ? `${chatId}:h` : chatId;
202
+ const list = (this.usage.get(key) ?? []).filter((t) => now - t < 3_600_000);
203
+ if (list.length >= (heavy ? 8 : 30))
204
+ return false;
205
+ list.push(now);
206
+ this.usage.set(key, list);
207
+ if (heavy)
208
+ return this.rateOk(chatId, false);
209
+ return true;
210
+ }
211
+ /** Changes found by personal monitors, sent to the Telegram chats that own them. */
212
+ async pushPersonal(deliveries) {
213
+ let sent = 0;
214
+ for (const d of deliveries.filter((x) => x.owner.startsWith('tg:'))) {
215
+ const chat = d.owner.slice(3);
216
+ await this.send(chat, `<b>Monitor #${d.monitor.id}</b>: ${esc(d.monitor.description)}\n${d.changes.slice(0, 6).map((c) => `• ${esc(c)}`).join('\n')}`).catch(() => { });
217
+ sent++;
218
+ }
219
+ return sent;
220
+ }
221
+ /** Turn one command into a reply. Exposed for tests. */
222
+ async respond(chatId, text, ctx = {}) {
223
+ const isOwnerChat = ctx.owner ?? this.allowed(chatId);
224
+ const [rawCmd = '', ...rest] = text.trim().split(/\s+/);
225
+ const cmd = rawCmd.toLowerCase().replace(/@.*$/, '');
226
+ const arg = rest.join(' ').slice(0, 200);
227
+ const o = this.oculon;
228
+ const needArg = (example) => ({ html: `Usage: ${esc(cmd)} ${esc(example)}` });
229
+ if (/^\/(wallet|token|rh|deployer|defi|protocol)$/.test(cmd) && !onchainEnabled())
230
+ return { html: esc(ONCHAIN_PAUSED_MESSAGE) };
231
+ switch (cmd) {
232
+ case '/start':
233
+ case '/help':
234
+ return { html: isOwnerChat ? helpHtml() : PUBLIC_HELP };
235
+ case '/scam': {
236
+ const msg = text.trim().replace(/^\S+\s*/, '');
237
+ if (msg.length < 8)
238
+ return { html: 'Forward or paste the message you received, or send /scam followed by the text.' };
239
+ const d = (await o.scamCheck(msg)).result;
240
+ const head = d.verdict === 'likely scam' ? '⚠️ <b>LIKELY SCAM</b>' : d.verdict === 'suspicious' ? '<b>SUSPICIOUS</b>' : '<b>No strong signs of a scam</b>';
241
+ return { html: `${head} (risk ${d.risk}/100)${d.explanation ? `\n\n${esc(d.explanation)}` : ''}${d.reasons.length ? `\n\n${d.reasons.slice(0, 6).map((x) => `• ${esc(x)}`).join('\n')}` : ''}\n\n${d.advice.map((x) => `→ ${esc(x)}`).join('\n')}` };
242
+ }
243
+ case '/monitors': {
244
+ const list = listPersonal(o.ctx, `tg:${chatId}`);
245
+ return { html: list.length ? `<b>Your monitors</b>\n${list.map((x) => `#${x.id} ${esc(x.description)}${x.lastChange ? ` <i>(changed ${esc(x.lastChange.slice(0, 16))}Z)</i>` : ''}`).join('\n')}\n\nRemove one with /unmonitor &lt;id&gt;.` : 'No monitors yet. Try /monitor internet outages in Iran' };
246
+ }
247
+ case '/unmonitor': {
248
+ const id = Number(arg);
249
+ return { html: Number.isInteger(id) && removePersonal(o.ctx, `tg:${chatId}`, id) ? `Removed monitor #${id}.` : 'No such monitor. See /monitors.' };
250
+ }
251
+ case '/radar': {
252
+ const r = await o.radar();
253
+ return { html: r.signals.length ? `<b>Radar</b>: ${r.signals.length} signals\n\n${r.signals.slice(0, 8).map(formatSignal).join('\n\n')}` : 'Radar: nothing stands out right now.' };
254
+ }
255
+ case '/signals': {
256
+ const s = o.signals(10);
257
+ return { html: s.length ? s.map(formatSignal).join('\n\n') : 'No signals yet. Try /radar.' };
258
+ }
259
+ case '/dossier': {
260
+ if (!arg)
261
+ return needArg('Nvidia');
262
+ const r = await o.dossier(arg);
263
+ const d = r.result;
264
+ const lines = [
265
+ `<b>${esc(d.wikipedia?.title ?? d.query)}</b>${d.wikipedia?.description ? ` — ${esc(d.wikipedia.description)}` : ''}`,
266
+ d.wikipedia?.spike ? `Wikipedia readers ${d.wikipedia.spike.toFixed(1)}× usual` : '',
267
+ ...d.markets.slice(0, 3).map((m) => `market: ${esc(m.question)} — ${pct(m.prices[0])}`),
268
+ '',
269
+ ...d.timeline.slice(0, 8).map((t) => `${esc(t.date.slice(0, 10))} <i>${esc(t.source)}</i> ${esc(t.text.slice(0, 120))}`),
270
+ ...(r.signals.length ? ['', ...r.signals.map(formatSignal)] : []),
271
+ ];
272
+ return { html: lines.filter((l, i, a) => l !== '' || a[i - 1] !== '').join('\n') };
273
+ }
274
+ case '/hype': {
275
+ if (!arg)
276
+ return needArg('ai agent');
277
+ const r = await o.hype(arg);
278
+ const d = r.result;
279
+ return { html: `<b>${esc(d.topic)}: ${esc(d.phase)}</b>\n${esc(d.summary)}` };
280
+ }
281
+ case '/footprint': {
282
+ if (!arg)
283
+ return needArg('openai.com');
284
+ const r = await o.footprint(arg);
285
+ const d = r.result;
286
+ const top = d.findings.slice(0, 10).map((f) => `[${f.score}] ${esc(f.kind)} <a href="${esc(f.url)}">${esc(f.value.slice(0, 90))}</a> (${esc(f.firstSeen.slice(0, 10))})`);
287
+ return { html: `<b>${esc(d.domain)}</b>, last ${d.windowDays} days: ${d.counts.subdomain} subdomains, ${d.counts.page} pages, ${d.counts.repo} repos\n${top.join('\n') || 'nothing new'}` };
288
+ }
289
+ case '/plane': {
290
+ if (!arg)
291
+ return needArg('N628TS');
292
+ const t = (await o.aircraft(arg)).result;
293
+ return {
294
+ html: [
295
+ `<b>${esc(t.info?.registration ?? t.query)}</b> ${esc([t.info?.manufacturer, t.info?.type].filter(Boolean).join(' '))}`,
296
+ t.info?.owner ? `owner: ${esc(t.info.owner)}` : '',
297
+ `status: ${esc(t.status)}${t.state?.altFt != null && t.status === 'AIRBORNE' ? ` at ${t.state.altFt} ft` : ''}`,
298
+ t.place ? `${esc(t.place.relation)} ${esc(t.place.airport)} (${t.place.km} km)` : '',
299
+ t.change ? `<b>${esc(t.change)}</b>` : '',
300
+ ]
301
+ .filter(Boolean)
302
+ .join('\n'),
303
+ };
304
+ }
305
+ case '/mil': {
306
+ const r = await o.military();
307
+ const d = r.result;
308
+ const regions = d.regions.slice(0, 8).map((g) => `${g.count} near ${esc(g.label)}${g.notable.length ? ` — ${g.notable.map((n) => esc(n.role)).join(', ')}` : ''}`);
309
+ return { html: `<b>Military air</b>: ${d.withPosition} aircraft with position\n${regions.join('\n')}${r.signals.length ? `\n\n${r.signals.slice(0, 4).map(formatSignal).join('\n\n')}` : ''}` };
310
+ }
311
+ case '/events': {
312
+ const r = await o.naturalEvents();
313
+ const ev = r.result.events.slice(0, 10).map((e) => `${e.severity ? `[${e.severity}] ` : ''}${esc(e.title)}${e.why ? ` — ${esc(e.why)}` : ''}`);
314
+ return { html: `<b>Natural events</b> (NASA EONET)\n${ev.join('\n') || 'none open'}` };
315
+ }
316
+ case '/lights': {
317
+ if (!arg)
318
+ return needArg('Gaza Strip');
319
+ const d = (await o.nightLights(arg)).result;
320
+ return { html: `<b>${esc(d.place.name)}</b>\nnight lights: <b>${esc(d.verdict)}</b>${d.ratio ? ` (${d.ratio >= 1 ? '+' : ''}${Math.round((d.ratio - 1) * 100)}%)` : ''}\n${d.recent.length} recent nights vs ${d.baseline.length} baseline nights, newest ${esc(d.latestDate ?? 'n/a')}` };
321
+ }
322
+ case '/image': {
323
+ if (!arg)
324
+ return needArg('Kyoto');
325
+ const r = await o.satelliteImage(arg);
326
+ if (!r.result.file)
327
+ return { html: `No image for ${esc(arg)} on ${esc(r.result.date)}.` };
328
+ return { photo: { file: r.result.file, caption: `${r.result.place.name} — ${r.result.date} (NASA MODIS true color)` } };
329
+ }
330
+ case '/ask': {
331
+ if (!arg)
332
+ return needArg('why is Nvidia in the news?');
333
+ const r = await o.ask(arg);
334
+ return { html: `${esc(r.answer)}\n\n<i>${r.steps.length} tool call(s), ${esc([...new Set(r.providers)].join(', '))}. AI-written from tool results; check the sources.</i>` };
335
+ }
336
+ case '/wallet': {
337
+ if (!arg)
338
+ return needArg('0x…');
339
+ const w = (await o.wallet(arg)).result;
340
+ return {
341
+ html: [
342
+ `<b>${esc(w.address)}</b>`,
343
+ w.portfolio ? `portfolio $${Math.round(w.portfolio.totalUsd).toLocaleString('en-US')} (Zerion)` : '',
344
+ ...(w.portfolio?.top.slice(0, 5).map((t) => ` ${esc(t.symbol)} $${Math.round(t.valueUsd).toLocaleString('en-US')}`) ?? []),
345
+ w.solana ? `${w.solana.sol.toFixed(3)} SOL, ${w.solana.tokens} token accounts` : '',
346
+ w.firstSeen ? `first tx ${esc(w.firstSeen.slice(0, 10))} (${w.ageDays} days)` : '',
347
+ w.robinhood ? `Robinhood Chain: ${w.robinhood.balanceEth.toFixed(4)} ETH, ${w.robinhood.txCount} txs` : '',
348
+ `risk: ${w.labels.length ? esc(w.labels.join(', ')) : 'no GoPlus labels'}${w.riskScore != null ? `, Webacy ${w.riskScore}` : ''}`,
349
+ ]
350
+ .filter(Boolean)
351
+ .join('\n'),
352
+ };
353
+ }
354
+ case '/token': {
355
+ if (!arg)
356
+ return needArg('0x…');
357
+ const t = (await o.token(arg.split(' ')[0], arg.split(' ')[1] ?? 'eth')).result;
358
+ return { html: `<b>${esc(t.security?.symbol || t.address)}: ${esc(t.verdict)}</b>\n${t.reasons.map((x) => `• ${esc(x)}`).join('\n')}${t.market ? `\nprice ${t.market.priceUsd} · mcap $${Math.round(t.market.marketCapUsd ?? 0).toLocaleString('en-US')}` : ''}` };
359
+ }
360
+ case '/space': {
361
+ const s = (await o.spaceWeather()).result;
362
+ return { html: `<b>Space weather: ${esc(s.stormLevel)}</b>\nKp now ${s.kpNow ?? '?'}, max 24h ${s.kpMax24h ?? '?'}${s.strongestFlare ? `\nstrongest flare (7d) ${esc(s.strongestFlare.maxClass)} at ${esc(s.strongestFlare.maxTime.slice(0, 16))}Z` : ''}` };
363
+ }
364
+ case '/ships': {
365
+ if (!arg)
366
+ return needArg('Port of Rotterdam');
367
+ const d = (await o.ships(arg, 30)).result;
368
+ if (!d.total)
369
+ return { html: `No AIS reports near ${esc(d.place.name)} in ${d.seconds}s (no receiver coverage there, or no traffic).` };
370
+ const types = Object.entries(d.byType).sort((x, y) => y[1] - x[1]).slice(0, 5).map(([t, n]) => `${esc(t)} ${n}`).join(', ');
371
+ return { html: `<b>${esc(d.place.name)}</b>\n${d.total} vessels in ${d.seconds}s · ${d.moving} moving · ${d.stationary} anchored/moored\n${types}` };
372
+ }
373
+ case '/url': {
374
+ if (!arg)
375
+ return needArg('paypa1-secure-login.top/verify');
376
+ const d = (await o.urlCheck(arg)).result;
377
+ const reasons = d.reasons.map((x) => `• ${esc(x)}`).join('\n');
378
+ const reg = d.domainInfo?.registered ? `\n<i>registered ${esc(d.domainInfo.registered.slice(0, 10))}${d.domainInfo.registrar ? ` via ${esc(d.domainInfo.registrar)}` : ''}</i>` : '';
379
+ const note = d.verdict === 'no known threats' ? '\n<i>No source flags it; that is not a guarantee.</i>' : '';
380
+ return { html: `<b>${esc(d.host)}</b>: <b>${esc(d.verdict.toUpperCase())}</b> (risk ${d.risk}/100)${reasons ? `\n${reasons}` : ''}${reg}${note}` };
381
+ }
382
+ case '/factcheck': {
383
+ if (!arg)
384
+ return needArg('The Great Wall of China is visible from space');
385
+ const d = (await o.factCheck(arg)).result;
386
+ const cited = [...d.factChecks, ...d.web].filter((e) => !d.cited.length || d.cited.includes(e.n)).slice(0, 5);
387
+ const refs = cited.map((e) => `[${e.n}] <a href="${esc(e.url)}">${esc(e.publisher)}</a>${e.rating ? ` "${esc(e.rating)}"` : ''}`).join('\n');
388
+ return { html: `<b>${esc(d.claim)}</b>\n<b>${esc(d.verdict.toUpperCase())}</b>${d.confidence ? ` · confidence ${d.confidence}%` : ''}\n\n${esc(d.summary)}${refs ? `\n\n${refs}` : ''}` };
389
+ }
390
+ case '/travel': {
391
+ if (!arg)
392
+ return needArg('Lisbon');
393
+ const d = (await o.travel(arg)).result;
394
+ const points = d.points.map((x) => `• ${esc(x)}`).join('\n') || 'No warnings from the sources checked.';
395
+ const wx = d.weather ? `\n\n<i>${d.weather.days.slice(0, 4).map((x) => `${x.date.slice(5)} ${esc(x.summary)} ${Math.round(x.tMin)}–${Math.round(x.tMax)}°C`).join(' · ')}</i>` : '';
396
+ return { html: `<b>${esc(d.place.name.split(',').slice(0, 2).join(','))}</b>: <b>${esc(d.level.toUpperCase())} risk</b>\n${points}${wx}` };
397
+ }
398
+ case '/audit': {
399
+ if (!arg)
400
+ return needArg('npm:lodash@4.17.15 npm:request');
401
+ const items = arg.split(/\s+/).map((x) => (x.includes(':') ? x : `npm:${x}`)).join(' ');
402
+ const r = (await o.audit(items)).result;
403
+ const flagged = r.packages.filter((p) => p.flags.length).slice(0, 8);
404
+ const body = flagged.map((p) => `<b>${esc(p.name)}@${esc(p.version ?? '?')}</b> risk ${p.risk}\n${p.flags.map((x) => ` • ${esc(x)}`).join('\n')}`).join('\n') || 'No flags.';
405
+ return { html: `<b>${r.summary.checked} package(s)</b>: ${r.summary.vulnerable} vulnerable, ${r.summary.deprecated} deprecated\n${body}` };
406
+ }
407
+ case '/recall': {
408
+ if (!arg)
409
+ return needArg('2018 Honda Accord');
410
+ const d = (await o.recall(arg)).result;
411
+ const head = d.vehicle ? `${d.vehicle.year} ${d.vehicle.make} ${d.vehicle.model}` : d.query;
412
+ const items = d.recalls.slice(0, 6).map((x) => `• ${x.parkIt ? '<b>DO NOT DRIVE</b> ' : x.parkOutside ? '<b>PARK OUTSIDE</b> ' : ''}<a href="${esc(x.url)}">${esc(x.title.slice(0, 90))}</a> <i>${esc(x.date ?? '')}</i>`).join('\n');
413
+ return { html: `<b>${esc(head)}</b>: ${d.recalls.length ? `${d.recalls.length} recall(s)` : 'no recalls found'}${items ? `\n${items}` : ''}${d.note ? `\n<i>${esc(d.note)}</i>` : ''}` };
414
+ }
415
+ case '/email': {
416
+ if (!arg)
417
+ return needArg('example.com');
418
+ const d = (await o.emailSecurity(arg)).result;
419
+ const fixes = d.fixes.slice(0, 3).map((x, i) => `${i + 1}. ${esc(x)}`).join('\n');
420
+ return { html: `<b>${esc(d.domain)}</b>: <b>${esc(d.verdict.toUpperCase())}</b> (score ${d.score}/100)\nSPF ${esc(d.spf.all ?? (d.spf.record ? 'present' : 'missing'))} · DMARC ${esc(d.dmarc.policy ? `p=${d.dmarc.policy}` : 'missing')} · DKIM ${d.dkim.selectorsFound.length ? 'found' : 'not found'}${fixes ? `\n\n${fixes}` : ''}` };
421
+ }
422
+ case '/airport': {
423
+ if (!arg)
424
+ return needArg('JFK');
425
+ const d = (await o.airport(arg)).result;
426
+ return { html: `<b>${esc(d.airport.name)}</b>: <b>${esc(d.verdict.toUpperCase())}</b>\n${d.points.map((x) => `• ${esc(x)}`).join('\n')}` };
427
+ }
428
+ case '/country': {
429
+ if (!arg)
430
+ return needArg('Argentina');
431
+ const d = (await o.country(arg)).result;
432
+ const ind = d.indicators.filter((i) => i.value != null && i.unit === '%').map((i) => `${esc(i.name)} ${i.value.toFixed(1)}% (${esc(i.year ?? '')})`).join(' · ');
433
+ const news = d.headlines.slice(0, 3).map((h) => `• <a href="${esc(h.url)}">${esc(h.title)}</a>`).join('\n');
434
+ return { html: `<b>${esc(d.name)}</b>\nHead of state: ${esc(d.leaders.headOfState ?? 'n/a')}${d.currency.perUsd ? ` · 1 USD = ${d.currency.perUsd.toFixed(2)} ${esc(d.currency.code ?? '')}` : ''}\n${ind}${d.advisories.us ? `\nUS advisory level ${d.advisories.us.level}: ${esc(d.advisories.us.text)}` : ''}${news ? `\n\n${news}` : ''}` };
435
+ }
436
+ case '/papers': {
437
+ if (!arg)
438
+ return needArg('solid-state battery');
439
+ const d = (await o.papers(arg)).result;
440
+ const top = d.mostCited.slice(0, 4).map((p) => `[${p.n}] <a href="${esc(p.openAccessUrl ?? p.url)}">${esc(p.title.slice(0, 100))}</a> <i>${p.year} · ${p.citations} cit.</i>`).join('\n');
441
+ return { html: `<b>${esc(d.topic)}</b>${d.trend ? ` · field ${esc(d.trend)}` : ''}${d.overview ? `\n\n${esc(d.overview.slice(0, 900))}` : ''}\n\n${top}` };
442
+ }
443
+ case '/monitor': {
444
+ if (!arg)
445
+ return needArg('internet outages in Iran');
446
+ const r = await addPersonal(o.ctx, `tg:${chatId}`, arg);
447
+ return { html: `Monitoring #${r.monitor.id}: ${esc(r.rule.description)}.\nI will message you here when it changes (checked about hourly; the first check records a baseline). /monitors lists yours.` };
448
+ }
449
+ case '/air': {
450
+ if (!arg)
451
+ return needArg('London');
452
+ const d = (await o.airQuality(arg)).result;
453
+ return { html: `<b>${esc(d.place.name)}</b>\nPM2.5 ${d.median != null ? `${d.median.toFixed(0)} µg/m³ · ${esc(d.category)}` : 'no fresh stations within 25 km'}\n${d.stations.map((s) => `${esc(s.name)}: ${s.value}`).join('\n')}` };
454
+ }
455
+ case '/rh': {
456
+ const r = (await o.robinhood()).result;
457
+ const fmt = (p) => `${esc(p.pool.name)} · liq $${Math.round(p.pool.liquidityUsd).toLocaleString('en-US')}${p.pool.change24h != null ? ` · ${p.pool.change24h.toFixed(0)}%` : ''}${p.flags.length ? ` · <i>${esc(p.flags[0])}</i>` : ''}`;
458
+ return {
459
+ html: `<b>Robinhood Chain</b>${r.stats ? ` · ${r.stats.transactionsToday.toLocaleString('en-US')} txs today` : ''}\n\n<b>Trending</b>\n${r.trending.slice(0, 6).map(fmt).join('\n')}\n\n<b>New pools</b>\n${r.fresh.slice(0, 6).map(fmt).join('\n')}`,
460
+ };
461
+ }
462
+ case '/case': {
463
+ if (!arg) {
464
+ const list = await o.caseList();
465
+ return { html: list.length ? list.map((k) => `#${k.id} ${esc(k.question.slice(0, 80))} <i>(${k.report?.confidence ?? '-'}, ${k.report?.findings.length ?? 0} findings${k.watch ? ', watching' : ''})</i>`).join('\n') : 'No cases yet. /case &lt;question&gt; opens one.' };
466
+ }
467
+ if (/^\d+$/.test(arg)) {
468
+ const k = await o.caseGet(Number(arg));
469
+ return { html: k?.markdown ? markdownToTelegram(k.markdown) : `No case #${esc(arg)}.` };
470
+ }
471
+ const m = /^watch\s+(\d+)(\s+off)?$/.exec(arg);
472
+ if (m)
473
+ return { html: (await o.caseWatch(Number(m[1]), !m[2])) ? `Case #${m[1]} watch ${m[2] ? 'off' : 'on'}.` : `No case #${m[1]}.` };
474
+ await this.send(chatId, `Investigating: <i>${esc(arg)}</i>\nThis takes 1-3 minutes.`);
475
+ const r = await o.caseInvestigate({ question: arg });
476
+ return { html: markdownToTelegram(r.case.markdown ?? '') };
477
+ }
478
+ case '/sanctions': {
479
+ if (!arg)
480
+ return needArg('0x… | IMO 1234567 | exact name');
481
+ const d = (await o.sanctions(arg)).result;
482
+ return { html: `<b>${esc(d.query.slice(0, 60))}: ${esc(d.verdict)}</b> <i>(OFAC SDN, ${d.listSize.toLocaleString('en-US')} entries)</i>${d.hits.map((h) => `\n• ${esc(h.kind)}: ${esc(h.entry.name)} [${esc(h.entry.program)}]${h.detail ? ` — ${esc(h.detail)}` : ''}`).join('')}` };
483
+ }
484
+ case '/narratives': {
485
+ const list = await o.narratives(14);
486
+ return { html: list.length ? `<b>Narratives</b>\n${list.slice(0, 12).map((n) => `${esc(n.name)} — ${n.daily[6]} today, ${n.total} total <i>(${esc(n.phase.toLowerCase())})</i>`).join('\n')}` : 'No narratives yet; they are built every 6 hours.' };
487
+ }
488
+ case '/health': {
489
+ if (!arg)
490
+ return needArg('Nvidia');
491
+ const d = (await o.health(arg)).result;
492
+ return { html: `<b>${esc(d.company)} health: ${d.score}/100</b>${d.change !== null ? ` (${d.change >= 0 ? '+' : ''}${d.change} vs 7-day avg)` : ''}\n${d.parts.map((p) => `${p.points > 0 ? '+' : ''}${p.points} ${esc(p.name)}: ${esc(p.why)}`).join('\n')}` };
493
+ }
494
+ case '/impact': {
495
+ const r = (await o.impact(arg || undefined, 50)).result;
496
+ if (!r.impacts.length)
497
+ return { html: 'No M6+ earthquakes or severe storms right now. Try /impact Tokyo' };
498
+ return { html: r.impacts.slice(0, 4).map((i) => `<b>${esc(i.event)}</b>\n~${i.exposedPopulation.toLocaleString('en-US')} people in listed places within ${i.radiusKm} km${i.settlements.length ? `: ${esc(i.settlements.slice(0, 3).map((s) => s.name).join(', '))}` : ' (open sea or remote)'}`).join('\n\n') };
499
+ }
500
+ case '/contradict': {
501
+ if (!arg)
502
+ return needArg('Anthropic IPO');
503
+ await this.send(chatId, `Reading sources on <i>${esc(arg)}</i>…`);
504
+ const d = (await o.contradictions(arg)).result;
505
+ return { html: d.contradictions.length ? `<b>${d.contradictions.length} contradiction(s) on ${esc(d.topic)}</b>\n${d.contradictions.slice(0, 5).map((x) => `• <b>${esc(x.about)}</b>\nA: ${esc(x.claimA.slice(0, 160))} (<a href="${esc(x.sourceA)}">source</a>)\nB: ${esc(x.claimB.slice(0, 160))} (<a href="${esc(x.sourceB)}">source</a>)`).join('\n')}` : `${d.sourcesRead.length} sources read on ${esc(d.topic)}: no conflicting facts.` };
506
+ }
507
+ case '/report': {
508
+ const r = await o.report(7);
509
+ return { document: { file: r.file, caption: `Oculon report, last 7 days: ${r.counts.signals} signals, ${r.counts.narratives} narratives, ${r.counts.cases} case files` } };
510
+ }
511
+ case '/scoops': {
512
+ const b = o.scoops();
513
+ const best = b.best.slice(0, 5).map((s) => `+${s.leadHours}h ${esc(s.subject)} (${esc(s.mediaSource ?? '')})`);
514
+ return { html: `<b>First to Know</b>\n${b.checked} checked · ${b.covered} covered by media · Oculon first ${b.oculonFirst} · media first ${b.mediaFirst}${b.medianLeadHours !== null ? ` · median ${b.medianLeadHours}h` : ''}${best.length ? `\n${best.join('\n')}` : ''}` };
515
+ }
516
+ case '/deployer': {
517
+ if (!arg)
518
+ return needArg('0x… (token or deployer on Robinhood Chain)');
519
+ const d = (await o.robinhoodDeployer(arg)).result;
520
+ return { html: `<b>Deployer ${esc(d.deployer.slice(0, 12))}…: ${esc(d.verdict)}</b>\n${esc(d.reasons.join('; '))}\n${d.tokens.slice(0, 8).map((t) => `${esc(t.symbol ?? '?')} liq $${t.reserveUsd.toLocaleString('en-US')}${t.dead ? ' (dead)' : ''}`).join('\n')}` };
521
+ }
522
+ case '/markets': {
523
+ const r = (await o.markets()).result;
524
+ if (!r.comparisons.length)
525
+ return { html: `Checked ${r.checked} Polymarket markets: no exact match on Kalshi or Manifold right now.` };
526
+ return { html: `<b>Market cross-check</b>\n${r.comparisons.slice(0, 8).map((x) => `${x.gapPp}pp · PM ${Math.round(x.polymarket.probability * 100)}% vs ${esc(x.other.venue)} ${Math.round(x.other.probability * 100)}% · ${esc(x.polymarket.question.slice(0, 80))}`).join('\n')}` };
527
+ }
528
+ case '/launches': {
529
+ if (!arg)
530
+ return needArg('OpenAI');
531
+ const d = (await o.launches(arg)).result;
532
+ return { html: `<b>Launch radar: ${esc(arg)}</b> (${d.items.length} in ${d.windowDays} days)\n${d.items.slice(0, 12).map((i) => `${esc(i.date.slice(0, 10))} ${esc(i.kind)} <a href="${esc(i.url)}">${esc(i.title.slice(0, 70))}</a>`).join('\n')}` };
533
+ }
534
+ case '/rewind': {
535
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(arg))
536
+ return needArg('2026-11-12');
537
+ const d = (await o.rewind(arg)).result;
538
+ return { html: `<b>Time machine: ${esc(d.date)}</b>\n${d.fused.filter((f) => f.sources.some((s) => s !== 'guardian')).slice(0, 8).map((f) => `[${f.score}] ${esc(f.title.slice(0, 80))} <i>(${esc(f.sources.join('+'))})</i>`).join('\n')}` };
539
+ }
540
+ case '/fence': {
541
+ const [sub, name, ...rest] = arg.split(/\s+/);
542
+ if (sub === 'add') {
543
+ if (!name || !rest.length)
544
+ return needArg('add hormuz Strait of Hormuz');
545
+ const f = await o.fenceAddAround(name, rest.join(' '), 100);
546
+ return { html: `Fence #${f.id} <b>${esc(f.name)}</b> watching ${esc(f.kinds.join(', '))}. New activity inside arrives with /alerts on.` };
547
+ }
548
+ if (sub === 'rm')
549
+ return { html: o.fenceRemove(Number(name)) ? `Removed fence #${esc(name)}.` : `No fence #${esc(name)}.` };
550
+ const list = o.fenceList();
551
+ return { html: list.length ? list.map((f) => `#${f.id} <b>${esc(f.name)}</b> ${esc(f.kinds.join(','))}${f.lastRun ? ` <i>(checked ${esc(f.lastRun.slice(0, 16))}Z)</i>` : ''}`).join('\n') : 'No fences. /fence add hormuz Strait of Hormuz' };
552
+ }
553
+ case '/brief': {
554
+ const b = await o.brief();
555
+ return { html: markdownToTelegram(b.markdown) };
556
+ }
557
+ case '/watch': {
558
+ const [sub, kind, ...rest] = arg.split(/\s+/);
559
+ if (sub === 'add') {
560
+ if (!kind || !rest.length)
561
+ return needArg('add company Nvidia (or describe it: /monitor internet outages in Iran)');
562
+ const w = o.watchAdd(kind, rest.join(' '));
563
+ return { html: `Watching #${w.id} ${esc(w.kind)} <b>${esc(w.target)}</b>. Changes arrive with /alerts on.` };
564
+ }
565
+ if (sub === 'rm')
566
+ return { html: o.watchRemove(Number(kind)) ? `Removed #${esc(kind)}.` : `No watch item #${esc(kind)}.` };
567
+ const list = o.watchList();
568
+ return { html: list.length ? list.map((w) => `#${w.id} ${esc(w.kind)} <b>${esc(w.label ?? w.target)}</b>${w.lastRun ? ` <i>(checked ${esc(w.lastRun.slice(0, 16))}Z)</i>` : ''}`).join('\n') : 'Watchlist is empty. /watch add company Nvidia' };
569
+ }
570
+ case '/score': {
571
+ const s = o.scoreboard();
572
+ return { html: `<b>Forecasts</b>: ${s.total} total, ${s.open} open, ${s.resolved} resolved\nBrier model ${s.brierModel?.toFixed(3) ?? 'n/a'} vs market ${s.brierMarket?.toFixed(3) ?? 'n/a'}\nskill vs market: ${s.skill == null ? 'n/a' : pct(s.skill)}` };
573
+ }
574
+ case '/sentinel':
575
+ case '/radar_image': {
576
+ if (!arg)
577
+ return needArg('Port of Rotterdam');
578
+ const r = await o.sentinel(arg, { kind: cmd === '/radar_image' ? 'radar' : 'optical' });
579
+ const s = r.result.shots[0];
580
+ if (!s.file)
581
+ return { html: `No ${s.kind === 'radar' ? 'radar' : 'clear'} image for ${esc(s.place.name)} between ${s.from} and ${s.to} (${esc(r.provenance.at(-1)?.note ?? 'no data')}).` };
582
+ return { photo: { file: s.file, caption: `${s.place.name.split(',').slice(0, 2).join(',')} · Sentinel-${s.kind === 'radar' ? '1 radar' : '2, 10 m'} · ${s.from} to ${s.to}` } };
583
+ }
584
+ case '/fires': {
585
+ if (!arg)
586
+ return needArg('Los Angeles');
587
+ const r = await o.fires(arg);
588
+ const f = r.result;
589
+ if (!f.place)
590
+ return { html: 'Place not found.' };
591
+ const rows = f.clusters.slice(0, 8).map((c) => `• ${c.count} hotspot(s), ${c.frp} MW at <a href="https://firms.modaps.eosdis.nasa.gov/map/#d:24hrs;@${c.lon.toFixed(3)},${c.lat.toFixed(3)},11z">${c.lat.toFixed(3)}, ${c.lon.toFixed(3)}</a>, last ${esc(c.last.slice(0, 16).replace('T', ' '))} UTC`);
592
+ return { html: `<b>Fires near ${esc(f.place.name.split(',')[0])}</b>, last ${f.days} day(s): ${f.hotspots.length} hotspots (${f.high} high confidence)\n${rows.join('\n') || 'none detected'}` };
593
+ }
594
+ case '/darkships': {
595
+ if (!arg)
596
+ return needArg('Gulf of Guinea');
597
+ const r = await o.darkShips(arg);
598
+ const d = r.result;
599
+ if (!d.place)
600
+ return { html: 'Place not found.' };
601
+ const rows = d.gaps.slice(0, 10).map((g) => `• <a href="${esc(g.url)}">${esc(g.vessel)}</a>${g.flag ? ` (${esc(g.flag)})` : ''} dark ${g.hours} h, moved ${g.km} km, back ${esc(g.on.slice(0, 10))}`);
602
+ return { html: `<b>AIS switched off near ${esc(d.place.name.split(',')[0])}</b>, last ${d.days} days: ${d.total}\n${rows.join('\n') || 'none in Global Fishing Watch data'}` };
603
+ }
604
+ case '/vessel': {
605
+ if (!arg)
606
+ return needArg('EVER GIVEN');
607
+ const r = await o.vessel(arg);
608
+ if (!r.result.length)
609
+ return { html: 'No vessel found.' };
610
+ return { html: r.result.slice(0, 3).map((v) => `<b>${esc(v.name ?? '?')}</b> IMO ${esc(v.imo ?? '?')} MMSI ${esc(v.mmsi ?? '?')} flag ${esc(v.flag ?? '?')} ${esc(v.types.join('/'))}\nAIS ${esc((v.firstSeen ?? '?').slice(0, 10))} to ${esc((v.lastSeen ?? '?').slice(0, 10))}${v.owners.length ? `\nowners: ${esc(v.owners.slice(0, 3).map((x) => x.name).join(', '))}` : ''}${v.earlierNames.length ? `\nearlier names: ${esc(v.earlierNames.join(', '))}` : ''}${v.sanctions ? `\nOFAC: <b>${esc(v.sanctions)}</b>` : ''}${v.url ? `\n<a href="${esc(v.url)}">track</a>` : ''}`).join('\n\n') };
611
+ }
612
+ case '/cloud': {
613
+ const r = await o.cloud();
614
+ const c = r.result;
615
+ const rows = c.incidents.slice(0, 12).map((i) => `• <b>${esc(i.service)}</b> <i>${esc(i.impact)}</i>: <a href="${esc(i.url)}">${esc(i.title.slice(0, 120))}</a>`);
616
+ return { html: `<b>Service status</b> (${c.checked} platforms)\n${rows.join('\n') || 'No open incidents.'}${c.degraded.length ? `\n\nDegraded: ${esc(c.degraded.map((d) => `${d.service} (${d.indicator})`).join(', '))}` : ''}` };
617
+ }
618
+ case '/bgp': {
619
+ const r = await o.bgp(arg || 'world');
620
+ const { country, asn, ip, incidents } = r.result;
621
+ const inc = incidents
622
+ ? `\n\n<b>Hijacks</b> (confidence 9+): ${incidents.hijacks.filter((h) => h.confidence >= 9 && !h.sameOrg).length} of ${incidents.hijacks.length}\n${incidents.hijacks.filter((h) => h.confidence >= 9 && !h.sameOrg).slice(0, 5).map((h) => `• ${esc(h.hijacker)} took ${esc(h.prefixes.slice(0, 2).join(', '))} from ${esc(h.victims.slice(0, 1).join('') || '?')}${h.ongoing ? ' (ongoing)' : ''}`).join('\n')}\n<b>Route leaks</b>: ${incidents.leaks.length}\n${incidents.leaks.slice(0, 4).map((l) => `• ${esc(l.leaker)}: ${l.prefixes} prefixes${l.finished ? '' : ' (ongoing)'}`).join('\n')}${incidents.attacks ? `\n<b>DDoS targets 24h</b>: ${esc(incidents.attacks.layer7.slice(0, 5).map((x) => `${x.name} ${Math.round(x.share * 100)}%`).join(', '))}` : ''}`
623
+ : '';
624
+ if (ip)
625
+ return { html: `<b>${esc(ip.ip)}</b> ${esc(ip.prefix ?? '')}\nnetwork ${esc(ip.origins.map((x) => `${x.name} (${x.asn})`).join(', ') || '?')}\nRPKI <b>${esc(ip.rpki ?? 'unknown')}</b> · ${esc([ip.city, ip.country].filter(Boolean).join(', ') || '?')}${ip.abuse.length ? `\nabuse: ${esc(ip.abuse.join(', '))}` : ''}` };
626
+ if (asn)
627
+ return { html: `<b>${esc(asn.asn)}</b> ${esc(asn.name ?? '')}${asn.visibilityV4 !== null ? `\nvisible to ${Math.round((asn.visibilityV4 ?? 0) * 100)}% of RIPE peers (IPv4), ${asn.prefixesV4} IPv4 / ${asn.prefixesV6} IPv6 prefixes, ${asn.neighbours} neighbours` : ''}${inc}` };
628
+ if (country?.latest && country.baseline)
629
+ return { html: `<b>${esc(country.country)}</b> routing: ${country.latest.v4} IPv4 prefixes visible now vs ${country.baseline.v4} usual (${country.v4Change != null ? `${(country.v4Change * 100).toFixed(1)}%` : 'n/a'}), ${country.latest.asns} networks${inc}` };
630
+ if (incidents)
631
+ return { html: `<b>Global routing incidents</b>${inc}` };
632
+ return { html: 'No routing data.' };
633
+ }
634
+ case '/vulns': {
635
+ const r = await o.vulns({ days: Number(arg) || 7 });
636
+ const rows = r.result.kev.slice(0, 12).map((k) => `• <b>${esc(k.cveID)}</b> ${esc(`${k.vendorProject} ${k.product}`)}: ${esc(k.vulnerabilityName.slice(0, 90))}${k.knownRansomwareCampaignUse === 'Known' ? ' <b>ransomware</b>' : ''} (added ${esc(k.dateAdded)})`);
637
+ return { html: `<b>Newly exploited in the wild</b> (CISA KEV, ${r.result.window.from.slice(0, 10)} on)\n${rows.join('\n') || 'none added'}\n\nNew critical CVEs (NVD): ${r.result.criticalCves.length}` };
638
+ }
639
+ case '/cve': {
640
+ if (!arg)
641
+ return needArg('CVE-2021-44228');
642
+ const d = (await o.cve(arg)).result;
643
+ return { html: `<b>${esc(d.id)}</b> ${d.cvss ? `${d.cvss.score} ${esc(d.cvss.severity)}` : 'no CVSS yet'}${d.kev ? '\n<b>Exploited in the wild (CISA KEV)</b>' : ''}${d.epss ? `\nEPSS ${(d.epss.score * 100).toFixed(1)}% in 30 days` : ''}\n${esc(d.description.slice(0, 500))}${d.packages.length ? `\nfixes: ${esc(d.packages.slice(0, 4).map((p) => `${p.name} ${p.fixed.join('/') || '?'}`).join(', '))}` : ''}` };
644
+ }
645
+ case '/regs': {
646
+ const r = await o.regs(arg ? { query: arg } : {});
647
+ const g = r.result;
648
+ const eo = g.executiveOrders.slice(0, 4).map((d) => `• <b>EO ${esc(d.executiveOrder ?? '')}</b> <a href="${esc(d.url)}">${esc(d.title.slice(0, 120))}</a>`);
649
+ const docs = g.documents.filter((d) => d.significant || d.type === 'Rule').slice(0, 8).map((d) => `• ${esc(d.publicationDate)} <i>${esc(d.type)}</i> <a href="${esc(d.url)}">${esc(d.title.slice(0, 110))}</a>`);
650
+ return { html: `<b>Federal Register</b>${arg ? ` "${esc(arg)}"` : ''}\n${[...eo, ...docs].join('\n') || 'nothing notable'}${g.publicInspection.length ? `\n\n${g.publicInspection.length} documents on public inspection (publish next)` : ''}` };
651
+ }
652
+ case '/defi': {
653
+ const d = (await o.defi()).result;
654
+ const usd = (n) => (n >= 1e9 ? `$${(n / 1e9).toFixed(1)}B` : `$${(n / 1e6).toFixed(1)}M`);
655
+ const rows = [
656
+ ...d.tvlDrops.slice(0, 6).map((p) => `• <b>${esc(p.name)}</b> TVL ${p.change1d.toFixed(0)}% in a day (${usd(p.prevTvl)} to ${usd(p.tvl)})`),
657
+ ...d.depegs.slice(0, 4).map((s) => `• <b>${esc(s.symbol)}</b> depeg at $${s.price.toFixed(4)} (${usd(s.circulating)} supply)`),
658
+ ...d.hacks.slice(0, 4).map((h) => `• hack <b>${esc(h.name)}</b> ${usd(h.amount)} (${esc(h.date.slice(0, 10))})`),
659
+ ];
660
+ return { html: `<b>DeFi risk</b>${d.fearGreed ? ` · fear &amp; greed ${d.fearGreed.value} ${esc(d.fearGreed.label)}` : ''}\n${rows.join('\n') || 'nothing alarming'}` };
661
+ }
662
+ case '/squawk': {
663
+ const s = (await o.squawks()).result;
664
+ const rows = s.aircraft.slice(0, 10).map((x) => `• <b>${x.code}</b> ${esc(x.callsign ?? x.hex)} ${esc(x.type ?? '')} ${x.altFt ?? '?'} ft${x.nearestAirport ? `, ${x.nearestAirport.km} km from ${esc(x.nearestAirport.name)}` : ''}`);
665
+ return { html: `<b>Emergency squawks</b>: ${s.total}\n${rows.join('\n') || 'none right now'}` };
666
+ }
667
+ case '/filings': {
668
+ if (!arg)
669
+ return needArg('cybersecurity incident');
670
+ const f = (await o.filings(arg, { days: 30 })).result;
671
+ const rows = f.hits.slice(0, 10).map((h) => `• ${esc(h.filed)} ${esc(h.form)} <a href="${esc(h.url)}">${esc(h.company.slice(0, 60))}</a>`);
672
+ return { html: `<b>SEC filings mentioning "${esc(arg)}"</b>, 30 days: ${f.total}${f.totalIsLowerBound ? '+' : ''}\n${rows.join('\n')}` };
673
+ }
674
+ case '/blackout': {
675
+ const r = await o.blackout(Number(arg) || 2);
676
+ const rows = r.result.outages.slice(0, 10).map((x) => `• ${x.verified ? '' : '<i>(unverified)</i> '}<b>${esc(x.country ?? '?')}</b>${x.network ? ` ${esc(x.network)}` : ''}${x.cause ? ` – ${esc(x.cause)}` : ''}, since ${esc(x.start.slice(0, 16).replace('T', ' '))}${x.end ? '' : ' (ongoing)'}${x.url ? ` <a href="${esc(x.url)}">source</a>` : ''}`);
677
+ const io = r.result.ioda.slice(0, 5).map((x) => esc(x.name)).join(', ');
678
+ return { html: `<b>Internet outages, last ${r.result.days} days</b>\n${rows.join('\n') || 'none reported'}${io ? `\n\nIODA top countries: ${io}` : ''}` };
679
+ }
680
+ case '/hazards': {
681
+ const r = await o.hazards(Number(arg) || 7);
682
+ const rows = r.result.slice(0, 12).map((h) => `• <b>${h.level === 'Red' ? 'RED' : 'orange'}</b> <a href="${esc(h.url)}">${esc(h.name)}</a>${h.countries ? ` (${esc(h.countries)})` : ''}${h.severity ? `, ${esc(h.severity)}` : ''}`);
683
+ return { html: `<b>GDACS alerts, last ${Number(arg) || 7} days</b>\n${rows.join('\n') || 'none'}` };
684
+ }
685
+ case '/podcast': {
686
+ if (!arg)
687
+ return needArg('Nvidia');
688
+ const r = await o.podcast(arg);
689
+ const t = r.result.transcript;
690
+ const ep = r.result.picked;
691
+ if (!ep)
692
+ return { html: 'No podcast episodes found.' };
693
+ if (!t)
694
+ return { html: `Found <b>${esc(ep.show)}: ${esc(ep.title)}</b> but could not transcribe it (${esc(r.provenance.at(-1)?.note ?? 'error')}).` };
695
+ const quotes = t.mentions.slice(0, 4).map((m) => `• <code>${fmtTime(m.start)}</code> ${esc(m.text.slice(0, 280))}`).join('\n');
696
+ return { html: `<b>${esc(ep.show)}</b>: ${esc(ep.title)} (${esc(ep.date.slice(0, 10))}, ${fmtTime(t.durationSec)})${ep.pageUrl ? ` <a href="${esc(ep.pageUrl)}">listen</a>` : ''}${t.summary ? `\n\n<i>Machine summary:</i> ${esc(t.summary.slice(0, 600))}` : ''}${quotes ? `\n\n<b>Mentions</b>\n${quotes}` : ''}` };
697
+ }
698
+ case '/exposure': {
699
+ if (!arg)
700
+ return needArg('example.com');
701
+ const r = await o.exposure(arg);
702
+ const e = r.result;
703
+ const rows = e.ips.slice(0, 8).map((x) => `• ${esc(x.ip)} ${x.cdn ? `<i>${esc(x.cdn)}</i> ` : ''}ports ${esc(x.ports.join(', ') || 'none')}${x.vulns.length ? `, <b>${x.vulns.length} CVEs</b>` : ''} (${esc(x.hosts.slice(0, 3).join(', '))})`).join('\n');
704
+ return { html: `<b>Exposure: ${esc(e.domain)}</b>\n${e.hostsChecked} hosts checked, ${e.resolved} IPs, ${e.vulns} known CVEs on non-CDN machines\n${rows}` };
705
+ }
706
+ case '/social': {
707
+ if (!arg)
708
+ return needArg('Nvidia');
709
+ const r = await o.pulse(arg);
710
+ const p = r.result;
711
+ const plat = Object.entries(p.byPlatform).map(([k, v]) => `${k} ${v}`).join(', ') || 'none';
712
+ const line = (x) => `• <i>${esc(x.platform)}</i> ${esc(x.author)}: <a href="${esc(x.url)}">${esc(x.text.slice(0, 120))}</a> (${x.engagement})`;
713
+ return { html: `<b>Social pulse: ${esc(arg)}</b>\n${p.posts} posts (${esc(plat)})${p.acceleration != null ? `, Reddit pace ${p.acceleration.toFixed(1)}x` : ''}\n\n<b>Most engaged</b>\n${p.top.slice(0, 6).map(line).join('\n')}` };
714
+ }
715
+ case '/calendar': {
716
+ const r = await o.calendar(Number(arg) || 7);
717
+ const items = r.result.items.slice(0, 30);
718
+ if (!items.length)
719
+ return { html: 'No catalysts found in that window.' };
720
+ let day = '';
721
+ const lines = [`<b>Catalysts ${r.result.from} to ${r.result.to}</b>`];
722
+ for (const i of items) {
723
+ if (i.date !== day)
724
+ lines.push('', `<b>${i.date}</b>`), (day = i.date);
725
+ lines.push(`${i.watched ? '★ ' : ''}${i.kind}: ${i.url ? `<a href="${esc(i.url)}">${esc(i.title)}</a>` : esc(i.title)}${i.detail ? ` <i>${esc(i.detail)}</i>` : ''}`);
726
+ }
727
+ return { html: lines.join('\n') };
728
+ }
729
+ case '/connect': {
730
+ const [a, b] = arg.split(/\s+(?:to|and|->)\s+/i);
731
+ if (!a || !b)
732
+ return needArg('Nvidia to Jensen Huang');
733
+ const r = o.connect(a, b);
734
+ return { html: r.path ? `<b>${esc(a)} → ${esc(b)}</b> (${r.path.length - 1} hops)\n${esc(describePath(r.path))}` : esc(r.note ?? 'no path') };
735
+ }
736
+ case '/live': {
737
+ const s = o.signals(200).filter((x) => x.module === 'live').slice(0, 10);
738
+ return { html: s.length ? `<b>Live streams</b>\n\n${s.map(formatSignal).join('\n\n')}` : 'Nothing flagged by the live streams yet. They run inside <code>oculon serve</code>.' };
739
+ }
740
+ case '/feedback': {
741
+ const st = feedbackStats(o.ctx);
742
+ const base = this.opts.alertMinScore ?? 70;
743
+ return { html: st.length ? `<b>Feedback</b> (base alert bar ${base})\n${st.map((m) => `${esc(m.module)}: ${m.useful} useful, ${m.noise} noise → bar ${base + m.shift}`).join('\n')}` : 'No votes yet. Tap Useful or Noise under an alert.' };
744
+ }
745
+ case '/alerts': {
746
+ const on = arg.toLowerCase() !== 'off';
747
+ const db = o.ctx.store.db;
748
+ if (on)
749
+ db.prepare('INSERT OR IGNORE INTO telegram_subs (chat_id, created_at) VALUES (?, ?)').run(chatId, Date.now());
750
+ else
751
+ db.prepare('DELETE FROM telegram_subs WHERE chat_id = ?').run(chatId);
752
+ return { html: on ? `Alerts on: signals scoring ${this.opts.alertMinScore ?? 70}+ will be sent here${this.opts.watchMinutes ? ` (scan every ${this.opts.watchMinutes} min)` : ' when the bot runs with a watch interval'}.` : 'Alerts off.' };
753
+ }
754
+ default:
755
+ return { html: `Unknown command. ${helpHtml()}` };
756
+ }
757
+ }
758
+ /** A tap on Useful / Noise under an alert. */
759
+ async handleCallback(q) {
760
+ const chatId = String(q.message?.chat.id ?? q.from.id);
761
+ const m = /^fb:([un]):(.+)$/.exec(q.data ?? '');
762
+ if (!this.allowed(chatId) || !m) {
763
+ await this.call('answerCallbackQuery', { callback_query_id: q.id }).catch(() => { });
764
+ return;
765
+ }
766
+ const verdict = m[1] === 'u' ? 'useful' : 'noise';
767
+ const s = recordFeedback(this.oculon.ctx, m[2], verdict, chatId);
768
+ const st = s ? feedbackStats(this.oculon.ctx).find((x) => x.module === s.module) : undefined;
769
+ const base = this.opts.alertMinScore ?? 70;
770
+ await this.call('answerCallbackQuery', {
771
+ callback_query_id: q.id,
772
+ text: s ? `Marked ${verdict}. ${s.module}: ${st?.useful ?? 0} useful, ${st?.noise ?? 0} noise, alert bar ${base + (st?.shift ?? 0)}.` : 'That signal is no longer stored.',
773
+ }).catch(() => { });
774
+ if (s && q.message) {
775
+ await this.call('editMessageReplyMarkup', { chat_id: q.message.chat.id, message_id: q.message.message_id, reply_markup: { inline_keyboard: [[{ text: verdict === 'useful' ? 'Marked useful' : 'Marked noise', callback_data: 'fb:done' }]] } }).catch(() => { });
776
+ }
777
+ this.log(`feedback ${verdict} on ${m[2]}`);
778
+ }
779
+ async handle(u) {
780
+ if (u.callback_query)
781
+ return this.handleCallback(u.callback_query);
782
+ const m = u.message;
783
+ const body = (m?.text ?? m?.caption ?? '').trim();
784
+ if (!m || !body)
785
+ return;
786
+ const chatId = String(m.chat.id);
787
+ const owner = this.allowed(chatId);
788
+ if (!owner && !this.isPublic) {
789
+ await this.send(chatId, `This Oculon bot is private. Your chat id is <code>${esc(chatId)}</code>. Add it to TELEGRAM_ALLOWED_CHATS to use the bot.`);
790
+ this.log(`rejected chat ${chatId}`);
791
+ return;
792
+ }
793
+ const isCmd = body.startsWith('/');
794
+ // In groups only commands are answered; in a private chat any other text is checked as a possible scam.
795
+ if (!isCmd && m.chat.type !== 'private')
796
+ return;
797
+ const text = isCmd ? body : `/scam ${body}`;
798
+ const cmd = text.split(/\s+/)[0].toLowerCase().replace(/@.*$/, '');
799
+ if (!owner) {
800
+ if (!PUBLIC_COMMANDS.has(cmd)) {
801
+ await this.send(chatId, `That command is not available here.\n\n${PUBLIC_HELP}`);
802
+ return;
803
+ }
804
+ if (!this.rateOk(chatId, HEAVY.has(cmd))) {
805
+ await this.send(chatId, 'You have reached the hourly limit. Try again a bit later, or use https://app.oculon.live');
806
+ return;
807
+ }
808
+ }
809
+ this.log(`chat ${owner ? chatId : 'public'}: ${text.slice(0, 40)}`);
810
+ try {
811
+ const r = await this.respond(chatId, text, { owner });
812
+ if (r.photo)
813
+ await this.sendPhoto(chatId, r.photo.file, r.photo.caption);
814
+ if (r.document)
815
+ await this.sendDocument(chatId, r.document.file, r.document.caption);
816
+ if (r.html)
817
+ await this.send(chatId, r.html);
818
+ }
819
+ catch (e) {
820
+ await this.send(chatId, `Error: ${esc(e.message)}`).catch(() => { });
821
+ }
822
+ }
823
+ /** Push signals the chat has not seen yet. Returns how many were sent. */
824
+ async pushAlerts(signals) {
825
+ const db = this.oculon.ctx.store.db;
826
+ const subs = db.prepare('SELECT chat_id FROM telegram_subs').all().map((r) => r.chat_id).filter((c) => this.allowed(c) || this.isPublic);
827
+ const min = this.opts.alertMinScore ?? 70;
828
+ let sent = 0;
829
+ for (const chat of subs) {
830
+ for (const s of signals.filter((x) => x.score >= alertBar(this.oculon.ctx, x.module, min))) {
831
+ const res = db.prepare('INSERT OR IGNORE INTO telegram_sent (chat_id, signal_id) VALUES (?, ?)').run(chat, s.id);
832
+ if (!res.changes)
833
+ continue;
834
+ await this.call('sendMessage', {
835
+ chat_id: chat,
836
+ text: `ALERT ${formatSignal(s)}`.slice(0, 3900),
837
+ parse_mode: 'HTML',
838
+ disable_web_page_preview: true,
839
+ reply_markup: { inline_keyboard: [[{ text: 'Useful', callback_data: `fb:u:${s.id}` }, { text: 'Noise', callback_data: `fb:n:${s.id}` }]] },
840
+ });
841
+ sent++;
842
+ }
843
+ }
844
+ return sent;
845
+ }
846
+ async scanAndAlert() {
847
+ const results = await Promise.allSettled([this.oculon.radar(), this.oculon.military(), this.oculon.naturalEvents()]);
848
+ const signals = results.flatMap((r) => (r.status === 'fulfilled' ? r.value.signals : []));
849
+ return this.pushAlerts(signals);
850
+ }
851
+ async pollOnce() {
852
+ const updates = await this.call('getUpdates', { offset: this.offset, timeout: 30, allowed_updates: ['message', 'callback_query'] });
853
+ for (const u of updates) {
854
+ this.offset = u.update_id + 1;
855
+ await this.handle(u);
856
+ }
857
+ return updates.length;
858
+ }
859
+ async start() {
860
+ this.running = true;
861
+ const me = await this.call('getMe', {});
862
+ this.log(`bot @${me.username} running; ${this.opts.allowedChats.length} allowed chat(s)`);
863
+ if (this.isPublic) {
864
+ await this.call('setMyCommands', { commands: ['scam', 'url', 'factcheck', 'recall', 'email', 'travel', 'airport', 'country', 'papers', 'audit', 'monitor', 'monitors', 'unmonitor', 'cve', 'hazards', 'blackout', 'alerts', 'help'].map((c) => ({ command: c, description: `Oculon ${c}` })) }).catch(() => { });
865
+ }
866
+ for (const chat of this.opts.allowedChats)
867
+ await this.call('setMyCommands', {
868
+ scope: { type: 'chat', chat_id: Number(chat) },
869
+ commands: ['ask', 'scam', 'monitors', 'unmonitor', 'url', 'factcheck', 'travel', 'audit', 'monitor', 'recall', 'email', 'airport', 'country', 'papers', 'case', 'brief', 'report', 'narratives', 'health', 'impact', 'contradict', 'sanctions', 'watch', 'fence', 'markets', 'launches', 'rewind', 'deployer', 'scoops', 'rh', 'ships', 'radar', 'signals', 'dossier', 'hype', 'footprint', 'plane', 'mil', 'events', 'lights', 'image', 'wallet', 'token', 'space', 'air', 'score', 'cloud', 'bgp', 'vulns', 'cve', 'regs', 'defi', 'squawk', 'filings', 'fires', 'sentinel', 'radar_image', 'darkships', 'vessel', 'blackout', 'hazards', 'podcast', 'exposure', 'social', 'calendar', 'connect', 'live', 'feedback', 'alerts'].filter((c) => onchainEnabled() || !/^(deployer|rh|wallet|token|defi|protocol)$/.test(c)).map((c) => ({ command: c, description: `Oculon ${c}` })),
870
+ }).catch(() => { });
871
+ if (this.opts.watchMinutes && this.opts.watchMinutes > 0) {
872
+ this.scheduler = startScheduler(this.oculon, {
873
+ scanMinutes: this.opts.watchMinutes,
874
+ log: (m) => this.log(`schedule ${m}`),
875
+ onSignals: async (signals) => {
876
+ const n = await this.pushAlerts(signals);
877
+ if (n)
878
+ this.log(`alerts sent: ${n}`);
879
+ },
880
+ onBrief: async (md) => {
881
+ await this.pushBrief(md);
882
+ },
883
+ onReport: async (file) => {
884
+ await this.pushReport(file, 'Weekly Oculon report');
885
+ },
886
+ });
887
+ }
888
+ while (this.running) {
889
+ try {
890
+ await this.pollOnce();
891
+ }
892
+ catch (e) {
893
+ this.log(`poll error: ${e.message}`);
894
+ await new Promise((r) => setTimeout(r, 5000));
895
+ }
896
+ }
897
+ }
898
+ stop() {
899
+ this.running = false;
900
+ this.scheduler?.stop();
901
+ }
902
+ /** Send the daily brief to every subscribed chat. Markdown is reduced to Telegram HTML (bold and links). */
903
+ async pushBrief(markdown) {
904
+ const subs = this.oculon.ctx.store.db.prepare('SELECT chat_id FROM telegram_subs').all().map((r) => r.chat_id).filter((c) => this.allowed(c));
905
+ const html = markdownToTelegram(markdown);
906
+ for (const chat of subs)
907
+ await this.send(chat, html);
908
+ return subs.length;
909
+ }
910
+ }
911
+ /** Minimal Markdown to Telegram HTML: headings and **bold** to <b>, [text](url) to links; everything else escaped. */
912
+ export function markdownToTelegram(md) {
913
+ return md
914
+ .split('\n')
915
+ .map((line) => {
916
+ const heading = /^#{1,3}\s+(.*)$/.exec(line);
917
+ const body = heading ? heading[1] : line;
918
+ let out = esc(body)
919
+ .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
920
+ .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, (_m, t, u) => `<a href="${u.replace(/"/g, '%22')}">${t}</a>`)
921
+ .replace(/^\s*[-*]\s+/, '• ');
922
+ if (heading)
923
+ out = `<b>${out}</b>`;
924
+ return out;
925
+ })
926
+ .join('\n');
927
+ }