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,180 @@
1
+ /**
2
+ * LLM layer over free-tier, OpenAI-compatible chat APIs with automatic fallback:
3
+ * Groq -> Gemini -> Mistral -> OpenRouter (free models). Only providers with a key are tried.
4
+ * Calls are not cached and go straight to fetch (they are POSTs with large bodies).
5
+ */
6
+ import { key, scrubSecrets } from './keys.js';
7
+ export const PROVIDERS = [
8
+ { name: 'groq', env: 'GROQ_API_KEY', url: 'https://api.groq.com/openai/v1/chat/completions', model: process.env.OCULON_GROQ_MODEL || 'openai/gpt-oss-120b' },
9
+ { name: 'gemini', env: 'GEMINI_API_KEY', url: 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions', model: process.env.OCULON_GEMINI_MODEL || 'gemini-2.5-flash' },
10
+ { name: 'mistral', env: 'MISTRAL_API_KEY', url: 'https://api.mistral.ai/v1/chat/completions', model: process.env.OCULON_MISTRAL_MODEL || 'mistral-medium-latest' },
11
+ // NVIDIA NIM (free developer credits). Its models reason before answering, which counts toward max_tokens.
12
+ { name: 'nvidia', env: 'NVIDIA_API_KEY', url: 'https://integrate.api.nvidia.com/v1/chat/completions', model: process.env.OCULON_NVIDIA_MODEL || 'nvidia/nemotron-3-ultra-550b-a55b', reasoningHeadroom: 4000 },
13
+ {
14
+ name: 'openrouter',
15
+ env: 'OPENROUTER_API_KEY',
16
+ url: 'https://openrouter.ai/api/v1/chat/completions',
17
+ model: process.env.OCULON_OPENROUTER_MODEL || 'nvidia/nemotron-3.5-super-vl:free',
18
+ extraHeaders: { 'x-title': 'Oculon' },
19
+ },
20
+ ];
21
+ export const availableProviders = () => [...(key('ANTHROPIC_API_KEY') ? [{ name: 'anthropic' }] : []), ...PROVIDERS.filter((p) => key(p.env))];
22
+ /** Daily budget hook for the paid provider; the SDK registers one backed by the quota table. */
23
+ let paidQuota = () => true;
24
+ export function setPaidQuota(fn) {
25
+ paidQuota = fn;
26
+ }
27
+ export const CLAUDE_MODEL = () => process.env.OCULON_CLAUDE_MODEL || 'claude-opus-5-5';
28
+ export const CLAUDE_DEEP_MODEL = () => process.env.OCULON_CLAUDE_DEEP_MODEL || 'claude-fable-5-2';
29
+ /** Raw Claude content kept on assistant messages so thinking blocks can be passed back unchanged. */
30
+ const RAW = new WeakMap();
31
+ /** OpenAI-style history to the Messages API shape: system lifted out, tool calls and results as blocks. */
32
+ export function toAnthropic(messages) {
33
+ const system = messages.filter((m) => m.role === 'system').map((m) => m.content ?? '').join('\n\n');
34
+ const out = [];
35
+ const push = (role, blocks) => {
36
+ if (!blocks.length)
37
+ return;
38
+ const last = out[out.length - 1];
39
+ if (last && last.role === role)
40
+ last.content.push(...blocks);
41
+ else
42
+ out.push({ role, content: blocks });
43
+ };
44
+ for (const m of messages) {
45
+ if (m.role === 'system')
46
+ continue;
47
+ if (m.role === 'tool')
48
+ push('user', [{ type: 'tool_result', tool_use_id: m.tool_call_id ?? '', content: m.content ?? '' }]);
49
+ else if (m.role === 'user')
50
+ push('user', [{ type: 'text', text: m.content || ' ' }]);
51
+ else {
52
+ const raw = RAW.get(m);
53
+ if (raw)
54
+ push('assistant', raw);
55
+ else {
56
+ const blocks = m.content ? [{ type: 'text', text: m.content }] : [];
57
+ for (const c of m.tool_calls ?? []) {
58
+ let input = {};
59
+ try {
60
+ input = JSON.parse(c.function.arguments || '{}');
61
+ }
62
+ catch { }
63
+ blocks.push({ type: 'tool_use', id: c.id, name: c.function.name, input });
64
+ }
65
+ push('assistant', blocks.length ? blocks : [{ type: 'text', text: ' ' }]);
66
+ }
67
+ }
68
+ }
69
+ return { system, messages: out };
70
+ }
71
+ async function callClaude(messages, opts, doFetch) {
72
+ const model = opts.premium === 'deep' ? CLAUDE_DEEP_MODEL() : CLAUDE_MODEL();
73
+ const { system, messages: msgs } = toAnthropic(messages);
74
+ const res = await doFetch('https://api.anthropic.com/v1/messages', {
75
+ method: 'POST',
76
+ headers: {
77
+ 'content-type': 'application/json',
78
+ 'x-api-key': key('ANTHROPIC_API_KEY'),
79
+ 'anthropic-version': '2023-06-01',
80
+ // drop_block: Oculon trims old tool output between rounds; affected thinking blocks are dropped instead of a 400.
81
+ // server-side fallback: a safety decline is retried on a fallback model inside the same call.
82
+ 'anthropic-beta': 'thinking-binding-controls-2026-08-01,server-side-fallback-2026-07-01',
83
+ },
84
+ body: JSON.stringify({
85
+ model,
86
+ // Thinking counts toward max_tokens on these models, so leave room above the answer size callers ask for.
87
+ max_tokens: Math.max(16_000, (opts.maxTokens ?? 1500) * 4),
88
+ thinking: { type: 'adaptive', block_binding: { prefix_mismatch_behavior: 'drop_block' } },
89
+ output_config: { effort: opts.premium === 'deep' ? 'high' : 'medium' },
90
+ fallbacks: 'default',
91
+ system: opts.json ? `${system}\n\nReply with a single JSON object and nothing else.` : system,
92
+ messages: msgs,
93
+ ...(opts.tools?.length ? { tools: opts.tools.map((t) => ({ name: t.function.name, description: t.function.description, input_schema: t.function.parameters })) } : {}),
94
+ }),
95
+ signal: AbortSignal.timeout(opts.timeoutMs ?? (opts.premium === 'deep' ? 300_000 : 180_000)),
96
+ });
97
+ const text = await res.text();
98
+ if (!res.ok)
99
+ throw new Error(`HTTP ${res.status} ${scrubSecrets(text).replace(/\s+/g, ' ').slice(0, 160)}`);
100
+ const j = JSON.parse(text);
101
+ if (j.stop_reason === 'refusal')
102
+ throw new Error('declined by safety classifier');
103
+ const content = (j.content ?? []).filter((b) => b.type !== 'fallback');
104
+ let answer = content.filter((b) => b.type === 'text').map((b) => b.text).join('').trim();
105
+ if (opts.json)
106
+ answer = answer.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
107
+ const calls = content.filter((b) => b.type === 'tool_use').map((b) => ({ id: b.id, type: 'function', function: { name: b.name, arguments: JSON.stringify(b.input ?? {}) } }));
108
+ const message = { role: 'assistant', content: answer || null, ...(calls.length ? { tool_calls: calls } : {}) };
109
+ RAW.set(message, content);
110
+ return { message, provider: 'anthropic', model: j.model ?? model };
111
+ }
112
+ /** Remember the raw Claude blocks when a caller copies an assistant message into its own history. */
113
+ export function carryRaw(from, to) {
114
+ const raw = RAW.get(from);
115
+ if (raw)
116
+ RAW.set(to, raw);
117
+ return to;
118
+ }
119
+ /** One chat completion; falls through providers on errors and rate limits. */
120
+ export async function chat(messages, opts = {}) {
121
+ const doFetch = opts.fetch ?? fetch;
122
+ const providers = PROVIDERS.filter((p) => key(p.env));
123
+ const errors = [];
124
+ if (opts.premium && key('ANTHROPIC_API_KEY')) {
125
+ if (!paidQuota('anthropic'))
126
+ errors.push('anthropic: daily budget spent (OCULON_QUOTA_ANTHROPIC)');
127
+ else {
128
+ try {
129
+ return await callClaude(messages, opts, doFetch);
130
+ }
131
+ catch (e) {
132
+ errors.push(`anthropic: ${e.name === 'TimeoutError' ? 'timeout' : scrubSecrets(e.message)}`);
133
+ }
134
+ }
135
+ }
136
+ if (!providers.length && !errors.length)
137
+ throw new Error('no LLM key configured (set ANTHROPIC_API_KEY, GROQ_API_KEY, GEMINI_API_KEY, MISTRAL_API_KEY, NVIDIA_API_KEY or OPENROUTER_API_KEY)');
138
+ for (const p of providers) {
139
+ try {
140
+ const res = await doFetch(p.url, {
141
+ method: 'POST',
142
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key(p.env)}`, ...p.extraHeaders },
143
+ body: JSON.stringify({
144
+ model: p.model,
145
+ messages,
146
+ temperature: opts.temperature ?? 0.2,
147
+ max_tokens: (opts.maxTokens ?? 1500) + (p.reasoningHeadroom ?? 0),
148
+ ...(opts.tools?.length ? { tools: opts.tools, tool_choice: 'auto' } : {}),
149
+ ...(opts.json ? { response_format: { type: 'json_object' } } : {}),
150
+ }),
151
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 60_000),
152
+ });
153
+ const text = await res.text();
154
+ if (!res.ok) {
155
+ errors.push(`${p.name}: HTTP ${res.status} ${scrubSecrets(text).replace(/\s+/g, ' ').slice(0, 120)}`);
156
+ continue;
157
+ }
158
+ const j = JSON.parse(text);
159
+ const message = j.choices?.[0]?.message;
160
+ // An empty answer (e.g. all tokens spent reasoning) falls through to the next provider.
161
+ if (!message || (!message.content?.trim() && !message.tool_calls?.length)) {
162
+ errors.push(`${p.name}: empty response`);
163
+ continue;
164
+ }
165
+ return { message: { role: 'assistant', content: message.content ?? null, ...(message.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) }, provider: p.name, model: p.model };
166
+ }
167
+ catch (e) {
168
+ errors.push(`${p.name}: ${e.name === 'TimeoutError' ? 'timeout' : scrubSecrets(e.message)}`);
169
+ }
170
+ }
171
+ throw new Error(`all LLM providers failed: ${errors.join(' | ')}`);
172
+ }
173
+ /** Plain-text completion helper. */
174
+ export async function complete(system, user, opts = {}) {
175
+ const r = await chat([
176
+ { role: 'system', content: system },
177
+ { role: 'user', content: user },
178
+ ], opts);
179
+ return { text: (r.message.content ?? '').trim(), provider: r.provider, model: r.model };
180
+ }
@@ -0,0 +1,15 @@
1
+ export declare const sha256: (data: Uint8Array | string) => Buffer;
2
+ /** Deterministic JSON: object keys sorted recursively, so the same record always hashes the same. */
3
+ export declare function canonicalJson(v: unknown): string;
4
+ export interface PathStep {
5
+ /** Sibling hash (hex). */
6
+ h: string;
7
+ /** Which side the sibling is on. */
8
+ side: 'L' | 'R';
9
+ }
10
+ /** Merkle tree over hex leaves; an odd node is paired with itself. Returns root and one path per leaf. */
11
+ export declare function merkle(leaves: string[]): {
12
+ root: string;
13
+ paths: PathStep[][];
14
+ };
15
+ export declare function applyPath(leaf: string, path: PathStep[]): string;
@@ -0,0 +1,46 @@
1
+ import { createHash } from 'node:crypto';
2
+ export const sha256 = (data) => createHash('sha256').update(data).digest();
3
+ /** Deterministic JSON: object keys sorted recursively, so the same record always hashes the same. */
4
+ export function canonicalJson(v) {
5
+ if (v === null || typeof v !== 'object')
6
+ return JSON.stringify(v);
7
+ if (Array.isArray(v))
8
+ return `[${v.map(canonicalJson).join(',')}]`;
9
+ const o = v;
10
+ return `{${Object.keys(o)
11
+ .filter((k) => o[k] !== undefined)
12
+ .sort()
13
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`)
14
+ .join(',')}}`;
15
+ }
16
+ /** Merkle tree over hex leaves; an odd node is paired with itself. Returns root and one path per leaf. */
17
+ export function merkle(leaves) {
18
+ if (!leaves.length)
19
+ throw new Error('merkle: no leaves');
20
+ let level = leaves.map((l) => Buffer.from(l, "hex"));
21
+ const paths = leaves.map(() => []);
22
+ let index = leaves.map((_, i) => i);
23
+ while (level.length > 1) {
24
+ const next = [];
25
+ for (let i = 0; i < level.length; i += 2) {
26
+ const left = level[i];
27
+ const right = level[i + 1] ?? left;
28
+ next.push(sha256(Buffer.concat([left, right])));
29
+ }
30
+ index = index.map((pos, leaf) => {
31
+ const sibling = pos % 2 === 0 ? (level[pos + 1] ?? level[pos]) : level[pos - 1];
32
+ paths[leaf].push({ h: sibling.toString('hex'), side: pos % 2 === 0 ? 'R' : 'L' });
33
+ return Math.floor(pos / 2);
34
+ });
35
+ level = next;
36
+ }
37
+ return { root: level[0].toString('hex'), paths };
38
+ }
39
+ export function applyPath(leaf, path) {
40
+ let h = Buffer.from(leaf, "hex");
41
+ for (const s of path) {
42
+ const sib = Buffer.from(s.h, 'hex');
43
+ h = sha256(s.side === 'R' ? Buffer.concat([h, sib]) : Buffer.concat([sib, h]));
44
+ }
45
+ return h.toString('hex');
46
+ }
@@ -0,0 +1,2 @@
1
+ /** Where Oculon keeps its database and files: OCULON_HOME, default ~/.oculon. */
2
+ export declare function oculonHome(): string;
@@ -0,0 +1,6 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ /** Where Oculon keeps its database and files: OCULON_HOME, default ~/.oculon. */
4
+ export function oculonHome() {
5
+ return process.env.OCULON_HOME || join(homedir(), '.oculon');
6
+ }
@@ -0,0 +1,17 @@
1
+ export interface Image {
2
+ width: number;
3
+ height: number;
4
+ /** RGBA, 4 bytes per pixel. */
5
+ rgba: Uint8Array;
6
+ }
7
+ /** Minimal PNG decoder: 8-bit, non-interlaced, all color types. Enough for map tiles and WMS images. */
8
+ export declare function decodePng(buf: Buffer): Image;
9
+ export interface Brightness {
10
+ /** Mean luminance (0-255) over pixels that have data. */
11
+ mean: number;
12
+ /** Share of pixels with data (alpha > 0). */
13
+ coverage: number;
14
+ /** Share of pixels brighter than 64, a rough "lit area" measure. */
15
+ litShare: number;
16
+ }
17
+ export declare function brightness(img: Image): Brightness;
@@ -0,0 +1,101 @@
1
+ import { inflateSync } from 'node:zlib';
2
+ const SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
3
+ const CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
4
+ function paeth(a, b, c) {
5
+ const p = a + b - c;
6
+ const pa = Math.abs(p - a);
7
+ const pb = Math.abs(p - b);
8
+ const pc = Math.abs(p - c);
9
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
10
+ }
11
+ /** Minimal PNG decoder: 8-bit, non-interlaced, all color types. Enough for map tiles and WMS images. */
12
+ export function decodePng(buf) {
13
+ if (!buf.subarray(0, 8).equals(SIG))
14
+ throw new Error('png: bad signature');
15
+ let pos = 8;
16
+ let width = 0;
17
+ let height = 0;
18
+ let depth = 0;
19
+ let colorType = 0;
20
+ let interlace = 0;
21
+ let palette = null;
22
+ let trns = null;
23
+ const idat = [];
24
+ while (pos < buf.length) {
25
+ const len = buf.readUInt32BE(pos);
26
+ const type = buf.toString('latin1', pos + 4, pos + 8);
27
+ const data = buf.subarray(pos + 8, pos + 8 + len);
28
+ pos += 12 + len;
29
+ if (type === 'IHDR') {
30
+ width = data.readUInt32BE(0);
31
+ height = data.readUInt32BE(4);
32
+ depth = data[8];
33
+ colorType = data[9];
34
+ interlace = data[12];
35
+ }
36
+ else if (type === 'PLTE')
37
+ palette = data;
38
+ else if (type === 'tRNS')
39
+ trns = data;
40
+ else if (type === 'IDAT')
41
+ idat.push(data);
42
+ else if (type === 'IEND')
43
+ break;
44
+ }
45
+ if (depth !== 8 || interlace !== 0)
46
+ throw new Error(`png: unsupported depth ${depth} / interlace ${interlace}`);
47
+ const ch = CHANNELS[colorType];
48
+ if (!ch)
49
+ throw new Error(`png: unsupported color type ${colorType}`);
50
+ const raw = inflateSync(Buffer.concat(idat));
51
+ const stride = width * ch;
52
+ const px = new Uint8Array(height * stride);
53
+ for (let y = 0; y < height; y++) {
54
+ const filter = raw[y * (stride + 1)];
55
+ const src = y * (stride + 1) + 1;
56
+ const dst = y * stride;
57
+ for (let x = 0; x < stride; x++) {
58
+ const v = raw[src + x];
59
+ const a = x >= ch ? px[dst + x - ch] : 0;
60
+ const b = y > 0 ? px[dst - stride + x] : 0;
61
+ const c = x >= ch && y > 0 ? px[dst - stride + x - ch] : 0;
62
+ px[dst + x] =
63
+ (filter === 0 ? v : filter === 1 ? v + a : filter === 2 ? v + b : filter === 3 ? v + ((a + b) >> 1) : v + paeth(a, b, c)) & 0xff;
64
+ }
65
+ }
66
+ const rgba = new Uint8Array(width * height * 4);
67
+ for (let i = 0; i < width * height; i++) {
68
+ const o = i * 4;
69
+ const s = i * ch;
70
+ if (colorType === 6)
71
+ rgba.set(px.subarray(s, s + 4), o);
72
+ else if (colorType === 2)
73
+ rgba.set([px[s], px[s + 1], px[s + 2], 255], o);
74
+ else if (colorType === 0)
75
+ rgba.set([px[s], px[s], px[s], 255], o);
76
+ else if (colorType === 4)
77
+ rgba.set([px[s], px[s], px[s], px[s + 1]], o);
78
+ else {
79
+ const idx = px[s];
80
+ rgba.set([palette?.[idx * 3] ?? 0, palette?.[idx * 3 + 1] ?? 0, palette?.[idx * 3 + 2] ?? 0, trns && idx < trns.length ? trns[idx] : 255], o);
81
+ }
82
+ }
83
+ return { width, height, rgba };
84
+ }
85
+ export function brightness(img) {
86
+ let sum = 0;
87
+ let n = 0;
88
+ let lit = 0;
89
+ const total = img.width * img.height;
90
+ for (let i = 0; i < total; i++) {
91
+ const o = i * 4;
92
+ if (img.rgba[o + 3] === 0)
93
+ continue;
94
+ const l = 0.2126 * img.rgba[o] + 0.7152 * img.rgba[o + 1] + 0.0722 * img.rgba[o + 2];
95
+ sum += l;
96
+ n++;
97
+ if (l > 64)
98
+ lit++;
99
+ }
100
+ return { mean: n ? sum / n : 0, coverage: total ? n / total : 0, litShare: n ? lit / n : 0 };
101
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Daily request budgets for free-tier APIs. Counted per source per UTC day in the database, so a busy
3
+ * dashboard or watch loop cannot burn a whole month's free quota. Cached responses do not count.
4
+ * Budgets sit a little under each provider's published free limit; override with OCULON_QUOTA_<SOURCE>=n.
5
+ */
6
+ import type { Store } from './store.js';
7
+ export declare const DAILY_BUDGET: Record<string, number>;
8
+ export declare function budgetFor(source: string): number | null;
9
+ /** Reserve one request; returns false when today's budget for the source is spent. */
10
+ export declare function takeQuota(store: Store, source: string): boolean;
11
+ export declare function quotaUsage(store: Store, day?: string): {
12
+ source: string;
13
+ used: number;
14
+ budget: number | null;
15
+ }[];
@@ -0,0 +1,90 @@
1
+ export const DAILY_BUDGET = {
2
+ gnews: 90, // 100/day free
3
+ nyt: 450, // 500/day
4
+ guardian: 450, // 500/day developer key
5
+ youtube: 90, // search costs 100 of 10,000 daily units
6
+ tavily: 30, // 1,000/month
7
+ exa: 30, // 1,000/month
8
+ firecrawl: 15, // 500 credits one-off / month
9
+ jina: 300,
10
+ finnhub: 3000,
11
+ adzuna: 230, // 250/day
12
+ courtlistener: 4000,
13
+ 'companies-house': 5000,
14
+ brandfetch: 90,
15
+ urlscan: 900,
16
+ 'safe-browsing': 9000,
17
+ zerion: 2000,
18
+ etherscan: 90_000,
19
+ webacy: 900,
20
+ openaq: 2000,
21
+ openalex: 9000,
22
+ bluesky: 2000,
23
+ coingecko: 300, // demo: 10,000/month
24
+ fred: 2000,
25
+ 'github-search': 1000,
26
+ geckoterminal: 2500,
27
+ kalshi: 2000,
28
+ manifold: 2000,
29
+ itunes: 1000,
30
+ huggingface: 3000,
31
+ npm: 5000,
32
+ wikidata: 2000,
33
+ ofac: 50,
34
+ blockscout: 20000,
35
+ gfw: 2000,
36
+ ripestat: 2000,
37
+ statuspage: 20000,
38
+ opensanctions: 300,
39
+ firms: 2000, // 5,000 transactions per 10 minutes
40
+ copernicus: 300, // free account: processing units are monthly, keep requests modest
41
+ 'cloudflare-radar': 5000,
42
+ ioda: 2000,
43
+ gdacs: 2000,
44
+ 'cisa-kev': 10, // 1.9 MB catalog, cached 6h
45
+ nvd: 150, // keyless: 5 requests per 30 s
46
+ epss: 300,
47
+ osv: 500,
48
+ 'github-advisories': 50, // shares GitHub's 60/hour keyless limit
49
+ 'federal-register': 300,
50
+ defillama: 500,
51
+ 'defillama-stablecoins': 200,
52
+ 'defillama-yields': 50, // ~10 MB per call
53
+ 'alternative-me': 100,
54
+ openchain: 1000,
55
+ '4byte': 500,
56
+ 'nasa-donki': 900, // 1,000/hour with a key; DEMO_KEY is 50/day
57
+ 'nasa-neows': 500,
58
+ openfda: 900, // 1,000/day per IP without a key
59
+ clinicaltrials: 2000,
60
+ gdelt: 2000,
61
+ // Paid, pay-per-use: kept small on purpose. Raise with OCULON_QUOTA_ANTHROPIC / OCULON_QUOTA_APIFY.
62
+ anthropic: 150,
63
+ apify: 40,
64
+ deepgram: 30, // transcriptions per day
65
+ 'shodan-internetdb': 2000,
66
+ };
67
+ const envName = (source) => `OCULON_QUOTA_${source.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;
68
+ export function budgetFor(source) {
69
+ const override = Number(process.env[envName(source)]);
70
+ if (Number.isFinite(override) && override > 0)
71
+ return override;
72
+ return DAILY_BUDGET[source] ?? null;
73
+ }
74
+ const today = () => new Date().toISOString().slice(0, 10);
75
+ /** Reserve one request; returns false when today's budget for the source is spent. */
76
+ export function takeQuota(store, source) {
77
+ const budget = budgetFor(source);
78
+ if (budget === null)
79
+ return true;
80
+ const day = today();
81
+ const row = store.db.prepare('SELECT used FROM quota WHERE source = ? AND day = ?').get(source, day);
82
+ if ((row?.used ?? 0) >= budget)
83
+ return false;
84
+ store.db.prepare('INSERT INTO quota (source, day, used) VALUES (?, ?, 1) ON CONFLICT(source, day) DO UPDATE SET used = used + 1').run(source, day);
85
+ return true;
86
+ }
87
+ export function quotaUsage(store, day = today()) {
88
+ const rows = store.db.prepare('SELECT source, used FROM quota WHERE day = ? ORDER BY used DESC').all(day);
89
+ return rows.map((r) => ({ ...r, budget: budgetFor(r.source) }));
90
+ }
@@ -0,0 +1,24 @@
1
+ export declare const sum: (xs: number[]) => number;
2
+ export declare const mean: (xs: number[]) => number;
3
+ export declare function median(xs: number[]): number;
4
+ export declare function std(xs: number[]): number;
5
+ /** Robust z-score of `x` against `baseline` (median/MAD, falls back to std). */
6
+ export declare function robustZ(x: number, baseline: number[]): number;
7
+ /** How many times larger `x` is than the baseline median. */
8
+ export declare function spikeRatio(x: number, baseline: number[]): number;
9
+ export declare const clamp: (x: number, lo: number, hi: number) => number;
10
+ /** Sum consecutive groups of `size` (from the end, so the last bucket is always full). */
11
+ export declare function bucketFromEnd(xs: number[], size: number, agg?: (g: number[]) => number): number[];
12
+ export type Phase = 'DORMANT' | 'EMERGING' | 'RISING' | 'PEAK' | 'COOLING' | 'STEADY';
13
+ export interface Trend {
14
+ phase: Phase;
15
+ /** recent (last 2 buckets) mean / earlier mean. */
16
+ momentum: number;
17
+ /** last bucket / previous bucket. */
18
+ acceleration: number;
19
+ }
20
+ /**
21
+ * Classify a series (oldest -> newest, at least 4 buckets) into a hype phase.
22
+ * Rules are deliberately simple and documented so results are explainable.
23
+ */
24
+ export declare function trend(series: number[]): Trend;
@@ -0,0 +1,67 @@
1
+ export const sum = (xs) => xs.reduce((a, b) => a + b, 0);
2
+ export const mean = (xs) => (xs.length ? sum(xs) / xs.length : 0);
3
+ export function median(xs) {
4
+ if (!xs.length)
5
+ return 0;
6
+ const s = [...xs].sort((a, b) => a - b);
7
+ const m = Math.floor(s.length / 2);
8
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
9
+ }
10
+ export function std(xs) {
11
+ if (xs.length < 2)
12
+ return 0;
13
+ const m = mean(xs);
14
+ return Math.sqrt(sum(xs.map((x) => (x - m) ** 2)) / (xs.length - 1));
15
+ }
16
+ /** Robust z-score of `x` against `baseline` (median/MAD, falls back to std). */
17
+ export function robustZ(x, baseline) {
18
+ if (!baseline.length)
19
+ return 0;
20
+ const med = median(baseline);
21
+ const mad = median(baseline.map((b) => Math.abs(b - med))) * 1.4826;
22
+ const spread = mad > 0 ? mad : std(baseline);
23
+ if (spread === 0)
24
+ return x === med ? 0 : x > med ? 10 : -10;
25
+ return (x - med) / spread;
26
+ }
27
+ /** How many times larger `x` is than the baseline median. */
28
+ export function spikeRatio(x, baseline) {
29
+ const med = median(baseline);
30
+ return med > 0 ? x / med : x > 0 ? Infinity : 1;
31
+ }
32
+ export const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
33
+ /** Sum consecutive groups of `size` (from the end, so the last bucket is always full). */
34
+ export function bucketFromEnd(xs, size, agg = sum) {
35
+ const out = [];
36
+ for (let end = xs.length; end - size >= 0; end -= size)
37
+ out.unshift(agg(xs.slice(end - size, end)));
38
+ return out;
39
+ }
40
+ /**
41
+ * Classify a series (oldest -> newest, at least 4 buckets) into a hype phase.
42
+ * Rules are deliberately simple and documented so results are explainable.
43
+ */
44
+ export function trend(series) {
45
+ const n = series.length;
46
+ if (n < 4 || sum(series) === 0)
47
+ return { phase: 'DORMANT', momentum: 1, acceleration: 1 };
48
+ const recent = mean(series.slice(n - 2));
49
+ const earlier = mean(series.slice(0, n - 2));
50
+ const last = series[n - 1];
51
+ const prev = series[n - 2];
52
+ const eps = 1e-9;
53
+ const momentum = earlier > eps ? recent / earlier : recent > 0 ? Infinity : 1;
54
+ const acceleration = prev > eps ? last / prev : last > 0 ? Infinity : 1;
55
+ let phase;
56
+ if (earlier <= eps && recent > 0)
57
+ phase = 'EMERGING';
58
+ else if (momentum >= 1.5 && acceleration >= 0.9)
59
+ phase = 'RISING';
60
+ else if (momentum >= 1.2 && acceleration < 0.9)
61
+ phase = 'PEAK';
62
+ else if (momentum <= 0.75)
63
+ phase = 'COOLING';
64
+ else
65
+ phase = 'STEADY';
66
+ return { phase, momentum, acceleration };
67
+ }
@@ -0,0 +1,20 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ export declare class Store {
3
+ readonly db: DatabaseSync;
4
+ constructor(path?: string);
5
+ cacheGet(key: string): {
6
+ body: string;
7
+ fetchedAt: number;
8
+ } | undefined;
9
+ cachePut(key: string, body: string, fetchedAt?: number): void;
10
+ /**
11
+ * Deletes everything the on-chain modules left behind (Robinhood Chain pools and deployers, wallet and
12
+ * token checks, DeFi): their signals, scoops, observations, entities, edges and watch targets.
13
+ */
14
+ purgeOnchain(): Record<string, number>;
15
+ /** Drop raw API responses older than `days` (derived entries such as calibration stay), optionally compacting the file. */
16
+ pruneCache(days?: number, vacuum?: boolean, now?: number): {
17
+ removed: number;
18
+ };
19
+ close(): void;
20
+ }